This commit is contained in:
fro1991
2025-02-01 19:49:27 +07:00
parent 42c2a8e481
commit 13a2c4d42c
57 changed files with 159 additions and 295 deletions

View File

@ -0,0 +1,14 @@
import { Container, DataGridInner } from '@/components';
import { LogActivityContextProvider } from './hooks';
export default function LogActivityPage() {
return (
<LogActivityContextProvider>
<Container>
<div className="grid gap-5 lg:gap-7.5">
<DataGridInner />
</div>
</Container>
</LogActivityContextProvider>
);
}

View File

@ -0,0 +1,43 @@
import { useState } from 'react';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { Calendar } from '@/components/ui/calendar';
import { DateRange } from 'react-day-picker';
import { format } from 'date-fns';
import { KeenIcon } from '@/components/keenicons';
import { cn } from '@/lib/utils';
interface DateRangePickerProps {
date: DateRange | undefined;
setDate: (date: DateRange | undefined) => void;
}
const DatePicker = ({ date, setDate }: any) => {
return (
<Popover>
<PopoverTrigger asChild>
<button
id="date"
className={cn(
'btn btn-sm btn-light data-[state=open]:bg-light-active',
!date && 'text-gray-400'
)}
>
<KeenIcon icon="calendar" className="me-0.5" />
{date?.to ? <>{format(date.to, 'LLL dd, y')}</> : <span>Pick a date</span>}
</button>
</PopoverTrigger>
<PopoverContent className="w-auto p-0" align="end">
<Calendar
initialFocus
mode="single"
defaultMonth={date?.to}
selected={date?.to}
onSelect={(value) => setDate({ from: value, to: value })}
numberOfMonths={1}
/>
</PopoverContent>
</Popover>
);
};
export { DatePicker };

View File

@ -0,0 +1,53 @@
import { useState } from 'react';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { Calendar } from '@/components/ui/calendar';
import { DateRange } from 'react-day-picker';
import { format } from 'date-fns';
import { KeenIcon } from '@/components/keenicons';
import { cn } from '@/lib/utils';
interface DateRangePickerProps {
date: DateRange | undefined;
setDate: (date: DateRange | undefined) => void;
}
const DateRangePicker = ({ date, setDate }: DateRangePickerProps) => {
return (
<Popover>
<PopoverTrigger asChild>
<button
id="date"
className={cn(
'btn btn-sm btn-light data-[state=open]:bg-light-active',
!date && 'text-gray-400'
)}
>
<KeenIcon icon="calendar" className="me-0.5" />
{date?.from ? (
date.to ? (
<>
{format(date.from, 'LLL dd, y')} - {format(date.to, 'LLL dd, y')}
</>
) : (
format(date.from, 'LLL dd, y')
)
) : (
<span>Pick a date range</span>
)}
</button>
</PopoverTrigger>
<PopoverContent className="w-auto p-0" align="end">
<Calendar
initialFocus
mode="range"
defaultMonth={date?.from}
selected={date}
onSelect={setDate}
numberOfMonths={2}
/>
</PopoverContent>
</Popover>
);
};
export { DateRangePicker };

View File

@ -0,0 +1,146 @@
import { ContentLoader, DefaultTooltip, KeenIcon, useDataGrid } from '@/components';
import { Button } from '@/components/ui/button';
import { useLogActivityContext } from '../hooks';
import { toAbsoluteUrl } from '@/utils';
import { DateRangePicker } from './DateRangePicker';
import { toast } from 'sonner';
import { useCallback, useState } from 'react';
import { DateRange } from 'react-day-picker';
type LoadingButton = 'filter' | 'reset' | 'export' | 'refresh' | null;
const ListToolBar = () => {
const { table, reload } = useDataGrid();
const { date, setDate, doExportData } = useLogActivityContext();
const [searchUsername, setSearchUsername] = useState('');
// const [filteredDate, setFilteredDate] = useState<DateRange | undefined>(undefined);
const [isLoading, setIsLoading] = useState(false);
const [loadingButton, setLoadingButton] = useState<LoadingButton>(null);
const [filter, setFilter] = useState<{
from: Date | undefined;
to: Date | undefined;
type?: string;
}>({
from: new Date(new Date().setDate(new Date().getDate() - 31)),
to: new Date(),
type: ''
});
const handleExport = () => {
const sorting = table.getState().sorting;
doExportData(sorting, table.getState().columnFilters);
};
const handleFilterData = useCallback(() => {
try {
setIsLoading(true);
setLoadingButton('filter');
const filters = [];
if (searchUsername) {
filters.push({
id: 'username',
value: searchUsername
});
}
if (date?.from && date?.to) {
filters.push({
id: 'user_activity.created_at',
value: {
from: `${date.from.toISOString().split('T')[0]} 00:00:00`,
to: `${date.to.toISOString().split('T')[0]} 23:59:59`
}
});
}
table.setColumnFilters(filters);
} catch (error) {
toast.error('Error filtering data');
} finally {
setLoadingButton(null);
setIsLoading(false);
}
}, [date, searchUsername, table]);
const handleResetData = () => {
const today = new Date();
const oneMonthAgo = new Date(today);
oneMonthAgo.setDate(today.getDate() - 31);
setDate({ from: oneMonthAgo, to: today });
setFilter({
from: oneMonthAgo,
to: today,
type: ''
});
setSearchUsername('');
table.setColumnFilters([]);
reload();
};
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 gap-3 items-center">
<div className="w-auto min-w-[120px]">
<label className="input input-sm">
<KeenIcon icon="magnifier" />
<input
type="text"
placeholder="Search username"
value={searchUsername}
onChange={(event) => setSearchUsername(event.target.value)}
/>
</label>
</div>
<div className="w-auto min-w-[220px]">
<DateRangePicker date={date} setDate={setDate} />
</div>
<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" />}
</Button>
</DefaultTooltip>
<DefaultTooltip title={'Reset Filter'} placement={'top'}>
<Button
variant="outline"
className="h-7.5 disabled:bg-gray-400"
onClick={handleResetData}
disabled={isLoading}
>
<KeenIcon icon="arrow-circle-left" />
</Button>
</DefaultTooltip>
</div>
<div className="flex gap-3">
<DefaultTooltip title={'Refresh'} placement={'top'}>
<Button variant={'outline'} className="h-7.5" onClick={() => reload()}>
<KeenIcon icon="arrows-circle" />
</Button>
</DefaultTooltip>
<DefaultTooltip title={'Export Data'} placement={'top'}>
<Button onClick={handleExport} className="h-7.5" variant={'outline'}>
<img
src={toAbsoluteUrl('/media/file-types/xls.svg')}
className="dark:hidden h-5"
alt="Export to Excel"
/>
</Button>
</DefaultTooltip>
</div>
</div>
</div>
</div>
);
};
export { ListToolBar };

View File

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

View File

@ -0,0 +1,243 @@
import React, { createContext, useCallback, 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 } from '@/components';
import { ListToolBar } from '../blocks';
import { useCallApi } from '@/hooks';
import { Badge } from '@/components/ui/badge';
import moment from 'moment';
import { getAuth } from '@/auth';
import { DateRange } from 'react-day-picker';
import { format } from 'date-fns';
import { doSaveLogActivity } from '@/actions/GlobalActions';
interface ContextProps {
doExportData: (sorting: any, filter: any) => Promise<any>;
date: DateRange | undefined;
setDate: (date: DateRange | undefined) => void;
}
const initialProps: ContextProps = {
doExportData: async () => ({ data: [], totalCount: 0 }),
date: undefined,
setDate: () => {}
};
const LogActivityContext = createContext<ContextProps>(initialProps);
const API_URL = apiConfig.service_dashboard;
const LogActivityContextProvider = ({ children }: { children: React.ReactNode }) => {
/* state */
const { GetData } = useCallApi();
const { GetExportData } = useCallApi();
/* action */
const [date, setDate] = useState<DateRange | undefined>({
from: new Date(new Date().setMonth(new Date().getMonth() - 1)),
to: new Date()
});
/* Data Grid Options */
const columns = useMemo<ColumnDef<any>[]>(
() => [
{
accessorFn: (row) => row.created_at,
id: 'created_at',
header: ({ column }) => <DataGridColumnHeader title="Timestamp" column={column} />,
enableSorting: true,
enableHiding: false,
cell: ({ row }) => moment(row.original.created_at).format('YYYY-MM-DD HH:mm:ss')
},
{
accessorFn: (row) => row.user.username,
id: 'username',
header: ({ column }) => <DataGridColumnHeader title="Username" column={column} />,
enableSorting: false,
enableHiding: false,
meta: {
headerClassName: 'w-[350px]'
}
},
{
accessorFn: (row) => row.module,
id: 'module',
header: ({ column }) => <DataGridColumnHeader title="Module" column={column} />,
enableSorting: false,
enableHiding: false,
meta: {
headerClassName: 'w-[350px]'
}
},
{
accessorFn: (row) => row.description,
id: 'description',
header: ({ column }) => <DataGridColumnHeader title="Description" column={column} />,
enableSorting: false,
enableHiding: false,
meta: {
headerClassName: 'w-[350px]'
}
},
{
accessorFn: (row) => row.action,
id: 'action',
header: ({ column }) => <DataGridColumnHeader title="Action" column={column} />,
enableSorting: false,
enableHiding: false,
cell: ({ row }) => {
const { action } = row.original;
const statusMap: any = {
C: ['Create', 'success'],
U: ['Update', 'default'],
D: ['Delete', 'destructive'],
l: ['Login', 'outline'],
O: ['Logout', 'outline'],
E: ['Export', 'outline']
};
return <Badge variant={statusMap[action][1]}>{statusMap[action][0]}</Badge>;
},
meta: {
headerClassName: 'w-[100px]',
cellClassName: 'text-center'
}
}
],
[]
);
const doGetListData = useCallback(
async (page: number, limit: number, sorting: any, filter: any) => {
const auth = getAuth();
let all_user = false;
if (auth) {
all_user = auth.role_name === 'Super Admin';
}
const user = localStorage.getItem('brillian-bri-tl-auth-v1=9.1.1');
const parsedUser = user ? JSON.parse(user) : null;
const desc = sorting.length > 0 ? sorting[0].desc : false;
sorting = [{ id: 'user_activity.created_at', desc }];
let dataFilter: any = {};
if (filter && filter.length > 0) {
filter.forEach((f: any) => {
if (f.id === 'username') {
dataFilter['username'] = { like: f.value };
} else if (f.id === 'user_activity.created_at') {
dataFilter['user_activity.created_at'] = f.value;
}
});
}
if (!dataFilter['user_activity.created_at']) {
const defaultFrom = date?.from || new Date(new Date().setMonth(new Date().getMonth() - 1));
const defaultTo = date?.to || new Date();
dataFilter['user_activity.created_at'] = {
from: `${format(defaultFrom, 'yyyy-MM-dd')} 00:00:00`,
to: `${format(defaultTo, 'yyyy-MM-dd')} 23:59:59`
};
}
const response = await GetData(`${API_URL}/user_activity/list`, {
limit: limit,
page: page + 1,
with_deleted: false,
order_field: sorting[0].id,
order_direction: sorting[0].desc === false ? 'ASC' : 'DESC',
filter: JSON.stringify(dataFilter),
all_user: all_user
});
return { data: response?.data.list, totalCount: response?.data.total_count };
},
[]
);
const doExportData = async (sorting: any, filter: any) => {
const user = localStorage.getItem('brillian-bri-tl-auth-v1=9.1.1');
const parsedUser = user ? JSON.parse(user) : null;
sorting = sorting.length === 0 ? [{ id: 'user_activity.created_at', desc: false }] : sorting;
filter = filter && filter.length > 0 ? filter : [];
const auth = getAuth();
let all_user = false;
if (auth) {
all_user = auth.role_name === 'Super Admin';
}
let dataFilter: any = {};
if (filter && filter.length > 0) {
filter.forEach((f: any) => {
if (f.id === 'username') {
dataFilter['username'] = { like: f.value };
} else if (f.id === 'user_activity.created_at') {
dataFilter['user_activity.created_at'] = f.value;
}
});
}
if (!dataFilter['user_activity.created_at']) {
const defaultFrom = new Date(new Date().setMonth(new Date().getMonth() - 1));
const defaultTo = new Date();
dataFilter['user_activity.created_at'] = {
from: `${format(defaultFrom, 'yyyy-MM-dd')} 00:00:00`,
to: `${format(defaultTo, 'yyyy-MM-dd')} 23:59:59`
};
}
let order = 'user_activity.created_at';
let param = {
all_user: false,
// order_field: sorting[0].id,
order_field: order,
order_direction: sorting[0].desc === false ? 'ASC' : 'DESC',
filter: JSON.stringify(dataFilter),
token: parsedUser?.access_token
};
console.log('param:', param);
let url = `${API_URL}/user_activity/export`;
GetExportData(url, param, 'user_activity_export_');
const createActivity = {
module: 'Update Pengajuan Kredit',
description: `Export Pengajuan Kredit => Log Activity`,
action: 'E'
};
doSaveLogActivity(createActivity);
};
return (
<LogActivityContext.Provider
value={{
date,
setDate,
doExportData
}}
>
<Toaster expand visibleToasts={9} duration={3000} />
<DataGridProvider
columns={columns}
pagination={{ size: 10 }}
toolbar={<ListToolBar />}
layout={{ card: true }}
sorting={[{ id: 'UserActivity.created_at', desc: true }]}
serverSide={true}
onFetchData={({ pageIndex, pageSize, sorting, columnFilters }) =>
doGetListData(pageIndex, pageSize, sorting, columnFilters)
}
>
{children}
</DataGridProvider>
</LogActivityContext.Provider>
);
};
export { LogActivityContextProvider, LogActivityContext };

View File

@ -0,0 +1,2 @@
export * from './LogActivityContext';
export * from './useLogActivityContext';

View File

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

View File

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

View File

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

View File

@ -0,0 +1,186 @@
import { useCallback, useRef, useState } from 'react';
import {
Dialog,
DialogBody,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle
} from '@/components/ui/dialog';
import { useManagePositionContext } from '../hooks';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { apiConfig } from '@/config/api.config';
import { Alert, useDataGrid } from '@/components';
import { toast } from 'sonner';
import { useCallApi } from '@/hooks';
import { Checkbox } from '@/components/ui/checkbox';
import { doSaveLogActivity } from '@/actions/GlobalActions';
const API_URL = apiConfig.service_dashboard;
interface MenuItem {
id: string;
name: string;
children?: MenuItem[];
}
const MenuItemComponent: React.FC<{
menu: MenuItem;
selectMenus: string[];
handleCheckboxChange: (id: string) => void;
}> = ({ menu, selectMenus, handleCheckboxChange }) => {
const { id, name, children = [] } = menu;
return (
<div className="mt-3">
<div className="text-sm flex items-center gap-3">
<Checkbox
checked={selectMenus.includes(id)}
id={`label-${id}`}
onCheckedChange={() => handleCheckboxChange(id)}
/>
<label htmlFor={`label-${id}`}>{name}</label>
</div>
{children.length > 0 && (
<div className="pl-5">
{children.map((child) => (
<MenuItemComponent
key={child.id}
menu={child}
selectMenus={selectMenus}
handleCheckboxChange={handleCheckboxChange}
/>
))}
</div>
)}
</div>
);
};
const AddDialog = () => {
const parentRef = useRef<any | null>(null);
const { showAddDialog, handleAddDialog, menus } = useManagePositionContext();
const { reload } = useDataGrid();
const { PostData } = useCallApi();
const [alert, setAlert] = useState({
show: false,
message: ''
});
const [selectMenus, setSelectMenus] = useState<string[]>([]);
const [formField, setFormField] = useState({
name: ''
});
/* actions */
const handleCheckboxChange = useCallback((key: string) => {
setSelectMenus((prev) =>
prev.includes(key) ? prev.filter((item) => item !== key) : [...prev, key]
);
}, []);
const doCreatePosition = useCallback(
async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
const response = await PostData(`${API_URL}/user_role/create`, {
name: formField.name,
roles: selectMenus,
status: 'Y',
application: 'ukln'
});
if (response?.status) {
setAlert((prev) => ({ ...prev, show: false, message: '' }));
handleAddDialog(false);
toast.success('Success Create Position');
reload();
const createActivity = {
module: 'Manage Position',
description: `Create New User => ${formField.name}`,
action: 'C'
};
doSaveLogActivity(createActivity);
} else {
setAlert((prev) => ({ ...prev, show: true, message: response?.message }));
}
},
[formField, selectMenus]
);
return (
<Dialog open={showAddDialog} onOpenChange={(open) => handleAddDialog(open)}>
<DialogContent className="container-fixed max-w-screen-lg flex flex-col p-10 overflow-hidden [&>button]:hidden">
<DialogHeader className="p-0 border-0">
<DialogTitle></DialogTitle>
<DialogDescription></DialogDescription>
<div className="flex items-center justify-between flex-wrap grow gap-5 pb-7.5">
<div className="flex flex-col justify-center gap-2">
<h1 className="text-xl font-semibold leading-none text-gray-900">
Positions - Create
</h1>
<div className="flex items-center gap-2 text-sm font-normal text-gray-700"></div>
</div>
<Button
variant={'outline'}
color="#ddd"
size={'sm'}
onClick={() => handleAddDialog(false)}
>
Close
</Button>
</div>
</DialogHeader>
<DialogBody className="scrollable-y py-0 mb-5 ps-0 pe-3 -me-7" ref={parentRef}>
<div className="flex flex-col items-stretch grow gap-5 lg:gap-7.5">
{alert.show && (
<Alert variant="danger">
<h3>{alert.message}</h3>
</Alert>
)}
<form action="" onSubmit={doCreatePosition}>
<div className="card-body grid gap-5">
<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="grid md:grid-cols-3 w-full gap-5">
{menus.map((menu) => (
<div className="card" key={menu.id}>
<div className="card-body">
<MenuItemComponent
menu={menu}
selectMenus={selectMenus}
handleCheckboxChange={handleCheckboxChange}
/>
</div>
</div>
))}
</div>
<div className="flex justify-end pt-2.5">
<Button className="btn btn-primary" type="submit">
Save Changes
</Button>
</div>
</div>
</form>
</div>
</DialogBody>
</DialogContent>
</Dialog>
);
};
export { AddDialog };

View File

@ -0,0 +1,97 @@
import {
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle
} from '@/components/ui/dialog';
import { useManagePositionContext } 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, selectedPosition } = useManagePositionContext();
const { reload } = useDataGrid();
const [enforce, setEnforce] = useState(false);
const { DeleteData } = useCallApi();
const [alert, setAlert] = useState({
show: false,
message: ''
});
/* actions */
const doDeleteData = useCallback(async () => {
if (!selectedPosition) {
toast.success('Please Select Position');
return;
}
const response = await DeleteData(
`${API_URL}/user_role/delete/${selectedPosition.id}/${enforce}`,
{
id: selectedPosition.id
}
);
if (response?.status) {
setAlert((prev) => ({ ...prev, show: false, message: '' }));
handleDeleteDialog(false, null);
toast.success('Success Delete Position');
reload();
const createActivity = {
module: 'Manage Position',
description: `Delete Position => ${selectedPosition.name}`,
action: 'D'
};
doSaveLogActivity(createActivity);
} else {
setAlert((prev) => ({ ...prev, show: true, message: response?.message }));
}
}, [selectedPosition, 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">
<DialogTitle></DialogTitle>
<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,226 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import {
Dialog,
DialogBody,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle
} from '@/components/ui/dialog';
import { useManagePositionContext } 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 { Checkbox } from '@/components/ui/checkbox';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue
} from '@/components/ui/select';
import { doSaveLogActivity } from '@/actions/GlobalActions';
const API_URL = apiConfig.service_dashboard;
interface MenuItem {
id: string;
name: string;
children?: MenuItem[];
}
const MenuItemComponent: React.FC<{
menu: MenuItem;
selectMenus: string[];
handleCheckboxChange: (id: string) => void;
}> = ({ menu, selectMenus, handleCheckboxChange }) => {
const { id, name, children = [] } = menu;
return (
<div className="mt-3">
<div className="text-sm flex items-center gap-3">
<Checkbox
checked={selectMenus.includes(id)}
id={`label-${id}`}
onCheckedChange={() => handleCheckboxChange(id)}
/>
<label htmlFor={`label-${id}`}>{name}</label>
</div>
{children.length > 0 && (
<div className="pl-5">
{children.map((child) => (
<MenuItemComponent
key={child.id}
menu={child}
selectMenus={selectMenus}
handleCheckboxChange={handleCheckboxChange}
/>
))}
</div>
)}
</div>
);
};
const EditDialog = () => {
const parentRef = useRef<any | null>(null);
const { showEditDialog, handleEditDialog, menus, selectedPosition } = useManagePositionContext();
const { reload } = useDataGrid();
const { PutData } = useCallApi();
const [alert, setAlert] = useState({
show: false,
message: ''
});
const [selectMenus, setSelectMenus] = useState<string[]>([]);
const [formField, setFormField] = useState({
name: '',
status: ''
});
/* actions */
const handleCheckboxChange = useCallback((key: string) => {
setSelectMenus((prev) =>
prev.includes(key) ? prev.filter((item) => item !== key) : [...prev, key]
);
}, []);
const doEditPosition = useCallback(
async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
if (!selectedPosition) {
toast.success('Please Select Position');
return;
}
const response = await PutData(`${API_URL}/user_role/update/${selectedPosition.id}`, {
name: formField.name,
roles: selectMenus,
status: formField.status
});
if (response?.status) {
setAlert((prev) => ({ ...prev, show: false, message: '' }));
handleEditDialog(false, null);
toast.success('Success Update Position');
reload();
const createActivity = {
module: 'Manage Position',
description: `Edit Position => ${selectedPosition.name}`,
action: 'U'
};
doSaveLogActivity(createActivity);
} else {
setAlert((prev) => ({ ...prev, show: true, message: response?.message }));
}
},
[formField, selectMenus, selectedPosition]
);
useEffect(() => {
if (selectedPosition) {
setFormField((prev) => ({
...prev,
name: selectedPosition.name,
status: selectedPosition.status
}));
setSelectMenus(selectedPosition.roles);
}
}, [selectedPosition]);
return (
<Dialog open={showEditDialog} onOpenChange={(open) => handleEditDialog(open, null)}>
<DialogContent className="container-fixed max-w-[1024px] 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">Positions - Edit</h1>
</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" className="mb-3">
<h3>{alert.message}</h3>
</Alert>
)}
<form action="" onSubmit={doEditPosition}>
<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-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>
<div className="grid md:grid-cols-3 w-full gap-5">
{menus.map((menu) => (
<div className="card" key={menu.id}>
<div className="card-body p-5 pt-2">
<MenuItemComponent
menu={menu}
selectMenus={selectMenus}
handleCheckboxChange={handleCheckboxChange}
/>
</div>
</div>
))}
</div>
<hr />
<div className="flex justify-end">
<Button className="btn btn-primary" type="submit">
Save Changes
</Button>
</div>
</div>
</form>
</div>
</DialogBody>
</DialogContent>
</Dialog>
);
};
export { EditDialog };

View File

@ -0,0 +1,43 @@
import { DefaultTooltip, KeenIcon, useDataGrid } from '@/components';
import { useManagePositionContext } from '../hooks';
import { Button } from '@/components/ui/button';
const ListToolBar = () => {
const { table, reload } = useDataGrid();
const { handleAddDialog } = useManagePositionContext();
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">
<label className="input input-sm w-1/6">
<KeenIcon icon="magnifier" />
<input
type="text"
placeholder="Search roles"
value={(table.getColumn('name')?.getFilterValue() as string) ?? ''}
onChange={(event) => table.getColumn('name')?.setFilterValue(event.target.value)}
/>
</label>
<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,204 @@
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: selectedPosition | null) => void;
showAddDialog: boolean;
handleAddDialog: (show: boolean) => void;
showDeleteDialog: boolean;
handleDeleteDialog: (show: boolean, selected_user: selectedPosition | null) => void;
selectedPosition: selectedPosition | null;
menus: any[];
}
interface selectedPosition {
id: string;
name: string;
roles: string[];
status: string;
}
const initialProps: ContextProps = {
showEditDialog: false,
handleEditDialog: () => {},
showAddDialog: false,
handleAddDialog: () => {},
showDeleteDialog: false,
handleDeleteDialog: () => {},
selectedPosition: null,
menus: []
};
const ManagePositionContext = createContext<ContextProps>(initialProps);
const API_URL = apiConfig.service_dashboard;
const API_URL_MD = apiConfig.service_master_data;
const ManagePositionContextProvider = ({ children }: { children: React.ReactNode }) => {
/* state */
const [showEditDialog, setShowEditDialog] = useState(false);
const [showAddDialog, setShowAddDialog] = useState(false);
const [showDeleteDialog, setShowDeleteDialog] = useState(false);
const [selectedPosition, setSelectedPosition] = useState<selectedPosition | null>(null);
const [menus, setMenus] = useState<any[]>([]);
const { GetData } = useCallApi();
/* action */
const handleEditDialog = useCallback((show: boolean, selected_user: selectedPosition | null) => {
setSelectedPosition(show ? selected_user : null);
setShowEditDialog(show);
}, []);
const handleAddDialog = useCallback((show: boolean) => {
setShowAddDialog(show);
}, []);
const handleDeleteDialog = useCallback(
(show: boolean, selected_user: selectedPosition | null) => {
setSelectedPosition(show ? selected_user : null);
setShowDeleteDialog(show);
},
[]
);
/* Data Grid Options */
const columns = useMemo<ColumnDef<any>[]>(
() => [
{
accessorFn: (row) => row.name,
id: 'name',
header: ({ column }) => <DataGridColumnHeader title="Name" column={column} />,
enableSorting: true,
enableHiding: false
},
{
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)}
>
<KeenIcon icon="notepad-edit" />
</button>
<button
className="btn btn-sm btn-icon btn-clear btn-light"
onClick={() => handleDeleteDialog(true, row)}
>
<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: 'name', desc: false }] : sorting;
filter = filter.length == 0 ? {} : { any: filter[0].value.toLowerCase() };
const response = await GetData(`${API_URL}/user_role/list`, {
limit: limit,
page: page + 1,
with_deleted: false,
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 fetchMenus = useCallback(async () => {
const params = {
limit: 100,
page: 1,
with_deleted: false,
order_field: 'order_number',
order_direction: 'ASC',
filter: JSON.stringify({})
};
const response = await GetData(`${API_URL}/menus/list`, params);
if (response?.status) {
setMenus(() => [...response.data.list]);
} else {
setMenus(() => []);
}
}, []);
useEffect(() => {
fetchMenus();
}, [fetchMenus]);
return (
<ManagePositionContext.Provider
value={{
showEditDialog,
handleEditDialog,
selectedPosition,
showAddDialog,
handleAddDialog,
menus,
showDeleteDialog,
handleDeleteDialog
}}
>
<Toaster expand visibleToasts={9} duration={3000} />
<DataGridProvider
columns={columns}
pagination={{ size: 10 }}
toolbar={<ListToolBar />}
layout={{ card: true }}
sorting={[{ id: 'name', desc: false }]}
serverSide={true}
onFetchData={({ pageIndex, pageSize, sorting, columnFilters }) =>
doGetListData(pageIndex, pageSize, sorting, columnFilters)
}
>
{children}
</DataGridProvider>
</ManagePositionContext.Provider>
);
};
export { ManagePositionContextProvider, ManagePositionContext };
export type { selectedPosition };

View File

@ -0,0 +1,2 @@
export * from './ManagePositionContext';
export * from './useManagePositionContext';

View File

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

View File

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

View File

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

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,244 @@
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: undefined,
id_role_old: undefined
});
if (response?.status) {
if (formField.id_role_old != '') {
const responseUserDeleteRole = await PutData(
`${API_URL}/user/delete_role/${selectedUser}/${formField.id_role_old}`,
{}
);
}
const responseUserAddRole = await PutData(
`${API_URL}/user/add_role/${selectedUser}/${formField.id_role}`,
{}
);
setAlert((prev) => ({ ...prev, show: false, message: '' }));
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.roles;
setFormField((prev) => ({
...prev,
name: response.data.name,
username: response.data.username,
email: response.data.email,
id_role: id_role.length != 0 ? id_role[0].id : '',
id_role_old: id_role.length != 0 ? id_role[0].id : '',
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,249 @@
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 ConfigUserContext = createContext<ContextProps>(initialProps);
const API_URL = apiConfig.service_dashboard;
const ConfigUserContextProvider = ({ 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 { roles } = data.row.original;
let html = <p className="text-danger italic">Unassigned</p>;
for (let _role of roles) {
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 (
<ConfigUserContext.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>
</ConfigUserContext.Provider>
);
};
export { ConfigUserContextProvider, ConfigUserContext };
export type { SelectedUser };

View File

@ -0,0 +1,2 @@
export * from './ConfigUserContext';
export * from './useUserContext';

View File

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

View File

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