Private
Public Access
primeros cambios hechos para tener el multitenant
This commit is contained in:
1 parent
34ad4424f9
commit
4e082e8767
132 files changed
+6202
-762
No files matched your search
@@ -3,12 +3,11 @@ import {
|
||||
getAuthTokens,
|
||||
getTokenExpiry,
|
||||
notifyAuthChange,
|
||||
removeAuthTokens,
|
||||
removeToken,
|
||||
setAuthTokens,
|
||||
setToken
|
||||
} from '$lib/hooks/token';
|
||||
import { getCurrentUser, removeCurrentUser, setCurrentUser } from '$lib/hooks/user';
|
||||
import { getCurrentUser, setCurrentUser } from '$lib/hooks/user';
|
||||
import { aplicarSesion, cerrarSesion } from '$lib/hooks/session';
|
||||
|
||||
export class TokenRefresher {
|
||||
private timer: ReturnType<typeof setInterval> | null = null;
|
||||
@@ -68,26 +67,10 @@ export class TokenRefresher {
|
||||
if (!res.ok) throw new Error('Refresh failed');
|
||||
|
||||
const data = await res.json();
|
||||
setAuthTokens({
|
||||
access_token: data.access_token,
|
||||
refresh_token: data.refresh_token,
|
||||
expires_in: data.expires_in,
|
||||
token_type: data.token_type,
|
||||
permissions: data.permissions
|
||||
});
|
||||
setToken(data.access_token);
|
||||
|
||||
const currentUser = getCurrentUser();
|
||||
if (currentUser) {
|
||||
setCurrentUser({ ...currentUser, permissions: data.permissions ?? [] });
|
||||
}
|
||||
|
||||
aplicarSesion(data);
|
||||
this.schedule();
|
||||
} catch {
|
||||
removeAuthTokens();
|
||||
removeToken();
|
||||
removeCurrentUser();
|
||||
notifyAuthChange();
|
||||
cerrarSesion();
|
||||
this.stop();
|
||||
this.onExpired();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
import { goto } from '$app/navigation';
|
||||
import { API_URL } from './env';
|
||||
import { cerrarSesion } from './hooks/session';
|
||||
import { getToken } from './hooks/token';
|
||||
|
||||
export class ApiError extends Error {
|
||||
status: number;
|
||||
|
||||
constructor(status: number, message: string) {
|
||||
super(message);
|
||||
this.status = status;
|
||||
}
|
||||
}
|
||||
|
||||
type ApiOptions = Omit<RequestInit, 'body'> & {
|
||||
body?: unknown;
|
||||
auth?: boolean;
|
||||
rawBody?: BodyInit | null;
|
||||
};
|
||||
|
||||
export async function apiFetch<T>(path: string, options: ApiOptions = {}): Promise<T> {
|
||||
const { auth = true, body, rawBody, headers, ...rest } = options;
|
||||
const finalHeaders = new Headers(headers);
|
||||
|
||||
if (auth) {
|
||||
const token = getToken();
|
||||
if (token) finalHeaders.set('Authorization', `Bearer ${token}`);
|
||||
}
|
||||
|
||||
let finalBody: BodyInit | null | undefined = rawBody;
|
||||
if (body !== undefined) {
|
||||
finalHeaders.set('Content-Type', 'application/json');
|
||||
finalBody = JSON.stringify(body);
|
||||
}
|
||||
|
||||
const response = await fetch(`${API_URL}${path}`, {
|
||||
...rest,
|
||||
headers: finalHeaders,
|
||||
body: finalBody
|
||||
});
|
||||
|
||||
if (response.status === 401) {
|
||||
cerrarSesion();
|
||||
void goto('/login');
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
const data = await response.json().catch(() => ({}));
|
||||
throw new ApiError(response.status, data.error || data.message || 'Error en la petición');
|
||||
}
|
||||
|
||||
if (response.status === 204) return undefined as T;
|
||||
return (await response.json()) as T;
|
||||
}
|
||||
|
||||
export function mensajeError(error: unknown): string {
|
||||
if (error instanceof Error) return error.message;
|
||||
return 'Error desconocido';
|
||||
}
|
||||
@@ -9,7 +9,7 @@
|
||||
import UserMenu from './UserMenu.svelte';
|
||||
import type { GruposYPermisosResponse, Usuario } from '../../types';
|
||||
import { getCurrentUser } from '$lib/hooks/user';
|
||||
import { ObtenerGruposDeUsuario } from '$lib/hooks/ObtenerGruposDeUsuario';
|
||||
import { ObtenerGruposDeUsuario } from '$lib/hooks/gruposPermisosUsuario';
|
||||
import { onMount } from 'svelte';
|
||||
|
||||
interface Prop {
|
||||
@@ -19,19 +19,22 @@
|
||||
|
||||
let { usuario, grupos }: Prop = $props();
|
||||
|
||||
const nombreEmpresa = $derived(usuario?.empresa?.nombre ?? 'Repuestera');
|
||||
|
||||
onMount(() => {
|
||||
if (typeof usuario === 'undefined') {
|
||||
usuario = getCurrentUser() ?? undefined;
|
||||
}
|
||||
if (typeof grupos === 'undefined') {
|
||||
grupos = usuario
|
||||
? ObtenerGruposDeUsuario(usuario)
|
||||
: Promise.resolve({ email: '', groups: [] });
|
||||
grupos =
|
||||
usuario && usuario.empresa
|
||||
? ObtenerGruposDeUsuario(usuario)
|
||||
: Promise.resolve({ email: '', groups: [] });
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<CarbonHeader companyName="Repuestera" href="/menu">
|
||||
<CarbonHeader companyName={nombreEmpresa} href="/menu">
|
||||
<HeaderNav>
|
||||
{#if !usuario}
|
||||
<HeaderNavItem text="Inicio" href="/" />
|
||||
|
||||
@@ -1,19 +1,40 @@
|
||||
<script lang="ts">
|
||||
import Logout from 'carbon-icons-svelte/lib/Logout.svelte';
|
||||
import ChevronDown from 'carbon-icons-svelte/lib/ChevronDown.svelte';
|
||||
import { getCurrentUser, removeCurrentUser } from '$lib/hooks/user';
|
||||
import { notifyAuthChange, removeAuthTokens, removeToken } from '$lib/hooks/token';
|
||||
import { goto } from '$app/navigation';
|
||||
import Building from 'carbon-icons-svelte/lib/Building.svelte';
|
||||
import UserAdmin from 'carbon-icons-svelte/lib/UserAdmin.svelte';
|
||||
import Password from 'carbon-icons-svelte/lib/Password.svelte';
|
||||
import Checkmark from 'carbon-icons-svelte/lib/Checkmark.svelte';
|
||||
import { getCurrentUser } from '$lib/hooks/user';
|
||||
import { cerrarSesion } from '$lib/hooks/session';
|
||||
import { AUTH_CHANGE_EVENT } from '$lib/hooks/token';
|
||||
import { cambiarEmpresa } from '$lib/hooks/tenant';
|
||||
import { goto, invalidateAll } from '$app/navigation';
|
||||
|
||||
let user = $state(getCurrentUser());
|
||||
let dropdownOpen = $state(false);
|
||||
let cambiando = $state(false);
|
||||
let error = $state('');
|
||||
|
||||
$effect(() => {
|
||||
const sync = () => {
|
||||
user = getCurrentUser();
|
||||
};
|
||||
window.addEventListener(AUTH_CHANGE_EVENT, sync);
|
||||
return () => window.removeEventListener(AUTH_CHANGE_EVENT, sync);
|
||||
});
|
||||
|
||||
const empresas = $derived(user?.empresas ?? []);
|
||||
const empresaActual = $derived(user?.empresa ?? null);
|
||||
const esAdminEmpresa = $derived(
|
||||
user?.empresa_rol === 'OWNER' ||
|
||||
user?.empresa_rol === 'ADMIN' ||
|
||||
(user?.permissions ?? []).some((p) => p === 3 || p === 7)
|
||||
);
|
||||
|
||||
function handleLogout() {
|
||||
removeAuthTokens();
|
||||
removeToken();
|
||||
removeCurrentUser();
|
||||
notifyAuthChange();
|
||||
goto('/login');
|
||||
cerrarSesion();
|
||||
void goto('/login');
|
||||
}
|
||||
|
||||
function toggleDropdown() {
|
||||
@@ -23,6 +44,25 @@
|
||||
function closeDropdown() {
|
||||
dropdownOpen = false;
|
||||
}
|
||||
|
||||
async function seleccionarEmpresa(id: number) {
|
||||
if (!id || id === empresaActual?.id) {
|
||||
dropdownOpen = false;
|
||||
return;
|
||||
}
|
||||
|
||||
cambiando = true;
|
||||
error = '';
|
||||
try {
|
||||
await cambiarEmpresa(id);
|
||||
await goto('/menu');
|
||||
await invalidateAll();
|
||||
} catch (e) {
|
||||
error = e instanceof Error ? e.message : 'No se pudo cambiar de empresa';
|
||||
} finally {
|
||||
cambiando = false;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
{#if user}
|
||||
@@ -38,22 +78,96 @@
|
||||
>{(user?.name?.[0] || user?.email?.[0])?.toUpperCase()}</span
|
||||
>
|
||||
</div>
|
||||
{#if empresaActual}
|
||||
<span class="hidden max-w-40 truncate text-xs sm:inline">{empresaActual.nombre}</span>
|
||||
{/if}
|
||||
<ChevronDown size={16} />
|
||||
</button>
|
||||
{#if dropdownOpen}
|
||||
<div
|
||||
class="bg-grey-800 absolute top-full right-0 z-50 mt-1 overflow-hidden border shadow-lg"
|
||||
class="bg-grey-800 absolute top-full right-0 z-50 mt-1 w-64 overflow-hidden border shadow-lg"
|
||||
role="menu"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="flex w-full items-center gap-2 px-4 py-2.5 text-sm text-gray-300 transition-colors hover:bg-gray-700"
|
||||
role="menuitem"
|
||||
onclick={handleLogout}
|
||||
>
|
||||
<Logout size={16} />
|
||||
Cerrar Sesion
|
||||
</button>
|
||||
<div class="border-b border-gray-600 px-4 py-3">
|
||||
<p class="truncate text-sm font-semibold text-gray-100">{user.name}</p>
|
||||
<p class="truncate text-xs text-gray-400">{user.email}</p>
|
||||
{#if empresaActual}
|
||||
<p class="mt-1 text-xs text-gray-300">
|
||||
{empresaActual.nombre}
|
||||
{#if user.empresa_rol}
|
||||
<span class="text-gray-500">· {user.empresa_rol}</span>
|
||||
{/if}
|
||||
</p>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
{#if empresas.length > 1}
|
||||
<div class="border-b border-gray-600 py-2">
|
||||
<p class="px-4 pb-1 text-[0.65rem] tracking-wider text-gray-400 uppercase">
|
||||
Cambiar empresa
|
||||
</p>
|
||||
{#each empresas as empresa (empresa.id)}
|
||||
<button
|
||||
type="button"
|
||||
class="flex w-full items-center justify-between gap-2 px-4 py-2 text-left text-sm text-gray-300 transition-colors hover:bg-gray-700 disabled:opacity-50"
|
||||
role="menuitem"
|
||||
disabled={cambiando || empresa.id === empresaActual?.id}
|
||||
onclick={() => seleccionarEmpresa(empresa.id)}
|
||||
>
|
||||
<span class="truncate">{empresa.nombre}</span>
|
||||
{#if empresa.id === empresaActual?.id}
|
||||
<Checkmark size={16} />
|
||||
{/if}
|
||||
</button>
|
||||
{/each}
|
||||
{#if error}
|
||||
<p class="px-4 pt-1 text-xs text-red-400">{error}</p>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="py-1">
|
||||
{#if esAdminEmpresa}
|
||||
<a
|
||||
href="/empresa"
|
||||
class="flex w-full items-center gap-2 px-4 py-2.5 text-sm text-gray-300 no-underline transition-colors hover:bg-gray-700"
|
||||
role="menuitem"
|
||||
onclick={closeDropdown}
|
||||
>
|
||||
<Building size={16} />
|
||||
Mi empresa
|
||||
</a>
|
||||
{/if}
|
||||
{#if user.es_plataforma_admin}
|
||||
<a
|
||||
href="/plataforma"
|
||||
class="flex w-full items-center gap-2 px-4 py-2.5 text-sm text-gray-300 no-underline transition-colors hover:bg-gray-700"
|
||||
role="menuitem"
|
||||
onclick={closeDropdown}
|
||||
>
|
||||
<UserAdmin size={16} />
|
||||
Plataforma
|
||||
</a>
|
||||
{/if}
|
||||
<a
|
||||
href="/cambiar-contraseña"
|
||||
class="flex w-full items-center gap-2 px-4 py-2.5 text-sm text-gray-300 no-underline transition-colors hover:bg-gray-700"
|
||||
role="menuitem"
|
||||
onclick={closeDropdown}
|
||||
>
|
||||
<Password size={16} />
|
||||
Cambiar contraseña
|
||||
</a>
|
||||
<button
|
||||
type="button"
|
||||
class="flex w-full items-center gap-2 px-4 py-2.5 text-sm text-gray-300 transition-colors hover:bg-gray-700"
|
||||
role="menuitem"
|
||||
onclick={handleLogout}
|
||||
>
|
||||
<Logout size={16} />
|
||||
Cerrar sesión
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import { API_URL } from '$lib/env';
|
||||
import { handleResponse } from '$lib/handleRespondeJSON';
|
||||
import type { Usuario } from '../../types';
|
||||
import type { Miembro } from '../../types';
|
||||
import { getToken } from './token';
|
||||
|
||||
export async function ObtenerUsuarios(tamaño: number, pagina: number, fetch2?: Function) {
|
||||
let fetchfn = fetch2 ? fetch2 : fetch;
|
||||
const req = await fetchfn(`${API_URL}/usuarios?p=${pagina}&s=${tamaño}`, {
|
||||
const req = await fetchfn(`${API_URL}/empresa/miembros?p=${pagina}&s=${tamaño}`, {
|
||||
headers: { Authorization: `Bearer ${getToken()}` }
|
||||
});
|
||||
return handleResponse<{ usuarios: Usuario[]; total: number }>(req);
|
||||
return handleResponse<{ usuarios: Miembro[]; miembros: Miembro[]; total: number }>(req);
|
||||
}
|
||||
File renamed without changes.
@@ -1,47 +1,22 @@
|
||||
import type { LoginRequest, LoginResponse } from '../../types';
|
||||
import type { AuthResponse, LoginRequest } from '../../types';
|
||||
import { API_URL } from '../env';
|
||||
import { decodeJwtPayload, notifyAuthChange, setAuthTokens, setToken } from './token';
|
||||
import { setCurrentUser } from './user';
|
||||
import { aplicarSesion } from './session';
|
||||
|
||||
async function handleResponse<T>(response: Response): Promise<T> {
|
||||
if (!response.ok) {
|
||||
const error = await response.json().catch(() => ({ message: 'Error desconocido' }));
|
||||
throw new Error(error.error || 'Error en la petición');
|
||||
throw new Error(error.error || error.message || 'Error en la petición');
|
||||
}
|
||||
return response.json();
|
||||
}
|
||||
|
||||
export async function login(credentials: LoginRequest): Promise<LoginResponse> {
|
||||
export async function login(credentials: LoginRequest): Promise<AuthResponse> {
|
||||
const response = await fetch(`${API_URL}/auth/login`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(credentials)
|
||||
});
|
||||
const data = await handleResponse<LoginResponse>(response);
|
||||
|
||||
setAuthTokens({
|
||||
access_token: data.access_token,
|
||||
expires_in: data.expires_in,
|
||||
refresh_token: data.refresh_token,
|
||||
token_type: data.token_type,
|
||||
permissions: data.permissions
|
||||
});
|
||||
setToken(data.access_token);
|
||||
|
||||
const payload = decodeJwtPayload<{
|
||||
sub?: number | string;
|
||||
email?: string;
|
||||
name?: string;
|
||||
permissions?: number[];
|
||||
}>(data.access_token);
|
||||
|
||||
setCurrentUser({
|
||||
id: Number(payload?.sub ?? 0),
|
||||
email: payload?.email ?? credentials.email,
|
||||
name: payload?.name ?? credentials.email,
|
||||
permissions: payload?.permissions ?? data.permissions ?? []
|
||||
});
|
||||
notifyAuthChange();
|
||||
|
||||
const data = await handleResponse<AuthResponse>(response);
|
||||
aplicarSesion(data);
|
||||
return data;
|
||||
}
|
||||
@@ -1,10 +1,11 @@
|
||||
import type { RegisterResponse } from '../../types';
|
||||
import type { AuthResponse } from '../../types';
|
||||
import { API_URL } from '../env';
|
||||
import { aplicarSesion } from './session';
|
||||
|
||||
async function handleResponse<T>(response: Response): Promise<T> {
|
||||
if (!response.ok) {
|
||||
const error = await response.json().catch(() => ({ message: 'Error desconocido' }));
|
||||
throw new Error(error.message || 'Error en la petición');
|
||||
throw new Error(error.error || error.message || 'Error en la petición');
|
||||
}
|
||||
return response.json();
|
||||
}
|
||||
@@ -13,11 +14,16 @@ export async function register(data: {
|
||||
email: string;
|
||||
password: string;
|
||||
name: string;
|
||||
}): Promise<RegisterResponse> {
|
||||
empresa_nombre?: string;
|
||||
empresa_cuit?: string;
|
||||
empresa_slug?: string;
|
||||
}): Promise<AuthResponse> {
|
||||
const response = await fetch(`${API_URL}/auth/register`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(data)
|
||||
});
|
||||
return handleResponse<RegisterResponse>(response);
|
||||
const result = await handleResponse<AuthResponse>(response);
|
||||
aplicarSesion(result);
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
import type { AuthResponse, MeResponse, Usuario } from '../../types';
|
||||
import {
|
||||
getAuthTokens,
|
||||
getToken,
|
||||
notifyAuthChange,
|
||||
removeAuthTokens,
|
||||
removeToken,
|
||||
setAuthTokens,
|
||||
setToken
|
||||
} from './token';
|
||||
import { getCurrentUser, removeCurrentUser, setCurrentUser } from './user';
|
||||
|
||||
export function usuarioDesdeSesion(data: AuthResponse | MeResponse): Usuario {
|
||||
if ('usuario' in data && data.usuario) {
|
||||
return {
|
||||
...data.usuario,
|
||||
permissions: data.permissions,
|
||||
empresa: data.empresa ?? undefined,
|
||||
empresas: data.empresas,
|
||||
empresa_rol: data.empresa_rol,
|
||||
es_plataforma_admin: data.es_plataforma_admin,
|
||||
debe_cambiar_password: data.debe_cambiar_password
|
||||
};
|
||||
}
|
||||
|
||||
const me = data as MeResponse;
|
||||
return {
|
||||
...me,
|
||||
permissions: me.permissions,
|
||||
empresa: me.empresa ?? undefined,
|
||||
empresas: me.empresas,
|
||||
empresa_rol: me.empresa_rol,
|
||||
es_plataforma_admin: me.es_plataforma_admin
|
||||
};
|
||||
}
|
||||
|
||||
export function aplicarSesion(data: AuthResponse): void {
|
||||
setAuthTokens({
|
||||
access_token: data.access_token,
|
||||
refresh_token: data.refresh_token,
|
||||
expires_in: data.expires_in,
|
||||
token_type: data.token_type,
|
||||
permissions: data.permissions,
|
||||
empresa: data.empresa,
|
||||
empresas: data.empresas,
|
||||
empresa_rol: data.empresa_rol,
|
||||
es_plataforma_admin: data.es_plataforma_admin,
|
||||
usuario: data.usuario,
|
||||
debe_cambiar_password: data.debe_cambiar_password
|
||||
});
|
||||
setToken(data.access_token);
|
||||
setCurrentUser(usuarioDesdeSesion(data));
|
||||
notifyAuthChange();
|
||||
}
|
||||
|
||||
export function aplicarMe(data: MeResponse): void {
|
||||
const actual = getAuthTokens();
|
||||
if (actual) {
|
||||
setAuthTokens({
|
||||
...actual,
|
||||
permissions: data.permissions,
|
||||
empresa: data.empresa ?? null,
|
||||
empresas: data.empresas,
|
||||
empresa_rol: data.empresa_rol,
|
||||
es_plataforma_admin: data.es_plataforma_admin,
|
||||
usuario: usuarioDesdeSesion(data),
|
||||
debe_cambiar_password: data.debe_cambiar_password
|
||||
});
|
||||
}
|
||||
setCurrentUser(usuarioDesdeSesion(data));
|
||||
notifyAuthChange();
|
||||
}
|
||||
|
||||
export function cerrarSesion(): void {
|
||||
removeAuthTokens();
|
||||
removeToken();
|
||||
removeCurrentUser();
|
||||
notifyAuthChange();
|
||||
}
|
||||
|
||||
export function esPlataformaAdmin(): boolean {
|
||||
return getCurrentUser()?.es_plataforma_admin === true;
|
||||
}
|
||||
|
||||
export function empresaActual() {
|
||||
return getCurrentUser()?.empresa ?? getAuthTokens()?.empresa ?? null;
|
||||
}
|
||||
|
||||
export async function recargarSesion(apiUrl: string): Promise<MeResponse | null> {
|
||||
const token = getToken();
|
||||
if (!token) return null;
|
||||
|
||||
const response = await fetch(`${apiUrl}/auth/me`, {
|
||||
headers: { Authorization: `Bearer ${token}` }
|
||||
});
|
||||
if (!response.ok) return null;
|
||||
const data = (await response.json()) as MeResponse;
|
||||
aplicarMe(data);
|
||||
return data;
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
import { apiFetch } from '$lib/api';
|
||||
import type {
|
||||
AuthResponse,
|
||||
EmpresaActual,
|
||||
EmpresaPlataforma,
|
||||
EmpresaResumen,
|
||||
Invitacion,
|
||||
InvitacionCreada,
|
||||
InvitacionInfo,
|
||||
Miembro,
|
||||
PlataformaAdmin
|
||||
} from '../../types';
|
||||
import { aplicarSesion } from './session';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Empresas y sesión
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export async function obtenerMisEmpresas() {
|
||||
return apiFetch<{
|
||||
empresas: EmpresaResumen[];
|
||||
es_plataforma_admin: boolean;
|
||||
rol_plataforma: string;
|
||||
}>('/auth/empresas');
|
||||
}
|
||||
|
||||
export async function cambiarEmpresa(empresaID: number): Promise<AuthResponse> {
|
||||
const data = await apiFetch<AuthResponse>('/auth/empresa/cambiar', {
|
||||
method: 'POST',
|
||||
body: { empresa_id: empresaID }
|
||||
});
|
||||
aplicarSesion(data);
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function obtenerEmpresaActual(): Promise<EmpresaActual> {
|
||||
return apiFetch<EmpresaActual>('/empresa');
|
||||
}
|
||||
|
||||
export async function actualizarEmpresa(dto: {
|
||||
nombre?: string;
|
||||
slug?: string;
|
||||
cuit?: string;
|
||||
}): Promise<void> {
|
||||
await apiFetch('/empresa', { method: 'PUT', body: dto });
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Miembros de la empresa
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export async function obtenerMiembros(pagina = 0, tamano = 10) {
|
||||
return apiFetch<{ usuarios: Miembro[]; miembros: Miembro[]; total: number }>(
|
||||
`/empresa/miembros?p=${pagina}&s=${tamano}`
|
||||
);
|
||||
}
|
||||
|
||||
export async function crearMiembro(dto: {
|
||||
name: string;
|
||||
email: string;
|
||||
password?: string;
|
||||
rol?: string;
|
||||
grupo_id?: number;
|
||||
}) {
|
||||
return apiFetch<{
|
||||
usuario: Miembro;
|
||||
password_temporal: string;
|
||||
usuario_existente: boolean;
|
||||
}>('/empresa/miembros', { method: 'POST', body: dto });
|
||||
}
|
||||
|
||||
export async function actualizarMiembro(
|
||||
id: number,
|
||||
dto: { name?: string; email?: string; rol?: string; activo?: boolean }
|
||||
): Promise<Miembro> {
|
||||
return apiFetch<Miembro>(`/empresa/miembros/${id}`, { method: 'PUT', body: dto });
|
||||
}
|
||||
|
||||
export async function eliminarMiembro(id: number): Promise<void> {
|
||||
await apiFetch(`/empresa/miembros/${id}`, { method: 'DELETE' });
|
||||
}
|
||||
|
||||
export async function resetearPasswordMiembro(id: number, newPassword: string): Promise<void> {
|
||||
await apiFetch('/auth/cambiar-contraseña', {
|
||||
method: 'POST',
|
||||
body: { user_id: id, new_password: newPassword }
|
||||
});
|
||||
}
|
||||
|
||||
export async function cambiarPasswordPropia(oldPassword: string, newPassword: string): Promise<void> {
|
||||
await apiFetch('/auth/cambiar-contraseña', {
|
||||
method: 'POST',
|
||||
body: { old_password: oldPassword, new_password: newPassword }
|
||||
});
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Invitaciones
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export async function obtenerInvitaciones() {
|
||||
return apiFetch<{ invitaciones: Invitacion[] }>('/empresa/invitaciones');
|
||||
}
|
||||
|
||||
export async function crearInvitacion(dto: {
|
||||
email: string;
|
||||
rol?: string;
|
||||
grupo_id?: number;
|
||||
expira_horas?: number;
|
||||
}): Promise<InvitacionCreada> {
|
||||
return apiFetch<InvitacionCreada>('/empresa/invitaciones', { method: 'POST', body: dto });
|
||||
}
|
||||
|
||||
export async function eliminarInvitacion(id: number): Promise<void> {
|
||||
await apiFetch(`/empresa/invitaciones/${id}`, { method: 'DELETE' });
|
||||
}
|
||||
|
||||
export async function obtenerInvitacionPublica(token: string): Promise<InvitacionInfo> {
|
||||
return apiFetch<InvitacionInfo>(`/auth/invitaciones/${encodeURIComponent(token)}`, {
|
||||
auth: false
|
||||
});
|
||||
}
|
||||
|
||||
export async function aceptarInvitacion(
|
||||
token: string,
|
||||
dto: { name?: string; password?: string }
|
||||
): Promise<AuthResponse | { message: string }> {
|
||||
const data = await apiFetch<AuthResponse | { message: string }>(
|
||||
`/auth/invitaciones/${encodeURIComponent(token)}/aceptar`,
|
||||
{ method: 'POST', body: dto, auth: false }
|
||||
);
|
||||
if ('access_token' in data) {
|
||||
aplicarSesion(data);
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Plataforma
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export async function listarEmpresasPlataforma() {
|
||||
return apiFetch<{ empresas: EmpresaPlataforma[]; total: number }>('/plataforma/empresas');
|
||||
}
|
||||
|
||||
export async function crearEmpresaPlataforma(dto: {
|
||||
nombre: string;
|
||||
slug?: string;
|
||||
cuit?: string;
|
||||
owner_email: string;
|
||||
owner_name?: string;
|
||||
owner_password?: string;
|
||||
}) {
|
||||
return apiFetch<{
|
||||
empresa: EmpresaPlataforma;
|
||||
owner: Miembro;
|
||||
password_temporal: string;
|
||||
owner_existente: boolean;
|
||||
}>('/plataforma/empresas', { method: 'POST', body: dto });
|
||||
}
|
||||
|
||||
export async function actualizarEmpresaPlataforma(
|
||||
id: number,
|
||||
dto: { nombre?: string; slug?: string; cuit?: string; activa?: boolean }
|
||||
): Promise<EmpresaPlataforma> {
|
||||
return apiFetch<EmpresaPlataforma>(`/plataforma/empresas/${id}`, { method: 'PUT', body: dto });
|
||||
}
|
||||
|
||||
export async function listarAdminsPlataforma() {
|
||||
return apiFetch<{ admins: PlataformaAdmin[] }>('/plataforma/admins');
|
||||
}
|
||||
|
||||
export async function agregarAdminPlataforma(dto: {
|
||||
usuario_id?: number;
|
||||
email?: string;
|
||||
rol?: string;
|
||||
}) {
|
||||
return apiFetch('/plataforma/admins', { method: 'POST', body: dto });
|
||||
}
|
||||
|
||||
export async function quitarAdminPlataforma(usuarioID: number): Promise<void> {
|
||||
await apiFetch(`/plataforma/admins/${usuarioID}`, { method: 'DELETE' });
|
||||
}
|
||||
|
||||
export async function listarUsuariosGlobales(pagina = 0, tamano = 20) {
|
||||
return apiFetch<{
|
||||
usuarios: Array<{
|
||||
id: number;
|
||||
email: string;
|
||||
name: string;
|
||||
activo: boolean;
|
||||
debe_cambiar_password: boolean;
|
||||
rol_plataforma: string;
|
||||
empresas: number;
|
||||
created_at: string;
|
||||
}>;
|
||||
total: number;
|
||||
}>(`/plataforma/usuarios?p=${pagina}&s=${tamano}`);
|
||||
}
|
||||
@@ -1,9 +1,17 @@
|
||||
import type { EmpresaResumen, Usuario } from '../../types';
|
||||
|
||||
export interface AuthTokens {
|
||||
access_token: string;
|
||||
refresh_token: string;
|
||||
expires_in: number;
|
||||
token_type: string;
|
||||
permissions?: number[];
|
||||
empresa?: EmpresaResumen | null;
|
||||
empresas?: EmpresaResumen[];
|
||||
empresa_rol?: string;
|
||||
es_plataforma_admin?: boolean;
|
||||
usuario?: Usuario;
|
||||
debe_cambiar_password?: boolean;
|
||||
}
|
||||
|
||||
export const AUTH_CHANGE_EVENT = 'auth-change';
|
||||
|
||||
@@ -3,13 +3,22 @@
|
||||
import 'carbon-components-svelte/css/all.css';
|
||||
import favicon from '$lib/assets/favicon.svg';
|
||||
import { AUTH_CHANGE_EVENT, getToken } from '$lib/hooks/token';
|
||||
import { getCurrentUser } from '$lib/hooks/user';
|
||||
import { goto } from '$app/navigation';
|
||||
import { browser } from '$app/environment';
|
||||
import { page } from '$app/state';
|
||||
import { TokenRefresher } from '$lib/TokenRefresher.svelte';
|
||||
|
||||
let { children } = $props();
|
||||
let theme = 'g100'; // "white" | "g10" | "g80" | "g90" | "g100"
|
||||
let token = $state(getToken());
|
||||
|
||||
const RUTAS_PUBLICAS = new Set(['/', '/login', '/register']);
|
||||
|
||||
function esRutaPublica(path: string): boolean {
|
||||
return RUTAS_PUBLICAS.has(path) || path.startsWith('/invitaciones/');
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
document.documentElement.setAttribute('theme', theme);
|
||||
});
|
||||
@@ -28,6 +37,30 @@
|
||||
};
|
||||
});
|
||||
|
||||
$effect(() => {
|
||||
if (!browser) return;
|
||||
|
||||
const path = page.url.pathname;
|
||||
|
||||
if (!token && !esRutaPublica(path)) {
|
||||
const destino = path === '/' ? '' : `?next=${encodeURIComponent(path + page.url.search)}`;
|
||||
void goto(`/login${destino}`, { replaceState: true });
|
||||
return;
|
||||
}
|
||||
|
||||
if (token && (path === '/login' || path === '/register')) {
|
||||
void goto('/menu', { replaceState: true });
|
||||
return;
|
||||
}
|
||||
|
||||
if (token && path !== '/cambiar-contraseña') {
|
||||
const usuario = getCurrentUser();
|
||||
if (usuario?.debe_cambiar_password) {
|
||||
void goto('/cambiar-contraseña', { replaceState: true });
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
let _refresher: TokenRefresher;
|
||||
|
||||
$effect(() => {
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
// Toda la autenticación vive en localStorage, por lo que la aplicación se
|
||||
// renderiza únicamente en el navegador.
|
||||
export const ssr = false;
|
||||
@@ -1,6 +1,6 @@
|
||||
<script lang="ts">
|
||||
import { getCurrentUser } from '$lib/hooks/user';
|
||||
import { ObtenerGruposDeUsuario } from '$lib/hooks/ObtenerGruposDeUsuario';
|
||||
import { ObtenerGruposDeUsuario } from '$lib/hooks/gruposPermisosUsuario';
|
||||
import Header from '$lib/components/Header.svelte';
|
||||
import LandingPage from '$lib/components/LandingPage.svelte';
|
||||
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
<script lang="ts">
|
||||
import {
|
||||
Button,
|
||||
InlineLoading,
|
||||
InlineNotification,
|
||||
PasswordInput
|
||||
} from 'carbon-components-svelte';
|
||||
import Card from '$lib/components/Card.svelte';
|
||||
import Header from '$lib/components/Header.svelte';
|
||||
import { API_URL } from '$lib/env';
|
||||
import { cambiarPasswordPropia } from '$lib/hooks/tenant';
|
||||
import { recargarSesion } from '$lib/hooks/session';
|
||||
import { getCurrentUser } from '$lib/hooks/user';
|
||||
import { goto } from '$app/navigation';
|
||||
|
||||
let oldPassword = $state('');
|
||||
let newPassword = $state('');
|
||||
let confirmPassword = $state('');
|
||||
let loading = $state(false);
|
||||
let error = $state('');
|
||||
let success = $state('');
|
||||
|
||||
const forzado = $derived(getCurrentUser()?.debe_cambiar_password === true);
|
||||
|
||||
async function handleSubmit() {
|
||||
error = '';
|
||||
success = '';
|
||||
|
||||
if (!oldPassword || !newPassword || !confirmPassword) {
|
||||
error = 'Completá todos los campos';
|
||||
return;
|
||||
}
|
||||
if (newPassword !== confirmPassword) {
|
||||
error = 'Las contraseñas nuevas no coinciden';
|
||||
return;
|
||||
}
|
||||
if (newPassword.length < 8) {
|
||||
error = 'La nueva contraseña debe tener al menos 8 caracteres';
|
||||
return;
|
||||
}
|
||||
|
||||
loading = true;
|
||||
try {
|
||||
await cambiarPasswordPropia(oldPassword, newPassword);
|
||||
await recargarSesion(API_URL);
|
||||
success = 'Contraseña actualizada correctamente';
|
||||
oldPassword = '';
|
||||
newPassword = '';
|
||||
confirmPassword = '';
|
||||
setTimeout(() => {
|
||||
void goto('/menu');
|
||||
}, 900);
|
||||
} catch (e) {
|
||||
error = e instanceof Error ? e.message : 'No se pudo cambiar la contraseña';
|
||||
} finally {
|
||||
loading = false;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
{#if !forzado}
|
||||
<Header />
|
||||
{/if}
|
||||
|
||||
<div class="password-container">
|
||||
<Card title={forzado ? 'Definí tu contraseña' : 'Cambiar contraseña'}>
|
||||
{#if forzado}
|
||||
<p class="subtitle">
|
||||
Estás usando una contraseña temporal. Para continuar necesitás elegir una nueva.
|
||||
</p>
|
||||
{:else}
|
||||
<p class="subtitle">Ingresá tu contraseña actual y la nueva.</p>
|
||||
{/if}
|
||||
|
||||
{#if error}
|
||||
<InlineNotification kind="error" title="Error" subtitle={error} hideCloseButton />
|
||||
{/if}
|
||||
{#if success}
|
||||
<InlineNotification kind="success" title="Listo" subtitle={success} hideCloseButton />
|
||||
{/if}
|
||||
|
||||
<form
|
||||
onsubmit={(e) => {
|
||||
e.preventDefault();
|
||||
handleSubmit();
|
||||
}}
|
||||
>
|
||||
<PasswordInput bind:value={oldPassword} labelText="Contraseña actual" />
|
||||
<PasswordInput bind:value={newPassword} labelText="Nueva contraseña" minlength={8} />
|
||||
<PasswordInput bind:value={confirmPassword} labelText="Repetir nueva contraseña" />
|
||||
<Button type="submit" disabled={loading} class="max-w-full!">
|
||||
{#if loading}
|
||||
<InlineLoading description="Guardando..." />
|
||||
{:else}
|
||||
Guardar contraseña
|
||||
{/if}
|
||||
</Button>
|
||||
</form>
|
||||
|
||||
{#if !forzado}
|
||||
<p><a href="/menu">Volver al panel</a></p>
|
||||
{/if}
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.password-container {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
min-height: 100vh;
|
||||
background: var(--cds-ui-background, #161616);
|
||||
padding: 2rem 1rem;
|
||||
}
|
||||
|
||||
.subtitle {
|
||||
color: var(--cds-text-secondary, #c6c6c6);
|
||||
margin-bottom: 1.5rem;
|
||||
}
|
||||
|
||||
form {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1rem;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,660 @@
|
||||
<script lang="ts">
|
||||
import Header from '$lib/components/Header.svelte';
|
||||
import {
|
||||
Button,
|
||||
InlineLoading,
|
||||
InlineNotification,
|
||||
Modal,
|
||||
Pagination,
|
||||
PasswordInput,
|
||||
Select,
|
||||
SelectItem,
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableContainer,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
Tag,
|
||||
TextInput,
|
||||
Toggle
|
||||
} from 'carbon-components-svelte';
|
||||
import { Add, Copy, Keychain, Pen, TrashCan } from 'carbon-icons-svelte';
|
||||
import { onMount } from 'svelte';
|
||||
import { getCurrentUser } from '$lib/hooks/user';
|
||||
import { obtenerGrupos } from '$lib/hooks/obtenerGrupos';
|
||||
import { agregarGrupoAUsuario } from '$lib/hooks/agregarGrupoAUsuario';
|
||||
import {
|
||||
actualizarEmpresa,
|
||||
actualizarMiembro,
|
||||
crearInvitacion,
|
||||
crearMiembro,
|
||||
eliminarInvitacion,
|
||||
eliminarMiembro,
|
||||
obtenerEmpresaActual,
|
||||
obtenerInvitaciones,
|
||||
obtenerMiembros,
|
||||
resetearPasswordMiembro
|
||||
} from '$lib/hooks/tenant';
|
||||
import type { EmpresaActual, Invitacion, InvitacionCreada, Miembro } from '../../types';
|
||||
|
||||
const usuarioActual = getCurrentUser();
|
||||
|
||||
let empresa = $state<EmpresaActual | null>(null);
|
||||
let miembros = $state<Miembro[]>([]);
|
||||
let grupos = $state<any[]>([]);
|
||||
let totalMiembros = $state(0);
|
||||
let pagina = $state(0);
|
||||
let tamano = 10;
|
||||
|
||||
let invitaciones = $state<Invitacion[]>([]);
|
||||
let cargando = $state(true);
|
||||
let error = $state('');
|
||||
let exito = $state('');
|
||||
|
||||
let formEmpresa = $state({ nombre: '', slug: '', cuit: '' });
|
||||
let guardandoEmpresa = $state(false);
|
||||
|
||||
let modalMiembro = $state(false);
|
||||
let modoMiembro = $state<'crear' | 'editar'>('crear');
|
||||
let miembroEditando = $state<Miembro | null>(null);
|
||||
let formMiembro = $state({ name: '', email: '', password: '', rol: 'MEMBER', grupo_id: 0, activo: true });
|
||||
let guardandoMiembro = $state(false);
|
||||
let errorMiembro = $state('');
|
||||
let passwordTemporal = $state('');
|
||||
|
||||
let modalEliminar = $state(false);
|
||||
let miembroAEliminar = $state<Miembro | null>(null);
|
||||
|
||||
let modalPassword = $state(false);
|
||||
let miembroPassword = $state<Miembro | null>(null);
|
||||
let nuevaPassword = $state('');
|
||||
let guardandoPassword = $state(false);
|
||||
|
||||
let modalInvitacion = $state(false);
|
||||
let formInvitacion = $state({ email: '', rol: 'MEMBER', grupo_id: 0, expira_horas: 168 });
|
||||
let invitacionCreada = $state<InvitacionCreada | null>(null);
|
||||
let guardandoInvitacion = $state(false);
|
||||
let errorInvitacion = $state('');
|
||||
let copiado = $state(false);
|
||||
|
||||
const puedeAdministrar = $derived(
|
||||
usuarioActual?.empresa_rol === 'OWNER' ||
|
||||
usuarioActual?.empresa_rol === 'ADMIN' ||
|
||||
(usuarioActual?.permissions ?? []).some((p) => p === 3 || p === 7)
|
||||
);
|
||||
const esOwner = $derived(usuarioActual?.empresa_rol === 'OWNER');
|
||||
|
||||
function nombreRol(rol: string): string {
|
||||
switch (rol) {
|
||||
case 'OWNER':
|
||||
return 'Owner';
|
||||
case 'ADMIN':
|
||||
return 'Administrador';
|
||||
default:
|
||||
return 'Miembro';
|
||||
}
|
||||
}
|
||||
|
||||
async function cargarEmpresa() {
|
||||
empresa = await obtenerEmpresaActual();
|
||||
formEmpresa = {
|
||||
nombre: empresa.nombre,
|
||||
slug: empresa.slug,
|
||||
cuit: empresa.cuit ?? ''
|
||||
};
|
||||
}
|
||||
|
||||
async function cargarMiembros() {
|
||||
const res = await obtenerMiembros(pagina, tamano);
|
||||
miembros = res.usuarios ?? res.miembros ?? [];
|
||||
totalMiembros = res.total;
|
||||
}
|
||||
|
||||
async function cargarInvitaciones() {
|
||||
const res = await obtenerInvitaciones();
|
||||
invitaciones = res.invitaciones ?? [];
|
||||
}
|
||||
|
||||
async function cargarGrupos() {
|
||||
try {
|
||||
grupos = await obtenerGrupos();
|
||||
} catch {
|
||||
grupos = [];
|
||||
}
|
||||
}
|
||||
|
||||
async function cargarTodo() {
|
||||
cargando = true;
|
||||
error = '';
|
||||
try {
|
||||
await Promise.all([cargarEmpresa(), cargarMiembros(), cargarInvitaciones(), cargarGrupos()]);
|
||||
} catch (e) {
|
||||
error = e instanceof Error ? e.message : 'No se pudo cargar la empresa';
|
||||
} finally {
|
||||
cargando = false;
|
||||
}
|
||||
}
|
||||
|
||||
onMount(cargarTodo);
|
||||
|
||||
function aviso(mensaje: string) {
|
||||
exito = mensaje;
|
||||
setTimeout(() => (exito = ''), 4000);
|
||||
}
|
||||
|
||||
async function guardarEmpresa() {
|
||||
guardandoEmpresa = true;
|
||||
error = '';
|
||||
try {
|
||||
await actualizarEmpresa({
|
||||
nombre: formEmpresa.nombre,
|
||||
slug: formEmpresa.slug,
|
||||
cuit: formEmpresa.cuit
|
||||
});
|
||||
await cargarEmpresa();
|
||||
aviso('Datos de la empresa actualizados');
|
||||
} catch (e) {
|
||||
error = e instanceof Error ? e.message : 'No se pudieron guardar los datos';
|
||||
} finally {
|
||||
guardandoEmpresa = false;
|
||||
}
|
||||
}
|
||||
|
||||
function abrirCrearMiembro() {
|
||||
modoMiembro = 'crear';
|
||||
miembroEditando = null;
|
||||
formMiembro = { name: '', email: '', password: '', rol: 'MEMBER', grupo_id: 0, activo: true };
|
||||
errorMiembro = '';
|
||||
passwordTemporal = '';
|
||||
modalMiembro = true;
|
||||
}
|
||||
|
||||
function abrirEditarMiembro(miembro: Miembro) {
|
||||
modoMiembro = 'editar';
|
||||
miembroEditando = miembro;
|
||||
formMiembro = {
|
||||
name: miembro.name,
|
||||
email: miembro.email,
|
||||
password: '',
|
||||
rol: miembro.rol,
|
||||
grupo_id: 0,
|
||||
activo: miembro.activo
|
||||
};
|
||||
errorMiembro = '';
|
||||
passwordTemporal = '';
|
||||
modalMiembro = true;
|
||||
}
|
||||
|
||||
async function guardarMiembro() {
|
||||
errorMiembro = '';
|
||||
guardandoMiembro = true;
|
||||
try {
|
||||
if (modoMiembro === 'crear') {
|
||||
const res = await crearMiembro({
|
||||
name: formMiembro.name,
|
||||
email: formMiembro.email,
|
||||
password: formMiembro.password || undefined,
|
||||
rol: formMiembro.rol,
|
||||
grupo_id: formMiembro.grupo_id || undefined
|
||||
});
|
||||
passwordTemporal = res.password_temporal;
|
||||
if (passwordTemporal) {
|
||||
aviso('Miembro creado. Copiá la contraseña temporal antes de cerrar.');
|
||||
} else {
|
||||
modalMiembro = false;
|
||||
aviso('Miembro agregado a la empresa');
|
||||
}
|
||||
} else if (miembroEditando) {
|
||||
await actualizarMiembro(miembroEditando.id, {
|
||||
name: formMiembro.name,
|
||||
email: formMiembro.email,
|
||||
rol: formMiembro.rol,
|
||||
activo: formMiembro.activo
|
||||
});
|
||||
if (formMiembro.grupo_id) {
|
||||
const res = await agregarGrupoAUsuario({
|
||||
usuario_id: miembroEditando.id,
|
||||
grupo_id: formMiembro.grupo_id
|
||||
}, () => {});
|
||||
if (res !== 'Ok') {
|
||||
errorMiembro = res;
|
||||
guardandoMiembro = false;
|
||||
return;
|
||||
}
|
||||
}
|
||||
modalMiembro = false;
|
||||
aviso('Miembro actualizado');
|
||||
}
|
||||
await Promise.all([cargarMiembros(), cargarInvitaciones()]);
|
||||
} catch (e) {
|
||||
errorMiembro = e instanceof Error ? e.message : 'No se pudo guardar el miembro';
|
||||
} finally {
|
||||
guardandoMiembro = false;
|
||||
}
|
||||
}
|
||||
|
||||
function abrirEliminar(miembro: Miembro) {
|
||||
miembroAEliminar = miembro;
|
||||
modalEliminar = true;
|
||||
}
|
||||
|
||||
async function confirmarEliminar() {
|
||||
if (!miembroAEliminar) return;
|
||||
try {
|
||||
await eliminarMiembro(miembroAEliminar.id);
|
||||
modalEliminar = false;
|
||||
await cargarMiembros();
|
||||
aviso('Miembro removido de la empresa');
|
||||
} catch (e) {
|
||||
error = e instanceof Error ? e.message : 'No se pudo remover el miembro';
|
||||
}
|
||||
}
|
||||
|
||||
function abrirPassword(miembro: Miembro) {
|
||||
miembroPassword = miembro;
|
||||
nuevaPassword = '';
|
||||
modalPassword = true;
|
||||
}
|
||||
|
||||
async function guardarPassword() {
|
||||
if (!miembroPassword) return;
|
||||
guardandoPassword = true;
|
||||
error = '';
|
||||
try {
|
||||
await resetearPasswordMiembro(miembroPassword.id, nuevaPassword);
|
||||
modalPassword = false;
|
||||
aviso('Contraseña restablecida. El usuario deberá cambiarla al ingresar.');
|
||||
} catch (e) {
|
||||
error = e instanceof Error ? e.message : 'No se pudo restablecer la contraseña';
|
||||
} finally {
|
||||
guardandoPassword = false;
|
||||
}
|
||||
}
|
||||
|
||||
function abrirInvitacion() {
|
||||
formInvitacion = { email: '', rol: 'MEMBER', grupo_id: 0, expira_horas: 168 };
|
||||
invitacionCreada = null;
|
||||
errorInvitacion = '';
|
||||
copiado = false;
|
||||
modalInvitacion = true;
|
||||
}
|
||||
|
||||
async function guardarInvitacion() {
|
||||
errorInvitacion = '';
|
||||
guardandoInvitacion = true;
|
||||
try {
|
||||
invitacionCreada = await crearInvitacion({
|
||||
email: formInvitacion.email,
|
||||
rol: formInvitacion.rol,
|
||||
grupo_id: formInvitacion.grupo_id || undefined,
|
||||
expira_horas: Number(formInvitacion.expira_horas) || 168
|
||||
});
|
||||
await cargarInvitaciones();
|
||||
} catch (e) {
|
||||
errorInvitacion = e instanceof Error ? e.message : 'No se pudo crear la invitación';
|
||||
} finally {
|
||||
guardandoInvitacion = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function copiarLink() {
|
||||
if (!invitacionCreada) return;
|
||||
try {
|
||||
await navigator.clipboard.writeText(invitacionCreada.link);
|
||||
copiado = true;
|
||||
setTimeout(() => (copiado = false), 2000);
|
||||
} catch {
|
||||
copiado = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function cancelarInvitacion(invitacion: Invitacion) {
|
||||
try {
|
||||
await eliminarInvitacion(invitacion.id);
|
||||
await cargarInvitaciones();
|
||||
aviso('Invitación cancelada');
|
||||
} catch (e) {
|
||||
error = e instanceof Error ? e.message : 'No se pudo cancelar la invitación';
|
||||
}
|
||||
}
|
||||
|
||||
function estadoInvitacion(invitacion: Invitacion): string {
|
||||
if (invitacion.usada_en) return 'Usada';
|
||||
if (new Date(invitacion.expira_en).getTime() < Date.now()) return 'Expirada';
|
||||
return 'Pendiente';
|
||||
}
|
||||
|
||||
function tipoTag(estado: string): 'green' | 'gray' | 'red' {
|
||||
if (estado === 'Pendiente') return 'green';
|
||||
if (estado === 'Usada') return 'gray';
|
||||
return 'red';
|
||||
}
|
||||
|
||||
async function cambiarPagina(nueva: number) {
|
||||
pagina = nueva;
|
||||
try {
|
||||
await cargarMiembros();
|
||||
} catch (e) {
|
||||
error = e instanceof Error ? e.message : 'No se pudieron cargar los miembros';
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<Header />
|
||||
|
||||
<div class="page-container">
|
||||
<div class="mb-6 flex flex-wrap items-center justify-between gap-3">
|
||||
<div>
|
||||
<h1 class="page-title">Mi empresa</h1>
|
||||
{#if empresa}
|
||||
<p class="mt-1 text-sm text-gray-400">
|
||||
{empresa.nombre}
|
||||
<Tag type="blue" class="ml-2">{nombreRol(empresa.rol)}</Tag>
|
||||
</p>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{#if error}
|
||||
<InlineNotification kind="error" title="Error" subtitle={error} hideCloseButton />
|
||||
{/if}
|
||||
{#if exito}
|
||||
<InlineNotification kind="success" title="Listo" subtitle={exito} hideCloseButton />
|
||||
{/if}
|
||||
|
||||
{#if !puedeAdministrar}
|
||||
<InlineNotification
|
||||
kind="warning"
|
||||
title="Acceso limitado"
|
||||
subtitle="Tu rol no permite administrar la empresa."
|
||||
hideCloseButton
|
||||
/>
|
||||
{:else if cargando}
|
||||
<InlineLoading description="Cargando empresa..." />
|
||||
{:else}
|
||||
<section class="mb-10">
|
||||
<h2 class="section-title">Datos de la empresa</h2>
|
||||
<div class="grid gap-4 md:grid-cols-3">
|
||||
<TextInput bind:value={formEmpresa.nombre} labelText="Nombre" />
|
||||
<TextInput bind:value={formEmpresa.slug} labelText="Identificador (slug)" />
|
||||
<TextInput bind:value={formEmpresa.cuit} labelText="CUIT" />
|
||||
</div>
|
||||
<Button class="mt-4" disabled={guardandoEmpresa} onclick={guardarEmpresa}>
|
||||
{guardandoEmpresa ? 'Guardando...' : 'Guardar datos'}
|
||||
</Button>
|
||||
</section>
|
||||
|
||||
<section class="mb-10">
|
||||
<div class="mb-3 flex flex-wrap items-center justify-between gap-2">
|
||||
<h2 class="section-title mb-0!">Miembros ({totalMiembros})</h2>
|
||||
<Button size="small" icon={Add} onclick={abrirCrearMiembro}>Agregar miembro</Button>
|
||||
</div>
|
||||
|
||||
<TableContainer>
|
||||
<Table size="compact">
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
<TableHeader>Email</TableHeader>
|
||||
<TableHeader>Nombre</TableHeader>
|
||||
<TableHeader>Rol</TableHeader>
|
||||
<TableHeader>Estado</TableHeader>
|
||||
<TableHeader>Acciones</TableHeader>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
{#if miembros.length === 0}
|
||||
<TableRow>
|
||||
<TableCell colspan={5}>No hay miembros para mostrar</TableCell>
|
||||
</TableRow>
|
||||
{/if}
|
||||
{#each miembros as miembro (miembro.id)}
|
||||
<TableRow>
|
||||
<TableCell>{miembro.email}</TableCell>
|
||||
<TableCell>{miembro.name}</TableCell>
|
||||
<TableCell>
|
||||
<Tag type={miembro.rol === 'OWNER' ? 'purple' : miembro.rol === 'ADMIN' ? 'blue' : 'gray'}>
|
||||
{nombreRol(miembro.rol)}
|
||||
</Tag>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Tag type={miembro.activo && miembro.membresia_activa ? 'green' : 'red'}>
|
||||
{miembro.activo && miembro.membresia_activa ? 'Activo' : 'Inactivo'}
|
||||
</Tag>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<div class="flex flex-wrap gap-1">
|
||||
<Button size="small" icon={Pen} onclick={() => abrirEditarMiembro(miembro)}>
|
||||
Editar
|
||||
</Button>
|
||||
<Button
|
||||
size="small"
|
||||
kind="secondary"
|
||||
icon={Keychain}
|
||||
onclick={() => abrirPassword(miembro)}
|
||||
>
|
||||
Contraseña
|
||||
</Button>
|
||||
<Button
|
||||
size="small"
|
||||
kind="danger"
|
||||
icon={TrashCan}
|
||||
onclick={() => abrirEliminar(miembro)}
|
||||
>
|
||||
Quitar
|
||||
</Button>
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
{/each}
|
||||
</TableBody>
|
||||
</Table>
|
||||
<Pagination
|
||||
totalItems={totalMiembros}
|
||||
pageSize={tamano}
|
||||
page={pagina + 1}
|
||||
pageInputDisabled
|
||||
pageSizeInputDisabled
|
||||
on:click:button--next={() => cambiarPagina(pagina + 1)}
|
||||
on:click:button--previous={() => pagina > 0 && cambiarPagina(pagina - 1)}
|
||||
/>
|
||||
</TableContainer>
|
||||
</section>
|
||||
|
||||
<section class="mb-10">
|
||||
<div class="mb-3 flex flex-wrap items-center justify-between gap-2">
|
||||
<h2 class="section-title mb-0!">Invitaciones</h2>
|
||||
<Button size="small" icon={Add} onclick={abrirInvitacion}>Invitar persona</Button>
|
||||
</div>
|
||||
|
||||
<TableContainer>
|
||||
<Table size="compact">
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
<TableHeader>Email</TableHeader>
|
||||
<TableHeader>Rol</TableHeader>
|
||||
<TableHeader>Expira</TableHeader>
|
||||
<TableHeader>Estado</TableHeader>
|
||||
<TableHeader>Acciones</TableHeader>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
{#if invitaciones.length === 0}
|
||||
<TableRow>
|
||||
<TableCell colspan={5}>No hay invitaciones pendientes</TableCell>
|
||||
</TableRow>
|
||||
{/if}
|
||||
{#each invitaciones as invitacion (invitacion.id)}
|
||||
{@const estado = estadoInvitacion(invitacion)}
|
||||
<TableRow>
|
||||
<TableCell>{invitacion.email}</TableCell>
|
||||
<TableCell>{nombreRol(invitacion.rol)}</TableCell>
|
||||
<TableCell>{new Date(invitacion.expira_en).toLocaleString()}</TableCell>
|
||||
<TableCell><Tag type={tipoTag(estado)}>{estado}</Tag></TableCell>
|
||||
<TableCell>
|
||||
<Button
|
||||
size="small"
|
||||
kind="danger"
|
||||
icon={TrashCan}
|
||||
onclick={() => cancelarInvitacion(invitacion)}
|
||||
>
|
||||
Cancelar
|
||||
</Button>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
{/each}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</TableContainer>
|
||||
</section>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<Modal
|
||||
bind:open={modalMiembro}
|
||||
modalHeading={modoMiembro === 'crear' ? 'Agregar miembro' : 'Editar miembro'}
|
||||
primaryButtonText={modoMiembro === 'crear' ? 'Agregar' : 'Guardar'}
|
||||
secondaryButtonText="Cerrar"
|
||||
on:click:button--primary={guardarMiembro}
|
||||
on:click:button--secondary={() => (modalMiembro = false)}
|
||||
hasScrollingContent
|
||||
>
|
||||
{#if errorMiembro}
|
||||
<InlineNotification kind="error" title="Error" subtitle={errorMiembro} hideCloseButton />
|
||||
{/if}
|
||||
|
||||
{#if passwordTemporal}
|
||||
<InlineNotification
|
||||
kind="success"
|
||||
title="Contraseña temporal"
|
||||
subtitle={passwordTemporal}
|
||||
hideCloseButton
|
||||
/>
|
||||
<p class="mb-4 text-sm text-gray-400">
|
||||
Compartila con la persona. Deberá cambiarla al ingresar.
|
||||
</p>
|
||||
<Button size="small" onclick={() => (modalMiembro = false)}>Cerrar</Button>
|
||||
{:else}
|
||||
<div class="flex flex-col gap-4">
|
||||
<TextInput bind:value={formMiembro.name} labelText="Nombre" />
|
||||
<TextInput bind:value={formMiembro.email} labelText="Email" type="email" />
|
||||
{#if modoMiembro === 'crear'}
|
||||
<PasswordInput
|
||||
bind:value={formMiembro.password}
|
||||
labelText="Contraseña (opcional)"
|
||||
helperText="Si la dejás vacía, se genera una temporal."
|
||||
/>
|
||||
{/if}
|
||||
<Select bind:selected={formMiembro.rol} labelText="Rol">
|
||||
<SelectItem value="MEMBER" text="Miembro" />
|
||||
<SelectItem value="ADMIN" text="Administrador" />
|
||||
{#if esOwner}
|
||||
<SelectItem value="OWNER" text="Owner" />
|
||||
{/if}
|
||||
</Select>
|
||||
<Select bind:selected={formMiembro.grupo_id} labelText="Asignar grupo (rol)">
|
||||
<SelectItem value={0} text="Sin cambio" />
|
||||
{#each grupos as grupo}
|
||||
<SelectItem value={grupo.id} text={grupo.nombre} />
|
||||
{/each}
|
||||
</Select>
|
||||
{#if modoMiembro === 'editar'}
|
||||
<Toggle bind:toggled={formMiembro.activo} labelText="Membresía activa" />
|
||||
{/if}
|
||||
{#if guardandoMiembro}
|
||||
<InlineLoading description="Guardando..." />
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
</Modal>
|
||||
|
||||
<Modal
|
||||
bind:open={modalEliminar}
|
||||
modalHeading="Quitar miembro"
|
||||
primaryButtonText="Quitar"
|
||||
secondaryButtonText="Cancelar"
|
||||
danger
|
||||
on:click:button--primary={confirmarEliminar}
|
||||
on:click:button--secondary={() => (modalEliminar = false)}
|
||||
>
|
||||
<p>
|
||||
¿Querés quitar a <strong>{miembroAEliminar?.email}</strong> de la empresa? El usuario global no se
|
||||
elimina, solo pierde acceso a esta empresa.
|
||||
</p>
|
||||
</Modal>
|
||||
|
||||
<Modal
|
||||
bind:open={modalPassword}
|
||||
modalHeading="Restablecer contraseña"
|
||||
primaryButtonText="Restablecer"
|
||||
secondaryButtonText="Cancelar"
|
||||
on:click:button--primary={guardarPassword}
|
||||
on:click:button--secondary={() => (modalPassword = false)}
|
||||
>
|
||||
<p class="mb-4 text-sm text-gray-400">
|
||||
Nueva contraseña para <strong>{miembroPassword?.email}</strong>. El usuario deberá cambiarla al
|
||||
ingresar.
|
||||
</p>
|
||||
<PasswordInput bind:value={nuevaPassword} labelText="Nueva contraseña" minlength={8} />
|
||||
{#if guardandoPassword}
|
||||
<InlineLoading description="Guardando..." />
|
||||
{/if}
|
||||
</Modal>
|
||||
|
||||
<Modal
|
||||
bind:open={modalInvitacion}
|
||||
modalHeading="Invitar persona"
|
||||
primaryButtonText={invitacionCreada ? 'Cerrar' : 'Crear invitación'}
|
||||
secondaryButtonText="Cancelar"
|
||||
on:click:button--primary={() => {
|
||||
if (invitacionCreada) modalInvitacion = false;
|
||||
else guardarInvitacion();
|
||||
}}
|
||||
on:click:button--secondary={() => (modalInvitacion = false)}
|
||||
hasScrollingContent
|
||||
>
|
||||
{#if errorInvitacion}
|
||||
<InlineNotification kind="error" title="Error" subtitle={errorInvitacion} hideCloseButton />
|
||||
{/if}
|
||||
|
||||
{#if invitacionCreada}
|
||||
<InlineNotification
|
||||
kind={invitacionCreada.email_enviado ? 'success' : 'warning'}
|
||||
title={invitacionCreada.email_enviado ? 'Invitación enviada' : 'No se pudo enviar el email'}
|
||||
subtitle={invitacionCreada.email_enviado
|
||||
? 'La persona recibió el link por email.'
|
||||
: 'Compartí el link manualmente.'}
|
||||
hideCloseButton
|
||||
/>
|
||||
<div class="mt-4 flex items-end gap-2">
|
||||
<TextInput readonly labelText="Link de invitación" value={invitacionCreada.link} />
|
||||
<Button icon={Copy} onclick={copiarLink}>{copiado ? 'Copiado' : 'Copiar'}</Button>
|
||||
</div>
|
||||
{:else}
|
||||
<div class="flex flex-col gap-4">
|
||||
<TextInput bind:value={formInvitacion.email} labelText="Email" type="email" />
|
||||
<Select bind:selected={formInvitacion.grupo_id} labelText="Rol (grupo)">
|
||||
{#each grupos as grupo}
|
||||
<SelectItem value={grupo.id} text={grupo.nombre} />
|
||||
{/each}
|
||||
</Select>
|
||||
<Select bind:selected={formInvitacion.expira_horas} labelText="Vigencia">
|
||||
<SelectItem value={24} text="24 horas" />
|
||||
<SelectItem value={168} text="7 días" />
|
||||
<SelectItem value={720} text="30 días" />
|
||||
</Select>
|
||||
{#if guardandoInvitacion}
|
||||
<InlineLoading description="Creando invitación..." />
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
</Modal>
|
||||
|
||||
<style>
|
||||
.section-title {
|
||||
font-size: 1.05rem;
|
||||
font-weight: 600;
|
||||
margin-bottom: 0.75rem;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,166 @@
|
||||
<script lang="ts">
|
||||
import {
|
||||
Button,
|
||||
InlineLoading,
|
||||
InlineNotification,
|
||||
PasswordInput,
|
||||
TextInput
|
||||
} from 'carbon-components-svelte';
|
||||
import Card from '$lib/components/Card.svelte';
|
||||
import { page } from '$app/state';
|
||||
import { goto } from '$app/navigation';
|
||||
import { onMount } from 'svelte';
|
||||
import { aceptarInvitacion, obtenerInvitacionPublica } from '$lib/hooks/tenant';
|
||||
import type { InvitacionInfo } from '../../../types';
|
||||
|
||||
let token = $derived(page.params.token ?? '');
|
||||
let info = $state<InvitacionInfo | null>(null);
|
||||
let cargando = $state(true);
|
||||
let enviando = $state(false);
|
||||
let error = $state('');
|
||||
let errorCarga = $state('');
|
||||
|
||||
let name = $state('');
|
||||
let password = $state('');
|
||||
let confirmPassword = $state('');
|
||||
|
||||
onMount(async () => {
|
||||
try {
|
||||
info = await obtenerInvitacionPublica(token);
|
||||
} catch (e) {
|
||||
errorCarga = e instanceof Error ? e.message : 'Invitación no encontrada';
|
||||
} finally {
|
||||
cargando = false;
|
||||
}
|
||||
});
|
||||
|
||||
async function handleSubmit() {
|
||||
error = '';
|
||||
|
||||
if (!info) return;
|
||||
if (!info.usuario_existente && !name.trim()) {
|
||||
error = 'Ingresá tu nombre';
|
||||
return;
|
||||
}
|
||||
if (!password) {
|
||||
error = 'Ingresá tu contraseña';
|
||||
return;
|
||||
}
|
||||
if (!info.usuario_existente && password !== confirmPassword) {
|
||||
error = 'Las contraseñas no coinciden';
|
||||
return;
|
||||
}
|
||||
if (!info.usuario_existente && password.length < 8) {
|
||||
error = 'La contraseña debe tener al menos 8 caracteres';
|
||||
return;
|
||||
}
|
||||
|
||||
enviando = true;
|
||||
try {
|
||||
const resultado = await aceptarInvitacion(token, {
|
||||
name: name.trim() || undefined,
|
||||
password
|
||||
});
|
||||
if ('access_token' in resultado) {
|
||||
await goto('/menu');
|
||||
} else {
|
||||
await goto('/login');
|
||||
}
|
||||
} catch (e) {
|
||||
error = e instanceof Error ? e.message : 'No se pudo aceptar la invitación';
|
||||
} finally {
|
||||
enviando = false;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="invitacion-container">
|
||||
<Card title="Invitación">
|
||||
{#if cargando}
|
||||
<InlineLoading description="Cargando invitación..." />
|
||||
{:else if errorCarga}
|
||||
<InlineNotification kind="error" title="Invitación inválida" subtitle={errorCarga} hideCloseButton />
|
||||
<p><a href="/login">Ir a iniciar sesión</a></p>
|
||||
{:else if info}
|
||||
{#if !info.valida}
|
||||
<InlineNotification
|
||||
kind="error"
|
||||
title="Invitación no disponible"
|
||||
subtitle={info.usada
|
||||
? 'Esta invitación ya fue utilizada'
|
||||
: info.expirada
|
||||
? 'Esta invitación expiró'
|
||||
: 'La empresa no está disponible'}
|
||||
hideCloseButton
|
||||
/>
|
||||
<p><a href="/login">Ir a iniciar sesión</a></p>
|
||||
{:else}
|
||||
<p class="subtitle">
|
||||
Fuiste invitado a <strong>{info.empresa}</strong> con el rol <strong>{info.rol}</strong>.
|
||||
</p>
|
||||
<p class="email">Cuenta: <strong>{info.email}</strong></p>
|
||||
|
||||
{#if error}
|
||||
<InlineNotification kind="error" title="Error" subtitle={error} hideCloseButton />
|
||||
{/if}
|
||||
|
||||
<form
|
||||
onsubmit={(e) => {
|
||||
e.preventDefault();
|
||||
handleSubmit();
|
||||
}}
|
||||
>
|
||||
{#if !info.usuario_existente}
|
||||
<TextInput bind:value={name} labelText="Nombre" placeholder="Tu nombre" />
|
||||
{:else}
|
||||
<p class="hint">
|
||||
Ya tenés una cuenta con este email. Ingresá tu contraseña actual para sumarte a la
|
||||
empresa.
|
||||
</p>
|
||||
{/if}
|
||||
|
||||
<PasswordInput bind:value={password} labelText="Contraseña" />
|
||||
{#if !info.usuario_existente}
|
||||
<PasswordInput bind:value={confirmPassword} labelText="Repetir contraseña" />
|
||||
{/if}
|
||||
|
||||
<Button type="submit" disabled={enviando} class="max-w-full!">
|
||||
{#if enviando}
|
||||
<InlineLoading description="Aceptando..." />
|
||||
{:else}
|
||||
Aceptar invitación
|
||||
{/if}
|
||||
</Button>
|
||||
</form>
|
||||
{/if}
|
||||
{/if}
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.invitacion-container {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
min-height: 100vh;
|
||||
background: var(--cds-ui-background, #161616);
|
||||
padding: 2rem 1rem;
|
||||
}
|
||||
|
||||
.subtitle,
|
||||
.hint {
|
||||
color: var(--cds-text-secondary, #c6c6c6);
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
.email {
|
||||
color: var(--cds-text-secondary, #c6c6c6);
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
form {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1rem;
|
||||
}
|
||||
</style>
|
||||
@@ -9,6 +9,7 @@
|
||||
import Card from '$lib/components/Card.svelte';
|
||||
import { login as loginApi } from '$lib/hooks/login';
|
||||
import { goto } from '$app/navigation';
|
||||
import { page } from '$app/state';
|
||||
|
||||
let email: string = $state('');
|
||||
let password: string = $state('');
|
||||
@@ -26,7 +27,13 @@
|
||||
|
||||
try {
|
||||
const response = await loginApi({ email, password });
|
||||
goto('/menu');
|
||||
if (response.debe_cambiar_password) {
|
||||
await goto('/cambiar-contraseña');
|
||||
return;
|
||||
}
|
||||
|
||||
const next = page.url.searchParams.get('next');
|
||||
await goto(next && next.startsWith('/') ? next : '/menu');
|
||||
} catch (e) {
|
||||
error = e instanceof Error ? e.message : 'Error al iniciar sesión';
|
||||
} finally {
|
||||
|
||||
@@ -75,6 +75,6 @@
|
||||
pageSize={10}
|
||||
pageSizes={[10]}
|
||||
pageSizeInputDisabled={true}
|
||||
on:change={(e) => irAPagina(e.detail.page - 1)}
|
||||
on:change={(e) => irAPagina((e.detail.page ?? 1) - 1)}
|
||||
/>
|
||||
</div>
|
||||
@@ -2,6 +2,8 @@ import type { PageLoad } from './$types';
|
||||
import { obtenerLogs } from '$lib/hooks/logs/obtenerLogs';
|
||||
import { busquedaLogs } from '$lib/hooks/logs/busquedaLogs';
|
||||
|
||||
export const ssr = false;
|
||||
|
||||
export const load: PageLoad = async ({ url, depends, fetch }) => {
|
||||
depends('logs:pagina');
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
// @ts-nocheck
|
||||
export class ExportarLogs {
|
||||
#data;
|
||||
|
||||
|
||||
@@ -60,7 +60,7 @@
|
||||
fluid
|
||||
datePickerType="range"
|
||||
on:change={(e) => {
|
||||
const dates = e.detail;
|
||||
const dates = e.detail as { selectedDates: Date[] };
|
||||
filtros.fechaInicio = dates.selectedDates[0] ?? '';
|
||||
filtros.fechaFin = dates.selectedDates[1] ?? '';
|
||||
}}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
<script>
|
||||
<script lang="ts">
|
||||
import { DataTable, Tag } from 'carbon-components-svelte';
|
||||
import type { LogDetalle, LogEntry } from '../../types';
|
||||
|
||||
const headers = [
|
||||
{ key: 'id', value: '#' },
|
||||
@@ -8,12 +9,9 @@
|
||||
{ key: 'accion', value: 'Acción' }
|
||||
];
|
||||
|
||||
let { logs } = $props();
|
||||
let { logs }: { logs?: LogEntry[] } = $props();
|
||||
|
||||
/**
|
||||
* @param {string | number | Date} iso
|
||||
*/
|
||||
function formatFecha(iso) {
|
||||
function formatFecha(iso: string | number | Date) {
|
||||
return new Date(iso).toLocaleString('es-AR', {
|
||||
day: '2-digit',
|
||||
month: '2-digit',
|
||||
@@ -33,7 +31,7 @@
|
||||
{#if cell.key === 'created_at'}
|
||||
{formatFecha(row.created_at)}
|
||||
{:else if cell.key === 'usuario'}
|
||||
{row.usuario?.nombre ?? `#${row.usuarioId}`}
|
||||
{row.usuario?.name ?? row.usuario?.email ?? `#${row.usuarioId}`}
|
||||
{:else if cell.key === 'accion'}
|
||||
<Tag type="blue">{row.accion}</Tag>
|
||||
{:else}
|
||||
@@ -43,7 +41,10 @@
|
||||
|
||||
<svelte:fragment slot="expandedRow" let:row>
|
||||
{#if row.detalles && row.detalles.length > 0}
|
||||
{@const detallesConId = row.detalles.map((d, i) => ({ ...d, id: d.id || i + 1 }))}
|
||||
{@const detallesConId = row.detalles.map((d: LogDetalle, i: number) => ({
|
||||
...d,
|
||||
id: d.id || i + 1
|
||||
}))}
|
||||
<DataTable
|
||||
headers={[
|
||||
{ key: 'nombreTabla', value: 'Tabla' },
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import { obtenerMarcas } from '$lib/hooks/marcas/obtenerMarcas';
|
||||
|
||||
export async function load({depends, fetch }) {
|
||||
depends("marcas:load")
|
||||
const marcas = await obtenerMarcas(fetch);
|
||||
export const ssr = false;
|
||||
|
||||
return { marcas : marcas}
|
||||
export async function load({ depends, fetch }) {
|
||||
depends('marcas:load');
|
||||
const marcas = await obtenerMarcas(fetch);
|
||||
|
||||
return { marcas: marcas };
|
||||
}
|
||||
@@ -8,7 +8,7 @@
|
||||
open = $bindable(),
|
||||
onClose,
|
||||
marca
|
||||
}: { open?: boolean; onClose: () => void; marca: Marca} = $props();
|
||||
}: { open?: boolean; onClose: () => void; marca?: Marca | null } = $props();
|
||||
|
||||
let error = $state('');
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<script lang="ts">
|
||||
import { goto } from '$app/navigation';
|
||||
import { getCurrentUser } from '$lib/hooks/user';
|
||||
import { ObtenerGruposDeUsuario } from '$lib/hooks/ObtenerGruposDeUsuario';
|
||||
import { ObtenerGruposDeUsuario } from '$lib/hooks/gruposPermisosUsuario';
|
||||
import CardError from '$lib/components/CardError.svelte';
|
||||
import Header from '$lib/components/Header.svelte';
|
||||
import IconPreview from '$lib/components/IconPreview.svelte';
|
||||
@@ -24,7 +24,10 @@
|
||||
if (!usuario) goto('/login');
|
||||
});
|
||||
|
||||
let grupos = usuario ? ObtenerGruposDeUsuario(usuario) : undefined;
|
||||
let grupos =
|
||||
usuario && usuario.empresa
|
||||
? ObtenerGruposDeUsuario(usuario)
|
||||
: Promise.resolve({ email: '', groups: [] });
|
||||
|
||||
function hrefPermiso(alias: string): string {
|
||||
return alias.startsWith('/') ? alias : `/${alias}`;
|
||||
@@ -67,7 +70,14 @@
|
||||
{:then gg}
|
||||
{#if !gg || gg.groups.length === 0}
|
||||
<Text tag="p" type="body-long-01" color="secondary" class="py-8! text-center">
|
||||
No tienes grupos asignados
|
||||
{#if !usuario?.empresa}
|
||||
No tenés una empresa activa.
|
||||
{#if usuario?.es_plataforma_admin}
|
||||
<a href="/plataforma">Ir a la administración de plataforma</a>
|
||||
{/if}
|
||||
{:else}
|
||||
No tenés grupos asignados en esta empresa.
|
||||
{/if}
|
||||
</Text>
|
||||
{:else}
|
||||
{#each gg.groups as g (g.id)}
|
||||
|
||||
@@ -23,6 +23,7 @@
|
||||
import { crearPermiso } from '$lib/hooks/crearPermiso';
|
||||
import { actualizarPermiso } from '$lib/hooks/actualizarPermiso';
|
||||
import { eliminarPermiso } from '$lib/hooks/eliminarPermiso';
|
||||
import { esPlataformaAdmin } from '$lib/hooks/session';
|
||||
import type { Permiso } from '../../types';
|
||||
import Add from 'carbon-icons-svelte/lib/Add.svelte';
|
||||
import Edit from 'carbon-icons-svelte/lib/Edit.svelte';
|
||||
@@ -31,6 +32,8 @@
|
||||
let permisos: Permiso[] = $state([]);
|
||||
let loading = $state(true);
|
||||
let error = $state('');
|
||||
// El catálogo de permisos es global: solo plataforma puede editarlo.
|
||||
let puedeEditar = $state(esPlataformaAdmin());
|
||||
|
||||
let modalOpen = $state(false);
|
||||
let modalEditando = $state(false);
|
||||
@@ -173,10 +176,21 @@
|
||||
|
||||
<div class="page-container">
|
||||
<div class="flex justify-between">
|
||||
<h1 class="page-title">Gestión de Permisos</h1>
|
||||
<Button onclick={abrirModalCrear} icon={Add}>Nuevo Permiso</Button>
|
||||
<h1 class="page-title">Permisos</h1>
|
||||
{#if puedeEditar}
|
||||
<Button onclick={abrirModalCrear} icon={Add}>Nuevo Permiso</Button>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
{#if !puedeEditar}
|
||||
<InlineNotification
|
||||
kind="info"
|
||||
title="Catálogo global"
|
||||
subtitle="Los permisos solo pueden modificarse desde la administración de plataforma."
|
||||
hideCloseButton
|
||||
/>
|
||||
{/if}
|
||||
|
||||
{#if error}
|
||||
<InlineNotification kind="error" title="Error" subtitle={error} hideCloseButton />
|
||||
{/if}
|
||||
@@ -191,7 +205,9 @@
|
||||
{#each headers as header}
|
||||
<TableHeader>{header.value}</TableHeader>
|
||||
{/each}
|
||||
<TableHeader>Acciones</TableHeader>
|
||||
{#if puedeEditar}
|
||||
<TableHeader>Acciones</TableHeader>
|
||||
{/if}
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
@@ -212,19 +228,21 @@
|
||||
{/if}
|
||||
</TableCell>
|
||||
{/each}
|
||||
<TableCell class="acciones-cell">
|
||||
<Button kind="ghost" size="small" icon={Edit} onclick={() => abrirModalEditar(p)}>
|
||||
Editar
|
||||
</Button>
|
||||
<Button
|
||||
kind="ghost"
|
||||
size="small"
|
||||
icon={TrashCan}
|
||||
onclick={() => abrirModalEliminar(p)}
|
||||
>
|
||||
Eliminar
|
||||
</Button>
|
||||
</TableCell>
|
||||
{#if puedeEditar}
|
||||
<TableCell class="acciones-cell">
|
||||
<Button kind="ghost" size="small" icon={Edit} onclick={() => abrirModalEditar(p)}>
|
||||
Editar
|
||||
</Button>
|
||||
<Button
|
||||
kind="ghost"
|
||||
size="small"
|
||||
icon={TrashCan}
|
||||
onclick={() => abrirModalEliminar(p)}
|
||||
>
|
||||
Eliminar
|
||||
</Button>
|
||||
</TableCell>
|
||||
{/if}
|
||||
</TableRow>
|
||||
{/each}
|
||||
</TableBody>
|
||||
|
||||
@@ -0,0 +1,465 @@
|
||||
<script lang="ts">
|
||||
import Header from '$lib/components/Header.svelte';
|
||||
import {
|
||||
Button,
|
||||
InlineLoading,
|
||||
InlineNotification,
|
||||
Modal,
|
||||
Pagination,
|
||||
PasswordInput,
|
||||
Select,
|
||||
SelectItem,
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableContainer,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
Tag,
|
||||
TextInput
|
||||
} from 'carbon-components-svelte';
|
||||
import { Add, Pen, TrashCan } from 'carbon-icons-svelte';
|
||||
import { onMount } from 'svelte';
|
||||
import {
|
||||
actualizarEmpresaPlataforma,
|
||||
agregarAdminPlataforma,
|
||||
crearEmpresaPlataforma,
|
||||
listarAdminsPlataforma,
|
||||
listarEmpresasPlataforma,
|
||||
listarUsuariosGlobales,
|
||||
quitarAdminPlataforma
|
||||
} from '$lib/hooks/tenant';
|
||||
import type { EmpresaPlataforma, PlataformaAdmin } from '../../types';
|
||||
|
||||
let empresas = $state<EmpresaPlataforma[]>([]);
|
||||
let admins = $state<PlataformaAdmin[]>([]);
|
||||
let usuarios = $state<Awaited<ReturnType<typeof listarUsuariosGlobales>>['usuarios']>([]);
|
||||
let totalUsuarios = $state(0);
|
||||
let paginaUsuarios = $state(0);
|
||||
let tamanoUsuarios = 20;
|
||||
|
||||
let cargando = $state(true);
|
||||
let error = $state('');
|
||||
let exito = $state('');
|
||||
|
||||
let modalEmpresa = $state(false);
|
||||
let empresaEditando = $state<EmpresaPlataforma | null>(null);
|
||||
let formEmpresa = $state({
|
||||
nombre: '',
|
||||
slug: '',
|
||||
cuit: '',
|
||||
owner_email: '',
|
||||
owner_name: '',
|
||||
owner_password: ''
|
||||
});
|
||||
let guardandoEmpresa = $state(false);
|
||||
let errorEmpresa = $state('');
|
||||
let passwordTemporal = $state('');
|
||||
|
||||
let modalAdmin = $state(false);
|
||||
let formAdmin = $state({ email: '', rol: 'SUPERADMIN' });
|
||||
let guardandoAdmin = $state(false);
|
||||
let errorAdmin = $state('');
|
||||
|
||||
function aviso(mensaje: string) {
|
||||
exito = mensaje;
|
||||
setTimeout(() => (exito = ''), 4000);
|
||||
}
|
||||
|
||||
async function cargarEmpresas() {
|
||||
const res = await listarEmpresasPlataforma();
|
||||
empresas = res.empresas ?? [];
|
||||
}
|
||||
|
||||
async function cargarAdmins() {
|
||||
const res = await listarAdminsPlataforma();
|
||||
admins = res.admins ?? [];
|
||||
}
|
||||
|
||||
async function cargarUsuarios() {
|
||||
const res = await listarUsuariosGlobales(paginaUsuarios, tamanoUsuarios);
|
||||
usuarios = res.usuarios ?? [];
|
||||
totalUsuarios = res.total;
|
||||
}
|
||||
|
||||
async function cargarTodo() {
|
||||
cargando = true;
|
||||
error = '';
|
||||
try {
|
||||
await Promise.all([cargarEmpresas(), cargarAdmins(), cargarUsuarios()]);
|
||||
} catch (e) {
|
||||
error = e instanceof Error ? e.message : 'No se pudo cargar la plataforma';
|
||||
} finally {
|
||||
cargando = false;
|
||||
}
|
||||
}
|
||||
|
||||
onMount(cargarTodo);
|
||||
|
||||
function abrirCrearEmpresa() {
|
||||
empresaEditando = null;
|
||||
formEmpresa = {
|
||||
nombre: '',
|
||||
slug: '',
|
||||
cuit: '',
|
||||
owner_email: '',
|
||||
owner_name: '',
|
||||
owner_password: ''
|
||||
};
|
||||
passwordTemporal = '';
|
||||
errorEmpresa = '';
|
||||
modalEmpresa = true;
|
||||
}
|
||||
|
||||
function abrirEditarEmpresa(empresa: EmpresaPlataforma) {
|
||||
empresaEditando = empresa;
|
||||
formEmpresa = {
|
||||
nombre: empresa.nombre,
|
||||
slug: empresa.slug,
|
||||
cuit: empresa.cuit ?? '',
|
||||
owner_email: '',
|
||||
owner_name: '',
|
||||
owner_password: ''
|
||||
};
|
||||
passwordTemporal = '';
|
||||
errorEmpresa = '';
|
||||
modalEmpresa = true;
|
||||
}
|
||||
|
||||
async function guardarEmpresa() {
|
||||
errorEmpresa = '';
|
||||
guardandoEmpresa = true;
|
||||
try {
|
||||
if (empresaEditando) {
|
||||
await actualizarEmpresaPlataforma(empresaEditando.id, {
|
||||
nombre: formEmpresa.nombre,
|
||||
slug: formEmpresa.slug,
|
||||
cuit: formEmpresa.cuit
|
||||
});
|
||||
modalEmpresa = false;
|
||||
aviso('Empresa actualizada');
|
||||
} else {
|
||||
const res = await crearEmpresaPlataforma({
|
||||
nombre: formEmpresa.nombre,
|
||||
slug: formEmpresa.slug || undefined,
|
||||
cuit: formEmpresa.cuit || undefined,
|
||||
owner_email: formEmpresa.owner_email,
|
||||
owner_name: formEmpresa.owner_name || undefined,
|
||||
owner_password: formEmpresa.owner_password || undefined
|
||||
});
|
||||
passwordTemporal = res.password_temporal;
|
||||
aviso(
|
||||
passwordTemporal
|
||||
? 'Empresa creada. Copiá la contraseña temporal del owner.'
|
||||
: 'Empresa creada'
|
||||
);
|
||||
if (!passwordTemporal) modalEmpresa = false;
|
||||
}
|
||||
await Promise.all([cargarEmpresas(), cargarUsuarios()]);
|
||||
} catch (e) {
|
||||
errorEmpresa = e instanceof Error ? e.message : 'No se pudo guardar la empresa';
|
||||
} finally {
|
||||
guardandoEmpresa = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function alternarEmpresa(empresa: EmpresaPlataforma) {
|
||||
try {
|
||||
await actualizarEmpresaPlataforma(empresa.id, { activa: !empresa.activa });
|
||||
await cargarEmpresas();
|
||||
aviso(empresa.activa ? 'Empresa desactivada' : 'Empresa activada');
|
||||
} catch (e) {
|
||||
error = e instanceof Error ? e.message : 'No se pudo actualizar la empresa';
|
||||
}
|
||||
}
|
||||
|
||||
function abrirCrearAdmin() {
|
||||
formAdmin = { email: '', rol: 'SUPERADMIN' };
|
||||
errorAdmin = '';
|
||||
modalAdmin = true;
|
||||
}
|
||||
|
||||
async function guardarAdmin() {
|
||||
errorAdmin = '';
|
||||
guardandoAdmin = true;
|
||||
try {
|
||||
await agregarAdminPlataforma({ email: formAdmin.email, rol: formAdmin.rol });
|
||||
modalAdmin = false;
|
||||
await Promise.all([cargarAdmins(), cargarUsuarios()]);
|
||||
aviso('Administrador de plataforma agregado');
|
||||
} catch (e) {
|
||||
errorAdmin = e instanceof Error ? e.message : 'No se pudo agregar el administrador';
|
||||
} finally {
|
||||
guardandoAdmin = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function quitarAdmin(admin: PlataformaAdmin) {
|
||||
if (!confirm(`¿Quitar el rol de plataforma a ${admin.usuario?.email ?? `#${admin.usuario_id}`}?`)) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await quitarAdminPlataforma(admin.usuario_id);
|
||||
await Promise.all([cargarAdmins(), cargarUsuarios()]);
|
||||
aviso('Rol de plataforma removido');
|
||||
} catch (e) {
|
||||
error = e instanceof Error ? e.message : 'No se pudo remover el administrador';
|
||||
}
|
||||
}
|
||||
|
||||
async function cambiarPaginaUsuarios(nueva: number) {
|
||||
paginaUsuarios = nueva;
|
||||
try {
|
||||
await cargarUsuarios();
|
||||
} catch (e) {
|
||||
error = e instanceof Error ? e.message : 'No se pudieron cargar los usuarios';
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<Header />
|
||||
|
||||
<div class="page-container">
|
||||
<h1 class="page-title">Plataforma</h1>
|
||||
<p class="mb-6 text-sm text-gray-400">
|
||||
Administración global de empresas, administradores y usuarios.
|
||||
</p>
|
||||
|
||||
{#if error}
|
||||
<InlineNotification kind="error" title="Error" subtitle={error} hideCloseButton />
|
||||
{/if}
|
||||
{#if exito}
|
||||
<InlineNotification kind="success" title="Listo" subtitle={exito} hideCloseButton />
|
||||
{/if}
|
||||
|
||||
{#if cargando}
|
||||
<InlineLoading description="Cargando plataforma..." />
|
||||
{:else}
|
||||
<section class="mb-10">
|
||||
<div class="mb-3 flex flex-wrap items-center justify-between gap-2">
|
||||
<h2 class="section-title mb-0!">Empresas</h2>
|
||||
<Button size="small" icon={Add} onclick={abrirCrearEmpresa}>Nueva empresa</Button>
|
||||
</div>
|
||||
<TableContainer>
|
||||
<Table size="compact">
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
<TableHeader>ID</TableHeader>
|
||||
<TableHeader>Nombre</TableHeader>
|
||||
<TableHeader>Slug</TableHeader>
|
||||
<TableHeader>CUIT</TableHeader>
|
||||
<TableHeader>Miembros</TableHeader>
|
||||
<TableHeader>Owners</TableHeader>
|
||||
<TableHeader>Estado</TableHeader>
|
||||
<TableHeader>Acciones</TableHeader>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
{#if empresas.length === 0}
|
||||
<TableRow>
|
||||
<TableCell colspan={8}>No hay empresas registradas</TableCell>
|
||||
</TableRow>
|
||||
{/if}
|
||||
{#each empresas as empresa (empresa.id)}
|
||||
<TableRow>
|
||||
<TableCell>{empresa.id}</TableCell>
|
||||
<TableCell>{empresa.nombre}</TableCell>
|
||||
<TableCell>{empresa.slug}</TableCell>
|
||||
<TableCell>{empresa.cuit ?? '-'}</TableCell>
|
||||
<TableCell>{empresa.miembros}</TableCell>
|
||||
<TableCell>{empresa.owners}</TableCell>
|
||||
<TableCell>
|
||||
<Tag type={empresa.activa ? 'green' : 'red'}>
|
||||
{empresa.activa ? 'Activa' : 'Inactiva'}
|
||||
</Tag>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<div class="flex flex-wrap gap-1">
|
||||
<Button size="small" icon={Pen} onclick={() => abrirEditarEmpresa(empresa)}>
|
||||
Editar
|
||||
</Button>
|
||||
<Button
|
||||
size="small"
|
||||
kind={empresa.activa ? 'danger' : 'secondary'}
|
||||
onclick={() => alternarEmpresa(empresa)}
|
||||
>
|
||||
{empresa.activa ? 'Desactivar' : 'Activar'}
|
||||
</Button>
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
{/each}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</TableContainer>
|
||||
</section>
|
||||
|
||||
<section class="mb-10">
|
||||
<div class="mb-3 flex flex-wrap items-center justify-between gap-2">
|
||||
<h2 class="section-title mb-0!">Administradores de plataforma</h2>
|
||||
<Button size="small" icon={Add} onclick={abrirCrearAdmin}>Agregar admin</Button>
|
||||
</div>
|
||||
<TableContainer>
|
||||
<Table size="compact">
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
<TableHeader>Usuario</TableHeader>
|
||||
<TableHeader>Email</TableHeader>
|
||||
<TableHeader>Rol</TableHeader>
|
||||
<TableHeader>Estado</TableHeader>
|
||||
<TableHeader>Acciones</TableHeader>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
{#if admins.length === 0}
|
||||
<TableRow>
|
||||
<TableCell colspan={5}>No hay administradores</TableCell>
|
||||
</TableRow>
|
||||
{/if}
|
||||
{#each admins as admin (admin.usuario_id)}
|
||||
<TableRow>
|
||||
<TableCell>{admin.usuario?.name ?? `#${admin.usuario_id}`}</TableCell>
|
||||
<TableCell>{admin.usuario?.email ?? '-'}</TableCell>
|
||||
<TableCell>
|
||||
<Tag type={admin.rol === 'SUPERADMIN' ? 'purple' : 'blue'}>{admin.rol}</Tag>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Tag type={admin.activo ? 'green' : 'red'}>
|
||||
{admin.activo ? 'Activo' : 'Inactivo'}
|
||||
</Tag>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Button size="small" kind="danger" icon={TrashCan} onclick={() => quitarAdmin(admin)}>
|
||||
Quitar
|
||||
</Button>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
{/each}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</TableContainer>
|
||||
</section>
|
||||
|
||||
<section class="mb-10">
|
||||
<h2 class="section-title">Usuarios globales ({totalUsuarios})</h2>
|
||||
<TableContainer>
|
||||
<Table size="compact">
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
<TableHeader>ID</TableHeader>
|
||||
<TableHeader>Nombre</TableHeader>
|
||||
<TableHeader>Email</TableHeader>
|
||||
<TableHeader>Empresas</TableHeader>
|
||||
<TableHeader>Rol plataforma</TableHeader>
|
||||
<TableHeader>Estado</TableHeader>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
{#if usuarios.length === 0}
|
||||
<TableRow>
|
||||
<TableCell colspan={6}>No hay usuarios</TableCell>
|
||||
</TableRow>
|
||||
{/if}
|
||||
{#each usuarios as usuario (usuario.id)}
|
||||
<TableRow>
|
||||
<TableCell>{usuario.id}</TableCell>
|
||||
<TableCell>{usuario.name}</TableCell>
|
||||
<TableCell>{usuario.email}</TableCell>
|
||||
<TableCell>{usuario.empresas}</TableCell>
|
||||
<TableCell>{usuario.rol_plataforma || '-'}</TableCell>
|
||||
<TableCell>
|
||||
<Tag type={usuario.activo ? 'green' : 'red'}>
|
||||
{usuario.activo ? 'Activo' : 'Inactivo'}
|
||||
</Tag>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
{/each}
|
||||
</TableBody>
|
||||
</Table>
|
||||
<Pagination
|
||||
totalItems={totalUsuarios}
|
||||
pageSize={tamanoUsuarios}
|
||||
page={paginaUsuarios + 1}
|
||||
pageInputDisabled
|
||||
pageSizeInputDisabled
|
||||
on:click:button--next={() => cambiarPaginaUsuarios(paginaUsuarios + 1)}
|
||||
on:click:button--previous={() =>
|
||||
paginaUsuarios > 0 && cambiarPaginaUsuarios(paginaUsuarios - 1)}
|
||||
/>
|
||||
</TableContainer>
|
||||
</section>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<Modal
|
||||
bind:open={modalEmpresa}
|
||||
modalHeading={empresaEditando ? 'Editar empresa' : 'Nueva empresa'}
|
||||
primaryButtonText={empresaEditando ? 'Guardar' : 'Crear empresa'}
|
||||
secondaryButtonText="Cerrar"
|
||||
on:click:button--primary={guardarEmpresa}
|
||||
on:click:button--secondary={() => (modalEmpresa = false)}
|
||||
hasScrollingContent
|
||||
>
|
||||
{#if errorEmpresa}
|
||||
<InlineNotification kind="error" title="Error" subtitle={errorEmpresa} hideCloseButton />
|
||||
{/if}
|
||||
{#if passwordTemporal}
|
||||
<InlineNotification
|
||||
kind="success"
|
||||
title="Contraseña temporal del owner"
|
||||
subtitle={passwordTemporal}
|
||||
hideCloseButton
|
||||
/>
|
||||
<Button class="mt-4" size="small" onclick={() => (modalEmpresa = false)}>Cerrar</Button>
|
||||
{:else}
|
||||
<div class="flex flex-col gap-4">
|
||||
<TextInput bind:value={formEmpresa.nombre} labelText="Nombre de la empresa" />
|
||||
<TextInput bind:value={formEmpresa.slug} labelText="Slug (opcional)" />
|
||||
<TextInput bind:value={formEmpresa.cuit} labelText="CUIT (opcional)" />
|
||||
{#if !empresaEditando}
|
||||
<TextInput bind:value={formEmpresa.owner_email} labelText="Email del owner" type="email" />
|
||||
<TextInput bind:value={formEmpresa.owner_name} labelText="Nombre del owner (opcional)" />
|
||||
<PasswordInput
|
||||
bind:value={formEmpresa.owner_password}
|
||||
labelText="Contraseña del owner (opcional)"
|
||||
helperText="Si se deja vacía, se genera una temporal."
|
||||
/>
|
||||
{/if}
|
||||
{#if guardandoEmpresa}
|
||||
<InlineLoading description="Guardando..." />
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
</Modal>
|
||||
|
||||
<Modal
|
||||
bind:open={modalAdmin}
|
||||
modalHeading="Agregar administrador de plataforma"
|
||||
primaryButtonText="Agregar"
|
||||
secondaryButtonText="Cerrar"
|
||||
on:click:button--primary={guardarAdmin}
|
||||
on:click:button--secondary={() => (modalAdmin = false)}
|
||||
>
|
||||
{#if errorAdmin}
|
||||
<InlineNotification kind="error" title="Error" subtitle={errorAdmin} hideCloseButton />
|
||||
{/if}
|
||||
<div class="flex flex-col gap-4">
|
||||
<TextInput bind:value={formAdmin.email} labelText="Email del usuario" type="email" />
|
||||
<Select bind:selected={formAdmin.rol} labelText="Rol">
|
||||
<SelectItem value="SUPERADMIN" text="Superadmin" />
|
||||
<SelectItem value="SOPORTE" text="Soporte" />
|
||||
</Select>
|
||||
{#if guardandoAdmin}
|
||||
<InlineLoading description="Guardando..." />
|
||||
{/if}
|
||||
</div>
|
||||
</Modal>
|
||||
|
||||
<style>
|
||||
.section-title {
|
||||
font-size: 1.05rem;
|
||||
font-weight: 600;
|
||||
margin-bottom: 0.75rem;
|
||||
}
|
||||
</style>
|
||||
@@ -8,14 +8,14 @@
|
||||
} from 'carbon-components-svelte';
|
||||
import Card from '$lib/components/Card.svelte';
|
||||
import { register as registerApi } from '$lib/hooks/register';
|
||||
import { setToken } from '$lib/hooks/token';
|
||||
import { setCurrentUser } from '$lib/hooks/user';
|
||||
import { goto } from '$app/navigation';
|
||||
|
||||
let name: string = $state('');
|
||||
let email: string = $state('');
|
||||
let password: string = $state('');
|
||||
let confirmPassword: string = $state('');
|
||||
let empresaNombre: string = $state('');
|
||||
let empresaCuit: string = $state('');
|
||||
let loading: boolean = $state(false);
|
||||
let error: string = $state('');
|
||||
|
||||
@@ -39,10 +39,14 @@
|
||||
error = '';
|
||||
|
||||
try {
|
||||
const response = await registerApi({ name, email, password });
|
||||
// setToken(response.token);
|
||||
// setCurrentUser(response);
|
||||
goto('/menu');
|
||||
await registerApi({
|
||||
name,
|
||||
email,
|
||||
password,
|
||||
empresa_nombre: empresaNombre || undefined,
|
||||
empresa_cuit: empresaCuit || undefined
|
||||
});
|
||||
await goto('/menu');
|
||||
} catch (e) {
|
||||
error = e instanceof Error ? e.message : 'Error al registrar';
|
||||
} finally {
|
||||
@@ -53,7 +57,7 @@
|
||||
|
||||
<div class="register-container">
|
||||
<Card title="Crear Cuenta">
|
||||
<p class="subtitle">Ingresá tus datos para registrarte</p>
|
||||
<p class="subtitle">Creá tu usuario y tu empresa para empezar</p>
|
||||
|
||||
{#if error}
|
||||
<InlineNotification kind="error" title="Error" subtitle={error} hideCloseButton />
|
||||
@@ -73,6 +77,19 @@
|
||||
labelText="Confirmar Contraseña"
|
||||
placeholder="••••••••"
|
||||
/>
|
||||
|
||||
<p class="section-title">Datos de la empresa</p>
|
||||
<TextInput
|
||||
bind:value={empresaNombre}
|
||||
labelText="Nombre de la empresa"
|
||||
placeholder="Mi repuestera"
|
||||
/>
|
||||
<TextInput
|
||||
bind:value={empresaCuit}
|
||||
labelText="CUIT (opcional)"
|
||||
placeholder="20123456789"
|
||||
/>
|
||||
|
||||
<Button type="submit" disabled={loading} class="max-w-full!">
|
||||
{#if loading}
|
||||
<InlineLoading description="Registrando..." />
|
||||
@@ -81,7 +98,7 @@
|
||||
{/if}
|
||||
</Button>
|
||||
<p>
|
||||
Si no tenés cuenta <a href="/login">Inicia Sesión</a>
|
||||
Si ya tenés cuenta <a href="/login">Iniciá Sesión</a>
|
||||
</p>
|
||||
</form>
|
||||
</Card>
|
||||
@@ -94,6 +111,7 @@
|
||||
align-items: center;
|
||||
min-height: 100vh;
|
||||
background: var(--cds-ui-background, #161616);
|
||||
padding: 2rem 1rem;
|
||||
}
|
||||
|
||||
.subtitle {
|
||||
@@ -101,6 +119,14 @@
|
||||
margin-bottom: 1.5rem;
|
||||
}
|
||||
|
||||
.section-title {
|
||||
color: var(--cds-text-secondary, #c6c6c6);
|
||||
font-size: 0.75rem;
|
||||
letter-spacing: 0.08em;
|
||||
text-transform: uppercase;
|
||||
margin-top: 0.5rem;
|
||||
}
|
||||
|
||||
form {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
|
||||
@@ -31,9 +31,17 @@
|
||||
let openAlta = $state(false);
|
||||
let openEditar = $state(false);
|
||||
|
||||
let repuestoEliminar = $state({ id: 0 });
|
||||
let repuestoEditar = $state({ ID: 0, marcaId:0 });
|
||||
let repuestoAlta = $state({ id: 0 });
|
||||
let repuestoEliminar = $state({ ID: 0 });
|
||||
let repuestoEditar = $state({
|
||||
ID: 0,
|
||||
nombre: '',
|
||||
descripcion: '',
|
||||
marcaId: 0,
|
||||
aliases: [],
|
||||
precio: 0,
|
||||
stockMinimo: 0
|
||||
});
|
||||
let repuestoAlta = $state({ ID: 0 });
|
||||
let repuestoInfo = $state();
|
||||
|
||||
$effect(() => {
|
||||
@@ -169,7 +177,7 @@
|
||||
bind:show={openEliminar}
|
||||
onclose={() => {
|
||||
openEliminar = false;
|
||||
repuestoEliminar = { id: 0 };
|
||||
repuestoEliminar = { ID: 0 };
|
||||
}}
|
||||
repuesto={repuestoEliminar}
|
||||
></EliminarRepuestoForm>
|
||||
@@ -178,7 +186,7 @@
|
||||
bind:show={openAlta}
|
||||
onclose={() => {
|
||||
openAlta = false;
|
||||
repuestoAlta = { id: 0 };
|
||||
repuestoAlta = { ID: 0 };
|
||||
}}
|
||||
repuesto={repuestoAlta}
|
||||
></AltaRepuestoForm>
|
||||
@@ -187,7 +195,15 @@
|
||||
bind:open={openEditar}
|
||||
onClose={() => {
|
||||
openEditar = false;
|
||||
repuestoEditar = { ID: 0, marcaId: 0 };
|
||||
repuestoEditar = {
|
||||
ID: 0,
|
||||
nombre: '',
|
||||
descripcion: '',
|
||||
marcaId: 0,
|
||||
aliases: [],
|
||||
precio: 0,
|
||||
stockMinimo: 0
|
||||
};
|
||||
}}
|
||||
bind:repuesto={repuestoEditar}
|
||||
></EditarRepuestoForm>
|
||||
|
||||
@@ -2,31 +2,30 @@
|
||||
import Header from '$lib/components/Header.svelte';
|
||||
import {
|
||||
Button,
|
||||
DataTableSkeleton,
|
||||
Modal,
|
||||
Pagination,
|
||||
PaginationSkeleton,
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableContainer,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow
|
||||
TableRow,
|
||||
Tag
|
||||
} from 'carbon-components-svelte';
|
||||
import { Add, Keychain, Network_4, Pen, TrashCan } from 'carbon-icons-svelte';
|
||||
import CambiarContraseñaForm from './CambiarContraseñaForm.svelte';
|
||||
import CrearUsuarioForm from './CrearUsuarioForm.svelte';
|
||||
import EditarUsuarioForm from './EditarUsuarioForm.svelte';
|
||||
import EliminarUsuarioForm from './EliminarUsuarioForm.svelte';
|
||||
import type { Grupo, Usuario } from '../../types.js';
|
||||
import type { Grupo, Miembro } from '../../types.js';
|
||||
import { obtenerGruposDeUsuario } from '$lib/hooks/obtenerGruposDeUsuario.js';
|
||||
import QuitarGrupo from './QuitarGrupo.svelte';
|
||||
import AsignarGrupo from './AsignarGrupo.svelte';
|
||||
import { page } from '$app/state';
|
||||
import { goto } from '$app/navigation';
|
||||
import { goto, invalidate } from '$app/navigation';
|
||||
|
||||
let { data }: { data: Promise<{ usuarios: Usuario[]; total: number }> } = $props();
|
||||
let { data }: { data: Promise<{ usuarios: Miembro[]; total: number }> } = $props();
|
||||
|
||||
let pParam = $derived(Number(page.url.searchParams.get('p')) || 0);
|
||||
let sParam = $derived(Number(page.url.searchParams.get('s')) || 10);
|
||||
@@ -41,9 +40,13 @@
|
||||
let showAsignar = $state(false);
|
||||
let usugruSeleccionado = $state({ usuario_id: 0, grupo_id: 0 });
|
||||
|
||||
let usuarioModificar = $state({ id: 0, name: '', email: '' });
|
||||
let usuarioEliminar = $state({ id: 0 });
|
||||
let usuarioCambiarContraseña = $state({ id: 0 });
|
||||
let usuarioModificar = $state<Partial<Miembro> & { id: number }>({ id: 0 });
|
||||
let usuarioEliminar = $state<Partial<Miembro> & { id: number }>({ id: 0 });
|
||||
let usuarioCambiarContraseña = $state<Partial<Miembro> & { id: number }>({ id: 0 });
|
||||
|
||||
function recargar() {
|
||||
void invalidate('usuarios:load');
|
||||
}
|
||||
|
||||
function cerrarModal() {
|
||||
showCrearModal = false;
|
||||
@@ -53,19 +56,18 @@
|
||||
showQuitar = false;
|
||||
showAsignar = false;
|
||||
|
||||
usuarioModificar = { id: 0, name: '', email: '' };
|
||||
usuarioModificar = { id: 0 };
|
||||
usuarioEliminar = { id: 0 };
|
||||
usuarioCambiarContraseña = { id: 0 };
|
||||
usugruSeleccionado = { usuario_id: 0, grupo_id: 0 };
|
||||
}
|
||||
|
||||
let gruposUsuarioSeleccionado = $state<{
|
||||
usuario: Usuario | null;
|
||||
usuario: Miembro | null;
|
||||
grupos: Promise<Grupo[] | string>;
|
||||
} | null>(null);
|
||||
|
||||
function seleccionarUsuarioGrupo(u: Usuario) {
|
||||
// toggle
|
||||
function seleccionarUsuarioGrupo(u: Miembro) {
|
||||
if (gruposUsuarioSeleccionado?.usuario?.id === u.id) {
|
||||
gruposUsuarioSeleccionado = null;
|
||||
return;
|
||||
@@ -73,23 +75,27 @@
|
||||
|
||||
gruposUsuarioSeleccionado = {
|
||||
usuario: u,
|
||||
grupos: obtenerGruposDeUsuario({
|
||||
usuario_id: u.id
|
||||
})
|
||||
grupos: obtenerGruposDeUsuario({ usuario_id: u.id })
|
||||
};
|
||||
}
|
||||
|
||||
function nombreRol(rol?: string): string {
|
||||
if (rol === 'OWNER') return 'Owner';
|
||||
if (rol === 'ADMIN') return 'Administrador';
|
||||
return 'Miembro';
|
||||
}
|
||||
</script>
|
||||
|
||||
<Header />
|
||||
|
||||
<div class="page-container">
|
||||
<div class="flex justify-between">
|
||||
<h1>Gestión de Usuarios</h1>
|
||||
<h1>Gestión de Miembros</h1>
|
||||
<Button
|
||||
icon={Add}
|
||||
onclick={() => {
|
||||
showCrearModal = true;
|
||||
}}>Nuevo Usuario</Button
|
||||
}}>Agregar miembro</Button
|
||||
>
|
||||
</div>
|
||||
{#await data}
|
||||
@@ -102,9 +108,9 @@
|
||||
<TableHeader>id</TableHeader>
|
||||
<TableHeader>email</TableHeader>
|
||||
<TableHeader>Nombre</TableHeader>
|
||||
<TableHeader>Habilitado</TableHeader>
|
||||
<TableHeader>Rol</TableHeader>
|
||||
<TableHeader>Estado</TableHeader>
|
||||
<TableHeader>Fecha Creado</TableHeader>
|
||||
<TableHeader>Fecha Modificado</TableHeader>
|
||||
<TableHeader>Acciones</TableHeader>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
@@ -113,82 +119,88 @@
|
||||
<TableRow>
|
||||
<TableCell colspan={7}>
|
||||
<p class="flex justify-center">
|
||||
No hay Usuarios para mostrar {pParam > 1 ? `en pagina: ${pParam}` : ''}
|
||||
No hay miembros para mostrar {pParam > 1 ? `en pagina: ${pParam}` : ''}
|
||||
</p>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
{/if}
|
||||
{#each res.usuarios as u}
|
||||
{#each res.usuarios as u (u.id)}
|
||||
<TableRow>
|
||||
<TableCell>{u.id}</TableCell>
|
||||
<TableCell>{u.email}</TableCell>
|
||||
<TableCell>{u.name}</TableCell>
|
||||
<TableCell>{(u as any).deleted_at ? 'no' : 'si'}</TableCell>
|
||||
<TableCell>{new Date((u as any).created_at).toLocaleString()}</TableCell>
|
||||
<TableCell>{new Date((u as any).updated_at).toLocaleString()}</TableCell>
|
||||
<TableCell>
|
||||
<Button
|
||||
onclick={() => {
|
||||
usuarioModificar = u;
|
||||
showEditarModal = true;
|
||||
}}
|
||||
size="small"
|
||||
icon={Pen}>Editar</Button
|
||||
>
|
||||
<Tag type={u.rol === 'OWNER' ? 'purple' : u.rol === 'ADMIN' ? 'blue' : 'gray'}>
|
||||
{nombreRol(u.rol)}
|
||||
</Tag>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Tag type={u.activo && u.membresia_activa ? 'green' : 'red'}>
|
||||
{u.activo && u.membresia_activa ? 'Activo' : 'Inactivo'}
|
||||
</Tag>
|
||||
</TableCell>
|
||||
<TableCell>{new Date(u.created_at).toLocaleString()}</TableCell>
|
||||
<TableCell>
|
||||
<div class="flex flex-wrap gap-1">
|
||||
<Button
|
||||
onclick={() => {
|
||||
usuarioModificar = u;
|
||||
showEditarModal = true;
|
||||
}}
|
||||
size="small"
|
||||
icon={Pen}>Editar</Button
|
||||
>
|
||||
|
||||
<Button
|
||||
onclick={() => {
|
||||
usuarioEliminar = u;
|
||||
showEliminarModal = true;
|
||||
}}
|
||||
size="small"
|
||||
kind="danger"
|
||||
icon={TrashCan}>Eliminar</Button
|
||||
>
|
||||
<Button
|
||||
onclick={() => {
|
||||
usuarioEliminar = u;
|
||||
showEliminarModal = true;
|
||||
}}
|
||||
size="small"
|
||||
kind="danger"
|
||||
icon={TrashCan}>Quitar</Button
|
||||
>
|
||||
|
||||
<Button
|
||||
onclick={() => {
|
||||
usuarioCambiarContraseña = u;
|
||||
showCambiarContraseñaModal = true;
|
||||
}}
|
||||
size="small"
|
||||
kind="secondary"
|
||||
icon={Keychain}>CambiarContraseña</Button
|
||||
>
|
||||
<Button
|
||||
size="small"
|
||||
kind="secondary"
|
||||
onclick={() => seleccionarUsuarioGrupo(u)}
|
||||
icon={Network_4}>Grupos</Button
|
||||
>
|
||||
<Button
|
||||
onclick={() => {
|
||||
usuarioCambiarContraseña = u;
|
||||
showCambiarContraseñaModal = true;
|
||||
}}
|
||||
size="small"
|
||||
kind="secondary"
|
||||
icon={Keychain}>Contraseña</Button
|
||||
>
|
||||
<Button
|
||||
size="small"
|
||||
kind="secondary"
|
||||
onclick={() => seleccionarUsuarioGrupo(u)}
|
||||
icon={Network_4}>Grupos</Button
|
||||
>
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
{/each}
|
||||
</TableBody>
|
||||
</Table>
|
||||
{#await data}
|
||||
<PaginationSkeleton />
|
||||
{:then res}
|
||||
<Pagination
|
||||
totalItems={res.total}
|
||||
pageSize={sParam}
|
||||
page={pParam + 1}
|
||||
pageInputDisabled
|
||||
pageSizeInputDisabled
|
||||
on:click:button--next={() => {
|
||||
<Pagination
|
||||
totalItems={res.total}
|
||||
pageSize={sParam}
|
||||
page={pParam + 1}
|
||||
pageInputDisabled
|
||||
pageSizeInputDisabled
|
||||
on:click:button--next={() => {
|
||||
const url = new URL(page.url);
|
||||
url.searchParams.set('p', String(pParam + 1));
|
||||
goto(url, { invalidateAll: false });
|
||||
}}
|
||||
on:click:button--previous={() => {
|
||||
if (pParam > 0) {
|
||||
const url = new URL(page.url);
|
||||
url.searchParams.set('p', String(pParam + 1));
|
||||
url.searchParams.set('p', String(pParam - 1));
|
||||
goto(url, { invalidateAll: false });
|
||||
}}
|
||||
on:click:button--previous={() => {
|
||||
if (pParam > 0) {
|
||||
const url = new URL(page.url);
|
||||
url.searchParams.set('p', String(pParam - 1));
|
||||
goto(url, { invalidateAll: false });
|
||||
}
|
||||
}}
|
||||
/>
|
||||
{/await}
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</TableContainer>
|
||||
{/await}
|
||||
{#if gruposUsuarioSeleccionado?.usuario}
|
||||
@@ -197,9 +209,15 @@
|
||||
Cargando ...
|
||||
{:then grupos}
|
||||
{#if typeof grupos === 'string'}
|
||||
{() => {
|
||||
showError = grupos;
|
||||
}}
|
||||
{#if grupos}
|
||||
<Modal
|
||||
open
|
||||
primaryButtonText="Cerrar"
|
||||
on:click:button--primary={() => (showError = '')}
|
||||
>
|
||||
{grupos}
|
||||
</Modal>
|
||||
{/if}
|
||||
{:else if typeof grupos !== 'undefined'}
|
||||
<div class="flex justify-between">
|
||||
<h3>Grupos del usuario</h3>
|
||||
@@ -222,14 +240,13 @@
|
||||
<TableHeader>Nombre</TableHeader>
|
||||
<TableHeader>Descripcion</TableHeader>
|
||||
<TableHeader>Permisos</TableHeader>
|
||||
<TableHeader>Creado en</TableHeader>
|
||||
<TableHeader>Acciones</TableHeader>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
{#if grupos?.length == 0}
|
||||
<TableRow>
|
||||
<TableCell colspan={7}>No hay Grupos Asignados</TableCell>
|
||||
<TableCell colspan={5}>No hay Grupos Asignados</TableCell>
|
||||
</TableRow>
|
||||
{:else}
|
||||
{#each grupos as grupo}
|
||||
@@ -238,7 +255,6 @@
|
||||
<TableCell>{grupo.nombre}</TableCell>
|
||||
<TableCell>{grupo.descripcion}</TableCell>
|
||||
<TableCell>{grupo.permisos && grupo.permisos.map((x) => x.nombre)}</TableCell>
|
||||
<TableCell>{new Date((grupo as any).created_at).toLocaleString()}</TableCell>
|
||||
<TableCell>
|
||||
<Button
|
||||
kind="danger"
|
||||
@@ -264,12 +280,18 @@
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<CrearUsuarioForm bind:show={showCrearModal} onclose={cerrarModal} />
|
||||
<EditarUsuarioForm bind:show={showEditarModal} usuario={usuarioModificar} onclose={cerrarModal} />
|
||||
<CrearUsuarioForm bind:show={showCrearModal} onclose={cerrarModal} oncreado={recargar} />
|
||||
<EditarUsuarioForm
|
||||
bind:show={showEditarModal}
|
||||
usuario={usuarioModificar}
|
||||
onclose={cerrarModal}
|
||||
onactualizado={recargar}
|
||||
/>
|
||||
<EliminarUsuarioForm
|
||||
bind:show={showEliminarModal}
|
||||
usuario={usuarioEliminar}
|
||||
onclose={cerrarModal}
|
||||
oneliminado={recargar}
|
||||
/>
|
||||
<CambiarContraseñaForm
|
||||
bind:show={showCambiarContraseñaModal}
|
||||
|
||||
@@ -1,30 +1,35 @@
|
||||
<script lang="ts">
|
||||
import { Button, Modal, PasswordInput } from 'carbon-components-svelte';
|
||||
import { cambiarContraseña } from '$lib/hooks/cambiarContraseña.js';
|
||||
import { InlineNotification, Modal, PasswordInput } from 'carbon-components-svelte';
|
||||
import { resetearPasswordMiembro } from '$lib/hooks/tenant';
|
||||
import type { Miembro } from '../../types';
|
||||
|
||||
let {
|
||||
show = $bindable(),
|
||||
onclose,
|
||||
usuario
|
||||
}: { show?: boolean; onclose: () => void; usuario: { id: number } } = $props();
|
||||
}: { show?: boolean; onclose: () => void; usuario: Partial<Miembro> & { id: number } } = $props();
|
||||
|
||||
let password = $state('');
|
||||
let error = $state('');
|
||||
let guardando = $state(false);
|
||||
|
||||
async function handleSubmit(e: Event) {
|
||||
e.preventDefault();
|
||||
error = '';
|
||||
const result = await cambiarContraseña({
|
||||
old_password: 'adminoverride',
|
||||
new_password: password,
|
||||
user_id: usuario.id
|
||||
});
|
||||
if (result !== 'Ok') {
|
||||
error = result;
|
||||
if (password.length < 8) {
|
||||
error = 'La contraseña debe tener al menos 8 caracteres';
|
||||
return;
|
||||
}
|
||||
password = '';
|
||||
onclose();
|
||||
guardando = true;
|
||||
try {
|
||||
await resetearPasswordMiembro(usuario.id, password);
|
||||
password = '';
|
||||
onclose();
|
||||
} catch (e) {
|
||||
error = e instanceof Error ? e.message : 'No se pudo cambiar la contraseña';
|
||||
} finally {
|
||||
guardando = false;
|
||||
}
|
||||
}
|
||||
|
||||
function handleClose() {
|
||||
@@ -38,14 +43,17 @@
|
||||
<Modal
|
||||
formId="cambiarForm"
|
||||
bind:open={show}
|
||||
modalHeading="Cambiar Contraseña"
|
||||
primaryButtonText="Aceptar"
|
||||
modalHeading="Restablecer contraseña"
|
||||
primaryButtonText={guardando ? 'Guardando...' : 'Aceptar'}
|
||||
secondaryButtonText="Cerrar"
|
||||
on:click:button--secondary={handleClose}
|
||||
>
|
||||
{#if error}
|
||||
<div class="text-red-500">{error}</div>
|
||||
<InlineNotification kind="error" title="Error" subtitle={error} hideCloseButton />
|
||||
{/if}
|
||||
<PasswordInput labelText="Nueva Contraseña: " minlength={8} bind:value={password} />
|
||||
<p class="mb-4 text-sm text-gray-400">
|
||||
Nueva contraseña para <strong>{usuario.email}</strong>. Se le pedirá cambiarla al ingresar.
|
||||
</p>
|
||||
<PasswordInput labelText="Nueva contraseña" minlength={8} bind:value={password} />
|
||||
</Modal>
|
||||
</form>
|
||||
@@ -1,27 +1,53 @@
|
||||
<script lang="ts">
|
||||
import { crearUsuario } from '$lib/hooks/crearUsuario.js';
|
||||
import { Button, Modal, PasswordInput, TextInput } from 'carbon-components-svelte';
|
||||
import { Button, InlineNotification, Modal, PasswordInput, Select, SelectItem, TextInput } from 'carbon-components-svelte';
|
||||
import { crearMiembro } from '$lib/hooks/tenant';
|
||||
import { getCurrentUser } from '$lib/hooks/user';
|
||||
|
||||
let { show = $bindable(), onclose }: { show?: boolean; onclose: () => void } = $props();
|
||||
let {
|
||||
show = $bindable(),
|
||||
onclose,
|
||||
oncreado
|
||||
}: { show?: boolean; onclose: () => void; oncreado?: () => void } = $props();
|
||||
|
||||
const esOwner = getCurrentUser()?.empresa_rol === 'OWNER';
|
||||
|
||||
let name = $state('');
|
||||
let email = $state('');
|
||||
let password = $state('');
|
||||
let rol = $state('MEMBER');
|
||||
let error = $state('');
|
||||
let passwordTemporal = $state('');
|
||||
let guardando = $state(false);
|
||||
|
||||
async function handleSubmit(e: Event) {
|
||||
e.preventDefault();
|
||||
error = '';
|
||||
const result = await crearUsuario({ name, email, password });
|
||||
if (result !== 'Ok') {
|
||||
error = result;
|
||||
|
||||
if (passwordTemporal) {
|
||||
cerrar();
|
||||
return;
|
||||
}
|
||||
reset();
|
||||
onclose();
|
||||
|
||||
guardando = true;
|
||||
try {
|
||||
const res = await crearMiembro({ name, email, password: password || undefined, rol });
|
||||
oncreado?.();
|
||||
if (res.password_temporal) {
|
||||
passwordTemporal = res.password_temporal;
|
||||
name = '';
|
||||
email = '';
|
||||
password = '';
|
||||
} else {
|
||||
cerrar();
|
||||
}
|
||||
} catch (e) {
|
||||
error = e instanceof Error ? e.message : 'No se pudo crear el usuario';
|
||||
} finally {
|
||||
guardando = false;
|
||||
}
|
||||
}
|
||||
|
||||
function handleClose() {
|
||||
function cerrar() {
|
||||
reset();
|
||||
onclose();
|
||||
}
|
||||
@@ -30,7 +56,9 @@
|
||||
name = '';
|
||||
email = '';
|
||||
password = '';
|
||||
rol = 'MEMBER';
|
||||
error = '';
|
||||
passwordTemporal = '';
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -38,17 +66,42 @@
|
||||
<Modal
|
||||
formId="crearForm"
|
||||
bind:open={show}
|
||||
modalHeading="Registrar Nuevo Usuario"
|
||||
primaryButtonText="Crear"
|
||||
modalHeading="Agregar miembro"
|
||||
primaryButtonText={passwordTemporal ? 'Cerrar' : 'Crear'}
|
||||
secondaryButtonText="Cerrar"
|
||||
on:click:button--secondary={handleClose}
|
||||
on:click:button--secondary={cerrar}
|
||||
>
|
||||
{#if error}
|
||||
<div class="error-msg">{error}</div>
|
||||
{/if}
|
||||
<TextInput bind:value={name} labelText="Nombre" placeholder="Tu nombre" />
|
||||
<TextInput bind:value={email} labelText="Email" placeholder="tu@email.com" type="email" />
|
||||
<PasswordInput bind:value={password} labelText="Contraseña" placeholder="••••••••" minlength={8} />
|
||||
|
||||
{#if passwordTemporal}
|
||||
<InlineNotification
|
||||
kind="success"
|
||||
title="Contraseña temporal"
|
||||
subtitle={passwordTemporal}
|
||||
hideCloseButton
|
||||
/>
|
||||
<p class="hint">Compartila con la persona. Deberá cambiarla al ingresar.</p>
|
||||
{:else}
|
||||
<div class="flex flex-col gap-4">
|
||||
<TextInput bind:value={name} labelText="Nombre" placeholder="Tu nombre" />
|
||||
<TextInput bind:value={email} labelText="Email" placeholder="tu@email.com" type="email" />
|
||||
<PasswordInput
|
||||
bind:value={password}
|
||||
labelText="Contraseña (opcional)"
|
||||
placeholder="••••••••"
|
||||
helperText="Si la dejás vacía se genera una temporal."
|
||||
/>
|
||||
<Select bind:selected={rol} labelText="Rol">
|
||||
<SelectItem value="MEMBER" text="Miembro" />
|
||||
<SelectItem value="ADMIN" text="Administrador" />
|
||||
{#if esOwner}
|
||||
<SelectItem value="OWNER" text="Owner" />
|
||||
{/if}
|
||||
</Select>
|
||||
</div>
|
||||
{/if}
|
||||
</Modal>
|
||||
</form>
|
||||
|
||||
@@ -58,4 +111,9 @@
|
||||
margin-bottom: 1rem;
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
|
||||
.hint {
|
||||
color: var(--cds-text-secondary, #c6c6c6);
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
</style>
|
||||
@@ -1,28 +1,53 @@
|
||||
<script lang="ts">
|
||||
import { actualizarUsuario } from '$lib/hooks/actualizarUsuario.js';
|
||||
import { Button, Modal, TextInput } from 'carbon-components-svelte';
|
||||
import { Modal, Select, SelectItem, TextInput, Toggle } from 'carbon-components-svelte';
|
||||
import { actualizarMiembro } from '$lib/hooks/tenant';
|
||||
import { getCurrentUser } from '$lib/hooks/user';
|
||||
import type { Miembro } from '../../types';
|
||||
|
||||
let {
|
||||
show = $bindable(),
|
||||
onclose,
|
||||
usuario
|
||||
usuario,
|
||||
onactualizado
|
||||
}: {
|
||||
show?: boolean;
|
||||
onclose: () => void;
|
||||
usuario: { id: number; name: string; email: string };
|
||||
usuario: Partial<Miembro> & { id: number };
|
||||
onactualizado?: () => void;
|
||||
} = $props();
|
||||
|
||||
const esOwner = getCurrentUser()?.empresa_rol === 'OWNER';
|
||||
|
||||
let error = $state('');
|
||||
let guardando = $state(false);
|
||||
let name = $state('');
|
||||
let email = $state('');
|
||||
let rol = $state('MEMBER');
|
||||
let activo = $state(true);
|
||||
|
||||
$effect(() => {
|
||||
if (show) {
|
||||
name = usuario.name ?? '';
|
||||
email = usuario.email ?? '';
|
||||
rol = usuario.rol ?? 'MEMBER';
|
||||
activo = usuario.activo ?? true;
|
||||
error = '';
|
||||
}
|
||||
});
|
||||
|
||||
async function handleSubmit(e: Event) {
|
||||
e.preventDefault();
|
||||
error = '';
|
||||
const result = await actualizarUsuario(usuario);
|
||||
if (result !== 'Ok') {
|
||||
error = result;
|
||||
return;
|
||||
guardando = true;
|
||||
try {
|
||||
await actualizarMiembro(usuario.id, { name, email, rol, activo });
|
||||
onactualizado?.();
|
||||
onclose();
|
||||
} catch (e) {
|
||||
error = e instanceof Error ? e.message : 'No se pudo actualizar el usuario';
|
||||
} finally {
|
||||
guardando = false;
|
||||
}
|
||||
onclose();
|
||||
}
|
||||
|
||||
function handleClose() {
|
||||
@@ -35,16 +60,26 @@
|
||||
<Modal
|
||||
formId="editarForm"
|
||||
bind:open={show}
|
||||
modalHeading="Editar Usuario"
|
||||
primaryButtonText="Editar"
|
||||
modalHeading="Editar miembro"
|
||||
primaryButtonText={guardando ? 'Guardando...' : 'Guardar'}
|
||||
secondaryButtonText="Cerrar"
|
||||
on:click:button--secondary={handleClose}
|
||||
>
|
||||
{#if error}
|
||||
<div class="error-msg">{error}</div>
|
||||
{/if}
|
||||
<TextInput name="nombre" type="text" labelText="Nombre: " bind:value={usuario.name} />
|
||||
<TextInput name="email" type="text" labelText="Email" bind:value={usuario.email} />
|
||||
<div class="flex flex-col gap-4">
|
||||
<TextInput name="nombre" type="text" labelText="Nombre" bind:value={name} />
|
||||
<TextInput name="email" type="email" labelText="Email" bind:value={email} />
|
||||
<Select bind:selected={rol} labelText="Rol">
|
||||
<SelectItem value="MEMBER" text="Miembro" />
|
||||
<SelectItem value="ADMIN" text="Administrador" />
|
||||
{#if esOwner}
|
||||
<SelectItem value="OWNER" text="Owner" />
|
||||
{/if}
|
||||
</Select>
|
||||
<Toggle bind:toggled={activo} labelText="Membresía activa" />
|
||||
</div>
|
||||
</Modal>
|
||||
</form>
|
||||
|
||||
|
||||
@@ -1,28 +1,40 @@
|
||||
<script lang="ts">
|
||||
import { eliminarUsuario } from '$lib/hooks/eliminarUsuario.js';
|
||||
import { Button, Modal } from 'carbon-components-svelte';
|
||||
import { Modal } from 'carbon-components-svelte';
|
||||
import { eliminarMiembro } from '$lib/hooks/tenant';
|
||||
import type { Miembro } from '../../types';
|
||||
|
||||
let {
|
||||
show = $bindable(),
|
||||
onclose,
|
||||
usuario
|
||||
}: { show?: boolean; onclose: () => void; usuario: { id: number } } = $props();
|
||||
usuario,
|
||||
oneliminado
|
||||
}: {
|
||||
show?: boolean;
|
||||
onclose: () => void;
|
||||
usuario: Partial<Miembro> & { id: number };
|
||||
oneliminado?: () => void;
|
||||
} = $props();
|
||||
|
||||
let error = $state('');
|
||||
let guardando = $state(false);
|
||||
|
||||
async function handleSubmit(e: Event) {
|
||||
e.preventDefault();
|
||||
error = '';
|
||||
if (!usuario.id) {
|
||||
error = 'No se pudo obtener la id del usuario? recarga la pagina.';
|
||||
error = 'No se pudo obtener el usuario. Recargá la página.';
|
||||
return;
|
||||
}
|
||||
const result = await eliminarUsuario(usuario.id);
|
||||
if (result !== 'Ok') {
|
||||
error = result;
|
||||
return;
|
||||
guardando = true;
|
||||
try {
|
||||
await eliminarMiembro(usuario.id);
|
||||
oneliminado?.();
|
||||
onclose();
|
||||
} catch (e) {
|
||||
error = e instanceof Error ? e.message : 'No se pudo quitar el miembro';
|
||||
} finally {
|
||||
guardando = false;
|
||||
}
|
||||
onclose();
|
||||
}
|
||||
|
||||
function handleClose() {
|
||||
@@ -35,14 +47,26 @@
|
||||
<Modal
|
||||
formId="eliminarForm"
|
||||
bind:open={show}
|
||||
modalHeading="Eliminar Usuario"
|
||||
primaryButtonText="Eliminar"
|
||||
modalHeading="Quitar miembro"
|
||||
primaryButtonText={guardando ? 'Quitando...' : 'Quitar'}
|
||||
secondaryButtonText="Cerrar"
|
||||
danger
|
||||
on:click:button--secondary={handleClose}
|
||||
>
|
||||
{#if error}
|
||||
<div>{error}</div>
|
||||
<div class="error-msg">{error}</div>
|
||||
{/if}
|
||||
Esta seguro que quiere borrar este usuario?
|
||||
<p>
|
||||
¿Querés quitar a <strong>{usuario.email}</strong> de la empresa? Su usuario global no se elimina,
|
||||
solo pierde acceso.
|
||||
</p>
|
||||
</Modal>
|
||||
</form>
|
||||
|
||||
<style>
|
||||
.error-msg {
|
||||
color: #da1e28;
|
||||
margin-bottom: 1rem;
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
</style>
|
||||
Vendored
+118
-17
@@ -1,8 +1,119 @@
|
||||
export interface EmpresaResumen {
|
||||
id: number;
|
||||
nombre: string;
|
||||
slug: string;
|
||||
activa: boolean;
|
||||
rol?: string;
|
||||
}
|
||||
|
||||
export interface Usuario {
|
||||
id: number;
|
||||
email: string;
|
||||
name: string;
|
||||
permissions?: number[];
|
||||
activo?: boolean;
|
||||
debe_cambiar_password?: boolean;
|
||||
rol?: string;
|
||||
empresa?: EmpresaResumen;
|
||||
empresa_rol?: string;
|
||||
empresas?: EmpresaResumen[];
|
||||
es_plataforma_admin?: boolean;
|
||||
created_at?: string;
|
||||
updated_at?: string;
|
||||
deleted_at?: string | null;
|
||||
}
|
||||
|
||||
export interface AuthResponse {
|
||||
access_token: string;
|
||||
refresh_token: string;
|
||||
token_type: string;
|
||||
expires_in: number;
|
||||
permissions: number[];
|
||||
empresa?: EmpresaResumen | null;
|
||||
empresas: EmpresaResumen[];
|
||||
empresa_rol: string;
|
||||
es_plataforma_admin: boolean;
|
||||
usuario: Usuario;
|
||||
debe_cambiar_password: boolean;
|
||||
}
|
||||
|
||||
export interface MeResponse extends Usuario {
|
||||
permissions: number[];
|
||||
empresas: EmpresaResumen[];
|
||||
empresa_rol: string;
|
||||
es_plataforma_admin: boolean;
|
||||
}
|
||||
|
||||
export interface InvitacionInfo {
|
||||
email: string;
|
||||
empresa: string;
|
||||
empresa_id: number;
|
||||
rol: string;
|
||||
expira_en: string;
|
||||
valida: boolean;
|
||||
usada: boolean;
|
||||
expirada: boolean;
|
||||
usuario_existente: boolean;
|
||||
}
|
||||
|
||||
export interface Invitacion {
|
||||
id: number;
|
||||
empresa_id: number;
|
||||
email: string;
|
||||
rol: string;
|
||||
expira_en: string;
|
||||
usada_en?: string | null;
|
||||
creada_por: number;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface Miembro {
|
||||
id: number;
|
||||
email: string;
|
||||
name: string;
|
||||
activo: boolean;
|
||||
debe_cambiar_password: boolean;
|
||||
rol: string;
|
||||
membresia_activa: boolean;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export interface EmpresaActual {
|
||||
id: number;
|
||||
nombre: string;
|
||||
slug: string;
|
||||
cuit?: string | null;
|
||||
activa: boolean;
|
||||
rol: string;
|
||||
miembros_activos: number;
|
||||
es_plataforma_admin: boolean;
|
||||
}
|
||||
|
||||
export interface EmpresaPlataforma {
|
||||
id: number;
|
||||
nombre: string;
|
||||
slug: string;
|
||||
cuit?: string | null;
|
||||
activa: boolean;
|
||||
miembros: number;
|
||||
owners: number;
|
||||
created_at?: string;
|
||||
}
|
||||
|
||||
export interface PlataformaAdmin {
|
||||
usuario_id: number;
|
||||
rol: string;
|
||||
activo: boolean;
|
||||
usuario?: Usuario;
|
||||
}
|
||||
|
||||
export interface InvitacionCreada {
|
||||
invitacion: Invitacion;
|
||||
token: string;
|
||||
link: string;
|
||||
email_enviado: boolean;
|
||||
expira_en: string;
|
||||
}
|
||||
|
||||
export interface CrearRepuestoDto {
|
||||
@@ -15,7 +126,7 @@ export interface CrearRepuestoDto {
|
||||
}
|
||||
|
||||
export interface BusquedaLogsDto {
|
||||
usuarioId: uint;
|
||||
usuarioId: number;
|
||||
accion: string;
|
||||
fechaInicio: Date;
|
||||
fechaFin: Date;
|
||||
@@ -23,6 +134,7 @@ export interface BusquedaLogsDto {
|
||||
|
||||
export interface LogEntry {
|
||||
id: number;
|
||||
empresaId: number;
|
||||
usuarioId: number;
|
||||
accion: string;
|
||||
detalles?: LogDetalle[];
|
||||
@@ -50,6 +162,7 @@ interface ActualizarRepuestoDto {
|
||||
|
||||
export interface Grupo {
|
||||
id: number;
|
||||
empresaId?: number;
|
||||
nombre: string;
|
||||
descripcion?: string;
|
||||
imagen?: string;
|
||||
@@ -76,14 +189,8 @@ export interface GruposYPermisosResponse {
|
||||
export interface LoginRequest {
|
||||
email: string;
|
||||
password: string;
|
||||
}
|
||||
|
||||
export interface LoginResponse {
|
||||
access_token: string;
|
||||
refresh_token: string;
|
||||
token_type: string;
|
||||
expires_in: number;
|
||||
permissions: number[];
|
||||
empresa_id?: number;
|
||||
empresa_slug?: string;
|
||||
}
|
||||
|
||||
export interface RegisterResponse {
|
||||
@@ -92,13 +199,6 @@ export interface RegisterResponse {
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface MeResponse {
|
||||
id: number;
|
||||
email: string;
|
||||
name: string;
|
||||
permissions: number[];
|
||||
}
|
||||
|
||||
export interface BaseModel {
|
||||
ID: number;
|
||||
CreatedAt: string;
|
||||
@@ -107,11 +207,13 @@ export interface BaseModel {
|
||||
}
|
||||
|
||||
export interface Marca extends BaseModel {
|
||||
empresaId?: number;
|
||||
nombre: string;
|
||||
repuestos: Repuesto[];
|
||||
}
|
||||
|
||||
export interface Repuesto extends BaseModel {
|
||||
empresaId?: number;
|
||||
nombre: string;
|
||||
descripcion: string;
|
||||
precio: number;
|
||||
@@ -119,5 +221,4 @@ export interface Repuesto extends BaseModel {
|
||||
marcaId: number;
|
||||
marca: Marca | string;
|
||||
aliases: string[];
|
||||
// stocks?: Stock[]; // opcional si tienes entidad Stock
|
||||
}
|
||||
Reference in new issue
Block a user