dstpabuaran.com/resources/js/hooks/use-can.ts
Yoga Pangestu e7aa582572 feat: add cutting management functionality with CRUD operations
- Implemented CuttingIndex component for listing and managing cuttings.
- Added routes for cutting management in web.php.
- Created CuttingTest for testing cutting-related features including authorization, validation, and stock management.
- Updated roles create and edit pages to include necessary imports.
- Refactored settings and profile pages to streamline imports.
- Enhanced permissions checks for cutting management actions.
2026-08-04 02:24:11 +07:00

49 lines
1.2 KiB
TypeScript

import { usePage } from '@inertiajs/react';
type RoleOrPermission = { name: string } | string;
type User = {
id: number;
username?: string;
roles?: RoleOrPermission[];
permissions?: RoleOrPermission[];
[key: string]: unknown;
};
type PageProps = {
auth: {
user?: User;
};
};
function extractNames(items?: RoleOrPermission[]): string[] {
if (!items) return [];
return items.map((item) => (typeof item === 'string' ? item : item.name));
}
export function useCan() {
const { auth } = usePage().props as PageProps;
const user = auth.user;
const roleNames = extractNames(user?.roles);
const permissionNames = extractNames(user?.permissions);
function can(permission: string): boolean {
if (!user) return false;
if (roleNames.includes('developer') || roleNames.includes('owner')) return true;
return permissionNames.includes(permission);
}
function hasRole(role: string): boolean {
if (!user) return false;
return roleNames.includes(role);
}
function hasAnyRole(roles: string[]): boolean {
if (!user) return false;
return roles.some((role) => roleNames.includes(role));
}
return { can, hasRole, hasAnyRole };
}