From 279b642a7a34ff90431a7ba3bbf5069fda8d010a Mon Sep 17 00:00:00 2001 From: Ichsan Kurniawan <43689091+ichsankurnia@users.noreply.github.com> Date: Mon, 9 Nov 2026 17:32:31 +0700 Subject: [PATCH] Apply RBAC permissions across admin and tasks Enforce page access and action-level permissions across admin and task views, including exports and record actions. Move user creation to a client component behind server-side permission checks, standardize data fetching, and remove the deprecated user-role route. --- .../(main)/ClientDetailComponent.tsx | 3 +- .../[client_id]/(main)/ClientProfileCard.tsx | 17 +- .../client-detail/[client_id]/(main)/page.tsx | 5 +- .../AssignmentDetailComponent.tsx | 160 ++++---- .../DevelopmentActivityLog.tsx | 13 +- .../[client_id]/[assignment_id]/page.tsx | 5 +- .../[project_id]/WorkOrderCard.tsx | 122 +++--- .../project-detail/[project_id]/page.tsx | 3 + .../task/component/client/Client.tsx | 29 +- .../task/component/client/ClientGrid.tsx | 46 +-- .../task/component/client/ClientList.tsx | 47 +-- .../project-assignment/AssignmentGrid.tsx | 26 +- .../project-assignment/AssignmentList.tsx | 26 +- app/(dashboard)/task/page.tsx | 4 +- .../administration/area/component/index.tsx | 4 +- .../company/component/index.tsx | 2 +- .../division/component/index.tsx | 4 +- .../administration/user/component/index.tsx | 10 +- .../user/create/UserCreateClient.tsx | 338 +++++++++++++++++ app/admin/administration/user/create/page.tsx | 348 +----------------- app/admin/audit-trail/component/index.tsx | 29 +- app/admin/audit-trail/page.tsx | 47 +-- app/admin/day-off/component/index.tsx | 29 +- app/admin/day-off/page.tsx | 6 +- .../device/device-type/component/index.tsx | 31 +- app/admin/device/device-type/page.tsx | 44 +-- app/admin/device/device/component/index.tsx | 29 +- app/admin/device/device/page.tsx | 46 +-- .../global-parameter/component/index.tsx | 31 +- app/admin/global-parameter/page.tsx | 44 +-- .../employee-type/component/index.tsx | 2 - app/admin/information/employee-type/page.tsx | 37 +- .../master-status/component/index.tsx | 2 - app/admin/information/master-status/page.tsx | 37 +- .../information/position/component/index.tsx | 2 - app/admin/information/position/page.tsx | 39 +- .../user-role/component/ConfirmAsync.tsx | 75 ---- .../information/user-role/component/Form.tsx | 1 - .../information/user-role/component/index.tsx | 1 - .../information/user-role/component/type.ts | 4 - .../information/user-role/component/type.tsx | 12 - app/admin/information/user-role/page.tsx | 5 - app/admin/information/working-status/page.tsx | 37 +- app/admin/layout.tsx | 5 + .../manual/approval-autocheckout/page.tsx | 11 +- app/admin/manual/approval/page.tsx | 11 +- app/admin/manual/manual-presence/page.tsx | 2 +- .../client/component/index.tsx | 29 +- app/admin/project-assignment/client/page.tsx | 12 +- .../end-user/component/index.tsx | 27 +- .../project-assignment/end-user/page.tsx | 12 +- .../project-management/component/index.tsx | 27 +- .../project-management/page.tsx | 12 +- .../action-permissions/component/index.tsx | 59 +-- app/admin/rbac/action-permissions/page.tsx | 4 +- app/admin/rbac/menu/component/index.tsx | 59 +-- app/admin/rbac/menu/page.tsx | 4 +- app/admin/rbac/user-role/[id]/page.tsx | 14 +- app/admin/rbac/user-role/component/index.tsx | 49 +-- app/admin/rbac/user-role/create/page.tsx | 4 +- app/admin/rbac/user-role/edit/[id]/page.tsx | 2 + app/admin/rbac/user-role/page.tsx | 4 +- .../report/distribution/component/index.tsx | 11 +- app/admin/report/distribution/page.tsx | 5 +- app/admin/report/history/component/index.tsx | 13 +- app/admin/report/history/page.tsx | 7 +- app/admin/report/leave-permit-sick/page.tsx | 11 +- app/admin/report/monthly-presence/page.tsx | 11 +- lib/get-access-data.tsx | 30 +- 69 files changed, 1070 insertions(+), 1167 deletions(-) create mode 100644 app/admin/administration/user/create/UserCreateClient.tsx delete mode 100644 app/admin/information/user-role/component/ConfirmAsync.tsx delete mode 100644 app/admin/information/user-role/component/Form.tsx delete mode 100644 app/admin/information/user-role/component/index.tsx delete mode 100644 app/admin/information/user-role/component/type.ts delete mode 100644 app/admin/information/user-role/component/type.tsx delete mode 100644 app/admin/information/user-role/page.tsx diff --git a/app/(dashboard)/task/client-detail/[client_id]/(main)/ClientDetailComponent.tsx b/app/(dashboard)/task/client-detail/[client_id]/(main)/ClientDetailComponent.tsx index f81746a..8a8e6ed 100644 --- a/app/(dashboard)/task/client-detail/[client_id]/(main)/ClientDetailComponent.tsx +++ b/app/(dashboard)/task/client-detail/[client_id]/(main)/ClientDetailComponent.tsx @@ -71,9 +71,10 @@ const ConfirmDeleteWithInput = dynamic( interface Props { clientId: string; assignmentLists: IProjectAssignment[]; + actions?: string[] } -export default function ClientDetailComponent({ clientId, assignmentLists }: Props) { +export default function ClientDetailComponent({ clientId, assignmentLists, actions }: Props) { const router = useRouter(); const searchParams = useSearchParams(); const urlLayout = searchParams?.get('layout') as 'grid' | 'list' | null; diff --git a/app/(dashboard)/task/client-detail/[client_id]/(main)/ClientProfileCard.tsx b/app/(dashboard)/task/client-detail/[client_id]/(main)/ClientProfileCard.tsx index 1a88836..e8baf0f 100644 --- a/app/(dashboard)/task/client-detail/[client_id]/(main)/ClientProfileCard.tsx +++ b/app/(dashboard)/task/client-detail/[client_id]/(main)/ClientProfileCard.tsx @@ -9,9 +9,10 @@ import { IClient, CLIENT_FALLBACK_IMAGE } from '../../../types'; interface Props { client: IClient; clientId: string; + actions?: string[] } -export default function ClientProfileCard({ client, clientId }: Props) { +export default function ClientProfileCard({ client, clientId, actions }: Props) { const isActive = client.status_name?.toLowerCase() === 'active'; return ( @@ -60,12 +61,14 @@ export default function ClientProfileCard({ client, clientId }: Props) { {/* Right: + New assignment Button */}
- - - + {actions?.includes("CREATE") && + + + + }
diff --git a/app/(dashboard)/task/client-detail/[client_id]/(main)/page.tsx b/app/(dashboard)/task/client-detail/[client_id]/(main)/page.tsx index 16787e4..bf95aa5 100644 --- a/app/(dashboard)/task/client-detail/[client_id]/(main)/page.tsx +++ b/app/(dashboard)/task/client-detail/[client_id]/(main)/page.tsx @@ -9,6 +9,7 @@ import { getQueryStringFilteredAssignments } from '@/lib/fetchData'; import { getFilteredAssignments } from '../../../data'; import { getClientById, getAssignmentsByClient } from '../../../utils/queries'; import Reveal from '@/components/ui/reveal'; +import { getNonAdminAccessPagePermission } from '@/lib/get-access-data'; type Props = { params: Promise<{ client_id: string }> @@ -54,6 +55,8 @@ export async function generateMetadata({ params }: Props): Promise { } export default async function ClientDetailPage({ params, searchParams }: Props) { + const actions = await getNonAdminAccessPagePermission('/task', 'VIEW_CLIENT') + const { client_id } = await params; const searchParams_ = await searchParams; @@ -96,7 +99,7 @@ export default async function ClientDetailPage({ params, searchParams }: Props) - + (); const [showAllTeam, setShowAllTeam] = useState(false); @@ -201,7 +202,7 @@ export default function AssignmentDetail({ client, initialAssignment: assignment {/* Action Buttons: Keep Promote to Project (if IM), Update Technical Status, Update Admin Status */} {/* Action Buttons: Administration & Technical status (+ Promote if IM) */}
- {!isWorkOrder && ( + {!isWorkOrder && actions?.includes('PROMOTE_ASSIGNMENT') && ( )} - - + {actions?.includes('UPDATE_ADMINISTRATION_STATUS') && + + } + {actions?.includes("UPDATE_TECHNICAL_STATUS") && + + }
@@ -254,17 +259,19 @@ export default function AssignmentDetail({ client, initialAssignment: assignment {assignment.progress ?? 0}% - + {actions?.includes("UPDATE_ASSIGNMENT_PROGRESS") && + + }
@@ -375,6 +382,7 @@ export default function AssignmentDetail({ client, initialAssignment: assignment router.refresh()} @@ -542,14 +550,12 @@ export default function AssignmentDetail({ client, initialAssignment: assignment Add people from the team directory to start tracking who works on this assignment.

- + {actions?.includes("MANAGE_TEAM") && + + } ) : (
@@ -600,48 +606,56 @@ export default function AssignmentDetail({ client, initialAssignment: assignment )} -
+ {/* Modals */} - {action === 'UPDATE_ADMIN_STATUS' ? ( - { - router.refresh(); - handleClose(); - }} - /> - ) : null} + { + action === 'UPDATE_ADMIN_STATUS' ? ( + { + router.refresh(); + handleClose(); + }} + /> + ) : null + } - {action === 'UPDATE_STATUS' ? ( - - ) : null} + { + action === 'UPDATE_STATUS' ? ( + + ) : null + } - {action === 'MANAGE_EMPLOYEE' ? ( - - ) : null} + { + action === 'MANAGE_EMPLOYEE' ? ( + + ) : null + } - {action === 'UPDATE_REAL_PROGRESS' ? ( - { - router.refresh(); - handleClose(); - }} - /> - ) : null} + { + action === 'UPDATE_REAL_PROGRESS' ? ( + { + router.refresh(); + handleClose(); + }} + /> + ) : null + } ); } diff --git a/app/(dashboard)/task/client-detail/[client_id]/[assignment_id]/DevelopmentActivityLog.tsx b/app/(dashboard)/task/client-detail/[client_id]/[assignment_id]/DevelopmentActivityLog.tsx index 84597cd..0e49800 100644 --- a/app/(dashboard)/task/client-detail/[client_id]/[assignment_id]/DevelopmentActivityLog.tsx +++ b/app/(dashboard)/task/client-detail/[client_id]/[assignment_id]/DevelopmentActivityLog.tsx @@ -20,6 +20,7 @@ const AddActivityLogModal = dynamic( interface DevelopmentActivityLogProps { history?: IProjectAssignmentHistory[]; + actions?: string[] assignmentId?: number; assignmentName?: string; assignmentCode?: string; @@ -28,6 +29,7 @@ interface DevelopmentActivityLogProps { export function DevelopmentActivityLog({ history = [], + actions, assignmentId, assignmentName, assignmentCode, @@ -87,11 +89,8 @@ export function DevelopmentActivityLog({ )} - {assignmentId && ( - - + {actions?.includes("UPDATE_ADMINISTRATION_STATUS") && + + } + {actions?.includes("UPDATE_TECHNICAL_STATUS") && + + } } /> @@ -303,18 +304,19 @@ export default function WorkOrderCard({ workOrder, index, defaultOpen = false }: title="Assigned Team" badgeText={`${team.length} people`} action={ - + actions?.includes("MANAGE_TEAM") ? + : null } /> @@ -332,30 +334,36 @@ export default function WorkOrderCard({ workOrder, index, defaultOpen = false }: ) : null} - + {/* Modals */} - {action === 'UPDATE_ADMIN_STATUS' && selectedData ? ( - - ) : null} + { + action === 'UPDATE_ADMIN_STATUS' && selectedData ? ( + + ) : null + } - {action === 'UPDATE_STATUS' && selectedData ? ( - - ) : null} + { + action === 'UPDATE_STATUS' && selectedData ? ( + + ) : null + } - {action === 'MANAGE_EMPLOYEE' && selectedData ? ( - - ) : null} - + { + action === 'MANAGE_EMPLOYEE' && selectedData ? ( + + ) : null + } + ); } diff --git a/app/(dashboard)/task/client-detail/[client_id]/project-detail/[project_id]/page.tsx b/app/(dashboard)/task/client-detail/[client_id]/project-detail/[project_id]/page.tsx index d1bca23..b41e150 100644 --- a/app/(dashboard)/task/client-detail/[client_id]/project-detail/[project_id]/page.tsx +++ b/app/(dashboard)/task/client-detail/[client_id]/project-detail/[project_id]/page.tsx @@ -10,6 +10,7 @@ import FilterComponent from '@/app/(dashboard)/task/component/FilterComponent'; import { COMPLETE_STATUS_LIST, getFilteredAssignments, ONPROGRESS_STATUS_LIST } from '@/app/(dashboard)/task/data'; import { getClientById, getProjectAssignment } from '../../../../utils/queries'; import Reveal from '@/components/ui/reveal'; +import { getNonAdminAccessPagePermission } from '@/lib/get-access-data'; type Props = { params: Promise<{ client_id: string; project_id: string }> @@ -17,6 +18,8 @@ type Props = { }; export async function generateMetadata({ params, searchParams }: Props): Promise { + const actions = await getNonAdminAccessPagePermission('/task', 'VIEW_PROJECT') + const { client_id, project_id } = await params; const searchParams_ = await searchParams; const queryString = await getQueryStringFilteredAssignments(searchParams_ || {}); diff --git a/app/(dashboard)/task/component/client/Client.tsx b/app/(dashboard)/task/component/client/Client.tsx index c9d55dc..f4bafc9 100644 --- a/app/(dashboard)/task/component/client/Client.tsx +++ b/app/(dashboard)/task/component/client/Client.tsx @@ -39,9 +39,10 @@ const ConfirmDeleteWithInput = dynamic( interface ClientProps { clients: IClient[]; initialLayout?: 'grid' | 'list'; + actions: string[]; } -export default function Client({ clients, initialLayout = 'grid' }: ClientProps) { +export default function Client({ clients, actions, initialLayout = 'grid' }: ClientProps) { const router = useRouter(); const searchParams = useSearchParams(); const layout = searchParams?.get('layout') === 'list' ? 'list' : initialLayout; @@ -74,26 +75,28 @@ export default function Client({ clients, initialLayout = 'grid' }: ClientProps)

Try to change the filter or create one to get started.

- + {actions?.includes('CREATE') && + + } ) : null} {clients.length > 0 && layout === 'list' ? - + : null} {clients.length > 0 && layout === 'grid' ? - + : null} {action === 'EDIT' && ( diff --git a/app/(dashboard)/task/component/client/ClientGrid.tsx b/app/(dashboard)/task/component/client/ClientGrid.tsx index 54279a8..99caae4 100644 --- a/app/(dashboard)/task/component/client/ClientGrid.tsx +++ b/app/(dashboard)/task/component/client/ClientGrid.tsx @@ -36,12 +36,13 @@ const ClientMilestoneTimeline = dynamic( ); interface ClientGridProps { + actions: string[] clients: IClient[]; onEdit: (client: IClient) => void; onDelete: (client: IClient) => void; } -export default function ClientGrid({ clients, onEdit, onDelete }: ClientGridProps) { +export default function ClientGrid({ clients, actions, onEdit, onDelete }: ClientGridProps) { return (
{clients.map((client, i) => { @@ -245,33 +246,24 @@ export default function ClientGrid({ clients, onEdit, onDelete }: ClientGridProp
- - + + } + {actions?.includes('UPDATE_CLIENT') && + - - - - + } + {actions?.includes('DELETE_CLIENT') && + + }
diff --git a/app/(dashboard)/task/component/client/ClientList.tsx b/app/(dashboard)/task/component/client/ClientList.tsx index 6b8ea54..cbed40f 100644 --- a/app/(dashboard)/task/component/client/ClientList.tsx +++ b/app/(dashboard)/task/component/client/ClientList.tsx @@ -33,12 +33,13 @@ const ClientMilestoneTimeline = dynamic(() => import('./ClientMilestoneTimeline' }); interface ClientListProps { + actions: string[] clients: IClient[]; onEdit: (client: IClient) => void; onDelete: (client: IClient) => void; } -export default function ClientList({ clients, onEdit, onDelete }: ClientListProps) { +export default function ClientList({ clients, onEdit, onDelete, actions }: ClientListProps) { return (
{clients.map((client, index) => { @@ -245,34 +246,24 @@ export default function ClientList({ clients, onEdit, onDelete }: ClientListProp {/* Action Buttons: View Detail + More Actions Dropdown */}
- - + + } + {actions?.includes('UPDATE_CLIENT') && + - - - - - + } + {actions?.includes('DELETE_CLIENT') && + + }
diff --git a/app/(dashboard)/task/component/project-assignment/AssignmentGrid.tsx b/app/(dashboard)/task/component/project-assignment/AssignmentGrid.tsx index 0920200..347361a 100644 --- a/app/(dashboard)/task/component/project-assignment/AssignmentGrid.tsx +++ b/app/(dashboard)/task/component/project-assignment/AssignmentGrid.tsx @@ -76,6 +76,7 @@ function CompactPhaseStepper({ phaseIndex, progressColor }: { phaseIndex: number interface AssignmentGridProps { assignments: IProjectAssignment[]; clientId?: string; + actions?: string[] onManageTeam?: (assignment: IProjectAssignment) => void; onUpdateStatus?: (assignment: IProjectAssignment) => void; onUpdateAdministrationStatus?: (assignment: IProjectAssignment) => void; @@ -85,6 +86,7 @@ interface AssignmentGridProps { export default function AssignmentGrid({ assignments, clientId, + actions, onManageTeam, onUpdateStatus, onUpdateAdministrationStatus, @@ -187,7 +189,7 @@ export default function AssignmentGrid({ - {promoteAssignmentUrl && ( + {actions?.includes("PROMOTE_ASSIGNMENT") && promoteAssignmentUrl && ( @@ -195,40 +197,42 @@ export default function AssignmentGrid({ )} - - View Assignment Details - - {projectDetailUrl && ( + {actions?.includes("VIEW_ASSIGNMENT") && + + View Assignment Details + + } + {actions?.includes('VIEW_PROJECT') && projectDetailUrl && ( View Project Details )} - {!clientId && assignment.client?.id && ( + {actions?.includes('VIEW_CLIENT') && !clientId && assignment.client?.id && ( View Client )} - {editAssignmentUrl && ( + {actions?.includes("UPDATE_ASSIGNMEN") && editAssignmentUrl && ( Edit Assignment )} - {onManageTeam && ( + {actions?.includes("MANAGE_TEAM") && onManageTeam && ( onManageTeam(assignment)}> Manage Team )} - {onUpdateAdministrationStatus && ( + {actions?.includes("UPDATE_ADMINISTRATION_STATUS") && onUpdateAdministrationStatus && ( onUpdateAdministrationStatus(assignment)}> Update Administration Status )} - {onUpdateStatus && ( + {actions?.includes("UPDATE_TECHNICAL_STATUS") && onUpdateStatus && ( onUpdateStatus(assignment)}> Update Technical Status )} - {onDelete && ( + {actions?.includes("DELETE_ASSIGNMENT") && onDelete && ( onDelete(assignment)} className="text-destructive focus:text-destructive" diff --git a/app/(dashboard)/task/component/project-assignment/AssignmentList.tsx b/app/(dashboard)/task/component/project-assignment/AssignmentList.tsx index c3de6b3..81a634c 100644 --- a/app/(dashboard)/task/component/project-assignment/AssignmentList.tsx +++ b/app/(dashboard)/task/component/project-assignment/AssignmentList.tsx @@ -78,6 +78,7 @@ function PhaseStepper({ phaseIndex, progressColor }: { phaseIndex: number; progr interface AssignmentListProps { assignments: IProjectAssignment[]; clientId?: string; + actions?: string[] onManageTeam?: (assignment: IProjectAssignment) => void; onUpdateStatus?: (assignment: IProjectAssignment) => void; onUpdateAdministrationStatus?: (assignment: IProjectAssignment) => void; @@ -87,6 +88,7 @@ interface AssignmentListProps { export default function AssignmentList({ assignments, clientId, + actions, onManageTeam, onUpdateStatus, onUpdateAdministrationStatus, @@ -395,7 +397,7 @@ export default function AssignmentList({ - {promoteAssignmentUrl && ( + {actions?.includes('PROMOTE_ASSIGNMENT') && promoteAssignmentUrl && ( @@ -403,40 +405,42 @@ export default function AssignmentList({ )} - - View Assignment Details - - {projectDetailUrl && ( + {actions?.includes('VIEW_ASSIGNMENT') && + + View Assignment Details + + } + {actions?.includes('VIEW_PROJECT') && projectDetailUrl && ( View Project Details )} - {!clientId && assignment.client?.id && ( + {!clientId && assignment.client?.id && actions?.includes('VIEW_CLIENT') && ( View Client )} - {editAssignmentUrl && ( + {actions?.includes('UPDATE_ASSIGNMENT') && editAssignmentUrl && ( Edit Assignment )} - {onManageTeam && ( + {actions?.includes('MANAGE_TEAM') && onManageTeam && ( onManageTeam(assignment)}> Manage Team )} - {onUpdateAdministrationStatus && ( + {actions?.includes('UPDATE_ADMINISTRATION_STATUS') && onUpdateAdministrationStatus && ( onUpdateAdministrationStatus(assignment)}> Update Administration Status )} - {onUpdateStatus && ( + {actions?.includes('UPDATE_TECHNICAL_STATUS') && onUpdateStatus && ( onUpdateStatus(assignment)}> Update Technical Status )} - {onDelete && ( + {actions?.includes('DELETE_ASSIGNMENT') && onDelete && ( onDelete(assignment)} className="text-destructive focus:text-destructive" diff --git a/app/(dashboard)/task/page.tsx b/app/(dashboard)/task/page.tsx index 7b2d56b..3350f70 100644 --- a/app/(dashboard)/task/page.tsx +++ b/app/(dashboard)/task/page.tsx @@ -3,6 +3,7 @@ import type { Metadata } from 'next'; import { getFilteredClients } from './data'; import { getClients } from './utils/queries'; import { Loader2 } from 'lucide-react'; +import { getNonAdminAccessPagePermission } from '@/lib/get-access-data'; const HomeTask = lazy(() => import('./component/HomeTask')); const Client = lazy(() => import('./component/client/Client')); @@ -40,6 +41,7 @@ export async function generateMetadata(): Promise { } export default async function ClientsPage({ searchParams }: Props) { + const actions = await getNonAdminAccessPagePermission('/task', 'VIEW') const searchParams_ = await searchParams; // const view = searchParams_.view === 'assignments' ? 'assignments' : 'clients'; @@ -66,7 +68,7 @@ export default async function ClientsPage({ searchParams }: Props) { }> - + {/* }> {view === 'clients' ? diff --git a/app/admin/administration/area/component/index.tsx b/app/admin/administration/area/component/index.tsx index e35a34d..5c798c8 100644 --- a/app/admin/administration/area/component/index.tsx +++ b/app/admin/administration/area/component/index.tsx @@ -115,7 +115,7 @@ const ComponentAreaPage: FC = ({ data, actions }) => { { title: 'Action', key: 'action', - render: (_, record) => actions.includes('UPDATE') || actions.includes('DELETE') && ( + render: (_, record) => (actions.includes('UPDATE') || actions.includes('DELETE')) && ( @@ -166,7 +166,7 @@ const ComponentAreaPage: FC = ({ data, actions }) => {
- {actions.includes('CREATE') && + {actions?.includes('CREATE') && + +
+ {isUpdate ? 'Update user' : 'Create new user'} + {isUpdate ? 'Update user id ' + id : 'Add a new team to join to your department'} +
+ + + }> +
setShowConfirm(true)} scrollToFirstError layout="vertical" size='small'> +
+ {/* */} + + + + + + + + + + {!isUpdate && + + + + } + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Male + Female + + + + + + + + + + + Yes + No + + + + + + + + + + + + + + + + + + + + +
+
+ +
+
+
+
+ + {isUpdate && isFetching && + + } + + {showConfirm && + + + + Are you absolutely sure? + + This data will be stored on our server, you can change it whenever you want later. + + + + setShowConfirm(false)}>Cancel + + {isLoading && ( + + )} + Continue + + + + + } + + ); +} + +export default UserCreate; \ No newline at end of file diff --git a/app/admin/administration/user/create/page.tsx b/app/admin/administration/user/create/page.tsx index 0d88209..90c8450 100644 --- a/app/admin/administration/user/create/page.tsx +++ b/app/admin/administration/user/create/page.tsx @@ -1,338 +1,28 @@ -'use client' - -import { FC, Suspense, useEffect, useState } from 'react'; -import Link from 'next/link'; -import { useRouter, useSearchParams } from 'next/navigation'; -import { DatePicker, Form, Input, Radio, Select } from 'antd'; -import dayjs from 'dayjs'; -import { Icons } from '@/components/Icons'; -import { Button } from '@/components/ui/button'; -import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; -import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from '@/components/ui/alert-dialog'; -import useFetch from '@/hooks/useFetch'; -import useAxiosAuth from '@/lib/axios/useAxiosAuth'; -import { titleCase } from '@/lib/helper'; -import PageLoading from '@/components/loader/PageLoading'; +import { type Metadata } from 'next'; +import { Suspense } from 'react'; import LazyLoading from '@/components/loader/LazyLoading'; -import { type IUser } from '../component/type'; -import { type IRole } from '@/app/admin/information/user-role/component/type'; -import { type ICompany } from '../../company/component/type'; -import { type IArea } from '../../area/component/type'; -import { type IDivision } from '../../division/component/type'; -import { type IPosition } from '@/app/admin/information/position/component/type'; -import { type IEmployeeType } from '@/app/admin/information/employee-type/component/type'; -import { toast } from 'sonner'; +import { getAccessPagePermission } from '@/lib/get-access-data'; +import UserCreateClient from './UserCreateClient'; -type Props = {}; +export const dynamic = 'force-dynamic'; -const UserCreate: FC = ({ }) => { - const [isLoading, setIsLoading] = useState(false) - const [isFetching, setIsFetching] = useState(false) - const [showConfirm, setShowConfirm] = useState(false) +export const metadata: Metadata = { + title: "Admin | User Form", + description: "Create or update employee user information", +}; - const [form] = Form.useForm(); - const router = useRouter() - const searchParams = useSearchParams(); - const axios = useAxiosAuth() +type Props = { + searchParams: Promise<{ [key: string]: string | string[] | undefined }>; +}; - const isUpdate = searchParams!.get('is_update') as string || '' - const id = searchParams!.get('id') as string || '' - - const { data: companyList, isLoading: companyLoading } = useFetch('/company') - const { data: areaList, isLoading: areaLoading } = useFetch('/area') - const { data: divisionList, isLoading: divisionLoading } = useFetch('/division') - const { data: roleList, isLoading: roleLoading } = useFetch('/role') - const { data: positionList, isLoading: positionLoading } = useFetch('/position') - const { data: employeeTypeList, isLoading: employeeTypeLoading } = useFetch('/employee-type') - - useEffect(() => { - async function fetchData() { - setIsFetching(true) - try { - const res = await axios.get(`/user/${id}`) - const data: IUser = res.data.data - - form.setFieldsValue(data) - - if (data.company) form.setFieldValue('company_id', data.company.id) - if (data.area) form.setFieldValue('area_id', data.area.id) - if (data.division) form.setFieldValue('division_id', data.division.id) - if (data.role) form.setFieldValue('role_id', data.role.id) - if (data.employee_type) form.setFieldValue('employee_type_id', data.employee_type.id) - if (data.position) form.setFieldValue('position_id', data.position.id) - - if (data.birthday) form.setFieldValue('birthday', dayjs(data.birthday)) - if (data.contract_expiration_date) form.setFieldValue('contract_expiration_date', dayjs(data.contract_expiration_date)) - if (data.hire_date) form.setFieldValue('hire_date', dayjs(data.hire_date)) - if (data.resign_date) form.setFieldValue('resign_date', dayjs(data.resign_date)) - - setIsFetching(false) - } catch (error: any) { - handleError(`Failed fetch data, (${error.response.data.code || error.response.status || '-'}) ${error.response.data.message || error.response.statusText || error.message}`) - } - } - - if (isUpdate) { - fetchData() - } else { - form.resetFields() - } - }, [isUpdate, form, id]) - - - const handleSubmit = () => { - const payload = form.getFieldsValue() - if (payload.fullname) payload.fullname = titleCase(payload.fullname) - - !isUpdate ? handleCreate(payload) : handleUpdate(payload) - } - - const handleCreate = async (payload: IUser) => { - try { - setIsLoading(true) - await axios.post('/user', payload) - - handleSuccess('Data successfully created.') - } catch (error: any) { - handleError(`Data failed to create, (${error.response.data.code || error.response.status || '-'}) ${error.response.data.message || error.response.statusText || error.message}`) - } - } - - const handleUpdate = async (payload: IUser) => { - try { - setIsLoading(true) - await axios.put('/user/' + id, payload) - - handleSuccess('Data successfully updated.') - } catch (error: any) { - handleError(`Data failed to update, (${error.response.data.code || error.response.status || '-'}) ${error.response.data.message || error.response.statusText || error.message}`) - } - } - - const handleSuccess = (message: string) => { - toast.success(message) - router.replace('/admin/administration/user') - router.refresh() - form.resetFields() - } - - const handleError = (message: string) => { - toast.error(message) - setIsLoading(false) - } +export default async function UserCreatePage({ searchParams }: Props) { + const params = await searchParams; + const isUpdate = params?.is_update === 'true'; + await getAccessPagePermission('/administration/user', isUpdate ? 'UPDATE' : 'CREATE'); return ( - <> - - - - - -
- {isUpdate ? 'Update user' : 'Create new user'} - {isUpdate ? 'Update user id ' + id : 'Add a new team to join to your department'} -
-
- - }> -
setShowConfirm(true)} scrollToFirstError layout="vertical" size='small'> -
- {/* */} - - - - - - - - - - {!isUpdate && - - - - } - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Male - Female - - - - - - - - - - - Yes - No - - - - - - - - - - - - - - - - - - - - -
-
- -
-
-
-
-
- {isUpdate && isFetching && - - } - - {showConfirm && - - - - Are you absolutely sure? - - This data will be stored on our server, you can change it whenever you want later. - - - - setShowConfirm(false)}>Cancel - - {isLoading && ( - - )} - Continue - - - - - } - + }> + + ); } - -export default UserCreate; \ No newline at end of file diff --git a/app/admin/audit-trail/component/index.tsx b/app/admin/audit-trail/component/index.tsx index 9809fa4..7a59ccb 100644 --- a/app/admin/audit-trail/component/index.tsx +++ b/app/admin/audit-trail/component/index.tsx @@ -4,7 +4,7 @@ import { ChangeEvent, FC, useEffect, useState } from 'react'; import { MoreHorizontalIcon } from 'lucide-react'; import { Table } from 'antd'; import { TableProps, type ColumnsType } from 'antd/es/table'; -import { MixerHorizontalIcon, PlusCircledIcon } from '@radix-ui/react-icons'; +import { PlusCircledIcon } from '@radix-ui/react-icons'; import useAxiosAuth from '@/lib/axios/useAxiosAuth'; import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu'; import { Button } from '@/components/ui/button'; @@ -17,9 +17,10 @@ import { type ILogName } from './type'; type Props = { data: ILogName[] + actions?: string[] }; -const ComponentPage: FC = ({ data }) => { +const ComponentPage: FC = ({ data, actions }) => { const [filterData, setFilterData] = useState([]) const [selectedData, setSelectedData] = useState(undefined) const [showFormDialog, setShowFormDialog] = useState(false) @@ -107,7 +108,7 @@ const ComponentPage: FC = ({ data }) => { { title: 'Action', key: 'action', - render: (_, record) => ( + render: (_, record) => (actions?.includes('UPDATE') || actions?.includes('EDIT') || actions?.includes('DELETE')) && ( @@ -117,10 +118,14 @@ const ComponentPage: FC = ({ data }) => { - { setShowFormDialog(true); setSelectedData(record) }} >Edit - - Delete - + {(actions.includes('UPDATE') || actions.includes('EDIT')) && ( + { setShowFormDialog(true); setSelectedData(record) }} >Edit + )} + {(actions.includes('DELETE')) && ( + + Delete + + )} = ({ data }) => {
- + {(actions?.includes('CREATE')) && ( + + )} import('./component')); export const metadata: Metadata = { - title: "Admin | Log Name", + title: "Admin | Audit Trail", } -async function getData() { - const { BASE_URL_API } = process.env - const session = await getServerSession(authOptions) - - const res = await fetch(BASE_URL_API + '/log-name', { - headers: { - "Content-Type": "application/json", - Authorization: `Bearer ${session?.user.access_token}`, - }, - cache: 'no-cache', - next: { - tags: ['log-name'] - } - }) - - const data: ResponseData = await res.json() - - // Recommendation: handle errors - if (!res.ok) { - // This will activate the closest `error.js` Error Boundary - throw new Error(`Failed to fetch data, ${data.code || res.status} ${data.message || res.statusText}`) - } - - return data.data -} - -export default async function DeviceTypePage() { - const data = await getData() +export default async function AuditTrailPage() { + const actions = await getAccessPagePermission('/audit-trail') + const data = await fetchData('/log-name', 'no-cache', { tags: ['log-name'] }) return ( <> @@ -53,14 +27,17 @@ export default async function DeviceTypePage() { Log NameHere's a list of log audit name! -
- -
+ {actions.includes('EXPORT') && +
+ +
+ } }> diff --git a/app/admin/day-off/component/index.tsx b/app/admin/day-off/component/index.tsx index 5a40a4a..2307bb6 100644 --- a/app/admin/day-off/component/index.tsx +++ b/app/admin/day-off/component/index.tsx @@ -18,9 +18,10 @@ import { type IDayOff } from './type'; type Props = { data: IDayOff[] + actions?: string[] }; -const ComponentPage: FC = ({ data }) => { +const ComponentPage: FC = ({ data, actions }) => { const [filterData, setFilterData] = useState([]) const [selectedData, setSelectedData] = useState(undefined) const [showFormDialog, setShowFormDialog] = useState(false) @@ -33,7 +34,7 @@ const ComponentPage: FC = ({ data }) => { } }, [data]) - const handleDelete = (id: string | number) => { + const handleDelete = async (id: string | number) => { return axios.delete(`/dayoff/${id}`).then(res => res.data) } @@ -108,7 +109,7 @@ const ComponentPage: FC = ({ data }) => { { title: 'Action', key: 'action', - render: (_, record) => ( + render: (_, record) => (actions?.includes('UPDATE') || actions?.includes('EDIT') || actions?.includes('DELETE')) && ( @@ -118,10 +119,14 @@ const ComponentPage: FC = ({ data }) => { - { setShowFormDialog(true); setSelectedData(record) }} >Edit - - Delete - + {(actions.includes('UPDATE') || actions.includes('EDIT')) && ( + { setShowFormDialog(true); setSelectedData(record) }} >Edit + )} + {(actions.includes('DELETE')) && ( + + Delete + + )} = ({ data }) => {
- + {(actions?.includes('CREATE')) && ( + + )}
import('./component')); @@ -11,7 +12,8 @@ export const metadata: Metadata = { } -export default async function DeviceTypePage() { +export default async function DayOffPage() { + const actions = await getAccessPagePermission('/day-off') const data = await fetchData('/dayoff') return ( @@ -26,7 +28,7 @@ export default async function DeviceTypePage() { }> - + diff --git a/app/admin/device/device-type/component/index.tsx b/app/admin/device/device-type/component/index.tsx index 8b0c4ce..e7077f7 100644 --- a/app/admin/device/device-type/component/index.tsx +++ b/app/admin/device/device-type/component/index.tsx @@ -17,9 +17,10 @@ import { type IDeviceType } from './type'; type Props = { data: IDeviceType[] + actions?: string[] }; -const ComponentPage: FC = ({ data }) => { +const ComponentPage: FC = ({ data, actions }) => { const [filterData, setFilterData] = useState([]) const [selectedData, setSelectedData] = useState(undefined) const [showFormDialog, setShowFormDialog] = useState(false) @@ -32,7 +33,7 @@ const ComponentPage: FC = ({ data }) => { } }, [data]) - const handleDelete = (deviceTypeId: string | number) => { + const handleDelete = async (deviceTypeId: string | number) => { return axios.delete(`/device-type/${deviceTypeId}`).then(res => res.data) } @@ -107,7 +108,7 @@ const ComponentPage: FC = ({ data }) => { { title: 'Action', key: 'action', - render: (_, record) => ( + render: (_, record) => (actions?.includes('UPDATE') || actions?.includes('EDIT') || actions?.includes('DELETE')) && ( @@ -117,10 +118,14 @@ const ComponentPage: FC = ({ data }) => { - { setShowFormDialog(true); setSelectedData(record) }} >Edit - - Delete - + {(actions.includes('UPDATE') || actions.includes('EDIT')) && ( + { setShowFormDialog(true); setSelectedData(record) }} >Edit + )} + {(actions.includes('DELETE')) && ( + + Delete + + )} = ({ data }) => {
- +
- + {(actions?.includes('CREATE')) && ( + + )}
import('./component')); @@ -15,35 +14,9 @@ export const metadata: Metadata = { title: "Admin | Device Type", } -async function getData() { - const { BASE_URL_API } = process.env - const session = await getServerSession(authOptions) - - const res = await fetch(BASE_URL_API + '/device-type', { - headers: { - "Content-Type": "application/json", - Authorization: `Bearer ${session?.user.access_token}`, - }, - cache: 'no-cache', - next: { - tags: ['device-type'] - } - }) - - const data: ResponseData = await res.json() - - // Recommendation: handle errors - if (!res.ok) { - // This will activate the closest `error.js` Error Boundary - throw new Error(`Failed to fetch data, ${data.code || res.status} ${data.message || res.statusText}`) - } - - return data.data -} - - export default async function DeviceTypePage() { - const data = await getData() + const actions = await getAccessPagePermission('/device/device-type') + const data = await fetchData('/device-type', 'no-cache', { tags: ['device-type'] }) return ( <> @@ -54,14 +27,17 @@ export default async function DeviceTypePage() { Device TypeHere's a list of device types that have been registered! -
- -
+ {actions.includes('EXPORT') && +
+ +
+ } }> diff --git a/app/admin/device/device/component/index.tsx b/app/admin/device/device/component/index.tsx index 0e2f085..2eabb66 100644 --- a/app/admin/device/device/component/index.tsx +++ b/app/admin/device/device/component/index.tsx @@ -17,9 +17,10 @@ import { IDevice } from './type'; type Props = { data: IDevice[] + actions?: string[] }; -const ComponentPage: FC = ({ data }) => { +const ComponentPage: FC = ({ data, actions }) => { const [filterData, setFilterData] = useState([]) const [selectedData, setSelectedData] = useState(undefined) const [showFormDialog, setShowFormDialog] = useState(false) @@ -32,7 +33,7 @@ const ComponentPage: FC = ({ data }) => { } }, [data]) - const handleDelete = (deviceId: string | number) => { + const handleDelete = async (deviceId: string | number) => { return axios.delete(`/device/${deviceId}`).then(res => res.data) } @@ -117,7 +118,7 @@ const ComponentPage: FC = ({ data }) => { { title: 'Action', key: 'action', - render: (_, record) => ( + render: (_, record) => (actions?.includes('UPDATE') || actions?.includes('EDIT') || actions?.includes('DELETE')) && ( @@ -127,10 +128,14 @@ const ComponentPage: FC = ({ data }) => { - { setShowFormDialog(true); setSelectedData(record) }} >Edit - - Delete - + {(actions.includes('UPDATE') || actions.includes('EDIT')) && ( + { setShowFormDialog(true); setSelectedData(record) }} >Edit + )} + {(actions.includes('DELETE')) && ( + + Delete + + )} = ({ data }) => { Filter - + {(actions?.includes('CREATE')) && ( + + )}
import('./component')); @@ -15,35 +14,9 @@ export const metadata: Metadata = { title: "Admin | Device", } -async function getData() { - const { BASE_URL_API } = process.env - const session = await getServerSession(authOptions) - - const res = await fetch(BASE_URL_API + '/device', { - headers: { - "Content-Type": "application/json", - Authorization: `Bearer ${session?.user.access_token}`, - }, - cache: 'no-cache', - next: { - tags: ['device'] - } - }) - - const data: ResponseData = await res.json() - - // Recommendation: handle errors - if (!res.ok) { - // This will activate the closest `error.js` Error Boundary - throw new Error(`Failed to fetch data, ${data.code || res.status} ${data.message || res.statusText}`) - } - - return data.data -} - - -export default async function DivisionPage() { - const data = await getData() +export default async function DevicePage() { + const actions = await getAccessPagePermission('/device/device') + const data = await fetchData('/device', 'no-cache', { tags: ['device'] }) return ( <> @@ -54,14 +27,17 @@ export default async function DivisionPage() { DeviceHere's a list of devices that have been registered! -
- -
+ {actions.includes('EXPORT') && +
+ +
+ } }> diff --git a/app/admin/global-parameter/component/index.tsx b/app/admin/global-parameter/component/index.tsx index bd71e7d..ed3c6dc 100644 --- a/app/admin/global-parameter/component/index.tsx +++ b/app/admin/global-parameter/component/index.tsx @@ -17,9 +17,10 @@ import { type IGlobalParameter } from './type'; type Props = { data: IGlobalParameter[] + actions?: string[] }; -const ComponentPage: FC = ({ data }) => { +const ComponentPage: FC = ({ data, actions }) => { const [filterData, setFilterData] = useState([]) const [selectedData, setSelectedData] = useState(undefined) const [showFormDialog, setShowFormDialog] = useState(false) @@ -32,7 +33,7 @@ const ComponentPage: FC = ({ data }) => { } }, [data]) - const handleDelete = (id: string | number) => { + const handleDelete = async (id: string | number) => { return axios.delete(`/global-parameter/${id}`).then(res => res.data) } @@ -117,7 +118,7 @@ const ComponentPage: FC = ({ data }) => { { title: 'Action', key: 'action', - render: (_, record) => ( + render: (_, record) => (actions?.includes('UPDATE') || actions?.includes('EDIT') || actions?.includes('DELETE')) && ( @@ -127,10 +128,14 @@ const ComponentPage: FC = ({ data }) => { - { setShowFormDialog(true); setSelectedData(record) }} >Edit - - Delete - + {(actions.includes('UPDATE') || actions.includes('EDIT')) && ( + { setShowFormDialog(true); setSelectedData(record) }} >Edit + )} + {(actions.includes('DELETE')) && ( + + Delete + + )} = ({ data }) => {
- +
- + {(actions?.includes('CREATE')) && ( + + )}
import('./component')); @@ -15,35 +14,9 @@ export const metadata: Metadata = { title: "Admin | Global Parameter", } -async function getData() { - const { BASE_URL_API } = process.env - const session = await getServerSession(authOptions) - - const res = await fetch(BASE_URL_API + '/global-parameter', { - headers: { - "Content-Type": "application/json", - Authorization: `Bearer ${session?.user.access_token}`, - }, - cache: 'no-cache', - next: { - tags: ['global-parameter'] - } - }) - - const data: ResponseData = await res.json() - - // Recommendation: handle errors - if (!res.ok) { - // This will activate the closest `error.js` Error Boundary - throw new Error(`Failed to fetch data, ${data.code || res.status} ${data.message || res.statusText}`) - } - - return data.data -} - - export default async function GlobalParameterPage() { - const data = await getData() + const actions = await getAccessPagePermission('/global-parameter') + const data = await fetchData('/global-parameter', 'no-cache', { tags: ['global-parameter'] }) return ( <> @@ -54,14 +27,17 @@ export default async function GlobalParameterPage() { Global ParameterHere's a list of parameters that have been registered! -
- -
+ {actions.includes('EXPORT') && +
+ +
+ } }> diff --git a/app/admin/information/employee-type/component/index.tsx b/app/admin/information/employee-type/component/index.tsx index 47830aa..e8403f8 100644 --- a/app/admin/information/employee-type/component/index.tsx +++ b/app/admin/information/employee-type/component/index.tsx @@ -3,8 +3,6 @@ import { ChangeEvent, FC, useEffect, useState } from 'react'; import { Table } from 'antd'; import { TableProps, type ColumnsType } from 'antd/es/table'; -import { MixerHorizontalIcon } from '@radix-ui/react-icons'; -import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; import { type IEmployeeType } from './type'; diff --git a/app/admin/information/employee-type/page.tsx b/app/admin/information/employee-type/page.tsx index 56e4cad..1c8f49e 100644 --- a/app/admin/information/employee-type/page.tsx +++ b/app/admin/information/employee-type/page.tsx @@ -1,10 +1,9 @@ import { type Metadata } from 'next'; import { Suspense, lazy } from 'react'; -import { getServerSession } from 'next-auth'; -import { type ResponseData } from '@/types/types'; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; import LazyLoading from '@/components/loader/LazyLoading'; -import { authOptions } from '@/lib/auth'; +import fetchData from '@/lib/fetchData'; +import { getAccessPagePermission } from '@/lib/get-access-data'; const ComponentPage = lazy(() => import('./component')); @@ -13,35 +12,9 @@ export const metadata: Metadata = { title: "Admin | Master Employee Type", } -async function getData() { - const { BASE_URL_API } = process.env - const session = await getServerSession(authOptions) - - const res = await fetch(BASE_URL_API + '/employee-type', { - headers: { - "Content-Type": "application/json", - Authorization: `Bearer ${session?.user.access_token}`, - }, - cache: 'no-cache', - next: { - tags: ['employee-type'] - } - }) - - const data: ResponseData = await res.json() - - // Recommendation: handle errors - if (!res.ok) { - // This will activate the closest `error.js` Error Boundary - throw new Error(`Failed to fetch data, ${data.code || res.status} ${data.message || res.statusText}`) - } - - return data.data -} - - -export default async function page() { - const data = await getData() +export default async function EmployeeTypePage() { + await getAccessPagePermission('/information/employee-type') + const data = await fetchData('/employee-type', 'no-cache', { tags: ['employee-type'] }) return ( <> diff --git a/app/admin/information/master-status/component/index.tsx b/app/admin/information/master-status/component/index.tsx index 97dbbd7..d08c86c 100644 --- a/app/admin/information/master-status/component/index.tsx +++ b/app/admin/information/master-status/component/index.tsx @@ -3,8 +3,6 @@ import { ChangeEvent, FC, useEffect, useState } from 'react'; import { Table } from 'antd'; import { TableProps, type ColumnsType } from 'antd/es/table'; -import { MixerHorizontalIcon } from '@radix-ui/react-icons'; -import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; import { type IMasterStatus } from './type'; diff --git a/app/admin/information/master-status/page.tsx b/app/admin/information/master-status/page.tsx index 57e5670..cbcbd59 100644 --- a/app/admin/information/master-status/page.tsx +++ b/app/admin/information/master-status/page.tsx @@ -1,10 +1,9 @@ import { type Metadata } from 'next'; import { Suspense, lazy } from 'react'; -import { getServerSession } from 'next-auth'; -import { type ResponseData } from '@/types/types'; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; import LazyLoading from '@/components/loader/LazyLoading'; -import { authOptions } from '@/lib/auth'; +import fetchData from '@/lib/fetchData'; +import { getAccessPagePermission } from '@/lib/get-access-data'; const ComponentPage = lazy(() => import('./component')); @@ -13,35 +12,9 @@ export const metadata: Metadata = { title: "Admin | Master Status", } -async function getData() { - const { BASE_URL_API } = process.env - const session = await getServerSession(authOptions) - - const res = await fetch(BASE_URL_API + '/status', { - headers: { - "Content-Type": "application/json", - Authorization: `Bearer ${session?.user.access_token}`, - }, - cache: 'no-cache', - next: { - tags: ['status'] - } - }) - - const data: ResponseData = await res.json() - - // Recommendation: handle errors - if (!res.ok) { - // This will activate the closest `error.js` Error Boundary - throw new Error(`Failed to fetch data, ${data.code || res.status} ${data.message || res.statusText}`) - } - - return data.data -} - - -export default async function page() { - const data = await getData() +export default async function MasterStatusPage() { + await getAccessPagePermission('/information/master-status') + const data = await fetchData('/status', 'no-cache', { tags: ['status'] }) return ( <> diff --git a/app/admin/information/position/component/index.tsx b/app/admin/information/position/component/index.tsx index d89a6e2..653d3be 100644 --- a/app/admin/information/position/component/index.tsx +++ b/app/admin/information/position/component/index.tsx @@ -3,8 +3,6 @@ import { ChangeEvent, FC, useEffect, useState } from 'react'; import { Table } from 'antd'; import { TableProps, type ColumnsType } from 'antd/es/table'; -import { MixerHorizontalIcon } from '@radix-ui/react-icons'; -import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; import { type IPosition } from './type'; diff --git a/app/admin/information/position/page.tsx b/app/admin/information/position/page.tsx index 2797cab..c33c75a 100644 --- a/app/admin/information/position/page.tsx +++ b/app/admin/information/position/page.tsx @@ -1,10 +1,9 @@ import { type Metadata } from 'next'; import { Suspense, lazy } from 'react'; -import { getServerSession } from 'next-auth'; -import { type ResponseData } from '@/types/types'; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; import LazyLoading from '@/components/loader/LazyLoading'; -import { authOptions } from '@/lib/auth'; +import fetchData from '@/lib/fetchData'; +import { getAccessPagePermission } from '@/lib/get-access-data'; const ComponentPage = lazy(() => import('./component')); @@ -13,35 +12,9 @@ export const metadata: Metadata = { title: "Admin | Master Employee Position", } -async function getData() { - const { BASE_URL_API } = process.env - const session = await getServerSession(authOptions) - - const res = await fetch(BASE_URL_API + '/position', { - headers: { - "Content-Type": "application/json", - Authorization: `Bearer ${session?.user.access_token}`, - }, - cache: 'no-cache', - next: { - tags: ['position'] - } - }) - - const data: ResponseData = await res.json() - - // Recommendation: handle errors - if (!res.ok) { - // This will activate the closest `error.js` Error Boundary - throw new Error(`Failed to fetch data, ${data.code || res.status} ${data.message || res.statusText}`) - } - - return data.data -} - - -export default async function page() { - const data = await getData() +export default async function PositionPage() { + await getAccessPagePermission('/information/position') + const data = await fetchData('/position', 'no-cache', { tags: ['position'] }) return ( <> @@ -50,7 +23,7 @@ export default async function page() {
Position - Here's a list of empoyee's position that have been registered! + Here's a list of empoyee's position that have been registered!
diff --git a/app/admin/information/user-role/component/ConfirmAsync.tsx b/app/admin/information/user-role/component/ConfirmAsync.tsx deleted file mode 100644 index f281bd9..0000000 --- a/app/admin/information/user-role/component/ConfirmAsync.tsx +++ /dev/null @@ -1,75 +0,0 @@ -import { useRouter } from 'next/navigation'; -import { FC, ReactNode, useState } from 'react'; -import { Icons } from '@/components/Icons'; -import { AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from '@/components/ui/alert-dialog'; -import { type ResponseData } from '@/types/types'; -import { toast } from 'sonner'; - -type Props = { - title?: string - description?: string - onConfirm: () => Promise - okText?: string - cancelText?: string - contentSuccess?: ReactNode | string - onOkSuccess?: () => any -}; - -const ConfirmAsync: FC = ({ title, description, onConfirm, okText, cancelText, contentSuccess, onOkSuccess }) => { - const [isLoading, setIsloading] = useState(false) - const router = useRouter() - - const confirm = async () => { - if (isLoading) return - try { - setIsloading(true) - const res: ResponseData = await onConfirm() - setIsloading(false) - - console.log(res) - if (!res) return - - if (res.code === '00') { - showSuccess() - } else { - showError(res.message) - } - } catch (error: any) { - console.log(error) - setIsloading(false) - showError(error?.message) - } - } - - const showSuccess = () => { - router.refresh() - toast.success(contentSuccess || 'Data successfully removed.' as string) - onOkSuccess!() - }; - - const showError = (message?: string) => { - toast.error(message) - }; - - return ( - - - {title || 'Are you absolutely sure?'} - - {description || 'This action cannot be undone. This will permanently delete this data and remove from our servers.'} - - - - {cancelText || 'Cancel'} - - {isLoading && ( - - )} - {okText || 'Continue'} - - - - ); -} - -export default ConfirmAsync; \ No newline at end of file diff --git a/app/admin/information/user-role/component/Form.tsx b/app/admin/information/user-role/component/Form.tsx deleted file mode 100644 index c3e8370..0000000 --- a/app/admin/information/user-role/component/Form.tsx +++ /dev/null @@ -1 +0,0 @@ -export { default } from '@/app/admin/rbac/user-role/component/RoleForm'; diff --git a/app/admin/information/user-role/component/index.tsx b/app/admin/information/user-role/component/index.tsx deleted file mode 100644 index 4805002..0000000 --- a/app/admin/information/user-role/component/index.tsx +++ /dev/null @@ -1 +0,0 @@ -export { default } from '@/app/admin/rbac/user-role/component'; diff --git a/app/admin/information/user-role/component/type.ts b/app/admin/information/user-role/component/type.ts deleted file mode 100644 index d3a4c18..0000000 --- a/app/admin/information/user-role/component/type.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { type IRole } from '@/types/rbac'; - -export type { IRole }; - diff --git a/app/admin/information/user-role/component/type.tsx b/app/admin/information/user-role/component/type.tsx deleted file mode 100644 index c6e3f8e..0000000 --- a/app/admin/information/user-role/component/type.tsx +++ /dev/null @@ -1,12 +0,0 @@ -export interface IRole { - id: number, - name: string, - status: { - id: number, - code: "A" | 'N' | 'X', - name: "ACTIVE" | 'INACTIVE' | 'DELETED' - }, - description: string - allow_admin?: boolean - privilege?: any -} \ No newline at end of file diff --git a/app/admin/information/user-role/page.tsx b/app/admin/information/user-role/page.tsx deleted file mode 100644 index c31ef08..0000000 --- a/app/admin/information/user-role/page.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { redirect } from 'next/navigation'; - -export default function DeprecatedUserRolePage() { - redirect('/admin/rbac/user-role'); -} diff --git a/app/admin/information/working-status/page.tsx b/app/admin/information/working-status/page.tsx index 60f77ed..615c7ce 100644 --- a/app/admin/information/working-status/page.tsx +++ b/app/admin/information/working-status/page.tsx @@ -1,10 +1,9 @@ import { type Metadata } from 'next'; import { Suspense, lazy } from 'react'; -import { getServerSession } from 'next-auth'; -import { type ResponseData } from '@/types/types'; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; import LazyLoading from '@/components/loader/LazyLoading'; -import { authOptions } from '@/lib/auth'; +import fetchData from '@/lib/fetchData'; +import { getAccessPagePermission } from '@/lib/get-access-data'; const ComponentPage = lazy(() => import('./component')); @@ -13,35 +12,9 @@ export const metadata: Metadata = { title: "Admin | Master Working Status", } -async function getData(current_page?: string, limit?: string) { - const { BASE_URL_API } = process.env - const session = await getServerSession(authOptions) - - const res = await fetch(BASE_URL_API + '/presence/list-status', { - headers: { - "Content-Type": "application/json", - Authorization: `Bearer ${session?.user.access_token}`, - }, - cache: 'no-cache', - next: { - tags: ['working-status'] - } - }) - - const data: ResponseData = await res.json() - - // Recommendation: handle errors - if (!res.ok) { - // This will activate the closest `error.js` Error Boundary - throw new Error(`Failed to fetch data, ${data.code || res.status} ${data.message || res.statusText}`) - } - - return data.data -} - - -export default async function page() { - const data = await getData() +export default async function WorkingStatusPage() { + await getAccessPagePermission('/information/working-status') + const data = await fetchData('/presence/list-status', 'no-cache', { tags: ['working-status'] }) return ( <> diff --git a/app/admin/layout.tsx b/app/admin/layout.tsx index 8fd7bea..08abdba 100644 --- a/app/admin/layout.tsx +++ b/app/admin/layout.tsx @@ -1,5 +1,6 @@ import { Metadata } from "next"; import Link from "next/link"; +import { forbidden } from "next/navigation"; import { ToggleTheme } from "./components/ToggleTheme"; import { Button } from "@/components/ui/button"; import Notification from "./components/Notification"; @@ -22,6 +23,10 @@ export const metadata: Metadata = { export default async function AdminLayout({ children }: { children: React.ReactNode }) { const data = await getAccessData() + if (!data?.allow_admin_panel) { + forbidden() + } + const cleanPath = (path: string): string => { if (!path || path === '/') return '' const sanitized = path.replace(/\/+/g, '/') diff --git a/app/admin/manual/approval-autocheckout/page.tsx b/app/admin/manual/approval-autocheckout/page.tsx index e5c26f6..0f12d98 100644 --- a/app/admin/manual/approval-autocheckout/page.tsx +++ b/app/admin/manual/approval-autocheckout/page.tsx @@ -4,6 +4,7 @@ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/com import LazyLoading from '@/components/loader/LazyLoading'; import dayjs from 'dayjs'; import { fetchDataWithPost } from '@/lib/fetchData'; +import { getAccessPagePermission } from '@/lib/get-access-data'; const ExportComponent = lazy(() => import('./component/Export')); const ComponentPage = lazy(() => import('./component')); @@ -19,6 +20,8 @@ type Props = { }; const ApprovalAutoCheckoutPage: FC = async ({ searchParams }) => { + const actions = await getAccessPagePermission('/manual/approval-autocheckout') + const start_date = (await searchParams)!.start_date const end_date = (await searchParams)!.end_date @@ -33,9 +36,11 @@ const ApprovalAutoCheckoutPage: FC = async ({ searchParams }) => { Approval Auto Checkout Here's a list of employee attendance that forgot to checkout! - }> - - + {actions.includes('EXPORT') && + }> + + + } }> diff --git a/app/admin/manual/approval/page.tsx b/app/admin/manual/approval/page.tsx index cbf4820..0eb2071 100644 --- a/app/admin/manual/approval/page.tsx +++ b/app/admin/manual/approval/page.tsx @@ -4,6 +4,7 @@ import dayjs from 'dayjs'; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; import LazyLoading from '@/components/loader/LazyLoading'; import { fetchDataWithPost } from '@/lib/fetchData'; +import { getAccessPagePermission } from '@/lib/get-access-data'; const ExportComponent = lazy(() => import('./component/Export')); const ComponentPage = lazy(() => import('./component')); @@ -18,6 +19,8 @@ type Props = { }; const ApprovalNonWFOPage: FC = async ({ searchParams }) => { + const actions = await getAccessPagePermission('/manual/approval') + const start_date = (await searchParams)!.start_date const end_date = (await searchParams)!.end_date @@ -32,9 +35,11 @@ const ApprovalNonWFOPage: FC = async ({ searchParams }) => { Approval Attendance Here's a list of approval attendance those working outside the office! - }> - - + {actions.includes('EXPORT') && + }> + + + } }> diff --git a/app/admin/manual/manual-presence/page.tsx b/app/admin/manual/manual-presence/page.tsx index 41e3635..0fbe684 100644 --- a/app/admin/manual/manual-presence/page.tsx +++ b/app/admin/manual/manual-presence/page.tsx @@ -15,7 +15,7 @@ export const metadata: Metadata = { type Props = {}; const ManualPresencePage: FC = async () => { - const actions = await getAccessPagePermission('/manual/manual-presence', 'CREATE') + const actions = await getAccessPagePermission('/manual/manual-presence') const fetchUser = fetchData('/user') const fetchStatus = fetchData('/presence/list-status') diff --git a/app/admin/project-assignment/client/component/index.tsx b/app/admin/project-assignment/client/component/index.tsx index 56fe981..a59803e 100644 --- a/app/admin/project-assignment/client/component/index.tsx +++ b/app/admin/project-assignment/client/component/index.tsx @@ -5,10 +5,8 @@ import { MoreHorizontalIcon } from 'lucide-react'; import { Table } from 'antd'; import { TableProps, type ColumnsType } from 'antd/es/table'; import { PlusCircledIcon } from '@radix-ui/react-icons'; -import useAxiosAuth from '@/lib/axios/useAxiosAuth'; import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu'; import { Button } from '@/components/ui/button'; -import { AlertDialogTrigger } from '@/components/ui/alert-dialog'; import { Input } from '@/components/ui/input'; import { useRouter } from 'next/navigation'; import Link from 'next/link'; @@ -21,9 +19,10 @@ import { ConfirmDeleteWithInput } from '@/components/modal/ConfirmDeleteWithInpu type Props = { data: IClient[] + actions?: string[] }; -const ComponentPage: FC = ({ data }) => { +const ComponentPage: FC = ({ data, actions }) => { const [filterData, setFilterData] = useState([]) const [action, setAction] = useState<'CREATE' | 'EDIT' | 'DELETE' | undefined>(undefined) const [selectedData, setSelectedData] = useState() @@ -133,7 +132,7 @@ const ComponentPage: FC = ({ data }) => { title: 'Action', key: 'action', fixed: 'right', - render: (_, record) => ( + render: (_, record) => (actions?.includes('UPDATE') || actions?.includes('EDIT') || actions?.includes('DELETE')) && ( + {(actions?.includes('CREATE')) && ( + + )}
import('./component')); const ExportComponent = lazy(() => import('./component/Export')); @@ -11,6 +12,7 @@ export const metadata: Metadata = { title: "Client - Project Assignment | Admin", } export default async function ClientPage() { + const actions = await getAccessPagePermission('/project-assignment/client') const data = await fetchData('/client') return ( @@ -22,13 +24,15 @@ export default async function ClientPage() { Client ManagementHere's a list of clients that have been registered for project assignment! - }> - - + {actions.includes('EXPORT') && + }> + + + } }> - + diff --git a/app/admin/project-assignment/end-user/component/index.tsx b/app/admin/project-assignment/end-user/component/index.tsx index de0673f..9781270 100644 --- a/app/admin/project-assignment/end-user/component/index.tsx +++ b/app/admin/project-assignment/end-user/component/index.tsx @@ -18,9 +18,10 @@ import FormEndUser from '@/app/(dashboard)/task/component/FormEndUser'; type Props = { data: IEndUser[] + actions?: string[] }; -const ComponentPage: FC = ({ data }) => { +const ComponentPage: FC = ({ data, actions }) => { const [filterData, setFilterData] = useState([]) const [action, setAction] = useState<'CREATE' | 'EDIT' | 'DELETE' | undefined>(undefined) const [selectedData, setSelectedData] = useState() @@ -115,7 +116,7 @@ const ComponentPage: FC = ({ data }) => { title: 'Action', key: 'action', fixed: 'right', - render: (_, record) => ( + render: (_, record) => (actions?.includes('UPDATE') || actions?.includes('EDIT') || actions?.includes('DELETE')) && ( e?.stopPropagation()}> - { setAction('EDIT'); setSelectedData(record) }}>Edit End User - { setSelectedData(record); setAction('DELETE') }} className="text-destructive" onClick={(e) => e.stopPropagation()}> - Delete End User - + {(actions.includes('UPDATE') || actions.includes('EDIT')) && ( + { setAction('EDIT'); setSelectedData(record) }}>Edit End User + )} + {(actions.includes('DELETE')) && ( + { setSelectedData(record); setAction('DELETE') }} className="text-destructive" onClick={(e) => e.stopPropagation()}> + Delete End User + + )} ), @@ -156,10 +161,12 @@ const ComponentPage: FC = ({ data }) => {
- + {(actions?.includes('CREATE')) && ( + + )}
import('./component')); const ExportComponent = lazy(() => import('./component/Export')); @@ -11,6 +12,7 @@ export const metadata: Metadata = { title: "End User - Project Assignment | Admin", } export default async function EndUserPage() { + const actions = await getAccessPagePermission('/project-assignment/end-user') const data = await fetchData('/end-user') return ( @@ -22,13 +24,15 @@ export default async function EndUserPage() { End User ManagementHere's a list of end users that have been registered for project assignment! - }> - - + {actions.includes('EXPORT') && + }> + + + } }> - + diff --git a/app/admin/project-assignment/project-management/component/index.tsx b/app/admin/project-assignment/project-management/component/index.tsx index 1a6f30c..2efd272 100644 --- a/app/admin/project-assignment/project-management/component/index.tsx +++ b/app/admin/project-assignment/project-management/component/index.tsx @@ -17,9 +17,10 @@ import FormProject from './FormProject'; type Props = { data: IProjectAssignment[] + actions?: string[] }; -const ComponentPage: FC = ({ data }) => { +const ComponentPage: FC = ({ data, actions }) => { const [filterData, setFilterData] = useState([]) const [action, setAction] = useState<'CREATE' | 'EDIT' | 'DELETE' | undefined>(undefined) const [selectedData, setSelectedData] = useState() @@ -135,7 +136,7 @@ const ComponentPage: FC = ({ data }) => { title: 'Action', key: 'action', fixed: 'right', - render: (_, record) => ( + render: (_, record) => (actions?.includes('UPDATE') || actions?.includes('EDIT') || actions?.includes('DELETE')) && ( e?.stopPropagation()}> - { setAction('EDIT'); setSelectedData(record) }}>Edit Project - { setSelectedData(record); setAction('DELETE') }} className="text-destructive" onClick={(e) => e.stopPropagation()}> - Delete Project - + {(actions.includes('UPDATE') || actions.includes('EDIT')) && ( + { setAction('EDIT'); setSelectedData(record) }}>Edit Project + )} + {(actions.includes('DELETE')) && ( + { setSelectedData(record); setAction('DELETE') }} className="text-destructive" onClick={(e) => e.stopPropagation()}> + Delete Project + + )} ), @@ -176,10 +181,12 @@ const ComponentPage: FC = ({ data }) => {
- + {(actions?.includes('CREATE')) && ( + + )}
import('./component')); const ExportComponent = lazy(() => import('./component/Export')); @@ -11,6 +12,7 @@ export const metadata: Metadata = { title: "Project - Project Assignment | Admin", } export default async function ProjectManagementPage() { + const actions = await getAccessPagePermission('/project-assignment/project-management') const data = await fetchData('/project') return ( @@ -22,13 +24,15 @@ export default async function ProjectManagementPage() { Project ManagementHere's a list of projects that have been registered for project assignment! - }> - - + {actions.includes('EXPORT') && + }> + + + } }> - + diff --git a/app/admin/rbac/action-permissions/component/index.tsx b/app/admin/rbac/action-permissions/component/index.tsx index c187937..c6eaebb 100644 --- a/app/admin/rbac/action-permissions/component/index.tsx +++ b/app/admin/rbac/action-permissions/component/index.tsx @@ -19,9 +19,10 @@ import RbacBadge from '@/components/ui/rbac-badge'; type Props = { data: IPermission[]; + actions?: string[]; }; -const ComponentPermissionPage: FC = ({ data }) => { +const ComponentPermissionPage: FC = ({ data, actions }) => { const [filterData, setFilterData] = useState([]); const [selectedData, setSelectedData] = useState(undefined); const [showFormDialog, setShowFormDialog] = useState(false); @@ -97,7 +98,7 @@ const ComponentPermissionPage: FC = ({ data }) => { key: 'action', width: 80, align: 'center', - render: (_, record) => ( + render: (_, record) => actions?.includes('UPDATE') || actions?.includes('EDIT') || actions?.includes('DELETE') && ( @@ -107,19 +108,23 @@ const ComponentPermissionPage: FC = ({ data }) => { - { - setSelectedData(record); - setShowFormDialog(true); - }} - > - Edit Permission - - - - Delete Permission + {(actions.includes('UPDATE') || actions.includes('EDIT')) && ( + { + setSelectedData(record); + setShowFormDialog(true); + }} + > + Edit Permission - + )} + {(actions.includes('DELETE')) && ( + + + Delete Permission + + + )} = ({ data }) => { onChange={handleSearch} /> - + {(!actions || actions.includes('CREATE')) && ( + + )}
import('./component')); @@ -27,6 +28,7 @@ async function getPermissions() { } export default async function PermissionPage() { + const actions = await getAccessPagePermission(['/rbac/action-permissions', '/rbac/action-pemission']); const permissions = await getPermissions(); return ( @@ -42,7 +44,7 @@ export default async function PermissionPage() { }> - + diff --git a/app/admin/rbac/menu/component/index.tsx b/app/admin/rbac/menu/component/index.tsx index 0d4b4b7..b31f423 100644 --- a/app/admin/rbac/menu/component/index.tsx +++ b/app/admin/rbac/menu/component/index.tsx @@ -19,6 +19,7 @@ import { useRouter } from 'next/navigation'; type Props = { data: IMenu[]; + actions?: string[]; }; // Transform flat menu list into hierarchical tree for Antd Table @@ -61,7 +62,7 @@ function buildMenuTree(items: IMenu[]): IMenu[] { return roots; } -const ComponentMenuPage: FC = ({ data }) => { +const ComponentMenuPage: FC = ({ data, actions }) => { const [rawMenus, setRawMenus] = useState([]); const [filterData, setFilterData] = useState([]); const [selectedData, setSelectedData] = useState(undefined); @@ -205,7 +206,7 @@ const ComponentMenuPage: FC = ({ data }) => { key: 'row_action', width: 80, align: 'center', - render: (_, record) => ( + render: (_, record) => (actions?.includes('UPDATE') || actions?.includes('EDIT') || actions?.includes('DELETE')) && ( @@ -215,19 +216,23 @@ const ComponentMenuPage: FC = ({ data }) => { - { - setSelectedData(record); - setShowFormDialog(true); - }} - > - Edit Menu - - - - Delete Menu + {(actions.includes('UPDATE') || actions.includes('EDIT')) && ( + { + setSelectedData(record); + setShowFormDialog(true); + }} + > + Edit Menu - + )} + {(actions.includes('DELETE')) && ( + + + Delete Menu + + + )} = ({ data }) => { onChange={handleSearch} /> - + {(actions?.includes('CREATE')) && ( + + )}
import('./component')); @@ -27,6 +28,7 @@ async function getMenus() { } export default async function MenuPage() { + const actions = await getAccessPagePermission('/rbac/menu'); const menus = await getMenus(); return ( @@ -42,7 +44,7 @@ export default async function MenuPage() { }> - + diff --git a/app/admin/rbac/user-role/[id]/page.tsx b/app/admin/rbac/user-role/[id]/page.tsx index 1a6c6c3..12091cd 100644 --- a/app/admin/rbac/user-role/[id]/page.tsx +++ b/app/admin/rbac/user-role/[id]/page.tsx @@ -3,6 +3,7 @@ import { type Metadata } from 'next'; import Link from 'next/link'; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; import fetchData from '@/lib/fetchData'; +import { getAccessPagePermission } from '@/lib/get-access-data'; import { Button } from '@/components/ui/button'; import { type IRole } from '../component/type'; import RolePermissionRow from "../component/role-permission-row"; @@ -39,6 +40,7 @@ async function getRoleData(id: string): Promise { } const UserRoleDetailPage: FC = async ({ params }) => { + const actions = await getAccessPagePermission('/rbac/user-role', 'VIEW'); const { id } = await params; const data: IRole | undefined = await getRoleData(id); @@ -109,11 +111,13 @@ const UserRoleDetailPage: FC = async ({ params }) => { - - - + {(actions.includes('UPDATE') || actions.includes('EDIT')) && ( + + + + )}
diff --git a/app/admin/rbac/user-role/component/index.tsx b/app/admin/rbac/user-role/component/index.tsx index 948983b..7d7895e 100644 --- a/app/admin/rbac/user-role/component/index.tsx +++ b/app/admin/rbac/user-role/component/index.tsx @@ -17,9 +17,10 @@ import { type IRole } from './type'; type Props = { data: IRole[]; + actions?: string[]; }; -const ComponentRolePage: FC = ({ data }) => { +const ComponentRolePage: FC = ({ data, actions }) => { const [filterData, setFilterData] = useState([]); const [searchText, setSearchText] = useState(''); @@ -140,7 +141,7 @@ const ComponentRolePage: FC = ({ data }) => { key: 'action', width: 80, align: 'center', - render: (_, record) => ( + render: (_, record) => (actions?.includes('UPDATE') || actions?.includes('EDIT') || actions?.includes('DELETE')) && ( @@ -155,16 +156,20 @@ const ComponentRolePage: FC = ({ data }) => { View Details - - - Edit Role - - - - - Delete Role + {(actions.includes('UPDATE') || actions.includes('EDIT')) && ( + + + Edit Role + - + )} + {(actions.includes('DELETE')) && ( + + + Delete Role + + + )} = ({ data }) => { onChange={handleSearch} />
- - - + {(actions?.includes('CREATE')) && ( + + + + )}
; } diff --git a/app/admin/rbac/user-role/edit/[id]/page.tsx b/app/admin/rbac/user-role/edit/[id]/page.tsx index f47e80c..10dc503 100644 --- a/app/admin/rbac/user-role/edit/[id]/page.tsx +++ b/app/admin/rbac/user-role/edit/[id]/page.tsx @@ -1,5 +1,6 @@ import { type Metadata } from 'next'; import fetchData from '@/lib/fetchData'; +import { getAccessPagePermission } from '@/lib/get-access-data'; import RoleForm from '../../component/RoleForm'; import { type IRole } from '../../component/type'; @@ -34,6 +35,7 @@ async function getRoleData(id: string): Promise { } export default async function EditRolePage({ params }: Props) { + await getAccessPagePermission('/rbac/user-role', 'UPDATE'); const { id } = await params; const roleData = await getRoleData(id); diff --git a/app/admin/rbac/user-role/page.tsx b/app/admin/rbac/user-role/page.tsx index 77eb3d2..84539f1 100644 --- a/app/admin/rbac/user-role/page.tsx +++ b/app/admin/rbac/user-role/page.tsx @@ -3,6 +3,7 @@ import { Suspense, lazy } from 'react'; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; import LazyLoading from '@/components/loader/LazyLoading'; import fetchData from '@/lib/fetchData'; +import { getAccessPagePermission } from '@/lib/get-access-data'; const ComponentPage = lazy(() => import('./component')); @@ -27,6 +28,7 @@ async function getRoles() { } export default async function UserRolePage() { + const actions = await getAccessPagePermission('/rbac/user-role'); const roles = await getRoles(); return ( @@ -42,7 +44,7 @@ export default async function UserRolePage() { }> - + diff --git a/app/admin/report/distribution/component/index.tsx b/app/admin/report/distribution/component/index.tsx index 8d35126..4b1d608 100644 --- a/app/admin/report/distribution/component/index.tsx +++ b/app/admin/report/distribution/component/index.tsx @@ -12,9 +12,10 @@ const ExportComponent = lazy(() => import('./Export')); type Props = { data: IHistory[] + actions?: string[] }; -const ComponentPage: FC = ({ data }) => { +const ComponentPage: FC = ({ data, actions }) => { const [groupData, setGroupData] = useState(null) useEffect(() => { @@ -664,9 +665,11 @@ const ComponentPage: FC = ({ data }) => { Attendance Distribution Here's a list of all employee attendance distribution! - }> - - + {actions?.includes('EXPORT') && + }> + + + }
diff --git a/app/admin/report/distribution/page.tsx b/app/admin/report/distribution/page.tsx index a816a3b..ecaf01c 100644 --- a/app/admin/report/distribution/page.tsx +++ b/app/admin/report/distribution/page.tsx @@ -4,6 +4,7 @@ import { Card } from '@/components/ui/card'; import LazyLoading from '@/components/loader/LazyLoading'; import dayjs from 'dayjs'; import { fetchDataWithPost } from '@/lib/fetchData'; +import { getAccessPagePermission } from '@/lib/get-access-data'; const ComponentPage = lazy(() => import('./component')); @@ -18,6 +19,8 @@ type Props = { }; const AttendanceDistributionPage: FC = async ({ searchParams }) => { + const actions = await getAccessPagePermission('/report/distribution') + const start_date = (await searchParams)!.start_date const end_date = (await searchParams)!.end_date @@ -28,7 +31,7 @@ const AttendanceDistributionPage: FC = async ({ searchParams }) => {
}> - +
diff --git a/app/admin/report/history/component/index.tsx b/app/admin/report/history/component/index.tsx index 3b94771..a00ec37 100644 --- a/app/admin/report/history/component/index.tsx +++ b/app/admin/report/history/component/index.tsx @@ -13,9 +13,10 @@ import useDebounce from '@/hooks/useDebounce'; type Props = { data: IHistory[] + actions?: string[] }; -const ComponentPage: FC = ({ data }) => { +const ComponentPage: FC = ({ data, actions }) => { const [currentDataTable, setCurrentDataTable] = useState([]) const [searchText, setSearchText] = useState('') @@ -79,15 +80,17 @@ const ComponentPage: FC = ({ data }) => { Attendance History Here's a list of all employee attendance history!
- }> - - + {actions?.includes('EXPORT') && + }> + + + }
- +
import('./component')); @@ -17,6 +18,8 @@ type Props = { }; const MonthlyPresencePage: FC = async ({ searchParams }) => { + const actions = await getAccessPagePermission('/report/history') + const start_date = (await searchParams)!.start_date const end_date = (await searchParams)!.end_date @@ -27,9 +30,7 @@ const MonthlyPresencePage: FC = async ({ searchParams }) => {
}> - + diff --git a/app/admin/report/leave-permit-sick/page.tsx b/app/admin/report/leave-permit-sick/page.tsx index 9089502..50edc5e 100644 --- a/app/admin/report/leave-permit-sick/page.tsx +++ b/app/admin/report/leave-permit-sick/page.tsx @@ -4,6 +4,7 @@ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/com import LazyLoading from '@/components/loader/LazyLoading'; import dayjs from 'dayjs'; import { fetchDataWithPost } from '@/lib/fetchData'; +import { getAccessPagePermission } from '@/lib/get-access-data'; const ExportComponent = lazy(() => import('./component/Export')); const ComponentPage = lazy(() => import('./component')); @@ -18,6 +19,8 @@ type Props = { }; const LeavePermitSickReportPage: FC = async ({ searchParams }) => { + const actions = await getAccessPagePermission('/report/leave-permit-sick') + const start_date = (await searchParams)!.start_date const end_date = (await searchParams)!.end_date @@ -32,9 +35,11 @@ const LeavePermitSickReportPage: FC = async ({ searchParams }) => { Leave, Permit and Sick Report Here's a list of application form for leave, permit and sick! - }> - - + {actions.includes('EXPORT') && + }> + + + } }> diff --git a/app/admin/report/monthly-presence/page.tsx b/app/admin/report/monthly-presence/page.tsx index 5f86d05..e364fb0 100644 --- a/app/admin/report/monthly-presence/page.tsx +++ b/app/admin/report/monthly-presence/page.tsx @@ -4,6 +4,7 @@ import dayjs from 'dayjs'; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; import LazyLoading from '@/components/loader/LazyLoading'; import { fetchDataWithPost } from '@/lib/fetchData'; +import { getAccessPagePermission } from '@/lib/get-access-data'; const ComponentPage = lazy(() => import('./component')); const ExportComponent = lazy(() => import('./component/Export')); @@ -18,6 +19,8 @@ type Props = { }; const SummaryAttendancePage: FC = async ({ searchParams }) => { + const actions = await getAccessPagePermission('/report/monthly-presence') + const start_date = (await searchParams)!.start_date const end_date = (await searchParams)!.end_date @@ -32,9 +35,11 @@ const SummaryAttendancePage: FC = async ({ searchParams }) => { Summary Attendance Report Here's a list of summary employee attendance report! - }> - - + {actions.includes('EXPORT') && + }> + + + } }> diff --git a/lib/get-access-data.tsx b/lib/get-access-data.tsx index 060e575..2a959ef 100644 --- a/lib/get-access-data.tsx +++ b/lib/get-access-data.tsx @@ -44,24 +44,38 @@ export const getAccessData = cache(async () => { }); -export async function getAccessPagePermission(path: string, action: string = "view") { +export async function getAccessPagePermission(path: string | string[], action: string = "view") { const accessData = await getAccessData(); + const normalize = (p: string) => (p || '').trim().replace(/^\/+|\/+$/g, '').toLowerCase(); + const targetPaths = (Array.isArray(path) ? path : [path]).map(normalize); + // Check whether the current page is registered - const menu = accessData?.role_detail?.find((item: any) => item.menu?.path_url === path); + const menu = accessData?.role_detail?.find((item: any) => { + const itemPath = normalize(item.menu?.path_url || ''); + if (!itemPath) return false; + if (targetPaths.includes(itemPath)) return true; + if (targetPaths.includes('rbac/action-permissions') && itemPath === 'rbac/action-pemission') return true; + if (targetPaths.includes('rbac/action-pemission') && itemPath === 'rbac/action-permissions') return true; + return false; + }); if (!menu?.menu) { - // redirect(redirectPage); - forbidden() + forbidden(); } + // Role-specific assigned actions take precedence; fallback to menu actions if role actions are absent + const permittedActions: string[] = (Array.isArray(menu?.action) && menu.action.length > 0) + ? menu.action + : (Array.isArray(menu?.menu?.action) ? menu.menu.action : []); + // Check whether the user has permission - if (!menu?.menu?.action?.includes(action.toUpperCase())) { - // redirect(redirectPage); - forbidden() + const hasPermission = permittedActions.some((act: string) => act.toUpperCase() === action.toUpperCase()); + if (!hasPermission) { + forbidden(); } - return menu?.menu?.action; + return permittedActions; }