Emp perfis #25

Merged
killer-cf merged 4 commits from emp-perfis into master 2025-11-15 00:58:00 +00:00
25 changed files with 1584 additions and 1608 deletions

View File

@@ -1,74 +1,74 @@
<script lang="ts">
import { useConvexClient } from "convex-svelte";
import {
ExternalLink,
FileText,
File as FileIcon,
Upload,
Trash2,
Eye,
RefreshCw,
} from "lucide-svelte";
import { useConvexClient } from 'convex-svelte';
import { resolve } from '$app/paths';
import {
ExternalLink,
FileText,
File as FileIcon,
Upload,
Trash2,
Eye,
RefreshCw
} from 'lucide-svelte';
interface Props {
label: string;
helpUrl?: string;
value?: string; // storageId
disabled?: boolean;
required?: boolean;
onUpload: (file: globalThis.File) => Promise<void>;
onRemove: () => Promise<void>;
}
interface Props {
label: string;
helpUrl?: string;
value?: string; // storageId
disabled?: boolean;
required?: boolean;
onUpload: (file: globalThis.File) => Promise<void>;
onRemove: () => Promise<void>;
}
let {
label,
helpUrl,
value = $bindable(),
disabled = false,
required = false,
onUpload,
onRemove,
}: Props = $props();
let {
label,
helpUrl,
value = $bindable(),
disabled = false,
required = false,
onUpload,
onRemove
}: Props = $props();
const client = useConvexClient();
const client = useConvexClient() as unknown as {
storage: {
getUrl: (id: string) => Promise<string | null>;
};
};
let fileInput: HTMLInputElement;
let uploading = $state(false);
let error = $state<string | null>(null);
let fileName = $state<string>("");
let fileType = $state<string>("");
let previewUrl = $state<string | null>(null);
let fileUrl = $state<string | null>(null);
let fileInput: HTMLInputElement;
let uploading = $state(false);
let error = $state<string | null>(null);
let fileName = $state<string>('');
let fileType = $state<string>('');
let previewUrl = $state<string | null>(null);
let fileUrl = $state<string | null>(null);
const MAX_FILE_SIZE = 10 * 1024 * 1024; // 10MB
const ALLOWED_TYPES = [
"application/pdf",
"image/jpeg",
"image/jpg",
"image/png",
];
const MAX_FILE_SIZE = 10 * 1024 * 1024; // 10MB
const ALLOWED_TYPES = ['application/pdf', 'image/jpeg', 'image/jpg', 'image/png'];
// Buscar URL do arquivo quando houver um storageId
$effect(() => {
if (value && !fileName) {
// Tem storageId mas não é um upload recente
loadExistingFile(value);
void loadExistingFile(value);
}
});
async function loadExistingFile(storageId: string) {
try {
const url = await client.storage.getUrl(storageId as any);
const url = await client.storage.getUrl(storageId);
if (url) {
async function handleFileSelect(event: Event) {
const target = event.target as HTMLInputElement;
const file = target.files?.[0];
fileUrl = url;
// Detectar tipo pelo URL ou assumir PDF
if (url.includes('.pdf') || url.includes('application/pdf')) {
fileType = 'application/pdf';
} else {
fileType = 'image/jpeg';
previewUrl = url; // Para imagens, a URL serve como preview
// Para imagens, a URL serve como preview
previewUrl = url;
}
}
} catch (err) {
@@ -76,111 +76,130 @@
}
}
error = null;
async function handleFileSelect(event: Event) {
const target = event.target as HTMLInputElement;
const file = target.files?.[0];
// Validate file size
if (file.size > MAX_FILE_SIZE) {
error = "Arquivo muito grande. Tamanho máximo: 10MB";
target.value = "";
return;
}
if (!file) {
return;
}
// Validate file type
if (!ALLOWED_TYPES.includes(file.type)) {
error = "Tipo de arquivo não permitido. Use PDF ou imagens (JPG, PNG)";
target.value = "";
return;
}
error = null;
try {
uploading = true;
fileName = file.name;
fileType = file.type;
// Validate file size
if (file.size > MAX_FILE_SIZE) {
error = 'Arquivo muito grande. Tamanho máximo: 10MB';
target.value = '';
return;
}
// Create preview for images
if (file.type.startsWith("image/")) {
const reader = new FileReader();
reader.onload = (e) => {
previewUrl = e.target?.result as string;
};
reader.readAsDataURL(file);
}
// Validate file type
if (!ALLOWED_TYPES.includes(file.type)) {
error = 'Tipo de arquivo não permitido. Use PDF ou imagens (JPG, PNG)';
target.value = '';
return;
}
await onUpload(file);
} catch (err: any) {
error = err?.message || "Erro ao fazer upload do arquivo";
previewUrl = null;
} finally {
uploading = false;
target.value = "";
}
}
try {
uploading = true;
fileName = file.name;
fileType = file.type;
async function handleRemove() {
if (!confirm("Tem certeza que deseja remover este arquivo?")) {
return;
}
// Create preview for images
if (file.type.startsWith('image/')) {
const reader = new FileReader();
reader.onload = (e) => {
const result = e.target?.result;
if (typeof result === 'string') {
previewUrl = result;
}
};
reader.readAsDataURL(file);
} else {
previewUrl = null;
}
try {
uploading = true;
await onRemove();
fileName = "";
fileType = "";
previewUrl = null;
fileUrl = null;
} catch (err: any) {
error = err?.message || "Erro ao remover arquivo";
} finally {
uploading = false;
}
}
await onUpload(file);
} catch (err: unknown) {
if (err instanceof Error) {
error = err.message || 'Erro ao fazer upload do arquivo';
} else {
error = 'Erro ao fazer upload do arquivo';
}
previewUrl = null;
} finally {
uploading = false;
target.value = '';
}
}
function handleView() {
if (fileUrl) {
window.open(fileUrl, "_blank");
}
}
async function handleRemove() {
if (!confirm('Tem certeza que deseja remover este arquivo?')) {
return;
}
function openFileDialog() {
fileInput?.click();
}
try {
uploading = true;
await onRemove();
fileName = '';
fileType = '';
previewUrl = null;
fileUrl = null;
error = null;
} catch (err: unknown) {
if (err instanceof Error) {
error = err.message || 'Erro ao remover arquivo';
} else {
error = 'Erro ao remover arquivo';
}
} finally {
uploading = false;
}
}
function handleView() {
if (fileUrl) {
window.open(fileUrl, '_blank');
}
}
function openFileDialog() {
fileInput?.click();
}
</script>
<div class="form-control w-full">
<label class="label" for="file-upload-input">
<span class="label-text font-medium flex items-center gap-2">
{label}
{#if required}
<span class="text-error">*</span>
{/if}
{#if helpUrl}
<div
class="tooltip tooltip-right"
data-tip="Clique para acessar o link"
>
<a
href={helpUrl}
target="_blank"
rel="noopener noreferrer"
class="text-primary hover:text-primary-focus transition-colors"
aria-label="Acessar link"
>
<ExternalLink class="h-4 w-4" strokeWidth={2} />
</a>
</div>
{/if}
</span>
</label>
<label class="label" for="file-upload-input">
<span class="label-text flex items-center gap-2 font-medium">
{label}
{#if required}
<span class="text-error">*</span>
{/if}
{#if helpUrl}
<div class="tooltip tooltip-right" data-tip="Clique para acessar o link">
<a
href={resolve(helpUrl)}
target="_blank"
rel="noopener noreferrer"
class="text-primary hover:text-primary-focus transition-colors"
aria-label="Acessar link"
>
<ExternalLink class="h-4 w-4" strokeWidth={2} />
</a>
</div>
{/if}
</span>
</label>
<input
id="file-upload-input"
type="file"
bind:this={fileInput}
onchange={handleFileSelect}
accept=".pdf,.jpg,.jpeg,.png"
class="hidden"
{disabled}
/>
<input
id="file-upload-input"
type="file"
bind:this={fileInput}
onchange={handleFileSelect}
accept=".pdf,.jpg,.jpeg,.png"
class="hidden"
{disabled}
/>
{#if value || fileName}
<div class="border-base-300 bg-base-100 flex items-center gap-2 rounded-lg border p-3">
@@ -194,78 +213,78 @@
</div>
{:else}
<div class="bg-success/10 flex h-12 w-12 items-center justify-center rounded">
<File class="text-success h-6 w-6" strokeWidth={2} />
<FileIcon class="text-success h-6 w-6" strokeWidth={2} />
</div>
{/if}
</div>
<!-- File info -->
<div class="flex-1 min-w-0">
<p class="text-sm font-medium truncate">
{fileName || "Arquivo anexado"}
</p>
<p class="text-xs text-base-content/60">
{#if uploading}
Carregando...
{:else}
Enviado com sucesso
{/if}
</p>
</div>
<!-- File info -->
<div class="min-w-0 flex-1">
<p class="truncate text-sm font-medium">
{fileName || 'Arquivo anexado'}
</p>
<p class="text-base-content/60 text-xs">
{#if uploading}
Carregando...
{:else}
Enviado com sucesso
{/if}
</p>
</div>
<!-- Actions -->
<div class="flex gap-2">
{#if fileUrl}
<button
type="button"
onclick={handleView}
class="btn btn-sm btn-ghost text-info"
disabled={uploading || disabled}
title="Visualizar arquivo"
>
<Eye class="h-4 w-4" strokeWidth={2} />
</button>
{/if}
<button
type="button"
onclick={openFileDialog}
class="btn btn-sm btn-ghost"
disabled={uploading || disabled}
title="Substituir arquivo"
>
<RefreshCw class="h-4 w-4" strokeWidth={2} />
</button>
<button
type="button"
onclick={handleRemove}
class="btn btn-sm btn-ghost text-error"
disabled={uploading || disabled}
title="Remover arquivo"
>
<Trash2 class="h-4 w-4" strokeWidth={2} />
</button>
</div>
</div>
{:else}
<button
type="button"
onclick={openFileDialog}
class="btn btn-outline btn-block justify-start gap-2"
disabled={uploading || disabled}
>
{#if uploading}
<span class="loading loading-spinner loading-sm"></span>
Carregando...
{:else}
<Upload class="h-5 w-5" strokeWidth={2} />
Selecionar arquivo (PDF ou imagem, máx. 10MB)
{/if}
</button>
{/if}
<!-- Actions -->
<div class="flex gap-2">
{#if fileUrl}
<button
type="button"
onclick={handleView}
class="btn btn-sm btn-ghost text-info"
disabled={uploading || disabled}
title="Visualizar arquivo"
>
<Eye class="h-4 w-4" strokeWidth={2} />
</button>
{/if}
<button
type="button"
onclick={openFileDialog}
class="btn btn-sm btn-ghost"
disabled={uploading || disabled}
title="Substituir arquivo"
>
<RefreshCw class="h-4 w-4" strokeWidth={2} />
</button>
<button
type="button"
onclick={handleRemove}
class="btn btn-sm btn-ghost text-error"
disabled={uploading || disabled}
title="Remover arquivo"
>
<Trash2 class="h-4 w-4" strokeWidth={2} />
</button>
</div>
</div>
{:else}
<button
type="button"
onclick={openFileDialog}
class="btn btn-outline btn-block justify-start gap-2"
disabled={uploading || disabled}
>
{#if uploading}
<span class="loading loading-spinner loading-sm"></span>
Carregando...
{:else}
<Upload class="h-5 w-5" strokeWidth={2} />
Selecionar arquivo (PDF ou imagem, máx. 10MB)
{/if}
</button>
{/if}
{#if error}
<div class="label">
<span class="label-text-alt text-error">{error}</span>
</div>
{/if}
{#if error}
<div class="label">
<span class="label-text-alt text-error">{error}</span>
</div>
{/if}
</div>

View File

@@ -1,80 +1,77 @@
<script lang="ts">
import { useQuery } from "convex-svelte";
import { api } from "@sgse-app/backend/convex/_generated/api";
import { onMount } from "svelte";
import { page } from "$app/stores";
import type { Snippet } from "svelte";
import { useQuery } from 'convex-svelte';
import { api } from '@sgse-app/backend/convex/_generated/api';
import { onMount } from 'svelte';
import type { Snippet } from 'svelte';
let {
children,
requireAuth = true,
allowedRoles = [],
maxLevel = 3,
redirectTo = "/",
}: {
children: Snippet;
requireAuth?: boolean;
allowedRoles?: string[];
maxLevel?: number;
redirectTo?: string;
} = $props();
let {
children,
requireAuth = true,
allowedRoles = [],
maxLevel = 3,
redirectTo = '/'
}: {
children: Snippet;
requireAuth?: boolean;
allowedRoles?: string[];
maxLevel?: number;
redirectTo?: string;
} = $props();
let isChecking = $state(true);
let hasAccess = $state(false);
const currentUser = useQuery(api.auth.getCurrentUser, {});
let isChecking = $state(true);
let hasAccess = $state(false);
const currentUser = useQuery(api.auth.getCurrentUser, {});
onMount(() => {
checkAccess();
});
onMount(() => {
checkAccess();
});
function checkAccess() {
isChecking = true;
function checkAccess() {
isChecking = true;
// Aguardar um pouco para o authStore carregar do localStorage
setTimeout(() => {
// Verificar autenticação
if (requireAuth && !currentUser?.data) {
const currentPath = window.location.pathname;
window.location.href = `${redirectTo}?error=auth_required&redirect=${encodeURIComponent(currentPath)}`;
return;
}
// Aguardar um pouco para o authStore carregar do localStorage
setTimeout(() => {
// Verificar autenticação
if (requireAuth && !currentUser?.data) {
const currentPath = window.location.pathname;
window.location.href = `${redirectTo}?error=auth_required&redirect=${encodeURIComponent(currentPath)}`;
return;
}
// Verificar roles
if (allowedRoles.length > 0 && currentUser?.data) {
const hasRole = allowedRoles.includes(
currentUser.data.role?.nome ?? "",
);
if (!hasRole) {
const currentPath = window.location.pathname;
window.location.href = `${redirectTo}?error=access_denied&route=${encodeURIComponent(currentPath)}`;
return;
}
}
// Verificar roles
if (allowedRoles.length > 0 && currentUser?.data) {
const hasRole = allowedRoles.includes(currentUser.data.role?.nome ?? '');
if (!hasRole) {
const currentPath = window.location.pathname;
window.location.href = `${redirectTo}?error=access_denied&route=${encodeURIComponent(currentPath)}`;
return;
}
}
// Verificar nível
if (
currentUser?.data &&
currentUser.data.role?.nivel &&
currentUser.data.role.nivel > maxLevel
) {
const currentPath = window.location.pathname;
window.location.href = `${redirectTo}?error=access_denied&route=${encodeURIComponent(currentPath)}`;
return;
}
// Verificar nível
if (
currentUser?.data &&
currentUser.data.role?.nivel &&
currentUser.data.role.nivel > maxLevel
) {
const currentPath = window.location.pathname;
window.location.href = `${redirectTo}?error=access_denied&route=${encodeURIComponent(currentPath)}`;
return;
}
hasAccess = true;
isChecking = false;
}, 100);
}
hasAccess = true;
isChecking = false;
}, 100);
}
</script>
{#if isChecking}
<div class="flex justify-center items-center min-h-screen">
<div class="text-center">
<span class="loading loading-spinner loading-lg text-primary"></span>
<p class="mt-4 text-base-content/70">Verificando permissões...</p>
</div>
</div>
<div class="flex min-h-screen items-center justify-center">
<div class="text-center">
<span class="loading loading-spinner loading-lg text-primary"></span>
<p class="text-base-content/70 mt-4">Verificando permissões...</p>
</div>
</div>
{:else if hasAccess}
{@render children()}
{@render children()}
{/if}

View File

@@ -7,6 +7,7 @@
import { resolve } from "$app/paths";
import { UserPlus, Mail } from "lucide-svelte";
import { useAuth } from "@mmailaender/convex-better-auth-svelte/svelte";
import ProtectedRoute from "$lib/components/ProtectedRoute.svelte";
let { data } = $props();
@@ -128,6 +129,7 @@
}
</script>
<ProtectedRoute>
<main class="container mx-auto px-4 py-4">
<!-- Alerta de Acesso Negado / Autenticação -->
{#if showAlert}
@@ -823,6 +825,7 @@
</div>
{/if}
</main>
</ProtectedRoute>
<style>
@keyframes fadeIn {

View File

@@ -1,8 +1,10 @@
<script lang="ts">
import { ShoppingCart, ShoppingBag, Plus } from "lucide-svelte";
import { resolve } from "$app/paths";
import ProtectedRoute from "$lib/components/ProtectedRoute.svelte";
</script>
<ProtectedRoute>
<main class="container mx-auto px-4 py-4">
<div class="text-sm breadcrumbs mb-4">
<ul>
@@ -41,4 +43,5 @@
</div>
</div>
</main>
</ProtectedRoute>

View File

@@ -1,8 +1,10 @@
<script lang="ts">
import { Megaphone, Edit, Plus } from "lucide-svelte";
import { resolve } from "$app/paths";
import ProtectedRoute from "$lib/components/ProtectedRoute.svelte";
</script>
<ProtectedRoute>
<main class="container mx-auto px-4 py-4">
<div class="text-sm breadcrumbs mb-4">
<ul>
@@ -41,4 +43,5 @@
</div>
</div>
</main>
</ProtectedRoute>

View File

@@ -1,8 +1,10 @@
<script lang="ts">
import { BarChart3, ClipboardCheck, Plus, CheckCircle2, Clock, TrendingUp } from "lucide-svelte";
import { resolve } from "$app/paths";
import ProtectedRoute from "$lib/components/ProtectedRoute.svelte";
</script>
<ProtectedRoute>
<main class="container mx-auto px-4 py-4">
<!-- Breadcrumb -->
<div class="text-sm breadcrumbs mb-4">
@@ -86,4 +88,5 @@
</div>
</div>
</main>
</ProtectedRoute>

View File

@@ -1,8 +1,10 @@
<script lang="ts">
import { DollarSign, Building2, Plus, Calculator, TrendingUp, FileText } from "lucide-svelte";
import { resolve } from "$app/paths";
import ProtectedRoute from "$lib/components/ProtectedRoute.svelte";
</script>
<ProtectedRoute>
<main class="container mx-auto px-4 py-4">
<!-- Breadcrumb -->
<div class="text-sm breadcrumbs mb-4">
@@ -86,4 +88,5 @@
</div>
</div>
</main>
</ProtectedRoute>

View File

@@ -1,8 +1,10 @@
<script lang="ts">
import { Scale, BookOpen, Plus } from "lucide-svelte";
import { resolve } from "$app/paths";
import ProtectedRoute from "$lib/components/ProtectedRoute.svelte";
</script>
<ProtectedRoute>
<main class="container mx-auto px-4 py-4">
<div class="text-sm breadcrumbs mb-4">
<ul>
@@ -41,4 +43,5 @@
</div>
</div>
</main>
</ProtectedRoute>

View File

@@ -1,8 +1,10 @@
<script lang="ts">
import { FileText, ClipboardCopy, Plus, Users, FileDoc } from "lucide-svelte";
import { resolve } from "$app/paths";
import ProtectedRoute from "$lib/components/ProtectedRoute.svelte";
</script>
<ProtectedRoute>
<main class="container mx-auto px-4 py-4">
<!-- Breadcrumb -->
<div class="text-sm breadcrumbs mb-4">
@@ -86,4 +88,5 @@
</div>
</div>
</main>
</ProtectedRoute>

View File

@@ -7,6 +7,7 @@
import AprovarAusencias from '$lib/components/AprovarAusencias.svelte';
import CalendarioAusencias from '$lib/components/ausencias/CalendarioAusencias.svelte';
import { generateAvatarGallery } from '$lib/utils/avatars';
import ProtectedRoute from '$lib/components/ProtectedRoute.svelte';
import type { Id } from '@sgse-app/backend/convex/_generated/dataModel';
import { X, Calendar } from 'lucide-svelte';
import type { FunctionReturnType } from 'convex/server';
@@ -365,6 +366,7 @@
}
</script>
<ProtectedRoute>
<main class="min-h-screen pb-12">
<!-- BANNER HERO PREMIUM -->
<div class="relative mb-8 overflow-hidden">
@@ -2264,6 +2266,7 @@
</dialog>
{/if}
</main>
</ProtectedRoute>
<!-- Modal Wizard Solicitação de Férias -->
{#if mostrarWizard && funcionarioIdDisponivel}

View File

@@ -1,8 +1,10 @@
<script lang="ts">
import { Trophy, Award, Plus } from "lucide-svelte";
import { resolve } from "$app/paths";
import ProtectedRoute from "$lib/components/ProtectedRoute.svelte";
</script>
<ProtectedRoute>
<main class="container mx-auto px-4 py-4">
<div class="text-sm breadcrumbs mb-4">
<ul>
@@ -41,4 +43,5 @@
</div>
</div>
</main>
</ProtectedRoute>

View File

@@ -543,7 +543,7 @@
</div>
</div>
</div>
{:else if catalogoQuery.data}
{:else if catalogoQuery.data && catalogoQuery.data.length > 0}
<div class="space-y-2">
{#each catalogoQuery.data as item (item.recurso)}
{@const recursoExpandido = isRecursoExpandido(roleId, item.recurso)}
@@ -576,28 +576,40 @@
<!-- Lista de ações (visível quando expandido) -->
{#if recursoExpandido}
<div class="bg-base-100 border-base-300 border-t px-4 py-3">
<div class="space-y-2">
{#each ['ver', 'listar', 'criar', 'editar', 'excluir'] as acao (acao)}
<label
class="hover:bg-base-200 flex cursor-pointer items-center gap-3 rounded p-2 transition-colors"
>
<input
type="checkbox"
class="checkbox checkbox-primary"
checked={isConcedida(roleId, item.recurso, acao)}
disabled={salvando}
onchange={(e) =>
toggleAcao(roleId, item.recurso, acao, e.currentTarget.checked)}
/>
<span class="flex-1 font-medium capitalize">{acao}</span>
</label>
{/each}
</div>
{#if item.acoes.length === 0}
<p class="text-base-content/60 text-sm">
Nenhuma permissão cadastrada para este recurso.
</p>
{:else}
<div class="space-y-2">
{#each item.acoes as acao (acao)}
<label
class="hover:bg-base-200 flex cursor-pointer items-center gap-3 rounded p-2 transition-colors"
>
<input
type="checkbox"
class="checkbox checkbox-primary"
checked={isConcedida(roleId, item.recurso, acao)}
disabled={salvando}
onchange={(e) =>
toggleAcao(roleId, item.recurso, acao, e.currentTarget.checked)}
/>
<span class="flex-1 font-medium">{acao}</span>
</label>
{/each}
</div>
{/if}
</div>
{/if}
</div>
{/each}
</div>
{:else}
<div class="alert alert-info mt-4">
<span class="font-semibold">
Nenhuma permissão cadastrada ainda. Use o botão Criar permissão para começar.
</span>
</div>
{/if}
</div>
</div>

View File

@@ -41,19 +41,15 @@
const stats = $derived.by(() => {
if (carregando) return null;
const porNivel = {
0: roles.filter((r) => r.nivel === 0).length,
1: roles.filter((r) => r.nivel === 1).length,
2: roles.filter((r) => r.nivel === 2).length,
3: roles.filter((r) => r.nivel >= 3).length
};
const nivelMaximo = roles.filter((r) => r.nivel === 0).length;
const nivelAdministrativo = roles.filter((r) => r.nivel === 1).length;
const niveisLegado = roles.filter((r) => r.nivel > 1).length;
return {
total: roles.length,
nivelMaximo: porNivel[0],
nivelAlto: porNivel[1],
nivelMedio: porNivel[2],
nivelBaixo: porNivel[3],
nivelMaximo,
nivelAdministrativo,
niveisLegado,
comSetor: roles.filter((r) => r.setor).length
};
});
@@ -78,10 +74,11 @@
// Filtro por nível
if (filtroNivel !== '') {
if (filtroNivel === 3) {
resultado = resultado.filter((r) => r.nivel >= 3);
} else {
if (filtroNivel === 0 || filtroNivel === 1) {
resultado = resultado.filter((r) => r.nivel === filtroNivel);
} else {
// Qualquer outro valor é considerado legado
resultado = resultado.filter((r) => r.nivel > 1);
}
}
@@ -96,22 +93,19 @@
function obterCorNivel(nivel: number): string {
if (nivel === 0) return 'badge-error';
if (nivel === 1) return 'badge-warning';
if (nivel === 2) return 'badge-info';
// Níveis > 1 são considerados legado
return 'badge-ghost';
}
function obterTextoNivel(nivel: number): string {
if (nivel === 0) return 'Máximo';
if (nivel === 1) return 'Alto';
if (nivel === 2) return 'Médio';
if (nivel === 3) return 'Baixo';
return `Nível ${nivel}`;
if (nivel === 1) return 'Administrativo';
return `Legado (${nivel})`;
}
function obterCorCardNivel(nivel: number): string {
if (nivel === 0) return 'border-l-4 border-error';
if (nivel === 1) return 'border-l-4 border-warning';
if (nivel === 2) return 'border-l-4 border-info';
return 'border-l-4 border-base-300';
}
@@ -144,7 +138,7 @@
);
</script>
<ProtectedRoute allowedRoles={['ti_master', 'admin', 'ti_usuario']} maxLevel={3}>
<ProtectedRoute allowedRoles={['ti_master', 'admin', 'ti_usuario']} maxLevel={1}>
<div class="container mx-auto max-w-7xl px-4 py-6">
<!-- Header -->
<div class="mb-8 flex items-center justify-between">
@@ -176,31 +170,24 @@
<!-- Estatísticas -->
{#if stats}
<div class="mb-8 grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-5">
<div class="mb-8 grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-4">
<StatsCard title="Total de Perfis" value={stats.total} Icon={Users} color="primary" />
<StatsCard
title="Nível Máximo"
title="Nível Máximo (0)"
value={stats.nivelMaximo}
description="Acesso total"
description="Acesso total ao sistema"
Icon={Shield}
color="error"
/>
<StatsCard
title="Nível Alto"
value={stats.nivelAlto}
description="Acesso elevado"
title="Nível Administrativo (1)"
value={stats.nivelAdministrativo}
description="Perfis administrativos com acesso total"
Icon={AlertTriangle}
color="warning"
/>
<StatsCard
title="Nível Médio"
value={stats.nivelMedio}
description="Acesso padrão"
Icon={Info}
color="info"
/>
<StatsCard
title="Com Setor"
title="Perfis com Setor"
value={stats.comSetor}
description={stats.total > 0
? ((stats.comSetor / stats.total) * 100).toFixed(0) + '% do total'
@@ -209,6 +196,18 @@
color="secondary"
/>
</div>
{#if stats.niveisLegado > 0}
<div class="alert alert-warning mb-6">
<Info class="h-5 w-5" />
<div>
<h3 class="font-bold">Perfis com níveis legados</h3>
<p class="text-sm">
Existem {stats.niveisLegado} perfis com nível acima de 1. Esses perfis continuarão
sendo tratados como nível 1 (administrativo) após a migração.
</p>
</div>
</div>
{/if}
{/if}
<!-- Filtros -->

View File

@@ -4,7 +4,7 @@
import { resolve } from '$app/paths';
</script>
<ProtectedRoute allowedRoles={['admin', 'ti']} maxLevel={1}>
<ProtectedRoute allowedRoles={['ti_master', 'admin']} maxLevel={1}>
<!-- Breadcrumb -->
<div class="breadcrumbs mb-4 text-sm">
<ul>

View File

@@ -257,7 +257,7 @@
}
</script>
<ProtectedRoute allowedRoles={['ti_master', 'admin', 'ti_usuario']} maxLevel={3}>
<ProtectedRoute allowedRoles={['ti_master', 'admin', 'ti_usuario']} maxLevel={1}>
<div class="container mx-auto max-w-7xl px-4 py-6">
<!-- Mensagem de Feedback -->
{#if mensagem}

View File

@@ -278,7 +278,7 @@
}
</script>
<ProtectedRoute allowedRoles={['ti_master', 'admin', 'ti_usuario']} maxLevel={2}>
<ProtectedRoute allowedRoles={['ti_master', 'admin', 'ti_usuario']} maxLevel={1}>
<main class="container mx-auto max-w-7xl px-4 py-6">
<!-- Breadcrumb -->
<div class="breadcrumbs mb-4 text-sm">

View File

@@ -535,7 +535,7 @@
}
</script>
<ProtectedRoute allowedRoles={['ti_master', 'admin', 'ti_usuario']} maxLevel={3}>
<ProtectedRoute allowedRoles={['ti_master', 'admin', 'ti_usuario']} maxLevel={1}>
<div class="container mx-auto max-w-7xl px-4 py-6">
<!-- Header -->
<div class="mb-6 flex items-center justify-between">

View File

@@ -15,8 +15,8 @@ import type * as actions_smtp from "../actions/smtp.js";
import type * as actions_utils_nodeCrypto from "../actions/utils/nodeCrypto.js";
import type * as atestadosLicencas from "../atestadosLicencas.js";
import type * as ausencias from "../ausencias.js";
import type * as auth from "../auth.js";
import type * as auth_utils from "../auth/utils.js";
import type * as auth from "../auth.js";
import type * as chat from "../chat.js";
import type * as configuracaoEmail from "../configuracaoEmail.js";
import type * as crons from "../crons.js";
@@ -28,7 +28,6 @@ import type * as ferias from "../ferias.js";
import type * as funcionarios from "../funcionarios.js";
import type * as healthCheck from "../healthCheck.js";
import type * as http from "../http.js";
import type * as limparPerfisAntigos from "../limparPerfisAntigos.js";
import type * as logsAcesso from "../logsAcesso.js";
import type * as logsAtividades from "../logsAtividades.js";
import type * as logsLogin from "../logsLogin.js";
@@ -54,6 +53,14 @@ import type {
FunctionReference,
} from "convex/server";
/**
* A utility for referencing Convex functions in your app's API.
*
* Usage:
* ```js
* const myFunctionReference = api.myModule.myFunction;
* ```
*/
declare const fullApi: ApiFromModules<{
"actions/email": typeof actions_email;
"actions/linkPreview": typeof actions_linkPreview;
@@ -62,8 +69,8 @@ declare const fullApi: ApiFromModules<{
"actions/utils/nodeCrypto": typeof actions_utils_nodeCrypto;
atestadosLicencas: typeof atestadosLicencas;
ausencias: typeof ausencias;
auth: typeof auth;
"auth/utils": typeof auth_utils;
auth: typeof auth;
chat: typeof chat;
configuracaoEmail: typeof configuracaoEmail;
crons: typeof crons;
@@ -75,7 +82,6 @@ declare const fullApi: ApiFromModules<{
funcionarios: typeof funcionarios;
healthCheck: typeof healthCheck;
http: typeof http;
limparPerfisAntigos: typeof limparPerfisAntigos;
logsAcesso: typeof logsAcesso;
logsAtividades: typeof logsAtividades;
logsLogin: typeof logsLogin;
@@ -95,30 +101,14 @@ declare const fullApi: ApiFromModules<{
"utils/getClientIP": typeof utils_getClientIP;
verificarMatriculas: typeof verificarMatriculas;
}>;
declare const fullApiWithMounts: typeof fullApi;
/**
* A utility for referencing Convex functions in your app's public API.
*
* Usage:
* ```js
* const myFunctionReference = api.myModule.myFunction;
* ```
*/
export declare const api: FilterApi<
typeof fullApi,
typeof fullApiWithMounts,
FunctionReference<any, "public">
>;
/**
* A utility for referencing Convex functions in your app's internal API.
*
* Usage:
* ```js
* const myFunctionReference = internal.myModule.myFunction;
* ```
*/
export declare const internal: FilterApi<
typeof fullApi,
typeof fullApiWithMounts,
FunctionReference<any, "internal">
>;

View File

@@ -10,6 +10,7 @@
import {
ActionBuilder,
AnyComponents,
HttpActionBuilder,
MutationBuilder,
QueryBuilder,
@@ -18,9 +19,15 @@ import {
GenericQueryCtx,
GenericDatabaseReader,
GenericDatabaseWriter,
FunctionReference,
} from "convex/server";
import type { DataModel } from "./dataModel.js";
type GenericCtx =
| GenericActionCtx<DataModel>
| GenericMutationCtx<DataModel>
| GenericQueryCtx<DataModel>;
/**
* Define a query in this Convex app's public API.
*
@@ -85,12 +92,11 @@ export declare const internalAction: ActionBuilder<DataModel, "internal">;
/**
* Define an HTTP action.
*
* The wrapped function will be used to respond to HTTP requests received
* by a Convex deployment if the requests matches the path and method where
* this action is routed. Be sure to route your httpAction in `convex/http.js`.
* This function will be used to respond to HTTP requests received by a Convex
* deployment if the requests matches the path and method where this action
* is routed. Be sure to route your action in `convex/http.js`.
*
* @param func - The function. It receives an {@link ActionCtx} as its first argument
* and a Fetch API `Request` object as its second.
* @param func - The function. It receives an {@link ActionCtx} as its first argument.
* @returns The wrapped function. Import this function from `convex/http.js` and route it to hook it up.
*/
export declare const httpAction: HttpActionBuilder;

View File

@@ -16,6 +16,7 @@ import {
internalActionGeneric,
internalMutationGeneric,
internalQueryGeneric,
componentsGeneric,
} from "convex/server";
/**
@@ -80,14 +81,10 @@ export const action = actionGeneric;
export const internalAction = internalActionGeneric;
/**
* Define an HTTP action.
* Define a Convex HTTP action.
*
* The wrapped function will be used to respond to HTTP requests received
* by a Convex deployment if the requests matches the path and method where
* this action is routed. Be sure to route your httpAction in `convex/http.js`.
*
* @param func - The function. It receives an {@link ActionCtx} as its first argument
* and a Fetch API `Request` object as its second.
* @returns The wrapped function. Import this function from `convex/http.js` and route it to hook it up.
* @param func - The function. It receives an {@link ActionCtx} as its first argument, and a `Request` object
* as its second.
* @returns The wrapped endpoint function. Route a URL path to this function in `convex/http.js`.
*/
export const httpAction = httpActionGeneric;

View File

@@ -1,285 +0,0 @@
import { internalMutation, query } from "./_generated/server";
import { v } from "convex/values";
/**
* Listar todos os perfis (roles) do sistema
*/
export const listarTodosRoles = query({
args: {},
returns: v.array(
v.object({
_id: v.id("roles"),
nome: v.string(),
descricao: v.string(),
nivel: v.number(),
setor: v.optional(v.string()),
customizado: v.optional(v.boolean()),
editavel: v.optional(v.boolean()),
_creationTime: v.number(),
})
),
handler: async (ctx) => {
const roles = await ctx.db.query("roles").collect();
return roles.map((role) => ({
_id: role._id,
nome: role.nome,
descricao: role.descricao,
nivel: role.nivel,
setor: role.setor,
customizado: role.customizado,
editavel: role.editavel,
_creationTime: role._creationTime,
}));
},
});
/**
* Limpar perfis antigos/duplicados
*
* CRITÉRIOS:
* - Manter apenas: ti_master (nível 0), admin (nível 2), ti_usuario (nível 2)
* - Remover: admin antigo (nível 0), ti genérico (nível 1), outros duplicados
*/
export const limparPerfisAntigos = internalMutation({
args: {},
returns: v.object({
removidos: v.array(
v.object({
nome: v.string(),
descricao: v.string(),
nivel: v.number(),
motivo: v.string(),
})
),
mantidos: v.array(
v.object({
nome: v.string(),
descricao: v.string(),
nivel: v.number(),
})
),
}),
handler: async (ctx) => {
const roles = await ctx.db.query("roles").collect();
const removidos: Array<{
nome: string;
descricao: string;
nivel: number;
motivo: string;
}> = [];
const mantidos: Array<{
nome: string;
descricao: string;
nivel: number;
}> = [];
// Perfis que devem ser mantidos (apenas 1 de cada)
const perfisCorretos = new Map<string, boolean>();
perfisCorretos.set("ti_master", false);
perfisCorretos.set("admin", false);
perfisCorretos.set("ti_usuario", false);
for (const role of roles) {
let deveManter = false;
let motivo = "";
// TI_MASTER - Manter apenas o de nível 0
if (role.nome === "ti_master") {
if (role.nivel === 0 && !perfisCorretos.get("ti_master")) {
deveManter = true;
perfisCorretos.set("ti_master", true);
} else {
motivo =
role.nivel !== 0
? "TI_MASTER deve ser nível 0, este é nível " + role.nivel
: "TI_MASTER duplicado";
}
}
// ADMIN - Manter apenas o de nível 2
else if (role.nome === "admin") {
if (role.nivel === 2 && !perfisCorretos.get("admin")) {
deveManter = true;
perfisCorretos.set("admin", true);
} else {
motivo =
role.nivel !== 2
? "ADMIN deve ser nível 2, este é nível " + role.nivel
: "ADMIN duplicado";
}
}
// TI_USUARIO - Manter apenas o de nível 2
else if (role.nome === "ti_usuario") {
if (role.nivel === 2 && !perfisCorretos.get("ti_usuario")) {
deveManter = true;
perfisCorretos.set("ti_usuario", true);
} else {
motivo =
role.nivel !== 2
? "TI_USUARIO deve ser nível 2, este é nível " + role.nivel
: "TI_USUARIO duplicado";
}
}
// Perfis genéricos antigos (remover)
else if (role.nome === "ti") {
motivo =
"Perfil genérico 'ti' obsoleto - usar 'ti_master' ou 'ti_usuario'";
}
// Outros perfis específicos de setores (manter se forem nível >= 2)
else if (
role.nome === "rh" ||
role.nome === "financeiro" ||
role.nome === "controladoria" ||
role.nome === "licitacoes" ||
role.nome === "compras" ||
role.nome === "juridico" ||
role.nome === "comunicacao" ||
role.nome === "programas_esportivos" ||
role.nome === "secretaria_executiva" ||
role.nome === "gestao_pessoas" ||
role.nome === "usuario"
) {
if (role.nivel >= 2) {
deveManter = true;
} else {
motivo = `Perfil de setor com nível incorreto (${role.nivel}), deveria ser >= 2`;
}
}
// Perfis customizados (manter sempre)
else if (role.customizado) {
deveManter = true;
}
// Outros perfis desconhecidos
else {
motivo = "Perfil desconhecido ou obsoleto";
}
if (deveManter) {
mantidos.push({
nome: role.nome,
descricao: role.descricao,
nivel: role.nivel,
});
console.log(
`✅ MANTIDO: ${role.nome} (${role.descricao}) - Nível ${role.nivel}`
);
} else {
// Verificar se há usuários usando este perfil
const usuariosComRole = await ctx.db
.query("usuarios")
.withIndex("by_role", (q) => q.eq("roleId", role._id))
.collect();
if (usuariosComRole.length > 0) {
console.log(
`⚠️ AVISO: Não é possível remover "${role.nome}" porque ${usuariosComRole.length} usuário(s) ainda usa(m) este perfil`
);
mantidos.push({
nome: role.nome,
descricao: role.descricao,
nivel: role.nivel,
});
} else {
// Remover permissões associadas
const permissoes = await ctx.db
.query("rolePermissoes")
.withIndex("by_role", (q) => q.eq("roleId", role._id))
.collect();
for (const perm of permissoes) {
await ctx.db.delete(perm._id);
}
// Remover o role
await ctx.db.delete(role._id);
removidos.push({
nome: role.nome,
descricao: role.descricao,
nivel: role.nivel,
motivo: motivo || "Não especificado",
});
console.log(
`🗑️ REMOVIDO: ${role.nome} (${role.descricao}) - Nível ${role.nivel} - Motivo: ${motivo}`
);
}
}
}
return { removidos, mantidos };
},
});
/**
* Verificar se existem perfis com níveis incorretos
*/
export const verificarNiveisIncorretos = query({
args: {},
returns: v.array(
v.object({
nome: v.string(),
descricao: v.string(),
nivelAtual: v.number(),
nivelCorreto: v.number(),
problema: v.string(),
})
),
handler: async (ctx) => {
const roles = await ctx.db.query("roles").collect();
const problemas: Array<{
nome: string;
descricao: string;
nivelAtual: number;
nivelCorreto: number;
problema: string;
}> = [];
for (const role of roles) {
// TI_MASTER deve ser nível 0
if (role.nome === "ti_master" && role.nivel !== 0) {
problemas.push({
nome: role.nome,
descricao: role.descricao,
nivelAtual: role.nivel,
nivelCorreto: 0,
problema: "TI_MASTER deve ter acesso total (nível 0)",
});
}
// ADMIN deve ser nível 2
if (role.nome === "admin" && role.nivel !== 2) {
problemas.push({
nome: role.nome,
descricao: role.descricao,
nivelAtual: role.nivel,
nivelCorreto: 2,
problema: "ADMIN deve ser editável (nível 2)",
});
}
// TI_USUARIO deve ser nível 2
if (role.nome === "ti_usuario" && role.nivel !== 2) {
problemas.push({
nome: role.nome,
descricao: role.descricao,
nivelAtual: role.nivel,
nivelCorreto: 2,
problema: "TI_USUARIO deve ser editável (nível 2)",
});
}
// Perfil genérico "ti" não deveria existir
if (role.nome === "ti") {
problemas.push({
nome: role.nome,
descricao: role.descricao,
nivelAtual: role.nivel,
nivelCorreto: -1, // Indica que deve ser removido
problema: "Perfil genérico obsoleto - usar ti_master ou ti_usuario",
});
}
}
return problemas;
},
});

View File

@@ -3,27 +3,271 @@ import { v } from 'convex/values';
import type { Doc } from './_generated/dataModel';
import { getCurrentUserFunction } from './auth';
// Catálogo base de recursos e ações
// Ajuste/expanda conforme os módulos disponíveis no sistema
export const CATALOGO_RECURSOS = [
{
recurso: 'funcionarios',
acoes: [
'dashboard',
'ver',
'listar',
'criar',
'editar',
'excluir',
'aprovar_ausencias',
'aprovar_ferias'
]
},
{
recurso: 'simbolos',
acoes: ['dashboard', 'ver', 'listar', 'criar', 'editar', 'excluir']
}
] as const;
// Catálogo de permissões base para seed controlado via mutation
const PERMISSOES_BASE = {
permissoes: [
// Funcionários
{
nome: 'funcionarios.dashboard',
recurso: 'funcionarios',
acao: 'dashboard',
descricao: 'Acessar o painel de funcionários'
},
{
nome: 'funcionarios.ver',
recurso: 'funcionarios',
acao: 'ver',
descricao: 'Visualizar detalhes de funcionários'
},
{
nome: 'funcionarios.listar',
recurso: 'funcionarios',
acao: 'listar',
descricao: 'Listar funcionários'
},
{
nome: 'funcionarios.criar',
recurso: 'funcionarios',
acao: 'criar',
descricao: 'Criar novos funcionários'
},
{
nome: 'funcionarios.editar',
recurso: 'funcionarios',
acao: 'editar',
descricao: 'Editar dados de funcionários'
},
{
nome: 'funcionarios.excluir',
recurso: 'funcionarios',
acao: 'excluir',
descricao: 'Excluir funcionários'
},
{
nome: 'funcionarios.aprovar_ausencias',
recurso: 'funcionarios',
acao: 'aprovar_ausencias',
descricao: 'Aprovar ausências de funcionários'
},
{
nome: 'funcionarios.aprovar_ferias',
recurso: 'funcionarios',
acao: 'aprovar_ferias',
descricao: 'Aprovar férias de funcionários'
},
// Símbolos
{
nome: 'simbolos.dashboard',
recurso: 'simbolos',
acao: 'dashboard',
descricao: 'Acessar o painel de símbolos'
},
{
nome: 'simbolos.ver',
recurso: 'simbolos',
acao: 'ver',
descricao: 'Visualizar detalhes de símbolos'
},
{
nome: 'simbolos.listar',
recurso: 'simbolos',
acao: 'listar',
descricao: 'Listar símbolos'
},
{
nome: 'simbolos.criar',
recurso: 'simbolos',
acao: 'criar',
descricao: 'Criar novos símbolos'
},
{
nome: 'simbolos.editar',
recurso: 'simbolos',
acao: 'editar',
descricao: 'Editar símbolos'
},
{
nome: 'simbolos.excluir',
recurso: 'simbolos',
acao: 'excluir',
descricao: 'Excluir símbolos'
},
// TI - Usuários
{
nome: 'ti_usuarios.listar',
recurso: 'ti_usuarios',
acao: 'listar',
descricao: 'Listar usuários do sistema'
},
{
nome: 'ti_usuarios.criar',
recurso: 'ti_usuarios',
acao: 'criar',
descricao: 'Criar novos usuários de acesso'
},
{
nome: 'ti_usuarios.editar',
recurso: 'ti_usuarios',
acao: 'editar',
descricao: 'Editar usuários de acesso'
},
{
nome: 'ti_usuarios.bloquear',
recurso: 'ti_usuarios',
acao: 'bloquear',
descricao: 'Bloquear ou desbloquear usuários'
},
// TI - Perfis
{
nome: 'ti_perfis.listar',
recurso: 'ti_perfis',
acao: 'listar',
descricao: 'Listar perfis de acesso'
},
{
nome: 'ti_perfis.criar',
recurso: 'ti_perfis',
acao: 'criar',
descricao: 'Criar novos perfis de acesso'
},
{
nome: 'ti_perfis.editar',
recurso: 'ti_perfis',
acao: 'editar',
descricao: 'Editar perfis de acesso'
},
// TI - Painel de Permissões
{
nome: 'ti_painel_permissoes.gerenciar',
recurso: 'ti_painel_permissoes',
acao: 'gerenciar',
descricao: 'Gerenciar matriz de permissões por perfil'
},
// TI - Solicitações de Acesso
{
nome: 'ti_solicitacoes_acesso.ver',
recurso: 'ti_solicitacoes_acesso',
acao: 'ver',
descricao: 'Visualizar solicitações de acesso'
},
{
nome: 'ti_solicitacoes_acesso.aprovar',
recurso: 'ti_solicitacoes_acesso',
acao: 'aprovar',
descricao: 'Aprovar solicitações de acesso'
},
{
nome: 'ti_solicitacoes_acesso.reprovar',
recurso: 'ti_solicitacoes_acesso',
acao: 'reprovar',
descricao: 'Reprovar solicitações de acesso'
},
// TI - Configurações de E-mail
{
nome: 'ti_configuracoes_email.configurar',
recurso: 'ti_configuracoes_email',
acao: 'configurar',
descricao: 'Configurar parâmetros de envio de e-mail'
},
// TI - Monitoramento
{
nome: 'ti_monitoramento.ver',
recurso: 'ti_monitoramento',
acao: 'ver',
descricao: 'Acessar painel de monitoramento geral'
},
{
nome: 'ti_monitoramento_emails.ver',
recurso: 'ti_monitoramento_emails',
acao: 'ver',
descricao: 'Acessar monitoramento de envio de e-mails'
},
// TI - Notificações
{
nome: 'ti_notificacoes.configurar',
recurso: 'ti_notificacoes',
acao: 'configurar',
descricao: 'Configurar notificações do sistema'
},
// TI - Times
{
nome: 'ti_times.gerenciar',
recurso: 'ti_times',
acao: 'gerenciar',
descricao: 'Gerenciar times/equipes de TI'
},
// TI - Painel Administrativo
{
nome: 'ti_painel_administrativo.ver',
recurso: 'ti_painel_administrativo',
acao: 'ver',
descricao: 'Acessar painel administrativo de TI'
},
// Financeiro
{
nome: 'financeiro.ver',
recurso: 'financeiro',
acao: 'ver',
descricao: 'Acessar telas do módulo de financeiro'
},
// Controladoria
{
nome: 'controladoria.ver',
recurso: 'controladoria',
acao: 'ver',
descricao: 'Acessar telas do módulo de controladoria'
},
// Licitações
{
nome: 'licitacoes.ver',
recurso: 'licitacoes',
acao: 'ver',
descricao: 'Acessar telas do módulo de licitações'
},
// Compras
{
nome: 'compras.ver',
recurso: 'compras',
acao: 'ver',
descricao: 'Acessar telas do módulo de compras'
},
// Jurídico
{
nome: 'juridico.ver',
recurso: 'juridico',
acao: 'ver',
descricao: 'Acessar telas do módulo jurídico'
},
// Comunicação
{
nome: 'comunicacao.ver',
recurso: 'comunicacao',
acao: 'ver',
descricao: 'Acessar telas do módulo de comunicação'
},
// Programas Esportivos
{
nome: 'programas_esportivos.ver',
recurso: 'programas_esportivos',
acao: 'ver',
descricao: 'Acessar telas do módulo de programas esportivos'
},
// Secretaria Executiva
{
nome: 'secretaria_executiva.ver',
recurso: 'secretaria_executiva',
acao: 'ver',
descricao: 'Acessar telas do módulo de secretaria executiva'
},
// Gestão de Pessoas
{
nome: 'gestao_pessoas.ver',
recurso: 'gestao_pessoas',
acao: 'ver',
descricao: 'Acessar telas do módulo de gestão de pessoas'
}
]
} as const;
export const listarRecursosEAcoes = query({
args: {},
@@ -33,10 +277,18 @@ export const listarRecursosEAcoes = query({
acoes: v.array(v.string())
})
),
handler: async () => {
return CATALOGO_RECURSOS.map((r) => ({
recurso: r.recurso,
acoes: [...r.acoes]
handler: async (ctx) => {
const permissoes = await ctx.db.query('permissoes').collect();
const recursos: Record<string, Set<string>> = {};
for (const perm of permissoes) {
const set = (recursos[perm.recurso] ||= new Set<string>());
set.add(perm.acao);
}
return Object.entries(recursos).map(([recurso, acoes]) => ({
recurso,
acoes: Array.from(acoes).sort()
}));
}
});
@@ -56,7 +308,7 @@ export const listarPermissoesAcoesPorRole = query({
.withIndex('by_role', (q) => q.eq('roleId', args.roleId))
.collect();
// Carregar documentos de permissões
// Carregar documentos de permissões vinculadas a este role
const actionsByResource: Record<string, Set<string>> = {};
for (const rp of rolePerms) {
const perm = await ctx.db.get(rp.permissaoId);
@@ -65,13 +317,10 @@ export const listarPermissoesAcoesPorRole = query({
set.add(perm.acao);
}
// Normalizar para todos os recursos do catálogo
const result: Array<{ recurso: string; acoes: Array<string> }> = [];
for (const item of CATALOGO_RECURSOS) {
const granted = Array.from(actionsByResource[item.recurso] ?? new Set<string>());
result.push({ recurso: item.recurso, acoes: granted });
}
return result;
return Object.entries(actionsByResource).map(([recurso, acoes]) => ({
recurso,
acoes: Array.from(acoes).sort()
}));
}
});
@@ -84,24 +333,12 @@ export const atualizarPermissaoAcao = mutation({
},
returns: v.null(),
handler: async (ctx, args) => {
// Garantir documento de permissão (recurso+acao)
let permissao = await ctx.db
// Buscar documento de permissão (recurso+acao)
const permissao = await ctx.db
.query('permissoes')
.withIndex('by_recurso_e_acao', (q) => q.eq('recurso', args.recurso).eq('acao', args.acao))
.first();
if (!permissao) {
const nome = `${args.recurso}.${args.acao}`;
const descricao = `Permite ${args.acao} em ${args.recurso}`;
const id = await ctx.db.insert('permissoes', {
nome,
descricao,
recurso: args.recurso,
acao: args.acao
});
permissao = await ctx.db.get(id);
}
if (!permissao) return null;
// Verificar vínculo atual
@@ -128,6 +365,36 @@ export const atualizarPermissaoAcao = mutation({
}
});
export const seedPermissoesBase = mutation({
args: {},
returns: v.null(),
handler: async (ctx) => {
console.log('🔐 Seed de permissões base...');
for (const perm of PERMISSOES_BASE.permissoes) {
const existente = await ctx.db
.query('permissoes')
.withIndex('by_nome', (q) => q.eq('nome', perm.nome))
.first();
if (existente) {
console.log(` Permissão já existe: ${perm.nome}`);
continue;
}
await ctx.db.insert('permissoes', {
nome: perm.nome,
descricao: perm.descricao,
recurso: perm.recurso,
acao: perm.acao
});
console.log(` ✅ Permissão criada: ${perm.nome}`);
}
return null;
}
});
export const verificarAcao = query({
args: {
usuarioId: v.id('usuarios'),

View File

@@ -1,5 +1,5 @@
import { v } from 'convex/values';
import { query, mutation } from './_generated/server';
import { internalMutation, query, mutation } from './_generated/server';
import type { Id } from './_generated/dataModel';
import { getCurrentUserFunction } from './auth';
@@ -98,13 +98,16 @@ export const criar = mutation({
permissoesParaCopiar = permissoesOrigem.map((item) => item.permissaoId);
}
const nivelAjustado = Math.min(Math.max(Math.round(args.nivel), 0), 10);
// Agora só existem níveis 0 e 1.
// 0 = máximo (acesso total), 1 = administrativo (também com acesso total).
// Qualquer valor informado diferente de 0 é normalizado para 1.
const nivelNormalizado = Math.round(args.nivel) <= 0 ? 0 : 1;
const setor = args.setor?.trim();
const roleId = await ctx.db.insert('roles', {
nome: nomeNormalizado,
descricao: args.descricao.trim() || args.nome.trim(),
nivel: nivelAjustado,
nivel: nivelNormalizado,
setor: setor && setor.length > 0 ? setor : undefined,
customizado: true,
criadoPor: usuarioAtual._id,
@@ -123,3 +126,26 @@ export const criar = mutation({
return { sucesso: true as const, roleId };
}
});
/**
* Migração de níveis de roles para o novo modelo (apenas 0 e 1).
* - Mantém níveis 0 e 1 como estão.
* - Converte qualquer nível > 1 para 1.
*/
export const migrarNiveisRoles = internalMutation({
args: {},
returns: v.null(),
handler: async (ctx) => {
const roles = await ctx.db.query('roles').collect();
for (const role of roles) {
if (role.nivel <= 1) continue;
await ctx.db.patch(role._id, {
nivel: 1
});
}
return null;
}
});

File diff suppressed because it is too large Load Diff