feat: Gestao Avancada de Privilegios e Notificacoes do Modo Smart
This commit is contained in:
@@ -2,11 +2,12 @@ import React, { useState } from 'react';
|
|||||||
import { useMatrizAcessos, UsuarioMatriz } from '@/hooks/useMatrizAcessos';
|
import { useMatrizAcessos, UsuarioMatriz } from '@/hooks/useMatrizAcessos';
|
||||||
import { MatrizGrid } from './MatrizGrid';
|
import { MatrizGrid } from './MatrizGrid';
|
||||||
import { MatrizTemplatesModal } from './MatrizTemplatesModal';
|
import { MatrizTemplatesModal } from './MatrizTemplatesModal';
|
||||||
|
import { MatrizSmartAvancadoModal } from './MatrizSmartAvancadoModal';
|
||||||
import { SimuladorVisaoBar } from './SimuladorVisaoBar';
|
import { SimuladorVisaoBar } from './SimuladorVisaoBar';
|
||||||
import { Input } from '@/components/ui/input';
|
import { Input } from '@/components/ui/input';
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { Badge } from '@/components/ui/badge';
|
import { Badge } from '@/components/ui/badge';
|
||||||
import { Search, RefreshCw, Users, Shield, Factory, Sparkles } from 'lucide-react';
|
import { Search, RefreshCw, Users, Shield, Factory, Sparkles, SlidersHorizontal } from 'lucide-react';
|
||||||
|
|
||||||
interface MatrizAcessosPainelProps {
|
interface MatrizAcessosPainelProps {
|
||||||
onOpenNovoUsuario?: () => void;
|
onOpenNovoUsuario?: () => void;
|
||||||
@@ -28,6 +29,7 @@ export const MatrizAcessosPainel: React.FC<MatrizAcessosPainelProps> = ({
|
|||||||
|
|
||||||
const [busca, setBusca] = useState('');
|
const [busca, setBusca] = useState('');
|
||||||
const [selectedUserForTemplate, setSelectedUserForTemplate] = useState<UsuarioMatriz | null>(null);
|
const [selectedUserForTemplate, setSelectedUserForTemplate] = useState<UsuarioMatriz | null>(null);
|
||||||
|
const [smartAvancadoOpen, setSmartAvancadoOpen] = useState(false);
|
||||||
|
|
||||||
// Filtragem por nome, email ou cargo
|
// Filtragem por nome, email ou cargo
|
||||||
const usuariosFiltrados = usuarios.filter((u) => {
|
const usuariosFiltrados = usuarios.filter((u) => {
|
||||||
@@ -105,6 +107,16 @@ export const MatrizAcessosPainel: React.FC<MatrizAcessosPainelProps> = ({
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex items-center gap-2 w-full sm:w-auto justify-end">
|
<div className="flex items-center gap-2 w-full sm:w-auto justify-end">
|
||||||
|
<Button
|
||||||
|
size="sm"
|
||||||
|
variant="outline"
|
||||||
|
onClick={() => setSmartAvancadoOpen(true)}
|
||||||
|
className="text-xs h-9 border-emerald-500/30 bg-emerald-500/10 hover:bg-emerald-500/20 text-emerald-400 font-semibold"
|
||||||
|
>
|
||||||
|
<SlidersHorizontal className="h-3.5 w-3.5 mr-1.5" />
|
||||||
|
Avançado Modo Smart
|
||||||
|
</Button>
|
||||||
|
|
||||||
<Button
|
<Button
|
||||||
size="sm"
|
size="sm"
|
||||||
variant="outline"
|
variant="outline"
|
||||||
@@ -139,6 +151,7 @@ export const MatrizAcessosPainel: React.FC<MatrizAcessosPainelProps> = ({
|
|||||||
grupos={gruposModulos}
|
grupos={gruposModulos}
|
||||||
onToggleNivel={toggleNivel}
|
onToggleNivel={toggleNivel}
|
||||||
onOpenTemplates={(user) => setSelectedUserForTemplate(user)}
|
onOpenTemplates={(user) => setSelectedUserForTemplate(user)}
|
||||||
|
onOpenSmartAvancado={() => setSmartAvancadoOpen(true)}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
@@ -149,6 +162,12 @@ export const MatrizAcessosPainel: React.FC<MatrizAcessosPainelProps> = ({
|
|||||||
onClose={() => setSelectedUserForTemplate(null)}
|
onClose={() => setSelectedUserForTemplate(null)}
|
||||||
onSelectTemplate={aplicarTemplate}
|
onSelectTemplate={aplicarTemplate}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
{/* 6. MODAL DE GESTÃO AVANÇADA MODO SMART */}
|
||||||
|
<MatrizSmartAvancadoModal
|
||||||
|
isOpen={smartAvancadoOpen}
|
||||||
|
onClose={() => setSmartAvancadoOpen(false)}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import { UsuarioMatriz, GrupoRecurso, NivelAcesso } from '@/hooks/useMatrizAcess
|
|||||||
import { Badge } from '@/components/ui/badge';
|
import { Badge } from '@/components/ui/badge';
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
|
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
|
||||||
import { Sparkles, Eye, Edit3, ShieldAlert } from 'lucide-react';
|
import { Sparkles, Eye, Edit3, ShieldAlert, SlidersHorizontal } from 'lucide-react';
|
||||||
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
|
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
|
||||||
|
|
||||||
interface MatrizGridProps {
|
interface MatrizGridProps {
|
||||||
@@ -11,6 +11,7 @@ interface MatrizGridProps {
|
|||||||
grupos: GrupoRecurso[];
|
grupos: GrupoRecurso[];
|
||||||
onToggleNivel: (userId: string, resourceKey: string, tipo: 'V' | 'C') => void;
|
onToggleNivel: (userId: string, resourceKey: string, tipo: 'V' | 'C') => void;
|
||||||
onOpenTemplates: (user: UsuarioMatriz) => void;
|
onOpenTemplates: (user: UsuarioMatriz) => void;
|
||||||
|
onOpenSmartAvancado?: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const MatrizGrid: React.FC<MatrizGridProps> = ({
|
export const MatrizGrid: React.FC<MatrizGridProps> = ({
|
||||||
@@ -18,6 +19,7 @@ export const MatrizGrid: React.FC<MatrizGridProps> = ({
|
|||||||
grupos,
|
grupos,
|
||||||
onToggleNivel,
|
onToggleNivel,
|
||||||
onOpenTemplates,
|
onOpenTemplates,
|
||||||
|
onOpenSmartAvancado,
|
||||||
}) => {
|
}) => {
|
||||||
// Cores de fundo e borda para os grupos
|
// Cores de fundo e borda para os grupos
|
||||||
const corGrupoHeader: Record<string, string> = {
|
const corGrupoHeader: Record<string, string> = {
|
||||||
@@ -48,8 +50,20 @@ export const MatrizGrid: React.FC<MatrizGridProps> = ({
|
|||||||
colSpan={grupo.recursos.length}
|
colSpan={grupo.recursos.length}
|
||||||
className={`p-2.5 text-center border-r border-border/40 text-xs font-bold ${corGrupoHeader[grupo.cor]}`}
|
className={`p-2.5 text-center border-r border-border/40 text-xs font-bold ${corGrupoHeader[grupo.cor]}`}
|
||||||
>
|
>
|
||||||
<div className="flex items-center justify-center gap-1.5">
|
<div className="flex items-center justify-center gap-2 flex-wrap">
|
||||||
<span>{grupo.titulo}</span>
|
<span>{grupo.titulo}</span>
|
||||||
|
{grupo.key === 'smart' && onOpenSmartAvancado && (
|
||||||
|
<Button
|
||||||
|
size="sm"
|
||||||
|
variant="secondary"
|
||||||
|
onClick={onOpenSmartAvancado}
|
||||||
|
className="h-6 px-2 py-0 text-[10px] bg-emerald-500/20 hover:bg-emerald-500/30 text-emerald-300 border border-emerald-500/40 rounded-md font-semibold flex items-center gap-1 shadow-sm transition-transform active:scale-95"
|
||||||
|
title="Abrir Gestão Avançada de Privilégios e Notificações do Modo Smart"
|
||||||
|
>
|
||||||
|
<SlidersHorizontal className="h-3 w-3" />
|
||||||
|
Avançado
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
<span className="text-[10px] font-normal opacity-80 block truncate">
|
<span className="text-[10px] font-normal opacity-80 block truncate">
|
||||||
{grupo.descricao}
|
{grupo.descricao}
|
||||||
|
|||||||
@@ -0,0 +1,536 @@
|
|||||||
|
import React, { useState } from 'react';
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
|
DialogDescription,
|
||||||
|
} from '@/components/ui/dialog';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { Input } from '@/components/ui/input';
|
||||||
|
import { Badge } from '@/components/ui/badge';
|
||||||
|
import { Switch } from '@/components/ui/switch';
|
||||||
|
import { Label } from '@/components/ui/label';
|
||||||
|
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
|
||||||
|
import {
|
||||||
|
SlidersHorizontal,
|
||||||
|
Search,
|
||||||
|
CheckCircle2,
|
||||||
|
Save,
|
||||||
|
RotateCcw,
|
||||||
|
Shield,
|
||||||
|
Factory,
|
||||||
|
Eye,
|
||||||
|
Edit3,
|
||||||
|
Trash2,
|
||||||
|
Mail,
|
||||||
|
Phone,
|
||||||
|
MessageSquare,
|
||||||
|
AlertTriangle,
|
||||||
|
FileText,
|
||||||
|
Layers,
|
||||||
|
Flame,
|
||||||
|
Zap,
|
||||||
|
Box,
|
||||||
|
ExternalLink,
|
||||||
|
Truck,
|
||||||
|
Wrench,
|
||||||
|
FileSpreadsheet,
|
||||||
|
Info,
|
||||||
|
Sparkles,
|
||||||
|
Lock,
|
||||||
|
} from 'lucide-react';
|
||||||
|
import { useSmartPermissions } from '@/hooks/useSmartPermissions';
|
||||||
|
import { SMART_SUBMODULES } from '@/types/smartPermissions';
|
||||||
|
|
||||||
|
interface MatrizSmartAvancadoModalProps {
|
||||||
|
isOpen: boolean;
|
||||||
|
onClose: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const MatrizSmartAvancadoModal: React.FC<MatrizSmartAvancadoModalProps> = ({
|
||||||
|
isOpen,
|
||||||
|
onClose,
|
||||||
|
}) => {
|
||||||
|
const {
|
||||||
|
loading,
|
||||||
|
saving,
|
||||||
|
users,
|
||||||
|
selectedUserId,
|
||||||
|
setSelectedUserId,
|
||||||
|
selectedUser,
|
||||||
|
togglePermission,
|
||||||
|
updateNotificationConfig,
|
||||||
|
salvarConfiguracaoUsuario,
|
||||||
|
aplicarTemplateSmart,
|
||||||
|
recarregar,
|
||||||
|
} = useSmartPermissions();
|
||||||
|
|
||||||
|
const [busca, setBusca] = useState('');
|
||||||
|
|
||||||
|
const usersFiltrados = users.filter((u) => {
|
||||||
|
const termo = busca.toLowerCase();
|
||||||
|
return (
|
||||||
|
u.fullName.toLowerCase().includes(termo) ||
|
||||||
|
u.email.toLowerCase().includes(termo) ||
|
||||||
|
u.functionName.toLowerCase().includes(termo)
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
const getIconComponent = (icone: string) => {
|
||||||
|
switch (icone) {
|
||||||
|
case 'FileText':
|
||||||
|
return <FileText className="h-4 w-4 text-sky-400" />;
|
||||||
|
case 'Layers':
|
||||||
|
return <Layers className="h-4 w-4 text-indigo-400" />;
|
||||||
|
case 'Flame':
|
||||||
|
return <Flame className="h-4 w-4 text-orange-400" />;
|
||||||
|
case 'CheckCircle2':
|
||||||
|
return <CheckCircle2 className="h-4 w-4 text-emerald-400" />;
|
||||||
|
case 'Zap':
|
||||||
|
return <Zap className="h-4 w-4 text-amber-400" />;
|
||||||
|
case 'Box':
|
||||||
|
return <Box className="h-4 w-4 text-cyan-400" />;
|
||||||
|
case 'ExternalLink':
|
||||||
|
return <ExternalLink className="h-4 w-4 text-purple-400" />;
|
||||||
|
case 'Truck':
|
||||||
|
return <Truck className="h-4 w-4 text-amber-500" />;
|
||||||
|
case 'Wrench':
|
||||||
|
return <Wrench className="h-4 w-4 text-teal-400" />;
|
||||||
|
case 'FileSpreadsheet':
|
||||||
|
return <FileSpreadsheet className="h-4 w-4 text-emerald-500" />;
|
||||||
|
default:
|
||||||
|
return <Factory className="h-4 w-4 text-muted-foreground" />;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog open={isOpen} onOpenChange={(open) => !open && onClose()}>
|
||||||
|
<DialogContent className="max-w-6xl w-[96vw] max-h-[92vh] h-[880px] p-0 flex flex-col bg-card border-border shadow-2xl rounded-2xl overflow-hidden">
|
||||||
|
{/* CABEÇALHO DO MODAL */}
|
||||||
|
<div className="px-6 py-4 border-b border-border bg-muted/40 flex items-center justify-between">
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<div className="p-2.5 rounded-xl bg-emerald-500/10 text-emerald-400 border border-emerald-500/20">
|
||||||
|
<SlidersHorizontal className="h-5 w-5" />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<DialogTitle className="text-base sm:text-lg font-bold flex items-center gap-2">
|
||||||
|
Gestão Avançada de Privilégios & Notificações
|
||||||
|
<Badge variant="outline" className="bg-emerald-500/10 text-emerald-400 border-emerald-500/30 text-[10px] uppercase tracking-wider font-semibold">
|
||||||
|
Modo Smart
|
||||||
|
</Badge>
|
||||||
|
</DialogTitle>
|
||||||
|
<DialogDescription className="text-xs text-muted-foreground mt-0.5">
|
||||||
|
Controle granular de acesso por submódulo e canais de notificação (E-mail e WhatsApp via única).
|
||||||
|
</DialogDescription>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* CORPO PRINCIPAL COM SIDEBAR DE USUÁRIOS E ÁREA DE CONFIGURAÇÃO */}
|
||||||
|
<div className="flex-1 flex overflow-hidden">
|
||||||
|
{/* SIDEBAR DE USUÁRIOS */}
|
||||||
|
<div className="w-[300px] border-r border-border bg-background/50 flex flex-col">
|
||||||
|
<div className="p-3 border-b border-border">
|
||||||
|
<div className="relative">
|
||||||
|
<Search className="absolute left-2.5 top-2.5 h-3.5 w-3.5 text-muted-foreground" />
|
||||||
|
<Input
|
||||||
|
placeholder="Buscar colaborador..."
|
||||||
|
value={busca}
|
||||||
|
onChange={(e) => setBusca(e.target.value)}
|
||||||
|
className="pl-8 text-xs h-8 bg-card"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex-1 overflow-y-auto divide-y divide-border/40 p-1.5 space-y-0.5">
|
||||||
|
{loading ? (
|
||||||
|
<div className="py-12 text-center text-xs text-muted-foreground">
|
||||||
|
Carregando colaboradores...
|
||||||
|
</div>
|
||||||
|
) : usersFiltrados.length === 0 ? (
|
||||||
|
<div className="py-12 text-center text-xs text-muted-foreground">
|
||||||
|
Nenhum colaborador encontrado.
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
usersFiltrados.map((user) => {
|
||||||
|
const isSelected = user.userId === selectedUserId;
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
key={user.userId}
|
||||||
|
onClick={() => setSelectedUserId(user.userId)}
|
||||||
|
className={`w-full text-left p-2.5 rounded-xl transition-all flex items-center gap-2.5 ${
|
||||||
|
isSelected
|
||||||
|
? 'bg-emerald-500/15 border border-emerald-500/30 text-foreground shadow-sm'
|
||||||
|
: 'hover:bg-muted/50 text-muted-foreground hover:text-foreground'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<Avatar className="h-8 w-8 rounded-lg border border-border">
|
||||||
|
<AvatarImage src={user.profileImageUrl || ''} />
|
||||||
|
<AvatarFallback className="rounded-lg bg-primary/10 text-primary text-xs font-bold">
|
||||||
|
{user.fullName.substring(0, 2).toUpperCase()}
|
||||||
|
</AvatarFallback>
|
||||||
|
</Avatar>
|
||||||
|
<div className="min-w-0 flex-1">
|
||||||
|
<p className={`text-xs font-bold truncate ${isSelected ? 'text-emerald-400' : 'text-foreground'}`}>
|
||||||
|
{user.fullName}
|
||||||
|
</p>
|
||||||
|
<p className="text-[10px] text-muted-foreground truncate">
|
||||||
|
{user.functionName}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
{user.whatsappNumber && (
|
||||||
|
<div className="p-1 rounded-md bg-emerald-500/10 text-emerald-400" title={`WhatsApp: ${user.whatsappNumber}`}>
|
||||||
|
<MessageSquare className="h-3 w-3" />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
})
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* ÁREA DE CONFIGURAÇÃO DO USUÁRIO SELECIONADO */}
|
||||||
|
<div className="flex-1 flex flex-col bg-card overflow-y-auto">
|
||||||
|
{selectedUser ? (
|
||||||
|
<div className="p-6 space-y-6">
|
||||||
|
{/* CABEÇALHO DO USUÁRIO + AÇÕES RÁPIDAS */}
|
||||||
|
<div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 p-4 rounded-xl border border-border bg-muted/20">
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<Avatar className="h-12 w-12 rounded-xl border border-border shadow-sm">
|
||||||
|
<AvatarImage src={selectedUser.profileImageUrl || ''} />
|
||||||
|
<AvatarFallback className="rounded-xl bg-primary/10 text-primary text-sm font-bold">
|
||||||
|
{selectedUser.fullName.substring(0, 2).toUpperCase()}
|
||||||
|
</AvatarFallback>
|
||||||
|
</Avatar>
|
||||||
|
<div>
|
||||||
|
<h3 className="text-base font-bold text-foreground">
|
||||||
|
{selectedUser.fullName}
|
||||||
|
</h3>
|
||||||
|
<p className="text-xs text-muted-foreground flex items-center gap-2">
|
||||||
|
<span>{selectedUser.email}</span>
|
||||||
|
<span>•</span>
|
||||||
|
<span className="text-emerald-400 font-medium">{selectedUser.functionName}</span>
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* TEMPLATES E BOTÃO SALVAR */}
|
||||||
|
<div className="flex flex-wrap items-center gap-2">
|
||||||
|
<Button
|
||||||
|
size="sm"
|
||||||
|
variant="outline"
|
||||||
|
onClick={() => aplicarTemplateSmart(selectedUser.userId, 'operador')}
|
||||||
|
className="text-xs h-8 border-border hover:bg-muted"
|
||||||
|
title="Restringe para o padrão do chão de fábrica"
|
||||||
|
>
|
||||||
|
<Factory className="h-3.5 w-3.5 mr-1 text-emerald-400" />
|
||||||
|
Padrão Operador
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
size="sm"
|
||||||
|
variant="outline"
|
||||||
|
onClick={() => aplicarTemplateSmart(selectedUser.userId, 'admin')}
|
||||||
|
className="text-xs h-8 border-border hover:bg-muted"
|
||||||
|
title="Libera todos os 10 submódulos com acesso total"
|
||||||
|
>
|
||||||
|
<Shield className="h-3.5 w-3.5 mr-1 text-rose-400" />
|
||||||
|
Total Admin
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
size="sm"
|
||||||
|
onClick={() => salvarConfiguracaoUsuario(selectedUser.userId)}
|
||||||
|
disabled={saving}
|
||||||
|
className="text-xs h-8 bg-emerald-600 hover:bg-emerald-500 text-white font-semibold shadow-sm flex items-center gap-1.5"
|
||||||
|
>
|
||||||
|
<Save className={`h-3.5 w-3.5 ${saving ? 'animate-spin' : ''}`} />
|
||||||
|
{saving ? 'Salvando...' : 'Salvar Alterações'}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* SEÇÃO 1: MATRIZ DE ACESSO AOS SUBMÓDULOS */}
|
||||||
|
<div className="space-y-3">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<h4 className="text-xs font-bold uppercase tracking-wider text-muted-foreground flex items-center gap-1.5">
|
||||||
|
<Lock className="h-3.5 w-3.5 text-emerald-400" />
|
||||||
|
1. Permissões Granulares nos Submódulos (Modo Smart)
|
||||||
|
</h4>
|
||||||
|
<span className="text-[11px] text-muted-foreground">
|
||||||
|
Controle de Visualização, Edição/Apontamento e Exclusão
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="rounded-xl border border-border bg-background/50 overflow-hidden">
|
||||||
|
<table className="w-full text-left border-collapse">
|
||||||
|
<thead>
|
||||||
|
<tr className="border-b border-border/80 bg-muted/40 text-[11px] text-muted-foreground font-semibold">
|
||||||
|
<th className="p-3">Submódulo / Recurso</th>
|
||||||
|
<th className="p-3 text-center w-[110px]">
|
||||||
|
<span className="inline-flex items-center gap-1 text-sky-400">
|
||||||
|
<Eye className="h-3.5 w-3.5" />
|
||||||
|
Visualizar
|
||||||
|
</span>
|
||||||
|
</th>
|
||||||
|
<th className="p-3 text-center w-[120px]">
|
||||||
|
<span className="inline-flex items-center gap-1 text-emerald-400">
|
||||||
|
<Edit3 className="h-3.5 w-3.5" />
|
||||||
|
Apontar / Editar
|
||||||
|
</span>
|
||||||
|
</th>
|
||||||
|
<th className="p-3 text-center w-[110px]">
|
||||||
|
<span className="inline-flex items-center gap-1 text-rose-400">
|
||||||
|
<Trash2 className="h-3.5 w-3.5" />
|
||||||
|
Excluir
|
||||||
|
</span>
|
||||||
|
</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody className="divide-y divide-border/40 text-xs">
|
||||||
|
{SMART_SUBMODULES.map((sub) => {
|
||||||
|
const perm = selectedUser.permissions[sub.key] || {
|
||||||
|
can_view: false,
|
||||||
|
can_edit: false,
|
||||||
|
can_delete: false,
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<tr
|
||||||
|
key={sub.key}
|
||||||
|
className="hover:bg-muted/30 transition-colors"
|
||||||
|
>
|
||||||
|
<td className="p-3">
|
||||||
|
<div className="flex items-center gap-2.5">
|
||||||
|
<div className="p-1.5 rounded-lg bg-card border border-border/60">
|
||||||
|
{getIconComponent(sub.icone)}
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<p className="font-bold text-foreground text-xs">
|
||||||
|
{sub.nome}
|
||||||
|
</p>
|
||||||
|
<p className="text-[10px] text-muted-foreground">
|
||||||
|
{sub.descricao}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
|
||||||
|
{/* VISUALIZAR */}
|
||||||
|
<td className="p-3 text-center">
|
||||||
|
<div className="flex justify-center">
|
||||||
|
<Switch
|
||||||
|
checked={perm.can_view}
|
||||||
|
onCheckedChange={() =>
|
||||||
|
togglePermission(selectedUser.userId, sub.key, 'can_view')
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
|
||||||
|
{/* EDITAR / APONTAR */}
|
||||||
|
<td className="p-3 text-center">
|
||||||
|
<div className="flex justify-center">
|
||||||
|
<Switch
|
||||||
|
checked={perm.can_edit}
|
||||||
|
onCheckedChange={() =>
|
||||||
|
togglePermission(selectedUser.userId, sub.key, 'can_edit')
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
|
||||||
|
{/* EXCLUIR */}
|
||||||
|
<td className="p-3 text-center">
|
||||||
|
<div className="flex justify-center">
|
||||||
|
<Switch
|
||||||
|
checked={perm.can_delete}
|
||||||
|
onCheckedChange={() =>
|
||||||
|
togglePermission(selectedUser.userId, sub.key, 'can_delete')
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* SEÇÃO 2: NOTIFICAÇÕES & CANAL WHATSAPP VIA ÚNICA */}
|
||||||
|
<div className="space-y-4 pt-2">
|
||||||
|
<h4 className="text-xs font-bold uppercase tracking-wider text-muted-foreground flex items-center gap-1.5">
|
||||||
|
<MessageSquare className="h-3.5 w-3.5 text-emerald-400" />
|
||||||
|
2. Notificações do Usuário (E-mail & WhatsApp BrainSteel)
|
||||||
|
</h4>
|
||||||
|
|
||||||
|
{/* BANNER INFORMATIVO: REGRA DE VIA ÚNICA */}
|
||||||
|
<div className="p-3.5 rounded-xl border border-amber-500/30 bg-amber-500/10 text-amber-200 flex items-start gap-3">
|
||||||
|
<AlertTriangle className="h-5 w-5 text-amber-400 shrink-0 mt-0.5" />
|
||||||
|
<div className="text-xs space-y-1">
|
||||||
|
<p className="font-bold text-amber-300">
|
||||||
|
Comunicação Estritamente Unidirecional (Via Única) no WhatsApp
|
||||||
|
</p>
|
||||||
|
<p className="text-amber-200/90 leading-relaxed text-[11px]">
|
||||||
|
O número oficial da BrainSteel é configurado para <strong>somente enviar</strong> alertas, relatórios e métricas de produção. Mensagens de resposta enviadas pelo colaborador não serão recebidas nem respondidas pelo sistema.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* GRID DE CONFIGURAÇÕES DE CANAL */}
|
||||||
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||||
|
{/* CANAL WHATSAPP */}
|
||||||
|
<div className="p-4 rounded-xl border border-border bg-background/50 space-y-4">
|
||||||
|
<div className="flex items-center gap-2 text-emerald-400 font-bold text-xs">
|
||||||
|
<Phone className="h-4 w-4" />
|
||||||
|
Canal WhatsApp do Colaborador
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<Label className="text-[11px] text-muted-foreground">
|
||||||
|
Número de WhatsApp com DDD
|
||||||
|
</Label>
|
||||||
|
<Input
|
||||||
|
placeholder="Ex: 5511999998888 ou (11) 99999-8888"
|
||||||
|
value={selectedUser.whatsappNumber}
|
||||||
|
onChange={(e) =>
|
||||||
|
updateNotificationConfig(
|
||||||
|
selectedUser.userId,
|
||||||
|
'whatsappNumber',
|
||||||
|
e.target.value
|
||||||
|
)
|
||||||
|
}
|
||||||
|
className="h-8 text-xs bg-card"
|
||||||
|
/>
|
||||||
|
<span className="text-[10px] text-muted-foreground">
|
||||||
|
Informe o número com DDD para receber avisos automáticos.
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="pt-2 border-t border-border/40 space-y-3">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<div className="space-y-0.5">
|
||||||
|
<Label className="text-xs font-medium text-foreground">
|
||||||
|
Alertas de Apontamentos
|
||||||
|
</Label>
|
||||||
|
<p className="text-[10px] text-muted-foreground">
|
||||||
|
Notificar sobre novos apontamentos ou avanços forçados
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<Switch
|
||||||
|
checked={selectedUser.notifWhatsappApontamentos}
|
||||||
|
onCheckedChange={(val) =>
|
||||||
|
updateNotificationConfig(
|
||||||
|
selectedUser.userId,
|
||||||
|
'notifWhatsappApontamentos',
|
||||||
|
val
|
||||||
|
)
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<div className="space-y-0.5">
|
||||||
|
<Label className="text-xs font-medium text-foreground">
|
||||||
|
Resumo Diário de Métricas
|
||||||
|
</Label>
|
||||||
|
<p className="text-[10px] text-muted-foreground">
|
||||||
|
Receber fechamento diário de produção (peso e peças)
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<Switch
|
||||||
|
checked={selectedUser.notifWhatsappMetricas}
|
||||||
|
onCheckedChange={(val) =>
|
||||||
|
updateNotificationConfig(
|
||||||
|
selectedUser.userId,
|
||||||
|
'notifWhatsappMetricas',
|
||||||
|
val
|
||||||
|
)
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* CANAL E-MAIL */}
|
||||||
|
<div className="p-4 rounded-xl border border-border bg-background/50 space-y-4">
|
||||||
|
<div className="flex items-center gap-2 text-sky-400 font-bold text-xs">
|
||||||
|
<Mail className="h-4 w-4" />
|
||||||
|
Canal de E-mail ({selectedUser.email})
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-3 pt-2">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<div className="space-y-0.5">
|
||||||
|
<Label className="text-xs font-medium text-foreground">
|
||||||
|
Alertas de Apontamentos por E-mail
|
||||||
|
</Label>
|
||||||
|
<p className="text-[10px] text-muted-foreground">
|
||||||
|
Receber e-mail informativo a cada lote apontado
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<Switch
|
||||||
|
checked={selectedUser.notifEmailApontamentos}
|
||||||
|
onCheckedChange={(val) =>
|
||||||
|
updateNotificationConfig(
|
||||||
|
selectedUser.userId,
|
||||||
|
'notifEmailApontamentos',
|
||||||
|
val
|
||||||
|
)
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<div className="space-y-0.5">
|
||||||
|
<Label className="text-xs font-medium text-foreground">
|
||||||
|
Relatórios e Métricas por E-mail
|
||||||
|
</Label>
|
||||||
|
<p className="text-[10px] text-muted-foreground">
|
||||||
|
Receber resumos periódicos e PDFs automáticos
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<Switch
|
||||||
|
checked={selectedUser.notifEmailMetricas}
|
||||||
|
onCheckedChange={(val) =>
|
||||||
|
updateNotificationConfig(
|
||||||
|
selectedUser.userId,
|
||||||
|
'notifEmailMetricas',
|
||||||
|
val
|
||||||
|
)
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="flex-1 flex items-center justify-center text-xs text-muted-foreground">
|
||||||
|
Selecione um colaborador na barra lateral para configurar.
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* RODAPÉ DO MODAL */}
|
||||||
|
<div className="px-6 py-3 border-t border-border bg-muted/40 flex items-center justify-between text-xs">
|
||||||
|
<span className="text-muted-foreground text-[11px]">
|
||||||
|
As alterações passam a valer imediatamente no Modo Smart após salvar.
|
||||||
|
</span>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
onClick={onClose}
|
||||||
|
className="text-xs h-8"
|
||||||
|
>
|
||||||
|
Fechar
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -0,0 +1,235 @@
|
|||||||
|
import { useState, useEffect, useCallback } from 'react';
|
||||||
|
import { supabase } from '@/integrations/supabase/client';
|
||||||
|
import { toast } from 'sonner';
|
||||||
|
import { SMART_SUBMODULES, SmartUserConfig } from '@/types/smartPermissions';
|
||||||
|
|
||||||
|
export function useSmartPermissions() {
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [saving, setSaving] = useState(false);
|
||||||
|
const [users, setUsers] = useState<SmartUserConfig[]>([]);
|
||||||
|
const [selectedUserId, setSelectedUserId] = useState<string | null>(null);
|
||||||
|
|
||||||
|
const carregarDados = useCallback(async () => {
|
||||||
|
try {
|
||||||
|
setLoading(true);
|
||||||
|
|
||||||
|
// 1. Carregar profiles com functions
|
||||||
|
const { data: profiles, error: profError } = await (supabase as any)
|
||||||
|
.from('profiles')
|
||||||
|
.select(`
|
||||||
|
id,
|
||||||
|
email,
|
||||||
|
full_name,
|
||||||
|
profile_image_url,
|
||||||
|
whatsapp_number,
|
||||||
|
notif_email_apontamentos,
|
||||||
|
notif_email_metricas,
|
||||||
|
notif_whatsapp_apontamentos,
|
||||||
|
notif_whatsapp_metricas,
|
||||||
|
functions:function_id ( name )
|
||||||
|
`)
|
||||||
|
.order('full_name', { ascending: true });
|
||||||
|
|
||||||
|
if (profError) throw profError;
|
||||||
|
|
||||||
|
// 2. Carregar permissões da tabela smart_user_permissions
|
||||||
|
const { data: perms, error: permError } = await (supabase as any)
|
||||||
|
.from('smart_user_permissions')
|
||||||
|
.select('*');
|
||||||
|
|
||||||
|
if (permError) throw permError;
|
||||||
|
|
||||||
|
// Montar mapa de permissões por usuário
|
||||||
|
const permsByUser: Record<string, Record<string, { can_view: boolean; can_edit: boolean; can_delete: boolean }>> = {};
|
||||||
|
|
||||||
|
(perms || []).forEach((p: any) => {
|
||||||
|
if (!permsByUser[p.user_id]) {
|
||||||
|
permsByUser[p.user_id] = {};
|
||||||
|
}
|
||||||
|
permsByUser[p.user_id][p.resource_key] = {
|
||||||
|
can_view: Boolean(p.can_view),
|
||||||
|
can_edit: Boolean(p.can_edit),
|
||||||
|
can_delete: Boolean(p.can_delete),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
const formattedUsers: SmartUserConfig[] = (profiles || []).map((prof: any) => {
|
||||||
|
const userPerms = permsByUser[prof.id] || {};
|
||||||
|
const mergedPerms: Record<string, { can_view: boolean; can_edit: boolean; can_delete: boolean }> = {};
|
||||||
|
|
||||||
|
SMART_SUBMODULES.forEach((sub) => {
|
||||||
|
if (userPerms[sub.key]) {
|
||||||
|
mergedPerms[sub.key] = userPerms[sub.key];
|
||||||
|
} else {
|
||||||
|
// Default fallback
|
||||||
|
mergedPerms[sub.key] = { ...sub.padraoOperador };
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
userId: prof.id,
|
||||||
|
email: prof.email || '',
|
||||||
|
fullName: prof.full_name || prof.email?.split('@')[0] || 'Sem Nome',
|
||||||
|
functionName: prof.functions?.name || 'Não atribuído',
|
||||||
|
profileImageUrl: prof.profile_image_url,
|
||||||
|
whatsappNumber: prof.whatsapp_number || '',
|
||||||
|
notifEmailApontamentos: prof.notif_email_apontamentos !== false,
|
||||||
|
notifEmailMetricas: prof.notif_email_metricas !== false,
|
||||||
|
notifWhatsappApontamentos: prof.notif_whatsapp_apontamentos !== false,
|
||||||
|
notifWhatsappMetricas: prof.notif_whatsapp_metricas !== false,
|
||||||
|
permissions: mergedPerms,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
setUsers(formattedUsers);
|
||||||
|
if (formattedUsers.length > 0 && !selectedUserId) {
|
||||||
|
setSelectedUserId(formattedUsers[0].userId);
|
||||||
|
}
|
||||||
|
} catch (err: any) {
|
||||||
|
console.error('Erro ao carregar permissões do Modo Smart:', err);
|
||||||
|
toast.error('Não foi possível carregar as permissões do Modo Smart.');
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
}, [selectedUserId]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
carregarDados();
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const selectedUser = users.find((u) => u.userId === selectedUserId) || null;
|
||||||
|
|
||||||
|
// Atualizar permissão no estado local
|
||||||
|
const togglePermission = (
|
||||||
|
userId: string,
|
||||||
|
resourceKey: string,
|
||||||
|
field: 'can_view' | 'can_edit' | 'can_delete'
|
||||||
|
) => {
|
||||||
|
setUsers((prev) =>
|
||||||
|
prev.map((u) => {
|
||||||
|
if (u.userId !== userId) return u;
|
||||||
|
const current = u.permissions[resourceKey] || { can_view: false, can_edit: false, can_delete: false };
|
||||||
|
const updated = {
|
||||||
|
...current,
|
||||||
|
[field]: !current[field],
|
||||||
|
};
|
||||||
|
// Se desativar visualizar, desativa edição e exclusão por coerência
|
||||||
|
if (field === 'can_view' && !updated.can_view) {
|
||||||
|
updated.can_edit = false;
|
||||||
|
updated.can_delete = false;
|
||||||
|
}
|
||||||
|
// Se ativar edição ou exclusão, ativa automaticamente visualizar
|
||||||
|
if ((field === 'can_edit' || field === 'can_delete') && updated[field]) {
|
||||||
|
updated.can_view = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
...u,
|
||||||
|
permissions: {
|
||||||
|
...u.permissions,
|
||||||
|
[resourceKey]: updated,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
})
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
// Atualizar dados de notificação no estado local
|
||||||
|
const updateNotificationConfig = (
|
||||||
|
userId: string,
|
||||||
|
field: 'whatsappNumber' | 'notifEmailApontamentos' | 'notifEmailMetricas' | 'notifWhatsappApontamentos' | 'notifWhatsappMetricas',
|
||||||
|
value: any
|
||||||
|
) => {
|
||||||
|
setUsers((prev) =>
|
||||||
|
prev.map((u) => (u.userId === userId ? { ...u, [field]: value } : u))
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
// Salvar permissões e perfil do usuário no banco
|
||||||
|
const salvarConfiguracaoUsuario = async (userId: string) => {
|
||||||
|
const userToSave = users.find((u) => u.userId === userId);
|
||||||
|
if (!userToSave) return;
|
||||||
|
|
||||||
|
try {
|
||||||
|
setSaving(true);
|
||||||
|
|
||||||
|
// 1. Atualizar Profile
|
||||||
|
const { error: profError } = await (supabase as any)
|
||||||
|
.from('profiles')
|
||||||
|
.update({
|
||||||
|
whatsapp_number: userToSave.whatsappNumber.trim() || null,
|
||||||
|
notif_email_apontamentos: userToSave.notifEmailApontamentos,
|
||||||
|
notif_email_metricas: userToSave.notifEmailMetricas,
|
||||||
|
notif_whatsapp_apontamentos: userToSave.notifWhatsappApontamentos,
|
||||||
|
notif_whatsapp_metricas: userToSave.notifWhatsappMetricas,
|
||||||
|
updated_at: new Date().toISOString(),
|
||||||
|
})
|
||||||
|
.eq('id', userId);
|
||||||
|
|
||||||
|
if (profError) throw profError;
|
||||||
|
|
||||||
|
// 2. Fazer Upsert das permissões na tabela smart_user_permissions
|
||||||
|
const rowsToUpsert = Object.entries(userToSave.permissions).map(([resource_key, perm]) => ({
|
||||||
|
user_id: userId,
|
||||||
|
resource_key,
|
||||||
|
can_view: perm.can_view,
|
||||||
|
can_edit: perm.can_edit,
|
||||||
|
can_delete: perm.can_delete,
|
||||||
|
updated_at: new Date().toISOString(),
|
||||||
|
}));
|
||||||
|
|
||||||
|
const { error: permError } = await (supabase as any)
|
||||||
|
.from('smart_user_permissions')
|
||||||
|
.upsert(rowsToUpsert, { onConflict: 'user_id,resource_key' });
|
||||||
|
|
||||||
|
if (permError) throw permError;
|
||||||
|
|
||||||
|
toast.success(`Configurações de ${userToSave.fullName} salvas com sucesso!`);
|
||||||
|
} catch (err: any) {
|
||||||
|
console.error('Erro ao salvar configurações do Modo Smart:', err);
|
||||||
|
toast.error('Erro ao salvar configurações: ' + (err.message || 'Falha na requisição'));
|
||||||
|
} finally {
|
||||||
|
setSaving(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Aplicar Template Padrão (Chão de Fábrica ou Administrador)
|
||||||
|
const aplicarTemplateSmart = (userId: string, tipo: 'operador' | 'admin' | 'leitura') => {
|
||||||
|
setUsers((prev) =>
|
||||||
|
prev.map((u) => {
|
||||||
|
if (u.userId !== userId) return u;
|
||||||
|
const newPerms: Record<string, { can_view: boolean; can_edit: boolean; can_delete: boolean }> = {};
|
||||||
|
|
||||||
|
SMART_SUBMODULES.forEach((sub) => {
|
||||||
|
if (tipo === 'operador') {
|
||||||
|
newPerms[sub.key] = { ...sub.padraoOperador };
|
||||||
|
} else if (tipo === 'admin') {
|
||||||
|
newPerms[sub.key] = { can_view: true, can_edit: true, can_delete: true };
|
||||||
|
} else if (tipo === 'leitura') {
|
||||||
|
newPerms[sub.key] = { can_view: true, can_edit: false, can_delete: false };
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
...u,
|
||||||
|
permissions: newPerms,
|
||||||
|
};
|
||||||
|
})
|
||||||
|
);
|
||||||
|
toast.info(`Template ${tipo.toUpperCase()} aplicado na tela. Clique em "Salvar" para confirmar.`);
|
||||||
|
};
|
||||||
|
|
||||||
|
return {
|
||||||
|
loading,
|
||||||
|
saving,
|
||||||
|
users,
|
||||||
|
selectedUserId,
|
||||||
|
setSelectedUserId,
|
||||||
|
selectedUser,
|
||||||
|
togglePermission,
|
||||||
|
updateNotificationConfig,
|
||||||
|
salvarConfiguracaoUsuario,
|
||||||
|
aplicarTemplateSmart,
|
||||||
|
recarregar: carregarDados,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
import { useState, useEffect } from 'react';
|
||||||
|
import { useAuth } from '@/hooks/useAuth';
|
||||||
|
import { supabase } from '@/integrations/supabase/client';
|
||||||
|
import { SMART_SUBMODULES } from '@/types/smartPermissions';
|
||||||
|
|
||||||
|
export function useUserSmartAccess() {
|
||||||
|
const { user } = useAuth();
|
||||||
|
const [permissions, setPermissions] = useState<
|
||||||
|
Record<string, { can_view: boolean; can_edit: boolean; can_delete: boolean }>
|
||||||
|
>({});
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
let mounted = true;
|
||||||
|
|
||||||
|
async function loadPermissions() {
|
||||||
|
if (!user) {
|
||||||
|
setLoading(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
setLoading(true);
|
||||||
|
const { data, error } = await (supabase as any)
|
||||||
|
.from('smart_user_permissions')
|
||||||
|
.select('resource_key, can_view, can_edit, can_delete')
|
||||||
|
.eq('user_id', user.id);
|
||||||
|
|
||||||
|
if (error) throw error;
|
||||||
|
|
||||||
|
const permsMap: Record<
|
||||||
|
string,
|
||||||
|
{ can_view: boolean; can_edit: boolean; can_delete: boolean }
|
||||||
|
> = {};
|
||||||
|
|
||||||
|
// Preenche com padrão do operador primeiro
|
||||||
|
SMART_SUBMODULES.forEach((sub) => {
|
||||||
|
permsMap[sub.key] = { ...sub.padraoOperador };
|
||||||
|
});
|
||||||
|
|
||||||
|
// Sobrescreve com as regras salvas para este usuário
|
||||||
|
(data || []).forEach((row: any) => {
|
||||||
|
permsMap[row.resource_key] = {
|
||||||
|
can_view: Boolean(row.can_view),
|
||||||
|
can_edit: Boolean(row.can_edit),
|
||||||
|
can_delete: Boolean(row.can_delete),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
if (mounted) {
|
||||||
|
setPermissions(permsMap);
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Erro ao carregar permissões do usuário para o Modo Smart:', err);
|
||||||
|
} finally {
|
||||||
|
if (mounted) setLoading(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
loadPermissions();
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
mounted = false;
|
||||||
|
};
|
||||||
|
}, [user]);
|
||||||
|
|
||||||
|
const canView = (key: string) => permissions[key]?.can_view ?? true;
|
||||||
|
const canEdit = (key: string) => permissions[key]?.can_edit ?? false;
|
||||||
|
const canDelete = (key: string) => permissions[key]?.can_delete ?? false;
|
||||||
|
|
||||||
|
return {
|
||||||
|
loading,
|
||||||
|
permissions,
|
||||||
|
canView,
|
||||||
|
canEdit,
|
||||||
|
canDelete,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,107 @@
|
|||||||
|
export interface SmartSubmodule {
|
||||||
|
key: string;
|
||||||
|
nome: string;
|
||||||
|
descricao: string;
|
||||||
|
icone: string;
|
||||||
|
padraoOperador: {
|
||||||
|
can_view: boolean;
|
||||||
|
can_edit: boolean;
|
||||||
|
can_delete: boolean;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export const SMART_SUBMODULES: SmartSubmodule[] = [
|
||||||
|
{
|
||||||
|
key: 'smart_of',
|
||||||
|
nome: 'Ordens de Fabricação (OF)',
|
||||||
|
descricao: 'Acesso à seleção, listagem e busca de OFs ativas',
|
||||||
|
icone: 'FileText',
|
||||||
|
padraoOperador: { can_view: true, can_edit: false, can_delete: false },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'smart_fases',
|
||||||
|
nome: 'Fases & Etapas da Obra',
|
||||||
|
descricao: 'Filtro e navegação pelas etapas/fases de fabricação',
|
||||||
|
icone: 'Layers',
|
||||||
|
padraoOperador: { can_view: true, can_edit: false, can_delete: false },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'smart_processos',
|
||||||
|
nome: 'Processos de Fabricação',
|
||||||
|
descricao: 'Visualização e seleção de processos (Corte, Solda, Pintura, etc.)',
|
||||||
|
icone: 'Flame',
|
||||||
|
padraoOperador: { can_view: true, can_edit: false, can_delete: false },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'smart_apontamento',
|
||||||
|
nome: 'Apontamento de Peças',
|
||||||
|
descricao: 'Realização de apontamentos normais de produção no chão de fábrica',
|
||||||
|
icone: 'CheckCircle2',
|
||||||
|
padraoOperador: { can_view: true, can_edit: true, can_delete: false },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'smart_forcar_apontamento',
|
||||||
|
nome: 'Forçar Apontamento (Avanço sem restrição)',
|
||||||
|
descricao: 'Permissão para avançar peças furando fila ou com pendências de processos anteriores',
|
||||||
|
icone: 'Zap',
|
||||||
|
padraoOperador: { can_view: false, can_edit: false, can_delete: false },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'smart_3d',
|
||||||
|
nome: 'Modelo 3D BIM',
|
||||||
|
descricao: 'Visualizador interativo 3D de peças, montagens e conjuntos',
|
||||||
|
icone: 'Box',
|
||||||
|
padraoOperador: { can_view: true, can_edit: false, can_delete: false },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'smart_modo_completo',
|
||||||
|
nome: 'Acesso ao Modo Completo ERP',
|
||||||
|
descricao: 'Permissão para alternar da interface touch para o ERP gerencial',
|
||||||
|
icone: 'ExternalLink',
|
||||||
|
padraoOperador: { can_view: false, can_edit: false, can_delete: false },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'smart_romaneios',
|
||||||
|
nome: 'Romaneios & Embarque',
|
||||||
|
descricao: 'Acesso e conferência de romaneios de expedição de peças',
|
||||||
|
icone: 'Truck',
|
||||||
|
padraoOperador: { can_view: true, can_edit: false, can_delete: false },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'smart_montagem',
|
||||||
|
nome: 'Montagem & Canteiro',
|
||||||
|
descricao: 'Apontamentos e checklists de montagem externa',
|
||||||
|
icone: 'Wrench',
|
||||||
|
padraoOperador: { can_view: true, can_edit: true, can_delete: false },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'smart_relatorios',
|
||||||
|
nome: 'Relatórios & Exportação PDF',
|
||||||
|
descricao: 'Geração de resumos de produção, checklists e exportação de relatórios',
|
||||||
|
icone: 'FileSpreadsheet',
|
||||||
|
padraoOperador: { can_view: true, can_edit: true, can_delete: false },
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
export interface SmartUserPermission {
|
||||||
|
id?: string;
|
||||||
|
user_id: string;
|
||||||
|
resource_key: string;
|
||||||
|
can_view: boolean;
|
||||||
|
can_edit: boolean;
|
||||||
|
can_delete: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SmartUserConfig {
|
||||||
|
userId: string;
|
||||||
|
email: string;
|
||||||
|
fullName: string;
|
||||||
|
functionName: string;
|
||||||
|
profileImageUrl: string | null;
|
||||||
|
whatsappNumber: string;
|
||||||
|
notifEmailApontamentos: boolean;
|
||||||
|
notifEmailMetricas: boolean;
|
||||||
|
notifWhatsappApontamentos: boolean;
|
||||||
|
notifWhatsappMetricas: boolean;
|
||||||
|
permissions: Record<string, { can_view: boolean; can_edit: boolean; can_delete: boolean }>;
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user