All checks were successful
Build and Deploy / build-and-push (push) Successful in 1m53s
- Added sound_enabled column to users table with a default of true. - Implemented a pleasant pop sound (notification.mp3) that plays when a new unread notification arrives. - Added a toggle in the User Profile page allowing users to enable/disable the sound.
327 lines
16 KiB
TypeScript
327 lines
16 KiB
TypeScript
import React, { useState, useEffect, useRef } from 'react';
|
|
import { Camera, Save, Mail, User as UserIcon, Building, Shield, Loader2, CheckCircle2, Bell } from 'lucide-react';
|
|
import { getUserById, getTenants, getTeams, updateUser, uploadAvatar } from '../services/dataService';
|
|
import { User, Tenant } from '../types';
|
|
|
|
export const UserProfile: React.FC = () => {
|
|
const [user, setUser] = useState<User | null>(null);
|
|
const [tenant, setTenant] = useState<Tenant | null>(null);
|
|
const [teamName, setTeamName] = useState<string>('');
|
|
const [isLoading, setIsLoading] = useState(false);
|
|
const [isSuccess, setIsSuccess] = useState(false);
|
|
const [isUploading, setIsUploading] = useState(false);
|
|
const fileInputRef = useRef<HTMLInputElement>(null);
|
|
|
|
const [name, setName] = useState('');
|
|
const [bio, setBio] = useState('');
|
|
const [email, setEmail] = useState('');
|
|
|
|
useEffect(() => {
|
|
const fetchUserAndTenant = async () => {
|
|
const storedUserId = localStorage.getItem('ctms_user_id');
|
|
if (storedUserId) {
|
|
try {
|
|
const fetchedUser = await getUserById(storedUserId);
|
|
if (fetchedUser) {
|
|
setUser(fetchedUser);
|
|
setName(fetchedUser.name);
|
|
setBio(fetchedUser.bio || '');
|
|
setEmail(fetchedUser.email);
|
|
|
|
// Fetch tenant info
|
|
const tenants = await getTenants();
|
|
const userTenant = tenants.find(t => t.id === fetchedUser.tenant_id);
|
|
if (userTenant) {
|
|
setTenant(userTenant);
|
|
}
|
|
|
|
if (fetchedUser.team_id) {
|
|
const teams = await getTeams(fetchedUser.tenant_id);
|
|
const userTeam = teams.find(t => t.id === fetchedUser.team_id);
|
|
if (userTeam) setTeamName(userTeam.name);
|
|
}
|
|
}
|
|
} catch (err) {
|
|
console.error("Error fetching profile data:", err);
|
|
}
|
|
}
|
|
};
|
|
fetchUserAndTenant();
|
|
}, []);
|
|
|
|
const handleAvatarClick = () => {
|
|
fileInputRef.current?.click();
|
|
};
|
|
|
|
const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
|
|
const file = e.target.files?.[0];
|
|
if (!file || !user) return;
|
|
|
|
if (file.size > 2 * 1024 * 1024) {
|
|
alert('Arquivo muito grande. Máximo de 2MB.');
|
|
return;
|
|
}
|
|
|
|
setIsUploading(true);
|
|
try {
|
|
const newUrl = await uploadAvatar(user.id, file);
|
|
if (newUrl) {
|
|
setUser({ ...user, avatar_url: newUrl });
|
|
window.location.reload();
|
|
} else {
|
|
alert('Erro ao fazer upload da imagem.');
|
|
}
|
|
} catch (err) {
|
|
console.error(err);
|
|
alert('Erro ao conectar ao servidor.');
|
|
} finally {
|
|
setIsUploading(false);
|
|
}
|
|
};
|
|
|
|
const handleSubmit = async (e: React.FormEvent) => {
|
|
e.preventDefault();
|
|
if (!user) return;
|
|
|
|
setIsLoading(true);
|
|
setIsSuccess(false);
|
|
|
|
try {
|
|
const success = await updateUser(user.id, { name, bio, email });
|
|
if (success) {
|
|
setIsSuccess(true);
|
|
setUser({ ...user, name, bio, email });
|
|
setTimeout(() => setIsSuccess(false), 3000);
|
|
} else {
|
|
alert('Erro ao salvar alterações no servidor.');
|
|
}
|
|
} catch (err) {
|
|
console.error("Submit failed:", err);
|
|
alert('Erro ao conectar ao servidor.');
|
|
} finally {
|
|
setIsLoading(false);
|
|
}
|
|
};
|
|
|
|
if (!user) return <div className="p-8 text-center text-zinc-500 dark:text-zinc-400 transition-colors">Carregando perfil...</div>;
|
|
|
|
const backendUrl = import.meta.env.PROD ? '' : 'http://localhost:3001';
|
|
const displayAvatar = user.avatar_url
|
|
? (user.avatar_url.startsWith('http') ? user.avatar_url : `${backendUrl}${user.avatar_url}`)
|
|
: `https://ui-avatars.com/api/?name=${encodeURIComponent(user.name)}&background=random`;
|
|
|
|
const canEditEmail = user.role === 'admin' || user.role === 'super_admin';
|
|
|
|
return (
|
|
<div className="max-w-4xl mx-auto space-y-6 pb-12 transition-colors duration-300">
|
|
<div>
|
|
<h1 className="text-2xl font-bold text-zinc-900 dark:text-zinc-50 tracking-tight">Meu Perfil</h1>
|
|
<p className="text-zinc-500 dark:text-zinc-400 text-sm">Gerencie suas informações pessoais e preferências.</p>
|
|
</div>
|
|
|
|
<div className="grid grid-cols-1 md:grid-cols-3 gap-8">
|
|
{/* Left Column: Avatar & Basic Info */}
|
|
<div className="md:col-span-1 space-y-6">
|
|
<div className="bg-white dark:bg-zinc-900 p-6 rounded-2xl shadow-sm border border-zinc-200 dark:border-zinc-800 flex flex-col items-center text-center">
|
|
<input
|
|
type="file"
|
|
ref={fileInputRef}
|
|
onChange={handleFileChange}
|
|
accept="image/jpeg,image/png,image/webp"
|
|
className="hidden"
|
|
/>
|
|
<div className="relative group cursor-pointer" onClick={handleAvatarClick}>
|
|
<div className="w-32 h-32 rounded-full overflow-hidden border-4 border-zinc-50 dark:border-zinc-800 shadow-sm bg-zinc-100 dark:bg-zinc-800 flex items-center justify-center">
|
|
{isUploading ? (
|
|
<Loader2 className="animate-spin text-zinc-400 dark:text-zinc-500" size={32} />
|
|
) : (
|
|
<img src={displayAvatar} alt={user.name} className="w-full h-full object-cover" />
|
|
)}
|
|
</div>
|
|
<div className="absolute inset-0 bg-black/40 rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity duration-200">
|
|
<Camera className="text-white" size={28} />
|
|
</div>
|
|
<button className="absolute bottom-0 right-2 bg-white dark:bg-zinc-800 text-zinc-600 dark:text-zinc-400 p-2 rounded-full shadow-md border border-zinc-100 dark:border-zinc-700 hover:text-yellow-500 dark:hover:text-yellow-400 transition-colors">
|
|
<Camera size={16} />
|
|
</button>
|
|
</div>
|
|
|
|
<h2 className="mt-4 text-lg font-bold text-zinc-900 dark:text-zinc-100">{user.name}</h2>
|
|
<p className="text-zinc-500 dark:text-zinc-400 text-sm">{user.email}</p>
|
|
|
|
<div className="mt-4 flex justify-center gap-2 max-w-full overflow-hidden px-2">
|
|
<span className="px-3 py-1 bg-purple-100 text-purple-700 rounded-full text-xs font-semibold capitalize border border-purple-200 dark:bg-purple-900/30 dark:text-purple-400 dark:border-purple-800 whitespace-nowrap shrink-0">
|
|
{user.role === 'admin' ? 'Admin' : user.role === 'manager' ? 'Gerente' : user.role === 'super_admin' ? 'Super Admin' : 'Agente'}
|
|
</span>
|
|
{user.team_id && (
|
|
<span className="px-3 py-1 bg-blue-100 text-blue-700 rounded-full text-xs font-semibold border border-blue-200 dark:bg-blue-900/30 dark:text-blue-400 dark:border-blue-800 truncate max-w-[160px]" title={teamName || user.team_id}>
|
|
{teamName || user.team_id}
|
|
</span>
|
|
)}
|
|
</div>
|
|
</div>
|
|
|
|
<div className="bg-zinc-100 dark:bg-zinc-900 rounded-xl p-4 border border-zinc-200 dark:border-zinc-800">
|
|
<h3 className="text-xs font-bold text-zinc-500 dark:text-zinc-400 uppercase tracking-wider mb-3">Status da Conta</h3>
|
|
<div className="flex items-center gap-3 text-sm text-zinc-600 dark:text-zinc-300 mb-2">
|
|
<div className={`w-2 h-2 rounded-full ${user.status === 'active' ? 'bg-green-500' : 'bg-zinc-400'}`}></div>
|
|
{user.status === 'active' ? 'Ativo' : 'Inativo'}
|
|
</div>
|
|
<div className="flex items-center gap-3 text-sm text-zinc-600 dark:text-zinc-300">
|
|
<Building size={14} />
|
|
{tenant?.name || 'Organização'}
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
{/* Right Column: Edit Form */}
|
|
<div className="md:col-span-2">
|
|
<div className="bg-white dark:bg-zinc-900 rounded-2xl shadow-sm border border-zinc-200 dark:border-zinc-800 overflow-hidden">
|
|
<div className="px-6 py-4 border-b border-zinc-100 dark:border-zinc-800 bg-zinc-50/50 dark:bg-zinc-900/50 flex justify-between items-center">
|
|
<h3 className="font-bold text-zinc-800 dark:text-zinc-100">Informações Pessoais</h3>
|
|
{isSuccess && (
|
|
<span className="flex items-center gap-1.5 text-green-600 dark:text-green-400 text-sm font-medium animate-in fade-in slide-in-from-right-4">
|
|
<CheckCircle2 size={16} /> Salvo com sucesso
|
|
</span>
|
|
)}
|
|
</div>
|
|
|
|
<form onSubmit={handleSubmit} className="p-6 space-y-6">
|
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
|
<div className="space-y-2">
|
|
<label htmlFor="fullName" className="block text-sm font-medium text-zinc-700 dark:text-zinc-300">
|
|
Nome Completo
|
|
</label>
|
|
<div className="relative">
|
|
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
|
|
<UserIcon className="h-5 w-5 text-zinc-400 dark:text-zinc-500" />
|
|
</div>
|
|
<input
|
|
type="text"
|
|
id="fullName"
|
|
value={name}
|
|
onChange={(e) => setName(e.target.value)}
|
|
className="block w-full pl-10 pr-3 py-2 border border-zinc-200 dark:border-zinc-800 rounded-lg bg-white dark:bg-zinc-950 text-zinc-900 dark:text-zinc-100 placeholder-zinc-400 dark:placeholder-zinc-600 focus:outline-none focus:ring-2 focus:ring-yellow-400/20 focus:border-yellow-400 transition-all sm:text-sm"
|
|
/>
|
|
</div>
|
|
</div>
|
|
|
|
<div className="space-y-2">
|
|
<label htmlFor="email" className="block text-sm font-medium text-zinc-700 dark:text-zinc-300">
|
|
Endereço de E-mail
|
|
</label>
|
|
<div className="relative">
|
|
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
|
|
<Mail className="h-5 w-5 text-zinc-400 dark:text-zinc-500" />
|
|
</div>
|
|
<input
|
|
type="email"
|
|
id="email"
|
|
value={email}
|
|
onChange={(e) => setEmail(e.target.value)}
|
|
disabled={!canEditEmail}
|
|
className={`block w-full pl-10 pr-3 py-2 border border-zinc-200 dark:border-zinc-800 rounded-lg sm:text-sm transition-all ${
|
|
!canEditEmail
|
|
? 'bg-zinc-50 dark:bg-zinc-900/50 text-zinc-500 dark:text-zinc-500 cursor-not-allowed'
|
|
: 'bg-white dark:bg-zinc-950 text-zinc-900 dark:text-zinc-100 placeholder-zinc-400 dark:placeholder-zinc-600 focus:outline-none focus:ring-2 focus:ring-brand-yellow/20 focus:border-brand-yellow'
|
|
}`}
|
|
/>
|
|
</div>
|
|
{!canEditEmail && <p className="text-xs text-zinc-400 dark:text-zinc-500 mt-1">Contate o admin para alterar o e-mail.</p>}
|
|
</div>
|
|
</div>
|
|
|
|
<div className="space-y-2">
|
|
<label htmlFor="role" className="block text-sm font-medium text-zinc-700 dark:text-zinc-300">
|
|
Função e Permissões
|
|
</label>
|
|
<div className="relative">
|
|
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
|
|
<Shield className="h-5 w-5 text-zinc-400 dark:text-zinc-500" />
|
|
</div>
|
|
<input
|
|
type="text"
|
|
id="role"
|
|
value={user.role === 'admin' ? 'Administrador' : user.role === 'manager' ? 'Gerente' : user.role === 'super_admin' ? 'Super Admin' : 'Agente'}
|
|
disabled
|
|
className="block w-full pl-10 pr-3 py-2 border border-zinc-200 dark:border-zinc-800 rounded-lg bg-zinc-50 dark:bg-zinc-900/50 text-zinc-500 dark:text-zinc-500 cursor-not-allowed sm:text-sm"
|
|
/>
|
|
</div>
|
|
</div>
|
|
|
|
<div className="space-y-2">
|
|
<label htmlFor="bio" className="block text-sm font-medium text-zinc-700 dark:text-zinc-300">
|
|
Bio / Descrição
|
|
</label>
|
|
<textarea
|
|
id="bio"
|
|
rows={4}
|
|
value={bio}
|
|
onChange={(e) => setBio(e.target.value)}
|
|
className="block w-full p-3 border border-zinc-200 dark:border-zinc-800 rounded-lg bg-white dark:bg-zinc-950 text-zinc-900 dark:text-zinc-100 placeholder-zinc-400 dark:placeholder-zinc-600 focus:outline-none focus:ring-2 focus:ring-yellow-400/20 focus:border-yellow-400 transition-all sm:text-sm resize-none"
|
|
placeholder="Escreva uma breve descrição sobre você..."
|
|
/>
|
|
<p className="text-xs text-zinc-400 dark:text-zinc-500 text-right">{bio.length}/500 caracteres</p>
|
|
</div>
|
|
|
|
<div className="space-y-2 pt-2">
|
|
<div className="flex items-center justify-between p-4 bg-zinc-50 dark:bg-zinc-900/50 rounded-xl border border-zinc-200 dark:border-zinc-800">
|
|
<div>
|
|
<h4 className="text-sm font-semibold text-zinc-900 dark:text-zinc-100 flex items-center gap-2">
|
|
<Bell size={16} className="text-brand-yellow" /> Notificações Sonoras
|
|
</h4>
|
|
<p className="text-xs text-zinc-500 dark:text-zinc-400 mt-1">
|
|
Reproduzir um som quando você receber uma nova notificação.
|
|
</p>
|
|
</div>
|
|
<label className="relative inline-flex items-center cursor-pointer">
|
|
<input
|
|
type="checkbox"
|
|
className="sr-only peer"
|
|
checked={user.sound_enabled ?? true}
|
|
onChange={async (e) => {
|
|
const newStatus = e.target.checked;
|
|
setUser({...user, sound_enabled: newStatus});
|
|
await updateUser(user.id, { sound_enabled: newStatus });
|
|
}}
|
|
/>
|
|
<div className="w-11 h-6 bg-zinc-200 peer-focus:outline-none rounded-full peer dark:bg-zinc-700 peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-zinc-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all dark:border-zinc-600 peer-checked:bg-brand-yellow"></div>
|
|
</label>
|
|
</div>
|
|
</div>
|
|
|
|
<div className="pt-4 flex items-center justify-end border-t border-zinc-100 dark:border-zinc-800 mt-6 transition-colors">
|
|
<button
|
|
type="button"
|
|
onClick={() => {
|
|
setName(user.name);
|
|
setBio(user.bio || '');
|
|
}}
|
|
className="mr-3 px-4 py-2 text-sm font-medium text-zinc-600 dark:text-zinc-400 hover:text-zinc-800 dark:hover:text-zinc-200 hover:bg-zinc-50 dark:hover:bg-zinc-800 rounded-lg transition-colors"
|
|
>
|
|
Desfazer Alterações
|
|
</button>
|
|
<button
|
|
type="submit"
|
|
disabled={isLoading}
|
|
className="flex items-center gap-2 bg-zinc-900 dark:bg-yellow-400 text-white dark:text-zinc-950 px-6 py-2 rounded-lg text-sm font-medium hover:bg-zinc-800 dark:hover:opacity-90 focus:ring-2 focus:ring-offset-2 focus:ring-zinc-900 dark:focus:ring-yellow-400 transition-all disabled:opacity-70 disabled:cursor-not-allowed"
|
|
>
|
|
{isLoading ? (
|
|
<>
|
|
<Loader2 className="animate-spin h-4 w-4" /> Salvando...
|
|
</>
|
|
) : (
|
|
<>
|
|
<Save size={16} /> Salvar Alterações
|
|
</>
|
|
)}
|
|
</button>
|
|
</div>
|
|
</form>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
);
|
|
};
|