Merge branch 'master' into call-audio-video-jitsi
This commit is contained in:
@@ -9,7 +9,7 @@
|
||||
import NotificationBell from '$lib/components/chat/NotificationBell.svelte';
|
||||
import ChatWidget from '$lib/components/chat/ChatWidget.svelte';
|
||||
import PresenceManager from '$lib/components/chat/PresenceManager.svelte';
|
||||
import { getAvatarUrl } from '$lib/utils/avatarGenerator';
|
||||
|
||||
import { Menu, User, Home, UserPlus, XCircle, LogIn, Tag, Plus, Check } from 'lucide-svelte';
|
||||
import { authClient } from '$lib/auth';
|
||||
import { resolve } from '$app/paths';
|
||||
@@ -33,8 +33,8 @@
|
||||
return currentUser.data.avatar;
|
||||
}
|
||||
|
||||
// Fallback: gerar avatar baseado no nome
|
||||
return getAvatarUrl(currentUser.data.nome);
|
||||
// Fallback: retornar null para usar o ícone User do Lucide
|
||||
return null;
|
||||
});
|
||||
|
||||
// Função para gerar classes do menu ativo
|
||||
@@ -328,8 +328,9 @@
|
||||
>Contato</a
|
||||
>
|
||||
<span class="text-base-content/30">•</span>
|
||||
<a href={resolve('/abrir-chamado')} class="link link-hover hover:text-primary transition-colors"
|
||||
>Suporte</a
|
||||
<a
|
||||
href={resolve('/abrir-chamado')}
|
||||
class="link link-hover hover:text-primary transition-colors">Suporte</a
|
||||
>
|
||||
<span class="text-base-content/30">•</span>
|
||||
<a href={resolve('/')} class="link link-hover hover:text-primary transition-colors"
|
||||
@@ -365,7 +366,7 @@
|
||||
<span>Dashboard</span>
|
||||
</a>
|
||||
</li>
|
||||
{#each setores as s}
|
||||
{#each setores as s (s.link)}
|
||||
{@const isActive = currentPath.startsWith(s.link)}
|
||||
<li class="rounded-xl">
|
||||
<a
|
||||
@@ -400,7 +401,7 @@
|
||||
<!-- Botão de fechar moderno -->
|
||||
<button
|
||||
type="button"
|
||||
class="btn btn-sm btn-circle btn-ghost absolute top-4 right-4 z-10 hover:bg-error/20 hover:text-error transition-all duration-200"
|
||||
class="btn btn-sm btn-circle btn-ghost hover:bg-error/20 hover:text-error absolute top-4 right-4 z-10 transition-all duration-200"
|
||||
onclick={closeLoginModal}
|
||||
aria-label="Fechar modal"
|
||||
>
|
||||
@@ -408,28 +409,20 @@
|
||||
</button>
|
||||
|
||||
<!-- Decoração de fundo -->
|
||||
<div
|
||||
class="absolute -top-20 -right-20 h-40 w-40 rounded-full bg-primary/10 blur-3xl"
|
||||
></div>
|
||||
<div
|
||||
class="absolute -bottom-20 -left-20 h-40 w-40 rounded-full bg-primary/5 blur-3xl"
|
||||
></div>
|
||||
<div class="bg-primary/10 absolute -top-20 -right-20 h-40 w-40 rounded-full blur-3xl"></div>
|
||||
<div class="bg-primary/5 absolute -bottom-20 -left-20 h-40 w-40 rounded-full blur-3xl"></div>
|
||||
|
||||
<div class="relative z-10 p-8">
|
||||
<!-- Header com logo e título -->
|
||||
<div class="mb-8 text-center">
|
||||
<div class="avatar mb-5 mx-auto">
|
||||
<div class="avatar mx-auto mb-5">
|
||||
<div
|
||||
class="group relative w-24 overflow-hidden rounded-2xl bg-white p-4 shadow-xl ring-2 ring-primary/20 transition-all duration-300 hover:scale-105 hover:shadow-2xl"
|
||||
class="group ring-primary/20 relative w-24 overflow-hidden rounded-2xl bg-white p-4 shadow-xl ring-2 transition-all duration-300 hover:scale-105 hover:shadow-2xl"
|
||||
>
|
||||
<div
|
||||
class="absolute inset-0 bg-gradient-to-br from-primary/10 to-transparent opacity-0 transition-opacity duration-300 group-hover:opacity-100"
|
||||
class="from-primary/10 absolute inset-0 bg-gradient-to-br to-transparent opacity-0 transition-opacity duration-300 group-hover:opacity-100"
|
||||
></div>
|
||||
<img
|
||||
src={logo}
|
||||
alt="Logo SGSE"
|
||||
class="relative z-10 h-full w-full object-contain"
|
||||
/>
|
||||
<img src={logo} alt="Logo SGSE" class="relative z-10 h-full w-full object-contain" />
|
||||
</div>
|
||||
</div>
|
||||
<h3 class="text-primary mb-2 text-4xl font-bold tracking-tight">Login</h3>
|
||||
@@ -441,7 +434,7 @@
|
||||
<!-- Mensagem de erro -->
|
||||
{#if erroLogin}
|
||||
<div
|
||||
class="alert alert-error mb-6 border-error/30 bg-error/10 shadow-lg backdrop-blur-sm"
|
||||
class="alert alert-error border-error/30 bg-error/10 mb-6 shadow-lg backdrop-blur-sm"
|
||||
>
|
||||
<XCircle class="h-5 w-5 shrink-0 stroke-current" strokeWidth={2.5} />
|
||||
<span class="font-medium">{erroLogin}</span>
|
||||
@@ -453,16 +446,14 @@
|
||||
<!-- Campo Matrícula/E-mail -->
|
||||
<div class="form-control">
|
||||
<label class="label pb-2" for="login-matricula">
|
||||
<span class="text-primary label-text text-sm font-semibold"
|
||||
>Matrícula ou E-mail</span
|
||||
>
|
||||
<span class="text-primary label-text text-sm font-semibold">Matrícula ou E-mail</span>
|
||||
</label>
|
||||
<div class="relative">
|
||||
<input
|
||||
id="login-matricula"
|
||||
type="text"
|
||||
placeholder="Digite sua matrícula ou e-mail"
|
||||
class="input input-bordered input-primary w-full border-2 transition-all duration-200 focus:border-primary focus:shadow-lg focus:shadow-primary/20 disabled:opacity-50"
|
||||
class="input input-bordered input-primary focus:border-primary focus:shadow-primary/20 w-full border-2 transition-all duration-200 focus:shadow-lg disabled:opacity-50"
|
||||
bind:value={matricula}
|
||||
required
|
||||
disabled={carregandoLogin}
|
||||
@@ -481,7 +472,7 @@
|
||||
id="login-password"
|
||||
type="password"
|
||||
placeholder="Digite sua senha"
|
||||
class="input input-bordered input-primary w-full border-2 transition-all duration-200 focus:border-primary focus:shadow-lg focus:shadow-primary/20 disabled:opacity-50"
|
||||
class="input input-bordered input-primary focus:border-primary focus:shadow-primary/20 w-full border-2 transition-all duration-200 focus:shadow-lg disabled:opacity-50"
|
||||
bind:value={senha}
|
||||
required
|
||||
disabled={carregandoLogin}
|
||||
@@ -494,7 +485,7 @@
|
||||
<div class="form-control pt-2">
|
||||
<button
|
||||
type="submit"
|
||||
class="btn btn-primary btn-lg group relative w-full overflow-hidden border-0 bg-gradient-to-r from-primary via-primary to-primary/90 shadow-xl transition-all duration-300 hover:scale-[1.02] hover:shadow-2xl disabled:opacity-50"
|
||||
class="btn btn-primary btn-lg group from-primary via-primary to-primary/90 relative w-full overflow-hidden border-0 bg-gradient-to-r shadow-xl transition-all duration-300 hover:scale-[1.02] hover:shadow-2xl disabled:opacity-50"
|
||||
disabled={carregandoLogin}
|
||||
>
|
||||
<!-- Efeito de brilho animado -->
|
||||
@@ -506,14 +497,17 @@
|
||||
<span class="loading loading-spinner loading-sm"></span>
|
||||
<span class="font-semibold">Entrando...</span>
|
||||
{:else}
|
||||
<LogIn class="h-5 w-5 transition-transform duration-300 group-hover:scale-110" strokeWidth={2.5} />
|
||||
<LogIn
|
||||
class="h-5 w-5 transition-transform duration-300 group-hover:scale-110"
|
||||
strokeWidth={2.5}
|
||||
/>
|
||||
<span class="font-semibold">Entrar</span>
|
||||
{/if}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- Links auxiliares -->
|
||||
<div class="pt-4 space-y-3 text-center">
|
||||
<div class="space-y-3 pt-4 text-center">
|
||||
<a
|
||||
href={resolve('/abrir-chamado')}
|
||||
class="link link-primary block text-sm font-medium transition-all duration-200 hover:scale-105"
|
||||
@@ -548,7 +542,7 @@
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="btn btn-sm btn-circle btn-ghost absolute top-2 right-2 z-10 hover:bg-base-300"
|
||||
class="btn btn-sm btn-circle btn-ghost hover:bg-base-300 absolute top-2 right-2 z-10"
|
||||
onclick={closeAboutModal}
|
||||
>
|
||||
✕
|
||||
@@ -558,7 +552,7 @@
|
||||
<!-- Logo e Título -->
|
||||
<div class="flex flex-col items-center gap-3">
|
||||
<div class="avatar">
|
||||
<div class="w-20 rounded-xl bg-white p-3 shadow-lg ring-2 ring-primary/20">
|
||||
<div class="ring-primary/20 w-20 rounded-xl bg-white p-3 shadow-lg ring-2">
|
||||
<img src={logo} alt="Logo SGSE" class="h-full w-full object-contain" />
|
||||
</div>
|
||||
</div>
|
||||
@@ -574,10 +568,12 @@
|
||||
<div class="divider my-1"></div>
|
||||
|
||||
<!-- Informações de Versão -->
|
||||
<div class="bg-gradient-to-br from-primary/10 to-primary/5 space-y-2 rounded-xl border border-primary/10 p-4 shadow-sm">
|
||||
<div
|
||||
class="from-primary/10 to-primary/5 border-primary/10 space-y-2 rounded-xl border bg-gradient-to-br p-4 shadow-sm"
|
||||
>
|
||||
<div class="flex items-center justify-center gap-2">
|
||||
<Tag class="text-primary h-4 w-4" strokeWidth={2} />
|
||||
<p class="text-base-content/60 text-xs font-medium uppercase tracking-wide">Versão</p>
|
||||
<p class="text-base-content/60 text-xs font-medium tracking-wide uppercase">Versão</p>
|
||||
</div>
|
||||
<p class="text-primary text-2xl font-bold tracking-tight">1.0 11_2025</p>
|
||||
<div class="badge badge-warning badge-sm gap-1.5 px-3 py-1.5 text-xs">
|
||||
@@ -588,7 +584,9 @@
|
||||
|
||||
<!-- Desenvolvido por -->
|
||||
<div class="space-y-1.5">
|
||||
<p class="text-base-content/50 text-xs font-medium uppercase tracking-wide">Desenvolvido por</p>
|
||||
<p class="text-base-content/50 text-xs font-medium tracking-wide uppercase">
|
||||
Desenvolvido por
|
||||
</p>
|
||||
<p class="text-primary text-sm font-semibold">Secretaria de Esportes de Pernambuco</p>
|
||||
</div>
|
||||
|
||||
@@ -597,12 +595,16 @@
|
||||
|
||||
<!-- Informações Adicionais -->
|
||||
<div class="grid grid-cols-2 gap-3">
|
||||
<div class="bg-base-200/60 rounded-lg border border-base-300/50 p-3 shadow-sm transition-all hover:shadow-md">
|
||||
<p class="text-primary mb-1 text-xs font-semibold uppercase tracking-wide">Governo</p>
|
||||
<div
|
||||
class="bg-base-200/60 border-base-300/50 rounded-lg border p-3 shadow-sm transition-all hover:shadow-md"
|
||||
>
|
||||
<p class="text-primary mb-1 text-xs font-semibold tracking-wide uppercase">Governo</p>
|
||||
<p class="text-base-content/60 text-xs font-medium">Estado de Pernambuco</p>
|
||||
</div>
|
||||
<div class="bg-base-200/60 rounded-lg border border-base-300/50 p-3 shadow-sm transition-all hover:shadow-md">
|
||||
<p class="text-primary mb-1 text-xs font-semibold uppercase tracking-wide">Ano</p>
|
||||
<div
|
||||
class="bg-base-200/60 border-base-300/50 rounded-lg border p-3 shadow-sm transition-all hover:shadow-md"
|
||||
>
|
||||
<p class="text-primary mb-1 text-xs font-semibold tracking-wide uppercase">Ano</p>
|
||||
<p class="text-base-content/60 text-xs font-medium">2025</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
import type { Id } from '@sgse-app/backend/convex/_generated/dataModel';
|
||||
import ChatList from './ChatList.svelte';
|
||||
import ChatWindow from './ChatWindow.svelte';
|
||||
import { getAvatarUrl } from '$lib/utils/avatarGenerator';
|
||||
|
||||
import { SvelteSet } from 'svelte/reactivity';
|
||||
|
||||
const count = useQuery(api.chat.contarNotificacoesNaoLidas, {});
|
||||
@@ -38,11 +38,8 @@
|
||||
return usuario.fotoPerfilUrl;
|
||||
}
|
||||
|
||||
if (usuario.avatar) {
|
||||
return getAvatarUrl(usuario.avatar);
|
||||
}
|
||||
// Fallback: gerar avatar baseado no nome
|
||||
return getAvatarUrl(usuario.nome);
|
||||
// Fallback: retornar null para usar o ícone User do Lucide
|
||||
return null;
|
||||
});
|
||||
|
||||
// Posição do widget (arrastável)
|
||||
|
||||
@@ -27,6 +27,8 @@
|
||||
Video
|
||||
} from 'lucide-svelte';
|
||||
|
||||
import { Bell, X, ArrowLeft, LogOut, MoreVertical, Users, Clock, XCircle } from 'lucide-svelte';
|
||||
|
||||
interface Props {
|
||||
conversaId: string;
|
||||
}
|
||||
@@ -88,10 +90,7 @@
|
||||
const c = conversa();
|
||||
if (!c) return '💬';
|
||||
if (c.tipo === 'grupo') {
|
||||
return c.avatar || '👥';
|
||||
}
|
||||
if (c.outroUsuario?.avatar) {
|
||||
return c.outroUsuario.avatar;
|
||||
return '👥';
|
||||
}
|
||||
return '👤';
|
||||
}
|
||||
@@ -227,7 +226,6 @@
|
||||
<div class="relative shrink-0">
|
||||
{#if conversa() && conversa()?.tipo === 'individual' && conversa()?.outroUsuario}
|
||||
<UserAvatar
|
||||
avatar={conversa()?.outroUsuario?.avatar}
|
||||
fotoPerfilUrl={conversa()?.outroUsuario?.fotoPerfilUrl}
|
||||
nome={conversa()?.outroUsuario?.nome || 'Usuário'}
|
||||
size="md"
|
||||
@@ -284,18 +282,12 @@
|
||||
alt={participante.nome}
|
||||
class="h-full w-full object-cover"
|
||||
/>
|
||||
{:else if participante.avatar}
|
||||
<img
|
||||
src={getAvatarUrl(participante.avatar)}
|
||||
alt={participante.nome}
|
||||
class="h-full w-full object-cover"
|
||||
/>
|
||||
{:else}
|
||||
<img
|
||||
src={getAvatarUrl(participante.nome)}
|
||||
alt={participante.nome}
|
||||
class="h-full w-full object-cover"
|
||||
/>
|
||||
<div
|
||||
class="bg-base-200 flex h-full w-full items-center justify-center text-xs font-semibold"
|
||||
>
|
||||
{participante.nome.substring(0, 2).toUpperCase()}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
{/each}
|
||||
|
||||
@@ -1,41 +1,43 @@
|
||||
<script lang="ts">
|
||||
import { getAvatarUrl as generateAvatarUrl } from "$lib/utils/avatarGenerator";
|
||||
|
||||
interface Props {
|
||||
avatar?: string;
|
||||
fotoPerfilUrl?: string | null;
|
||||
nome: string;
|
||||
size?: "xs" | "sm" | "md" | "lg";
|
||||
}
|
||||
import { User } from 'lucide-svelte';
|
||||
|
||||
let { avatar, fotoPerfilUrl, nome, size = "md" }: Props = $props();
|
||||
interface Props {
|
||||
fotoPerfilUrl?: string | null;
|
||||
nome: string;
|
||||
size?: 'xs' | 'sm' | 'md' | 'lg' | 'xl';
|
||||
}
|
||||
|
||||
const sizeClasses = {
|
||||
xs: "w-8 h-8",
|
||||
sm: "w-10 h-10",
|
||||
md: "w-12 h-12",
|
||||
lg: "w-16 h-16",
|
||||
};
|
||||
let { fotoPerfilUrl, nome, size = 'md' }: Props = $props();
|
||||
|
||||
function getAvatarUrl(avatarId: string): string {
|
||||
// Usar gerador local ao invés da API externa
|
||||
return generateAvatarUrl(avatarId);
|
||||
}
|
||||
const sizeClasses = {
|
||||
xs: 'w-8 h-8',
|
||||
sm: 'w-10 h-10',
|
||||
md: 'w-12 h-12',
|
||||
lg: 'w-16 h-16',
|
||||
xl: 'w-32 h-32'
|
||||
};
|
||||
|
||||
const avatarUrlToShow = $derived(() => {
|
||||
if (fotoPerfilUrl) return fotoPerfilUrl;
|
||||
if (avatar) return getAvatarUrl(avatar);
|
||||
return getAvatarUrl(nome); // Fallback usando o nome
|
||||
});
|
||||
const iconSizes = {
|
||||
xs: 16,
|
||||
sm: 20,
|
||||
md: 24,
|
||||
lg: 32,
|
||||
xl: 64
|
||||
};
|
||||
</script>
|
||||
|
||||
<div class="avatar">
|
||||
<div class={`${sizeClasses[size]} rounded-full bg-base-200 overflow-hidden`}>
|
||||
<img
|
||||
src={avatarUrlToShow()}
|
||||
alt={`Avatar de ${nome}`}
|
||||
class="w-full h-full object-cover"
|
||||
/>
|
||||
</div>
|
||||
<div class="avatar placeholder">
|
||||
<div
|
||||
class={`${sizeClasses[size]} bg-base-200 text-base-content/50 flex items-center justify-center overflow-hidden rounded-full`}
|
||||
>
|
||||
{#if fotoPerfilUrl}
|
||||
<img
|
||||
src={fotoPerfilUrl}
|
||||
alt={`Foto de perfil de ${nome}`}
|
||||
class="h-full w-full object-cover"
|
||||
/>
|
||||
{:else}
|
||||
<User size={iconSizes[size]} />
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -34,6 +34,12 @@
|
||||
funcionarioId && dataHoje ? { funcionarioId, data: dataHoje } : 'skip'
|
||||
);
|
||||
|
||||
// Query para verificar dispensa ativa
|
||||
const dispensaQuery = useQuery(
|
||||
api.pontos.verificarDispensaAtiva,
|
||||
funcionarioId && dataHoje ? { funcionarioId, data: dataHoje } : 'skip'
|
||||
);
|
||||
|
||||
// Estados
|
||||
let mostrandoWebcam = $state(false);
|
||||
let registrando = $state(false);
|
||||
@@ -150,6 +156,22 @@
|
||||
async function registrarPonto() {
|
||||
if (registrando) return;
|
||||
|
||||
// Verificar se tem funcionário associado
|
||||
if (!temFuncionarioAssociado) {
|
||||
mensagemErroModal = 'Usuário não possui funcionário associado';
|
||||
detalhesErroModal = 'Você não possui um funcionário associado à sua conta. Entre em contato com o administrador do sistema.';
|
||||
mostrarModalErro = true;
|
||||
return;
|
||||
}
|
||||
|
||||
// Verificar se está dispensado antes de registrar
|
||||
if (estaDispensado) {
|
||||
mensagemErroModal = 'Registro dispensado pelo gestor';
|
||||
detalhesErroModal = motivoDispensa || 'Você está dispensado de registrar ponto no momento.';
|
||||
mostrarModalErro = true;
|
||||
return;
|
||||
}
|
||||
|
||||
// Verificar permissões antes de registrar
|
||||
const permissoes = await verificarPermissoes();
|
||||
if (!permissoes.localizacao || !permissoes.webcam) {
|
||||
@@ -296,6 +318,22 @@
|
||||
async function iniciarRegistroComFoto() {
|
||||
if (registrando || coletandoInfo) return;
|
||||
|
||||
// Verificar se tem funcionário associado
|
||||
if (!temFuncionarioAssociado) {
|
||||
mensagemErroModal = 'Usuário não possui funcionário associado';
|
||||
detalhesErroModal = 'Você não possui um funcionário associado à sua conta. Entre em contato com o administrador do sistema.';
|
||||
mostrarModalErro = true;
|
||||
return;
|
||||
}
|
||||
|
||||
// Verificar se está dispensado antes de abrir webcam
|
||||
if (estaDispensado) {
|
||||
mensagemErroModal = 'Registro dispensado pelo gestor';
|
||||
detalhesErroModal = motivoDispensa || 'Você está dispensado de registrar ponto no momento.';
|
||||
mostrarModalErro = true;
|
||||
return;
|
||||
}
|
||||
|
||||
// Verificar permissões antes de abrir webcam
|
||||
const permissoes = await verificarPermissoes();
|
||||
if (!permissoes.localizacao || !permissoes.webcam) {
|
||||
@@ -542,8 +580,13 @@
|
||||
}
|
||||
}
|
||||
|
||||
const dispensaAtiva = $derived(dispensaQuery?.data);
|
||||
const estaDispensado = $derived(dispensaAtiva?.dispensado ?? false);
|
||||
const motivoDispensa = $derived(dispensaAtiva?.motivo ?? null);
|
||||
const temFuncionarioAssociado = $derived(funcionarioId !== null);
|
||||
|
||||
const podeRegistrar = $derived.by(() => {
|
||||
return !registrando && !coletandoInfo && config !== undefined;
|
||||
return !registrando && !coletandoInfo && config !== undefined && !estaDispensado && temFuncionarioAssociado;
|
||||
});
|
||||
|
||||
// Referência para o modal
|
||||
@@ -650,55 +693,67 @@
|
||||
</script>
|
||||
|
||||
<div class="space-y-6">
|
||||
<!-- Relógio Sincronizado -->
|
||||
<div class="card bg-base-100 shadow-xl">
|
||||
<div class="card-body items-center">
|
||||
<RelogioSincronizado />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Mapa de Horários -->
|
||||
<div class="card bg-base-100 shadow-xl">
|
||||
<div class="card-body">
|
||||
<h2 class="card-title">
|
||||
<Clock class="h-5 w-5" />
|
||||
Horários do Dia
|
||||
</h2>
|
||||
<div class="mt-4 grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-4">
|
||||
{#each mapaHorarios as horario (horario.tipo)}
|
||||
<div
|
||||
class="card {horario.registrado
|
||||
? 'bg-success/10 border-success'
|
||||
: 'bg-base-200'} border-2"
|
||||
>
|
||||
<div class="card-body p-4">
|
||||
<div class="mb-2 flex items-center justify-between">
|
||||
<span class="font-semibold">{horario.label}</span>
|
||||
{#if horario.registrado}
|
||||
{#if horario.dentroDoPrazo}
|
||||
<CheckCircle2 class="text-success h-5 w-5" />
|
||||
{:else}
|
||||
<XCircle class="text-error h-5 w-5" />
|
||||
{/if}
|
||||
{/if}
|
||||
</div>
|
||||
<div class="text-2xl font-bold">{horario.horario}</div>
|
||||
{#if horario.registrado}
|
||||
<div class="text-base-content/70 text-sm">
|
||||
Registrado: {horario.horarioRegistrado}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
{/each}
|
||||
<!-- Alerta de Funcionário Não Associado -->
|
||||
{#if !temFuncionarioAssociado}
|
||||
<div class="alert alert-error shadow-lg">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
class="h-6 w-6 shrink-0 stroke-current"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
stroke-width="2"
|
||||
d="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z"
|
||||
/>
|
||||
</svg>
|
||||
<div>
|
||||
<h3 class="font-bold">Funcionário Não Associado</h3>
|
||||
<div class="text-sm">
|
||||
Você não possui um funcionário associado à sua conta.
|
||||
<br />
|
||||
Entre em contato com o administrador do sistema para associar um funcionário à sua conta.
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<!-- Alerta de Dispensa -->
|
||||
{#if estaDispensado && motivoDispensa && temFuncionarioAssociado}
|
||||
<div class="alert alert-warning shadow-lg">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
class="h-6 w-6 shrink-0 stroke-current"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
stroke-width="2"
|
||||
d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"
|
||||
/>
|
||||
</svg>
|
||||
<div>
|
||||
<h3 class="font-bold">Registro de Ponto Dispensado</h3>
|
||||
<div class="text-sm">
|
||||
Você está dispensado de registrar ponto no momento.
|
||||
<br />
|
||||
<strong>Motivo:</strong> {motivoDispensa}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<!-- Botões de Registro -->
|
||||
<div class="card bg-base-100 shadow-xl">
|
||||
<div class="card-body items-center">
|
||||
<h2 class="card-title mb-4">Registrar Ponto</h2>
|
||||
<div class="mb-6 w-full">
|
||||
<RelogioSincronizado />
|
||||
</div>
|
||||
<div class="flex w-full flex-col items-center gap-4">
|
||||
{#if sucesso}
|
||||
<div class="alert alert-success w-full">
|
||||
@@ -730,6 +785,11 @@
|
||||
class="btn btn-primary btn-lg"
|
||||
onclick={iniciarRegistroComFoto}
|
||||
disabled={!podeRegistrar}
|
||||
title={!temFuncionarioAssociado
|
||||
? 'Você não possui funcionário associado à sua conta'
|
||||
: estaDispensado
|
||||
? 'Você está dispensado de registrar ponto no momento'
|
||||
: ''}
|
||||
>
|
||||
{#if registrando}
|
||||
<span class="loading loading-spinner loading-sm"></span>
|
||||
@@ -738,6 +798,12 @@
|
||||
{:else}
|
||||
Registrando...
|
||||
{/if}
|
||||
{:else if !temFuncionarioAssociado}
|
||||
<XCircle class="h-5 w-5" />
|
||||
Funcionário Não Associado
|
||||
{:else if estaDispensado}
|
||||
<XCircle class="h-5 w-5" />
|
||||
Registro Indisponível
|
||||
{:else if proximoTipo === 'entrada' || proximoTipo === 'retorno_almoco'}
|
||||
<LogIn class="h-5 w-5" />
|
||||
Registrar Entrada
|
||||
@@ -750,6 +816,78 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Mapa de Horários -->
|
||||
<div class="card bg-base-100 shadow-xl">
|
||||
<div class="card-body">
|
||||
<h2 class="card-title mb-6">
|
||||
<Clock class="h-5 w-5" />
|
||||
Horário Padrão
|
||||
</h2>
|
||||
|
||||
<!-- Linha horizontal com espaçamento uniforme -->
|
||||
<div class="flex flex-wrap items-stretch justify-between gap-4 md:gap-6">
|
||||
{#each mapaHorarios as horario (horario.tipo)}
|
||||
<div class="flex-1 min-w-[140px] max-w-[220px] mx-auto">
|
||||
<div
|
||||
class="relative h-full rounded-xl border-2 transition-all duration-300 hover:shadow-lg {horario.registrado
|
||||
? horario.dentroDoPrazo
|
||||
? 'bg-gradient-to-br from-success/20 to-success/10 border-success shadow-md'
|
||||
: 'bg-gradient-to-br from-error/20 to-error/10 border-error shadow-md'
|
||||
: 'bg-gradient-to-br from-base-200 to-base-300 border-base-300'} p-5"
|
||||
>
|
||||
<!-- Status Icon -->
|
||||
<div class="absolute top-3 right-3">
|
||||
{#if horario.registrado}
|
||||
{#if horario.dentroDoPrazo}
|
||||
<CheckCircle2 class="h-5 w-5 text-success" />
|
||||
{:else}
|
||||
<XCircle class="h-5 w-5 text-error" />
|
||||
{/if}
|
||||
{:else}
|
||||
<Clock class="h-5 w-5 text-base-content/30" />
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<!-- Label -->
|
||||
<div class="mb-3">
|
||||
<span class="text-sm font-semibold text-base-content/80 uppercase tracking-wide">
|
||||
{horario.label}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<!-- Horário Padrão -->
|
||||
<div class="mb-2">
|
||||
<div class="text-3xl font-bold text-primary font-mono">
|
||||
{horario.horario}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Horário Registrado (se houver) -->
|
||||
{#if horario.registrado}
|
||||
<div class="mt-3 pt-3 border-t border-base-content/10">
|
||||
<div class="flex items-center gap-2">
|
||||
<div class="text-xs font-medium text-base-content/60">
|
||||
Registrado:
|
||||
</div>
|
||||
<div class="text-sm font-bold text-base-content">
|
||||
{horario.horarioRegistrado}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{:else}
|
||||
<div class="mt-3 pt-3 border-t border-base-content/10">
|
||||
<div class="text-xs text-base-content/40 italic">
|
||||
Aguardando registro
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Histórico e Saldo do Dia -->
|
||||
{#if historicoSaldo && registrosOrdenados.length > 0}
|
||||
<div class="card bg-base-100 shadow-xl">
|
||||
@@ -780,57 +918,224 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Lista de Registros -->
|
||||
<!-- Timeline de Registros -->
|
||||
<div class="divider"></div>
|
||||
<div class="space-y-2">
|
||||
<h3 class="font-semibold">Registros Realizados</h3>
|
||||
<div class="space-y-3">
|
||||
{#each registrosOrdenados as registro (registro._id)}
|
||||
<div class="card bg-base-200">
|
||||
<div class="card-body p-4">
|
||||
<div class="flex items-start justify-between gap-4">
|
||||
<div class="flex-1">
|
||||
<div class="mb-1 flex items-center gap-2">
|
||||
<span class="font-semibold">
|
||||
{config
|
||||
? getTipoRegistroLabel(registro.tipo, {
|
||||
nomeEntrada: config.nomeEntrada,
|
||||
nomeSaidaAlmoco: config.nomeSaidaAlmoco,
|
||||
nomeRetornoAlmoco: config.nomeRetornoAlmoco,
|
||||
nomeSaida: config.nomeSaida,
|
||||
})
|
||||
: getTipoRegistroLabel(registro.tipo)}
|
||||
</span>
|
||||
{#if registro.dentroDoPrazo}
|
||||
<CheckCircle2 class="h-4 w-4 text-success" />
|
||||
{:else}
|
||||
<XCircle class="h-4 w-4 text-error" />
|
||||
{/if}
|
||||
</div>
|
||||
<p class="text-lg font-bold">
|
||||
{formatarHoraPonto(registro.hora, registro.minuto)}
|
||||
</p>
|
||||
{#if registro.justificativa}
|
||||
<div class="mt-2 rounded bg-base-300 p-2">
|
||||
<p class="text-xs font-semibold opacity-70">Justificativa:</p>
|
||||
<p class="text-sm">{registro.justificativa}</p>
|
||||
<div class="space-y-4">
|
||||
<h3 class="font-semibold">Timeline do Dia</h3>
|
||||
|
||||
<!-- Timeline Visual com horários padrão e registros reais -->
|
||||
<div class="relative">
|
||||
<!-- Linha vertical central da timeline -->
|
||||
<div class="absolute left-1/2 top-0 bottom-0 w-1 bg-gradient-to-b from-primary/20 via-base-300 to-secondary/20 transform -translate-x-1/2"></div>
|
||||
|
||||
<!-- Container com duas colunas -->
|
||||
<div class="grid grid-cols-2 gap-4 relative">
|
||||
<!-- Coluna Entrada -->
|
||||
<div class="space-y-4 pr-2">
|
||||
<div class="sticky top-0 z-10 bg-base-100 pb-3 mb-2 border-b border-primary/20">
|
||||
<h4 class="text-lg font-bold text-primary text-center flex items-center justify-center gap-2">
|
||||
<LogIn class="h-5 w-5" />
|
||||
Entradas
|
||||
</h4>
|
||||
</div>
|
||||
|
||||
{#each registrosOrdenados.filter(r => r.tipo === 'entrada' || r.tipo === 'retorno_almoco') as registro (registro._id)}
|
||||
<div class="relative">
|
||||
<!-- Linha horizontal conectando à timeline -->
|
||||
<div class="absolute right-0 top-6 w-full h-0.5 bg-base-300/50" style="width: calc(100% - 0.5rem);"></div>
|
||||
|
||||
<!-- Card do registro -->
|
||||
<div class="card {registro.dentroDoPrazo ? 'bg-success/5 border-success/30' : 'bg-error/5 border-error/30'} border-2 shadow-md hover:shadow-lg transition-all">
|
||||
<div class="card-body p-4">
|
||||
<!-- Tipo de registro e status -->
|
||||
<div class="flex items-center gap-2 mb-2">
|
||||
{#if registro.dentroDoPrazo}
|
||||
<CheckCircle2 class="h-4 w-4 text-success flex-shrink-0" />
|
||||
{:else}
|
||||
<XCircle class="h-4 w-4 text-error flex-shrink-0" />
|
||||
{/if}
|
||||
<span class="text-sm font-semibold text-base-content/80">
|
||||
{config
|
||||
? getTipoRegistroLabel(registro.tipo, {
|
||||
nomeEntrada: config.nomeEntrada,
|
||||
nomeRetornoAlmoco: config.nomeRetornoAlmoco,
|
||||
})
|
||||
: getTipoRegistroLabel(registro.tipo)}
|
||||
</span>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
<div class="flex-shrink-0">
|
||||
<button
|
||||
class="btn btn-sm btn-outline btn-primary gap-2"
|
||||
onclick={() => imprimirComprovante(registro._id)}
|
||||
title="Imprimir Comprovante"
|
||||
>
|
||||
<Printer class="h-4 w-4" />
|
||||
Imprimir Comprovante
|
||||
</button>
|
||||
|
||||
<!-- Horário registrado -->
|
||||
<p class="text-3xl font-bold text-primary mb-1">
|
||||
{formatarHoraPonto(registro.hora, registro.minuto)}
|
||||
</p>
|
||||
|
||||
<!-- Comparação com horário esperado -->
|
||||
{#if config}
|
||||
{@const horarioEsperado = registro.tipo === 'entrada' ? config.horarioEntrada : config.horarioRetornoAlmoco}
|
||||
{@const [horaEsperada, minutoEsperado] = horarioEsperado.split(':').map(Number)}
|
||||
{@const minutosEsperados = horaEsperada * 60 + minutoEsperado}
|
||||
{@const minutosRegistrados = registro.hora * 60 + registro.minuto}
|
||||
{@const diferenca = minutosRegistrados - minutosEsperados}
|
||||
{@const diferencaAbs = Math.abs(diferenca)}
|
||||
{@const diferencaTexto = diferencaAbs >= 60
|
||||
? `${Math.floor(diferencaAbs / 60)}h ${diferencaAbs % 60}min`
|
||||
: `${diferencaAbs}min`}
|
||||
|
||||
<div class="flex items-center gap-2 text-xs mb-3">
|
||||
<span class="text-base-content/50">Esperado:</span>
|
||||
<span class="font-semibold">{horarioEsperado}</span>
|
||||
{#if diferencaAbs > 0}
|
||||
<span class="badge badge-xs {diferenca > 0 ? 'badge-warning' : 'badge-info'}">
|
||||
{diferenca > 0 ? '+' : '-'}{diferencaTexto}
|
||||
</span>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if registro.justificativa}
|
||||
<div class="mt-2 rounded-lg bg-base-300/50 p-2 text-xs mb-3">
|
||||
<p class="font-semibold opacity-70 mb-1">Justificativa:</p>
|
||||
<p class="text-base-content/80">{registro.justificativa}</p>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<button
|
||||
class="btn btn-sm btn-outline btn-primary gap-2 w-full"
|
||||
onclick={() => imprimirComprovante(registro._id)}
|
||||
title="Imprimir Comprovante"
|
||||
>
|
||||
<Printer class="h-4 w-4" />
|
||||
Imprimir Comprovante
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{/each}
|
||||
|
||||
<!-- Mostrar horários esperados que não foram registrados -->
|
||||
{#if config}
|
||||
{#each [
|
||||
{ tipo: 'entrada', horario: config.horarioEntrada, label: config.nomeEntrada || 'Entrada 1' },
|
||||
{ tipo: 'retorno_almoco', horario: config.horarioRetornoAlmoco, label: config.nomeRetornoAlmoco || 'Entrada 2' }
|
||||
] as horarioEsperado}
|
||||
{#if !registrosOrdenados.find(r => r.tipo === horarioEsperado.tipo)}
|
||||
<div class="relative opacity-50">
|
||||
<div class="absolute right-0 top-6 w-full h-0.5 bg-base-300/30 border-dashed" style="width: calc(100% - 0.5rem);"></div>
|
||||
<div class="card bg-base-200/50 border border-dashed border-base-300">
|
||||
<div class="card-body p-3">
|
||||
<p class="text-xs text-base-content/50 mb-1">{horarioEsperado.label} (não registrado)</p>
|
||||
<p class="text-xl font-bold text-base-content/40">{horarioEsperado.horario}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
{/each}
|
||||
{/if}
|
||||
</div>
|
||||
{/each}
|
||||
|
||||
<!-- Coluna Saída -->
|
||||
<div class="space-y-4 pl-2">
|
||||
<div class="sticky top-0 z-10 bg-base-100 pb-3 mb-2 border-b border-secondary/20">
|
||||
<h4 class="text-lg font-bold text-secondary text-center flex items-center justify-center gap-2">
|
||||
<LogOut class="h-5 w-5" />
|
||||
Saídas
|
||||
</h4>
|
||||
</div>
|
||||
|
||||
{#each registrosOrdenados.filter(r => r.tipo === 'saida_almoco' || r.tipo === 'saida') as registro (registro._id)}
|
||||
<div class="relative">
|
||||
<!-- Linha horizontal conectando à timeline -->
|
||||
<div class="absolute left-0 top-6 w-full h-0.5 bg-base-300/50" style="width: calc(100% - 0.5rem);"></div>
|
||||
|
||||
<!-- Card do registro -->
|
||||
<div class="card {registro.dentroDoPrazo ? 'bg-success/5 border-success/30' : 'bg-error/5 border-error/30'} border-2 shadow-md hover:shadow-lg transition-all">
|
||||
<div class="card-body p-4">
|
||||
<!-- Tipo de registro e status -->
|
||||
<div class="flex items-center gap-2 mb-2 justify-end">
|
||||
<span class="text-sm font-semibold text-base-content/80">
|
||||
{config
|
||||
? getTipoRegistroLabel(registro.tipo, {
|
||||
nomeSaidaAlmoco: config.nomeSaidaAlmoco,
|
||||
nomeSaida: config.nomeSaida,
|
||||
})
|
||||
: getTipoRegistroLabel(registro.tipo)}
|
||||
</span>
|
||||
{#if registro.dentroDoPrazo}
|
||||
<CheckCircle2 class="h-4 w-4 text-success flex-shrink-0" />
|
||||
{:else}
|
||||
<XCircle class="h-4 w-4 text-error flex-shrink-0" />
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<!-- Horário registrado -->
|
||||
<p class="text-3xl font-bold text-secondary mb-1 text-right">
|
||||
{formatarHoraPonto(registro.hora, registro.minuto)}
|
||||
</p>
|
||||
|
||||
<!-- Comparação com horário esperado -->
|
||||
{#if config}
|
||||
{@const horarioEsperado = registro.tipo === 'saida_almoco' ? config.horarioSaidaAlmoco : config.horarioSaida}
|
||||
{@const [horaEsperada, minutoEsperado] = horarioEsperado.split(':').map(Number)}
|
||||
{@const minutosEsperados = horaEsperada * 60 + minutoEsperado}
|
||||
{@const minutosRegistrados = registro.hora * 60 + registro.minuto}
|
||||
{@const diferenca = minutosRegistrados - minutosEsperados}
|
||||
{@const diferencaAbs = Math.abs(diferenca)}
|
||||
{@const diferencaTexto = diferencaAbs >= 60
|
||||
? `${Math.floor(diferencaAbs / 60)}h ${diferencaAbs % 60}min`
|
||||
: `${diferencaAbs}min`}
|
||||
|
||||
<div class="flex items-center gap-2 text-xs mb-3 justify-end">
|
||||
{#if diferencaAbs > 0}
|
||||
<span class="badge badge-xs {diferenca > 0 ? 'badge-warning' : 'badge-info'}">
|
||||
{diferenca > 0 ? '+' : '-'}{diferencaTexto}
|
||||
</span>
|
||||
{/if}
|
||||
<span class="font-semibold">{horarioEsperado}</span>
|
||||
<span class="text-base-content/50">Esperado:</span>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if registro.justificativa}
|
||||
<div class="mt-2 rounded-lg bg-base-300/50 p-2 text-xs mb-3">
|
||||
<p class="font-semibold opacity-70 mb-1">Justificativa:</p>
|
||||
<p class="text-base-content/80">{registro.justificativa}</p>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<button
|
||||
class="btn btn-sm btn-outline btn-primary gap-2 w-full"
|
||||
onclick={() => imprimirComprovante(registro._id)}
|
||||
title="Imprimir Comprovante"
|
||||
>
|
||||
<Printer class="h-4 w-4" />
|
||||
Imprimir Comprovante
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{/each}
|
||||
|
||||
<!-- Mostrar horários esperados que não foram registrados -->
|
||||
{#if config}
|
||||
{#each [
|
||||
{ tipo: 'saida_almoco', horario: config.horarioSaidaAlmoco, label: config.nomeSaidaAlmoco || 'Saída 1' },
|
||||
{ tipo: 'saida', horario: config.horarioSaida, label: config.nomeSaida || 'Saída 2' }
|
||||
] as horarioEsperado}
|
||||
{#if !registrosOrdenados.find(r => r.tipo === horarioEsperado.tipo)}
|
||||
<div class="relative opacity-50">
|
||||
<div class="absolute left-0 top-6 w-full h-0.5 bg-base-300/30 border-dashed" style="width: calc(100% - 0.5rem);"></div>
|
||||
<div class="card bg-base-200/50 border border-dashed border-base-300">
|
||||
<div class="card-body p-3">
|
||||
<p class="text-xs text-base-content/50 mb-1 text-right">{horarioEsperado.label} (não registrado)</p>
|
||||
<p class="text-xl font-bold text-base-content/40 text-right">{horarioEsperado.horario}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
{/each}
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -17,36 +17,45 @@
|
||||
async function atualizarTempo() {
|
||||
try {
|
||||
const config = await client.query(api.configuracaoRelogio.obterConfiguracao, {});
|
||||
const gmtOffset = config.gmtOffset ?? 0;
|
||||
|
||||
let timestampBase: number;
|
||||
|
||||
if (config.usarServidorExterno) {
|
||||
try {
|
||||
const resultado = await client.action(api.configuracaoRelogio.sincronizarTempo, {});
|
||||
if (resultado.sucesso && resultado.timestamp) {
|
||||
tempoAtual = new Date(resultado.timestamp);
|
||||
timestampBase = resultado.timestamp;
|
||||
sincronizado = true;
|
||||
usandoServidorExterno = resultado.usandoServidorExterno || false;
|
||||
offsetSegundos = resultado.offsetSegundos || 0;
|
||||
erro = null;
|
||||
} else {
|
||||
throw new Error('Falha ao sincronizar');
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('Erro ao sincronizar:', error);
|
||||
if (config.fallbackParaPC) {
|
||||
tempoAtual = new Date(obterTempoPC());
|
||||
timestampBase = obterTempoPC();
|
||||
sincronizado = false;
|
||||
usandoServidorExterno = false;
|
||||
erro = 'Usando relógio do PC (falha na sincronização)';
|
||||
} else {
|
||||
erro = 'Falha ao sincronizar tempo';
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Usar tempo do servidor Convex
|
||||
const tempoServidor = await obterTempoServidor(client);
|
||||
tempoAtual = new Date(tempoServidor);
|
||||
timestampBase = await obterTempoServidor(client);
|
||||
sincronizado = true;
|
||||
usandoServidorExterno = false;
|
||||
erro = null;
|
||||
}
|
||||
|
||||
// Aplicar GMT offset ao timestamp
|
||||
// O timestamp está em UTC, adicionar o offset em horas
|
||||
const timestampAjustado = timestampBase + (gmtOffset * 60 * 60 * 1000);
|
||||
tempoAtual = new Date(timestampAjustado);
|
||||
} catch (error) {
|
||||
console.error('Erro ao obter tempo:', error);
|
||||
tempoAtual = new Date(obterTempoPC());
|
||||
|
||||
@@ -1,63 +0,0 @@
|
||||
// Mapa de seeds para os 32 avatares
|
||||
const avatarSeeds: Record<string, string> = {
|
||||
// Masculinos (16)
|
||||
"avatar-m-1": "John",
|
||||
"avatar-m-2": "Peter",
|
||||
"avatar-m-3": "Michael",
|
||||
"avatar-m-4": "David",
|
||||
"avatar-m-5": "James",
|
||||
"avatar-m-6": "Robert",
|
||||
"avatar-m-7": "William",
|
||||
"avatar-m-8": "Joseph",
|
||||
"avatar-m-9": "Thomas",
|
||||
"avatar-m-10": "Charles",
|
||||
"avatar-m-11": "Daniel",
|
||||
"avatar-m-12": "Matthew",
|
||||
"avatar-m-13": "Anthony",
|
||||
"avatar-m-14": "Mark",
|
||||
"avatar-m-15": "Donald",
|
||||
"avatar-m-16": "Steven",
|
||||
// Femininos (16)
|
||||
"avatar-f-1": "Maria",
|
||||
"avatar-f-2": "Ana",
|
||||
"avatar-f-3": "Patricia",
|
||||
"avatar-f-4": "Jennifer",
|
||||
"avatar-f-5": "Linda",
|
||||
"avatar-f-6": "Barbara",
|
||||
"avatar-f-7": "Elizabeth",
|
||||
"avatar-f-8": "Jessica",
|
||||
"avatar-f-9": "Sarah",
|
||||
"avatar-f-10": "Karen",
|
||||
"avatar-f-11": "Nancy",
|
||||
"avatar-f-12": "Betty",
|
||||
"avatar-f-13": "Helen",
|
||||
"avatar-f-14": "Sandra",
|
||||
"avatar-f-15": "Ashley",
|
||||
"avatar-f-16": "Kimberly",
|
||||
};
|
||||
|
||||
/**
|
||||
* Gera URL do avatar usando API DiceBear com parâmetros simples
|
||||
*/
|
||||
export function getAvatarUrl(avatarId: string): string {
|
||||
const seed = avatarSeeds[avatarId] || avatarId || "default";
|
||||
|
||||
// Usar avataarstyle do DiceBear com parâmetros mínimos
|
||||
// API v7 suporta apenas parâmetros específicos
|
||||
return `https://api.dicebear.com/7.x/avataaars/svg?seed=${encodeURIComponent(seed)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Lista todos os IDs de avatares disponíveis
|
||||
*/
|
||||
export function getAllAvatarIds(): string[] {
|
||||
return Object.keys(avatarSeeds);
|
||||
}
|
||||
|
||||
/**
|
||||
* Verifica se um avatarId é válido
|
||||
*/
|
||||
export function isValidAvatarId(avatarId: string): boolean {
|
||||
return avatarId in avatarSeeds;
|
||||
}
|
||||
|
||||
@@ -1,283 +0,0 @@
|
||||
// Galeria de avatares inspirados em artistas do cinema
|
||||
// Usando DiceBear API com estilos variados para aparência cinematográfica
|
||||
|
||||
export interface Avatar {
|
||||
id: string;
|
||||
name: string;
|
||||
url: string;
|
||||
seed: string;
|
||||
style: string;
|
||||
}
|
||||
|
||||
// Avatares inspirados em artistas do cinema (30 avatares estilizados)
|
||||
const cinemaArtistsAvatars = [
|
||||
// 15 Masculinos - Inspirados em grandes atores
|
||||
{
|
||||
id: 'avatar-male-1',
|
||||
name: 'Leonardo DiCaprio',
|
||||
seed: 'Leonardo',
|
||||
style: 'adventurer',
|
||||
bgColor: 'C5CAE9',
|
||||
},
|
||||
{
|
||||
id: 'avatar-male-2',
|
||||
name: 'Brad Pitt',
|
||||
seed: 'Bradley',
|
||||
style: 'adventurer',
|
||||
bgColor: 'B2DFDB',
|
||||
},
|
||||
{
|
||||
id: 'avatar-male-3',
|
||||
name: 'Tom Hanks',
|
||||
seed: 'Thomas',
|
||||
style: 'adventurer-neutral',
|
||||
bgColor: 'DCEDC8',
|
||||
},
|
||||
{
|
||||
id: 'avatar-male-4',
|
||||
name: 'Morgan Freeman',
|
||||
seed: 'Morgan',
|
||||
style: 'adventurer',
|
||||
bgColor: 'F0F4C3',
|
||||
},
|
||||
{
|
||||
id: 'avatar-male-5',
|
||||
name: 'Robert De Niro',
|
||||
seed: 'Robert',
|
||||
style: 'adventurer-neutral',
|
||||
bgColor: 'E0E0E0',
|
||||
},
|
||||
{
|
||||
id: 'avatar-male-6',
|
||||
name: 'Al Pacino',
|
||||
seed: 'Alfredo',
|
||||
style: 'adventurer',
|
||||
bgColor: 'FFCCBC',
|
||||
},
|
||||
{
|
||||
id: 'avatar-male-7',
|
||||
name: 'Johnny Depp',
|
||||
seed: 'John',
|
||||
style: 'adventurer',
|
||||
bgColor: 'D1C4E9',
|
||||
},
|
||||
{
|
||||
id: 'avatar-male-8',
|
||||
name: 'Denzel Washington',
|
||||
seed: 'Denzel',
|
||||
style: 'adventurer-neutral',
|
||||
bgColor: 'B3E5FC',
|
||||
},
|
||||
{
|
||||
id: 'avatar-male-9',
|
||||
name: 'Will Smith',
|
||||
seed: 'Willard',
|
||||
style: 'adventurer',
|
||||
bgColor: 'FFF9C4',
|
||||
},
|
||||
{
|
||||
id: 'avatar-male-10',
|
||||
name: 'Tom Cruise',
|
||||
seed: 'TomC',
|
||||
style: 'adventurer-neutral',
|
||||
bgColor: 'CFD8DC',
|
||||
},
|
||||
{
|
||||
id: 'avatar-male-11',
|
||||
name: 'Samuel L Jackson',
|
||||
seed: 'Samuel',
|
||||
style: 'adventurer',
|
||||
bgColor: 'F8BBD0',
|
||||
},
|
||||
{
|
||||
id: 'avatar-male-12',
|
||||
name: 'Harrison Ford',
|
||||
seed: 'Harrison',
|
||||
style: 'adventurer-neutral',
|
||||
bgColor: 'C8E6C9',
|
||||
},
|
||||
{
|
||||
id: 'avatar-male-13',
|
||||
name: 'Keanu Reeves',
|
||||
seed: 'Keanu',
|
||||
style: 'adventurer',
|
||||
bgColor: 'BBDEFB',
|
||||
},
|
||||
{
|
||||
id: 'avatar-male-14',
|
||||
name: 'Matt Damon',
|
||||
seed: 'Matthew',
|
||||
style: 'adventurer-neutral',
|
||||
bgColor: 'FFE0B2',
|
||||
},
|
||||
{
|
||||
id: 'avatar-male-15',
|
||||
name: 'Christian Bale',
|
||||
seed: 'Christian',
|
||||
style: 'adventurer',
|
||||
bgColor: 'E1BEE7',
|
||||
},
|
||||
// 15 Femininos - Inspiradas em grandes atrizes
|
||||
{
|
||||
id: 'avatar-female-1',
|
||||
name: 'Meryl Streep',
|
||||
seed: 'Meryl',
|
||||
style: 'lorelei',
|
||||
bgColor: 'F8BBD0',
|
||||
},
|
||||
{
|
||||
id: 'avatar-female-2',
|
||||
name: 'Scarlett Johansson',
|
||||
seed: 'Scarlett',
|
||||
style: 'lorelei',
|
||||
bgColor: 'FFCCBC',
|
||||
},
|
||||
{
|
||||
id: 'avatar-female-3',
|
||||
name: 'Jennifer Lawrence',
|
||||
seed: 'Jennifer',
|
||||
style: 'lorelei-neutral',
|
||||
bgColor: 'E1BEE7',
|
||||
},
|
||||
{
|
||||
id: 'avatar-female-4',
|
||||
name: 'Angelina Jolie',
|
||||
seed: 'Angelina',
|
||||
style: 'lorelei',
|
||||
bgColor: 'C5CAE9',
|
||||
},
|
||||
{
|
||||
id: 'avatar-female-5',
|
||||
name: 'Cate Blanchett',
|
||||
seed: 'Catherine',
|
||||
style: 'lorelei-neutral',
|
||||
bgColor: 'B2DFDB',
|
||||
},
|
||||
{
|
||||
id: 'avatar-female-6',
|
||||
name: 'Nicole Kidman',
|
||||
seed: 'Nicole',
|
||||
style: 'lorelei',
|
||||
bgColor: 'DCEDC8',
|
||||
},
|
||||
{
|
||||
id: 'avatar-female-7',
|
||||
name: 'Julia Roberts',
|
||||
seed: 'Julia',
|
||||
style: 'lorelei-neutral',
|
||||
bgColor: 'FFF9C4',
|
||||
},
|
||||
{
|
||||
id: 'avatar-female-8',
|
||||
name: 'Emma Stone',
|
||||
seed: 'Emma',
|
||||
style: 'lorelei',
|
||||
bgColor: 'CFD8DC',
|
||||
},
|
||||
{
|
||||
id: 'avatar-female-9',
|
||||
name: 'Natalie Portman',
|
||||
seed: 'Natalie',
|
||||
style: 'lorelei-neutral',
|
||||
bgColor: 'F0F4C3',
|
||||
},
|
||||
{
|
||||
id: 'avatar-female-10',
|
||||
name: 'Charlize Theron',
|
||||
seed: 'Charlize',
|
||||
style: 'lorelei',
|
||||
bgColor: 'E0E0E0',
|
||||
},
|
||||
{
|
||||
id: 'avatar-female-11',
|
||||
name: 'Kate Winslet',
|
||||
seed: 'Kate',
|
||||
style: 'lorelei-neutral',
|
||||
bgColor: 'D1C4E9',
|
||||
},
|
||||
{
|
||||
id: 'avatar-female-12',
|
||||
name: 'Sandra Bullock',
|
||||
seed: 'Sandra',
|
||||
style: 'lorelei',
|
||||
bgColor: 'B3E5FC',
|
||||
},
|
||||
{
|
||||
id: 'avatar-female-13',
|
||||
name: 'Halle Berry',
|
||||
seed: 'Halle',
|
||||
style: 'lorelei-neutral',
|
||||
bgColor: 'C8E6C9',
|
||||
},
|
||||
{
|
||||
id: 'avatar-female-14',
|
||||
name: 'Anne Hathaway',
|
||||
seed: 'Anne',
|
||||
style: 'lorelei',
|
||||
bgColor: 'BBDEFB',
|
||||
},
|
||||
{
|
||||
id: 'avatar-female-15',
|
||||
name: 'Amy Adams',
|
||||
seed: 'Amy',
|
||||
style: 'lorelei-neutral',
|
||||
bgColor: 'FFE0B2',
|
||||
},
|
||||
];
|
||||
|
||||
/**
|
||||
* Gera uma galeria de avatares inspirados em artistas do cinema
|
||||
* Usa DiceBear API com estilos cinematográficos
|
||||
* @param count Número de avatares a gerar (padrão: 30)
|
||||
* @returns Array de objetos com id, name, url, seed e style
|
||||
*/
|
||||
export function generateAvatarGallery(count: number = 30): Avatar[] {
|
||||
const avatars: Avatar[] = [];
|
||||
|
||||
for (let i = 0; i < Math.min(count, cinemaArtistsAvatars.length); i++) {
|
||||
const avatar = cinemaArtistsAvatars[i];
|
||||
|
||||
// URL do DiceBear com estilo cinematográfico
|
||||
const url = `https://api.dicebear.com/7.x/${avatar.style}/svg?seed=${encodeURIComponent(avatar.seed)}&backgroundColor=${avatar.bgColor}&radius=50&size=200`;
|
||||
|
||||
avatars.push({
|
||||
id: avatar.id,
|
||||
name: avatar.name,
|
||||
url,
|
||||
seed: avatar.seed,
|
||||
style: avatar.style,
|
||||
});
|
||||
}
|
||||
|
||||
return avatars;
|
||||
}
|
||||
|
||||
/**
|
||||
* Obter URL do avatar por ID
|
||||
* @param avatarId ID do avatar (ex: "avatar-male-1")
|
||||
* @returns URL do avatar ou string vazia se não encontrado
|
||||
*/
|
||||
export function getAvatarUrl(avatarId: string): string {
|
||||
const gallery = generateAvatarGallery();
|
||||
const avatar = gallery.find(a => a.id === avatarId);
|
||||
return avatar?.url || '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Gerar avatar aleatório da galeria
|
||||
* @returns Avatar aleatório
|
||||
*/
|
||||
export function getRandomAvatar(): Avatar {
|
||||
const gallery = generateAvatarGallery();
|
||||
const randomIndex = Math.floor(Math.random() * gallery.length);
|
||||
return gallery[randomIndex];
|
||||
}
|
||||
|
||||
/**
|
||||
* Salvar avatar selecionado (retorna o ID para salvar no backend)
|
||||
* @param avatarId ID do avatar selecionado
|
||||
* @returns ID do avatar
|
||||
*/
|
||||
export function saveAvatarSelection(avatarId: string): string {
|
||||
return avatarId;
|
||||
}
|
||||
@@ -15,6 +15,13 @@ export interface InformacoesDispositivo {
|
||||
latitude?: number;
|
||||
longitude?: number;
|
||||
precisao?: number;
|
||||
altitude?: number | null;
|
||||
altitudeAccuracy?: number | null;
|
||||
heading?: number | null;
|
||||
speed?: number | null;
|
||||
confiabilidadeGPS?: number; // 0-1
|
||||
suspeitaSpoofing?: boolean;
|
||||
motivoSuspeita?: string;
|
||||
endereco?: string;
|
||||
cidade?: string;
|
||||
estado?: string;
|
||||
@@ -230,12 +237,289 @@ function obterInformacoesMemoria(): string {
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtém localização via GPS com múltiplas tentativas
|
||||
* Calcula distância entre duas coordenadas (fórmula de Haversine)
|
||||
* Retorna distância em metros
|
||||
*/
|
||||
function calcularDistancia(
|
||||
lat1: number,
|
||||
lon1: number,
|
||||
lat2: number,
|
||||
lon2: number
|
||||
): number {
|
||||
const R = 6371000; // Raio da Terra em metros
|
||||
const dLat = ((lat2 - lat1) * Math.PI) / 180;
|
||||
const dLon = ((lon2 - lon1) * Math.PI) / 180;
|
||||
const a =
|
||||
Math.sin(dLat / 2) * Math.sin(dLat / 2) +
|
||||
Math.cos((lat1 * Math.PI) / 180) *
|
||||
Math.cos((lat2 * Math.PI) / 180) *
|
||||
Math.sin(dLon / 2) *
|
||||
Math.sin(dLon / 2);
|
||||
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
|
||||
return R * c;
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtém timezone aproximado por coordenadas
|
||||
*/
|
||||
function obterTimezonePorCoordenadas(latitude: number, longitude: number): string {
|
||||
// Pernambuco está em UTC-3 (America/Recife)
|
||||
if (longitude >= -45 && longitude <= -30 && latitude >= -10 && latitude <= 5) {
|
||||
return 'America/Recife'; // UTC-3
|
||||
}
|
||||
|
||||
// Fallback: usar timezone do sistema
|
||||
try {
|
||||
return Intl.DateTimeFormat().resolvedOptions().timeZone;
|
||||
} catch {
|
||||
return 'America/Recife'; // Default
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Captura uma única leitura de localização com todas as propriedades disponíveis
|
||||
*/
|
||||
async function capturarLocalizacaoUnica(
|
||||
enableHighAccuracy: boolean = true,
|
||||
timeout: number = 10000
|
||||
): Promise<{
|
||||
latitude?: number;
|
||||
longitude?: number;
|
||||
precisao?: number;
|
||||
altitude?: number | null;
|
||||
altitudeAccuracy?: number | null;
|
||||
heading?: number | null;
|
||||
speed?: number | null;
|
||||
timestamp?: number;
|
||||
confiabilidade: number; // 0-1
|
||||
}> {
|
||||
return new Promise((resolve) => {
|
||||
if (typeof navigator === 'undefined' || !navigator.geolocation) {
|
||||
resolve({ confiabilidade: 0 });
|
||||
return;
|
||||
}
|
||||
|
||||
const timeoutId = setTimeout(() => {
|
||||
resolve({ confiabilidade: 0 });
|
||||
}, timeout + 1000);
|
||||
|
||||
navigator.geolocation.getCurrentPosition(
|
||||
(position) => {
|
||||
clearTimeout(timeoutId);
|
||||
const coords = position.coords;
|
||||
const { latitude, longitude, accuracy } = coords;
|
||||
|
||||
// Validar coordenadas básicas
|
||||
if (
|
||||
isNaN(latitude) ||
|
||||
isNaN(longitude) ||
|
||||
latitude === 0 ||
|
||||
longitude === 0 ||
|
||||
latitude < -90 ||
|
||||
latitude > 90 ||
|
||||
longitude < -180 ||
|
||||
longitude > 180
|
||||
) {
|
||||
resolve({ confiabilidade: 0 });
|
||||
return;
|
||||
}
|
||||
|
||||
// Calcular score de confiabilidade baseado em propriedades do GPS real
|
||||
const sinaisGPSReal = {
|
||||
temAltitude: coords.altitude !== null && coords.altitude !== 0,
|
||||
temAltitudeAccuracy: coords.altitudeAccuracy !== null && coords.altitudeAccuracy > 0,
|
||||
temHeading: coords.heading !== null && !isNaN(coords.heading),
|
||||
temSpeed: coords.speed !== null && !isNaN(coords.speed),
|
||||
precisaoBoa: accuracy < 20, // GPS real geralmente < 20m
|
||||
precisaoMedia: accuracy >= 20 && accuracy < 100,
|
||||
timestampPreciso: position.timestamp > 0
|
||||
};
|
||||
|
||||
// Calcular confiabilidade: cada sinal adiciona pontos
|
||||
let pontos = 0;
|
||||
const maxPontos = 7;
|
||||
|
||||
if (sinaisGPSReal.temAltitude) pontos += 1;
|
||||
if (sinaisGPSReal.temAltitudeAccuracy) pontos += 1;
|
||||
if (sinaisGPSReal.temHeading) pontos += 0.5;
|
||||
if (sinaisGPSReal.temSpeed) pontos += 0.5;
|
||||
if (sinaisGPSReal.precisaoBoa) pontos += 2;
|
||||
if (sinaisGPSReal.precisaoMedia) pontos += 1;
|
||||
if (sinaisGPSReal.timestampPreciso) pontos += 1;
|
||||
|
||||
const confiabilidade = Math.min(pontos / maxPontos, 1);
|
||||
|
||||
resolve({
|
||||
latitude,
|
||||
longitude,
|
||||
precisao: accuracy,
|
||||
altitude: coords.altitude ?? null,
|
||||
altitudeAccuracy: coords.altitudeAccuracy ?? null,
|
||||
heading: coords.heading ?? null,
|
||||
speed: coords.speed ?? null,
|
||||
timestamp: position.timestamp,
|
||||
confiabilidade
|
||||
});
|
||||
},
|
||||
(error) => {
|
||||
clearTimeout(timeoutId);
|
||||
console.warn('Erro ao obter localização:', error.code, error.message);
|
||||
resolve({ confiabilidade: 0 });
|
||||
},
|
||||
{
|
||||
enableHighAccuracy,
|
||||
timeout,
|
||||
maximumAge: 0 // Sempre obter nova leitura
|
||||
}
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtém localização via GPS com múltiplas leituras para detectar spoofing
|
||||
* Apps de spoofing geralmente retornam valores idênticos em todas as leituras
|
||||
*/
|
||||
async function obterLocalizacaoMultipla(): Promise<{
|
||||
latitude?: number;
|
||||
longitude?: number;
|
||||
precisao?: number;
|
||||
altitude?: number | null;
|
||||
altitudeAccuracy?: number | null;
|
||||
heading?: number | null;
|
||||
speed?: number | null;
|
||||
confiabilidade: number; // 0-1
|
||||
suspeitaSpoofing: boolean;
|
||||
motivoSuspeita?: string;
|
||||
}> {
|
||||
if (typeof navigator === 'undefined' || !navigator.geolocation) {
|
||||
return { confiabilidade: 0, suspeitaSpoofing: true, motivoSuspeita: 'Geolocalização não suportada' };
|
||||
}
|
||||
|
||||
// Capturar 3 leituras com intervalo de 2 segundos entre elas
|
||||
const leituras: Array<{
|
||||
lat: number;
|
||||
lon: number;
|
||||
precisao: number;
|
||||
altitude: number | null;
|
||||
confiabilidade: number;
|
||||
}> = [];
|
||||
|
||||
for (let i = 0; i < 3; i++) {
|
||||
const leitura = await capturarLocalizacaoUnica(true, 8000);
|
||||
|
||||
if (leitura.latitude && leitura.longitude && leitura.confiabilidade > 0) {
|
||||
leituras.push({
|
||||
lat: leitura.latitude,
|
||||
lon: leitura.longitude,
|
||||
precisao: leitura.precisao || 999,
|
||||
altitude: leitura.altitude ?? null,
|
||||
confiabilidade: leitura.confiabilidade
|
||||
});
|
||||
}
|
||||
|
||||
// Aguardar 2 segundos entre leituras (exceto na última)
|
||||
if (i < 2) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 2000));
|
||||
}
|
||||
}
|
||||
|
||||
if (leituras.length === 0) {
|
||||
return { confiabilidade: 0, suspeitaSpoofing: true, motivoSuspeita: 'Não foi possível obter localização' };
|
||||
}
|
||||
|
||||
// Se tivermos menos de 2 leituras, usar única leitura com baixa confiança
|
||||
if (leituras.length < 2) {
|
||||
const unica = leituras[0];
|
||||
return {
|
||||
latitude: unica.lat,
|
||||
longitude: unica.lon,
|
||||
precisao: unica.precisao,
|
||||
altitude: unica.altitude,
|
||||
altitudeAccuracy: null,
|
||||
heading: null,
|
||||
speed: null,
|
||||
confiabilidade: unica.confiabilidade * 0.5, // Reduzir confiança por ter apenas 1 leitura
|
||||
suspeitaSpoofing: true,
|
||||
motivoSuspeita: 'Apenas uma leitura obtida'
|
||||
};
|
||||
}
|
||||
|
||||
// Verificar se todas as leituras são idênticas (suspeito de spoofing)
|
||||
const primeiraLeitura = leituras[0];
|
||||
const todasIguais = leituras.every(
|
||||
(l) =>
|
||||
Math.abs(l.lat - primeiraLeitura.lat) < 0.00001 && // ~1 metro
|
||||
Math.abs(l.lon - primeiraLeitura.lon) < 0.00001
|
||||
);
|
||||
|
||||
if (todasIguais && leituras.length === 3) {
|
||||
// GPS real varia alguns metros, se todas são idênticas pode ser spoofing
|
||||
return {
|
||||
latitude: primeiraLeitura.lat,
|
||||
longitude: primeiraLeitura.lon,
|
||||
precisao: primeiraLeitura.precisao,
|
||||
altitude: primeiraLeitura.altitude,
|
||||
altitudeAccuracy: null,
|
||||
heading: null,
|
||||
speed: null,
|
||||
confiabilidade: primeiraLeitura.confiabilidade * 0.4, // Reduzir drasticamente confiança
|
||||
suspeitaSpoofing: true,
|
||||
motivoSuspeita: 'Todas as leituras são idênticas (GPS real varia alguns metros)'
|
||||
};
|
||||
}
|
||||
|
||||
// Calcular média das leituras e variância
|
||||
const mediaLat = leituras.reduce((sum, l) => sum + l.lat, 0) / leituras.length;
|
||||
const mediaLon = leituras.reduce((sum, l) => sum + l.lon, 0) / leituras.length;
|
||||
const mediaConfianca = leituras.reduce((sum, l) => sum + l.confiabilidade, 0) / leituras.length;
|
||||
|
||||
// Calcular distância máxima entre leituras
|
||||
let distanciaMaxima = 0;
|
||||
for (let i = 0; i < leituras.length; i++) {
|
||||
for (let j = i + 1; j < leituras.length; j++) {
|
||||
const dist = calcularDistancia(
|
||||
leituras[i].lat,
|
||||
leituras[i].lon,
|
||||
leituras[j].lat,
|
||||
leituras[j].lon
|
||||
);
|
||||
distanciaMaxima = Math.max(distanciaMaxima, dist);
|
||||
}
|
||||
}
|
||||
|
||||
// Se distância máxima for muito grande (> 100m), pode indicar problemas
|
||||
const suspeitoPorDistancia = distanciaMaxima > 100;
|
||||
|
||||
return {
|
||||
latitude: mediaLat,
|
||||
longitude: mediaLon,
|
||||
precisao: primeiraLeitura.precisao,
|
||||
altitude: primeiraLeitura.altitude,
|
||||
altitudeAccuracy: null,
|
||||
heading: null,
|
||||
speed: null,
|
||||
confiabilidade: suspeitoPorDistancia ? mediaConfianca * 0.6 : mediaConfianca,
|
||||
suspeitaSpoofing: suspeitoPorDistancia,
|
||||
motivoSuspeita: suspeitoPorDistancia
|
||||
? `Variação muito grande entre leituras (${Math.round(distanciaMaxima)}m)`
|
||||
: undefined
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtém localização via GPS com múltiplas tentativas e validações anti-spoofing
|
||||
*/
|
||||
async function obterLocalizacao(): Promise<{
|
||||
latitude?: number;
|
||||
longitude?: number;
|
||||
precisao?: number;
|
||||
altitude?: number | null;
|
||||
altitudeAccuracy?: number | null;
|
||||
heading?: number | null;
|
||||
speed?: number | null;
|
||||
confiabilidadeGPS?: number;
|
||||
suspeitaSpoofing?: boolean;
|
||||
motivoSuspeita?: string;
|
||||
endereco?: string;
|
||||
cidade?: string;
|
||||
estado?: string;
|
||||
@@ -246,127 +530,95 @@ async function obterLocalizacao(): Promise<{
|
||||
return {};
|
||||
}
|
||||
|
||||
// Tentar múltiplas estratégias
|
||||
const estrategias = [
|
||||
// Estratégia 1: Alta precisão (mais lento, mas mais preciso)
|
||||
{
|
||||
enableHighAccuracy: true,
|
||||
timeout: 10000,
|
||||
maximumAge: 0
|
||||
},
|
||||
// Estratégia 2: Precisão média (balanceado)
|
||||
{
|
||||
enableHighAccuracy: false,
|
||||
timeout: 8000,
|
||||
maximumAge: 30000
|
||||
},
|
||||
// Estratégia 3: Rápido (usa cache)
|
||||
{
|
||||
enableHighAccuracy: false,
|
||||
timeout: 5000,
|
||||
maximumAge: 60000
|
||||
}
|
||||
];
|
||||
// Usar múltiplas leituras para detectar spoofing
|
||||
const localizacaoMultipla = await obterLocalizacaoMultipla();
|
||||
|
||||
for (const options of estrategias) {
|
||||
try {
|
||||
const resultado = await new Promise<{
|
||||
latitude?: number;
|
||||
longitude?: number;
|
||||
precisao?: number;
|
||||
endereco?: string;
|
||||
cidade?: string;
|
||||
estado?: string;
|
||||
pais?: string;
|
||||
}>((resolve) => {
|
||||
const timeout = setTimeout(() => {
|
||||
resolve({});
|
||||
}, options.timeout + 1000);
|
||||
if (!localizacaoMultipla.latitude || !localizacaoMultipla.longitude) {
|
||||
console.warn('Não foi possível obter localização');
|
||||
return {
|
||||
confiabilidadeGPS: 0,
|
||||
suspeitaSpoofing: true,
|
||||
motivoSuspeita: 'Não foi possível obter localização'
|
||||
};
|
||||
}
|
||||
|
||||
navigator.geolocation.getCurrentPosition(
|
||||
async (position) => {
|
||||
clearTimeout(timeout);
|
||||
const { latitude, longitude, accuracy } = position.coords;
|
||||
const { latitude, longitude, precisao, altitude, altitudeAccuracy, heading, speed, confiabilidade, suspeitaSpoofing, motivoSuspeita } = localizacaoMultipla;
|
||||
|
||||
// Validar coordenadas
|
||||
if (isNaN(latitude) || isNaN(longitude) || latitude === 0 || longitude === 0) {
|
||||
resolve({});
|
||||
return;
|
||||
}
|
||||
// Tentar obter endereço via reverse geocoding
|
||||
let endereco = '';
|
||||
let cidade = '';
|
||||
let estado = '';
|
||||
let pais = '';
|
||||
|
||||
// Tentar obter endereço via reverse geocoding
|
||||
let endereco = '';
|
||||
let cidade = '';
|
||||
let estado = '';
|
||||
let pais = '';
|
||||
|
||||
try {
|
||||
const response = await fetch(
|
||||
`https://nominatim.openstreetmap.org/reverse?format=json&lat=${latitude}&lon=${longitude}&zoom=18&addressdetails=1`,
|
||||
{
|
||||
headers: {
|
||||
'User-Agent': 'SGSE-App/1.0'
|
||||
}
|
||||
}
|
||||
);
|
||||
if (response.ok) {
|
||||
const data = (await response.json()) as {
|
||||
address?: {
|
||||
road?: string;
|
||||
house_number?: string;
|
||||
city?: string;
|
||||
town?: string;
|
||||
state?: string;
|
||||
country?: string;
|
||||
};
|
||||
};
|
||||
if (data.address) {
|
||||
const addr = data.address;
|
||||
if (addr.road) {
|
||||
endereco = `${addr.road}${addr.house_number ? `, ${addr.house_number}` : ''}`;
|
||||
}
|
||||
cidade = addr.city || addr.town || '';
|
||||
estado = addr.state || '';
|
||||
pais = addr.country || '';
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('Erro ao obter endereço:', error);
|
||||
}
|
||||
|
||||
resolve({
|
||||
latitude,
|
||||
longitude,
|
||||
precisao: accuracy,
|
||||
endereco,
|
||||
cidade,
|
||||
estado,
|
||||
pais,
|
||||
});
|
||||
},
|
||||
(error) => {
|
||||
clearTimeout(timeout);
|
||||
console.warn('Erro ao obter localização:', error.code, error.message);
|
||||
resolve({});
|
||||
},
|
||||
options
|
||||
);
|
||||
});
|
||||
|
||||
// Se obteve localização, retornar
|
||||
if (resultado.latitude && resultado.longitude) {
|
||||
console.log('Localização obtida com sucesso:', resultado);
|
||||
return resultado;
|
||||
try {
|
||||
const response = await fetch(
|
||||
`https://nominatim.openstreetmap.org/reverse?format=json&lat=${latitude}&lon=${longitude}&zoom=18&addressdetails=1`,
|
||||
{
|
||||
headers: {
|
||||
'User-Agent': 'SGSE-App/1.0'
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('Erro na estratégia de geolocalização:', error);
|
||||
continue;
|
||||
);
|
||||
if (response.ok) {
|
||||
const data = (await response.json()) as {
|
||||
address?: {
|
||||
road?: string;
|
||||
house_number?: string;
|
||||
city?: string;
|
||||
town?: string;
|
||||
state?: string;
|
||||
country?: string;
|
||||
};
|
||||
};
|
||||
if (data.address) {
|
||||
const addr = data.address;
|
||||
if (addr.road) {
|
||||
endereco = `${addr.road}${addr.house_number ? `, ${addr.house_number}` : ''}`;
|
||||
}
|
||||
cidade = addr.city || addr.town || '';
|
||||
estado = addr.state || '';
|
||||
pais = addr.country || '';
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('Erro ao obter endereço:', error);
|
||||
}
|
||||
|
||||
// Validar timezone vs localização
|
||||
if (typeof navigator !== 'undefined') {
|
||||
const timezoneAtual = Intl.DateTimeFormat().resolvedOptions().timeZone;
|
||||
const timezoneEsperado = obterTimezonePorCoordenadas(latitude, longitude);
|
||||
|
||||
// Se timezone é muito diferente, pode ser suspeito
|
||||
if (timezoneAtual !== timezoneEsperado && timezoneAtual !== 'America/Recife' && timezoneEsperado !== 'America/Recife') {
|
||||
console.warn(`Timezone inconsistente: esperado ${timezoneEsperado}, atual ${timezoneAtual}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Se todas as estratégias falharam, retornar vazio
|
||||
console.warn('Não foi possível obter localização após todas as tentativas');
|
||||
return {};
|
||||
console.log('Localização obtida com validações:', {
|
||||
latitude,
|
||||
longitude,
|
||||
confiabilidade: confiabilidade.toFixed(2),
|
||||
suspeitaSpoofing,
|
||||
motivoSuspeita
|
||||
});
|
||||
|
||||
return {
|
||||
latitude,
|
||||
longitude,
|
||||
precisao,
|
||||
altitude,
|
||||
altitudeAccuracy,
|
||||
heading,
|
||||
speed,
|
||||
confiabilidadeGPS: confiabilidade,
|
||||
suspeitaSpoofing: suspeitaSpoofing || false,
|
||||
motivoSuspeita,
|
||||
endereco,
|
||||
cidade,
|
||||
estado,
|
||||
pais
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -439,6 +691,13 @@ export async function obterInformacoesDispositivo(): Promise<InformacoesDisposit
|
||||
informacoes.latitude = localizacao.latitude;
|
||||
informacoes.longitude = localizacao.longitude;
|
||||
informacoes.precisao = localizacao.precisao;
|
||||
informacoes.altitude = localizacao.altitude ?? null;
|
||||
informacoes.altitudeAccuracy = localizacao.altitudeAccuracy ?? null;
|
||||
informacoes.heading = localizacao.heading ?? null;
|
||||
informacoes.speed = localizacao.speed ?? null;
|
||||
informacoes.confiabilidadeGPS = localizacao.confiabilidadeGPS;
|
||||
informacoes.suspeitaSpoofing = localizacao.suspeitaSpoofing;
|
||||
informacoes.motivoSuspeita = localizacao.motivoSuspeita;
|
||||
informacoes.endereco = localizacao.endereco;
|
||||
informacoes.cidade = localizacao.cidade;
|
||||
informacoes.estado = localizacao.estado;
|
||||
|
||||
Reference in New Issue
Block a user