Private
Public Access
feat: hecho filtro de busqueda para los logs
This commit is contained in:
1 parent
1c0da9d70f
commit
a25afa1750
12 files changed
+288
-57
No files matched your search
@@ -1 +1,45 @@
|
||||
package logs
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
dto_builders "repuestera_back/dto/Builders"
|
||||
dto "repuestera_back/dto/Logs"
|
||||
"repuestera_back/models/logs"
|
||||
r "repuestera_back/repositorios"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func BusquedaLogs(c *gin.Context) {
|
||||
pag, err := strconv.ParseUint(c.Param("p"), 10, 64)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
var filtros dto.BusquedaLogsDto
|
||||
if err := c.ShouldBindJSON(&filtros); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
var logs []logs.Log
|
||||
|
||||
if logs, err = r.ObtenerRepositorios().Logs.ObtenerConFiltros(int(pag), filtros); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
logsdto := dto_builders.NewLogTablaBuilder().ConLogs(logs).Build()
|
||||
|
||||
cantpags, err := r.ObtenerRepositorios().Logs.CantPaginasConFiltros(filtros)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"logs": logsdto,
|
||||
"maxlenght": cantpags,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package dto
|
||||
|
||||
import "time"
|
||||
|
||||
type BusquedaLogsDto struct {
|
||||
UsuarioID uint `json:"usuarioId"`
|
||||
Accion string `json:"accion"`
|
||||
FechaInicio time.Time `json:"fechaInicio"`
|
||||
FechaFin time.Time `json:"fechaFin"`
|
||||
}
|
||||
@@ -6,10 +6,11 @@ import (
|
||||
|
||||
"gorm.io/datatypes"
|
||||
)
|
||||
|
||||
type LogTablaDto struct {
|
||||
ID uint64 `gorm:"primaryKey" json:"id"`
|
||||
UsuarioID uint `gorm:"index;not null" json:"usuarioId"`
|
||||
Accion string `gorm:"type:varchar(50);not null" json:"accion"`
|
||||
Detalles datatypes.JSONSlice[logs.LogDetalle] `gorm:"type:json" json:"detalles,omitempty"`
|
||||
ID uint64 `json:"id"`
|
||||
UsuarioID uint `json:"usuarioId"`
|
||||
Accion string `json:"accion"`
|
||||
Detalles datatypes.JSONSlice[logs.LogDetalle] `json:"detalles,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package repositorios
|
||||
|
||||
import (
|
||||
dto "repuestera_back/dto/Logs"
|
||||
"repuestera_back/models/logs"
|
||||
|
||||
"gorm.io/gorm"
|
||||
@@ -10,6 +11,8 @@ type RepositorioLogs interface {
|
||||
IRepositorio[*logs.Log]
|
||||
ObtenerPorPaginas(pag uint) ([]logs.Log, error)
|
||||
CantPaginas() (int64, error)
|
||||
ObtenerConFiltros(p int, f dto.BusquedaLogsDto) ([]logs.Log, error)
|
||||
CantPaginasConFiltros(f dto.BusquedaLogsDto) (int64, error)
|
||||
}
|
||||
|
||||
type repositorioLogs struct {
|
||||
@@ -41,3 +44,58 @@ func (r *repositorioLogs) CantPaginas() (int64, error) {
|
||||
}
|
||||
return pags, nil
|
||||
}
|
||||
|
||||
func (r *repositorioLogs) ObtenerConFiltros(p int, f dto.BusquedaLogsDto) ([]logs.Log, error) {
|
||||
var logss []logs.Log
|
||||
|
||||
db := r.db.Model(&logs.Log{})
|
||||
|
||||
if f.UsuarioID != 0 {
|
||||
db = db.Where("usuario_id = ?", f.UsuarioID)
|
||||
}
|
||||
|
||||
if f.Accion != "" {
|
||||
db = db.Where("accion LIKE ?", "%"+f.Accion+"%")
|
||||
}
|
||||
|
||||
if !f.FechaInicio.IsZero() {
|
||||
db = db.Where("created_at >= ?", f.FechaInicio)
|
||||
}
|
||||
|
||||
if !f.FechaFin.IsZero() {
|
||||
db = db.Where("created_at <= ?", f.FechaFin)
|
||||
}
|
||||
|
||||
err := db.
|
||||
Limit(10).
|
||||
Offset(10 * p).
|
||||
Find(&logss).Error
|
||||
|
||||
return logss, err
|
||||
}
|
||||
|
||||
func (r *repositorioLogs) CantPaginasConFiltros(f dto.BusquedaLogsDto) (int64, error) {
|
||||
var cantpags int64
|
||||
|
||||
db := r.db.Model(&logs.Log{})
|
||||
|
||||
if f.UsuarioID != 0 {
|
||||
db = db.Where("usuario_id = ?", f.UsuarioID)
|
||||
}
|
||||
|
||||
if f.Accion != "" {
|
||||
db = db.Where("accion LIKE ?", "%"+f.Accion+"%")
|
||||
}
|
||||
|
||||
if !f.FechaInicio.IsZero() {
|
||||
db = db.Where("created_at >= ?", f.FechaInicio)
|
||||
}
|
||||
|
||||
if !f.FechaFin.IsZero() {
|
||||
db = db.Where("created_at <= ?", f.FechaFin)
|
||||
}
|
||||
|
||||
err := db.Count(&cantpags).Error
|
||||
|
||||
return cantpags, err
|
||||
}
|
||||
@@ -12,9 +12,9 @@ func LogsRoute(r *gin.Engine) {
|
||||
repuestoGrupo.Use(middleware.AuthMiddleware(), middleware.PermisoMiddleware(5))
|
||||
{
|
||||
repuestoGrupo.GET("/:p/", logs.ObtenerLogs)
|
||||
repuestoGrupo.POST("/:p/busqueda", logs.BusquedaLogs)
|
||||
|
||||
repuestoGrupo.GET("/:p/log", logs.ObtenerLog)
|
||||
// repuestoGrupo.GET("/:id", repuestos.ObtenerRepuesto)
|
||||
// repuestoGrupo.POST("/", repuestos.CrearRepuesto)
|
||||
// repuestoGrupo.PUT("/:id", repuestos.ActualizarRepuesto)
|
||||
// repuestoGrupo.DELETE("/:id", repuestos.EliminarRepuesto)
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import { API_URL } from '$lib/env';
|
||||
import type { RespuestaPagina } from '../../../routes/logs/LogsEstado.svelte';
|
||||
import type { BusquedaLogsDto, LogEntry } from '../../../types';
|
||||
import { getToken } from '../token';
|
||||
|
||||
export async function busquedaLogs(
|
||||
pagina: number,
|
||||
filtros: BusquedaLogsDto,
|
||||
fetch2: Function
|
||||
): Promise<RespuestaPagina<LogEntry> | { error: string }> {
|
||||
const fetchFn = fetch2 ? fetch2 : fetch;
|
||||
const res = await fetchFn(`${API_URL}/logs/${pagina}/busqueda`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: `Bearer ${getToken()}`
|
||||
},
|
||||
body: JSON.stringify(filtros)
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok) {
|
||||
return { error: data.error };
|
||||
}
|
||||
const totalPages = Math.ceil(data.maxlenght / 10);
|
||||
return { logs: data.logs, maxPagina: Math.max(0, totalPages - 1), totalItems: data.maxlenght };
|
||||
}
|
||||
@@ -3,8 +3,12 @@ import type { RespuestaPagina } from '../../../routes/logs/LogsEstado.svelte';
|
||||
import type { LogEntry } from '../../../types';
|
||||
import { getToken } from '../token';
|
||||
|
||||
export async function obtenerLogs(pagina: number): Promise<RespuestaPagina<LogEntry>> {
|
||||
const res = await fetch(`${API_URL}/logs/${pagina}/`, {
|
||||
export async function obtenerLogs(
|
||||
pagina: number,
|
||||
fetch2: Function
|
||||
): Promise<RespuestaPagina<LogEntry>> {
|
||||
const fetchFn = fetch2 ? fetch2 : fetch;
|
||||
const res = await fetchFn(`${API_URL}/logs/${pagina}/`, {
|
||||
headers: {
|
||||
Authorization: `Bearer ${getToken()}`
|
||||
}
|
||||
|
||||
@@ -1,41 +1,27 @@
|
||||
<script lang="ts">
|
||||
import Header from '$lib/components/Header.svelte';
|
||||
import {
|
||||
DataTable,
|
||||
Pagination,
|
||||
InlineLoading,
|
||||
Tag,
|
||||
Tile,
|
||||
Button
|
||||
} from 'carbon-components-svelte';
|
||||
import { Pagination, InlineLoading, Tile, Button } from 'carbon-components-svelte';
|
||||
import Renew from 'carbon-icons-svelte/lib/Renew.svelte';
|
||||
import { LogsCache } from './LogsEstado.svelte';
|
||||
import type { LogEntry } from '../../types';
|
||||
import { obtenerLogs } from '$lib/hooks/logs/obtenerLogs';
|
||||
import { Export } from 'carbon-icons-svelte';
|
||||
import { goto, invalidate } from '$app/navigation';
|
||||
import { ExportarLogs } from './ExportarLogs';
|
||||
import TablaLogs from './TablaLogs.svelte';
|
||||
import FiltrosLogs from './FiltrosLogs.svelte';
|
||||
import { page } from '$app/state';
|
||||
|
||||
const cache = new LogsCache<LogEntry>();
|
||||
let { data } = $props();
|
||||
|
||||
let logs = $state<LogEntry[]>([]);
|
||||
let error = $state<string | null>(null);
|
||||
|
||||
async function irAPagina(pagina: number, forzar = false) {
|
||||
error = null;
|
||||
try {
|
||||
logs = await cache.cargarPagina(pagina, obtenerLogs, forzar);
|
||||
} catch (e) {
|
||||
error = e instanceof Error ? e.message : 'Error desconocido al cargar los logs';
|
||||
}
|
||||
function irAPagina(pagina: number) {
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
params.set('pagina', String(pagina));
|
||||
goto(`?${params}`, { replaceState: true });
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
irAPagina(0);
|
||||
});
|
||||
let pageNum = $derived(Number(page.url.searchParams.get('pagina') ?? '0') + 1);
|
||||
|
||||
const cargandoActual = $derived.by(() => cache.estaCargando(cache.pagina));
|
||||
function recargar() {
|
||||
invalidate('logs:pagina');
|
||||
}
|
||||
</script>
|
||||
|
||||
<Header />
|
||||
@@ -48,8 +34,7 @@
|
||||
size="small"
|
||||
icon={Renew}
|
||||
iconDescription="Recargar página actual"
|
||||
disabled={cargandoActual}
|
||||
onclick={() => irAPagina(cache.pagina, true)}
|
||||
onclick={recargar}
|
||||
>
|
||||
Recargar
|
||||
</Button>
|
||||
@@ -58,9 +43,9 @@
|
||||
size="small"
|
||||
icon={Export}
|
||||
iconDescription="Exportar CSV"
|
||||
disabled={!(logs && logs.length != 0)}
|
||||
disabled={!(data.logs && data.logs.length != 0)}
|
||||
onclick={() => {
|
||||
new ExportarLogs(logs).descargarCSV();
|
||||
new ExportarLogs(data.logs).descargarCSV();
|
||||
}}
|
||||
>
|
||||
Exportar CSV
|
||||
@@ -68,28 +53,25 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{#if error}
|
||||
{#if data.error}
|
||||
<Tile>
|
||||
<p class="mb-2 text-red-600">{error}</p>
|
||||
<Button size="small" onclick={() => irAPagina(cache.pagina, true)}>Reintentar</Button>
|
||||
<p class="mb-2 text-red-600">{data.error}</p>
|
||||
<Button size="small" onclick={recargar}>Reintentar</Button>
|
||||
</Tile>
|
||||
{:else if cargandoActual && logs.length === 0}
|
||||
<InlineLoading description="Cargando logs…" />
|
||||
{:else if logs.length === 0}
|
||||
{:else if data.logs && data.logs.length === 0}
|
||||
<Tile>
|
||||
<p>No hay logs en esta página.</p>
|
||||
</Tile>
|
||||
{:else}
|
||||
<div class="flex flex-col gap-2">
|
||||
<FiltrosLogs bind:logs />
|
||||
|
||||
<TablaLogs {logs} />
|
||||
<FiltrosLogs />
|
||||
<TablaLogs logs={data.logs} />
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<Pagination
|
||||
page={cache.pagina + 1}
|
||||
totalItems={cache.totalItems}
|
||||
page={pageNum}
|
||||
totalItems={data.totalItems}
|
||||
pageSize={10}
|
||||
pageSizes={[10]}
|
||||
pageSizeInputDisabled={true}
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
import type { PageLoad } from './$types';
|
||||
import { obtenerLogs } from '$lib/hooks/logs/obtenerLogs';
|
||||
import { busquedaLogs } from '$lib/hooks/logs/busquedaLogs';
|
||||
|
||||
export const load: PageLoad = async ({ url, depends, fetch }) => {
|
||||
depends('logs:pagina');
|
||||
|
||||
const pagina = Number(url.searchParams.get('pagina') ?? '0');
|
||||
const usuarioId = url.searchParams.get('usuarioId');
|
||||
const accion = url.searchParams.get('accion');
|
||||
const fechaInicio = url.searchParams.get('fechaInicio');
|
||||
const fechaFin = url.searchParams.get('fechaFin');
|
||||
|
||||
const tieneFiltros = usuarioId || accion || fechaInicio || fechaFin;
|
||||
|
||||
try {
|
||||
if (tieneFiltros) {
|
||||
let filtros: any = {
|
||||
usuarioId: usuarioId ? Number(usuarioId) : 0,
|
||||
accion: accion ?? ''
|
||||
};
|
||||
|
||||
if (fechaInicio) {
|
||||
filtros.fechaInicio = new Date(fechaInicio);
|
||||
}
|
||||
if (fechaFin) {
|
||||
filtros.fechaFin = new Date(fechaFin);
|
||||
}
|
||||
|
||||
const res = await busquedaLogs(pagina, filtros, fetch);
|
||||
if ('error' in res) {
|
||||
return { logs: [], error: res.error, totalItems: 0, maxPagina: 0 };
|
||||
}
|
||||
if (typeof res.logs === 'undefined') res.logs = [];
|
||||
return {
|
||||
logs: res.logs,
|
||||
error: null,
|
||||
totalItems: res.totalItems,
|
||||
maxPagina: res.maxPagina
|
||||
};
|
||||
}
|
||||
|
||||
const res = await obtenerLogs(pagina, fetch);
|
||||
return { logs: res.logs, error: null, totalItems: res.totalItems, maxPagina: res.maxPagina };
|
||||
} catch (e) {
|
||||
return {
|
||||
logs: [],
|
||||
error: e instanceof Error ? e.message : 'Error desconocido al cargar los logs',
|
||||
totalItems: 0,
|
||||
maxPagina: 0
|
||||
};
|
||||
}
|
||||
};
|
||||
@@ -1,5 +1,6 @@
|
||||
<script>
|
||||
<script lang="ts">
|
||||
import {
|
||||
Button,
|
||||
DatePicker,
|
||||
DatePickerInput,
|
||||
Disclosure,
|
||||
@@ -10,27 +11,66 @@
|
||||
Tile
|
||||
} from 'carbon-components-svelte';
|
||||
|
||||
let { logs = $bindable() } = $props();
|
||||
import { goto, invalidate } from '$app/navigation';
|
||||
|
||||
let filtros = $state({
|
||||
idusu: 0
|
||||
usuarioId: 0,
|
||||
accion: '',
|
||||
fechaInicio: '',
|
||||
fechaFin: ''
|
||||
});
|
||||
|
||||
function aplicarFiltros() {
|
||||
const params = new URLSearchParams();
|
||||
params.set('pagina', '0');
|
||||
if (filtros.usuarioId != 0) params.set('usuarioId', String(filtros.usuarioId));
|
||||
if (filtros.accion != '') params.set('accion', filtros.accion);
|
||||
if (filtros.fechaInicio != '') params.set('fechaInicio', filtros.fechaInicio);
|
||||
if (filtros.fechaFin != '') params.set('fechaFin', filtros.fechaFin);
|
||||
goto(`?${params}`);
|
||||
// invalidate('logs:pagina');
|
||||
}
|
||||
$inspect(filtros);
|
||||
function limpiarFiltros() {
|
||||
filtros = { usuarioId: 0, accion: '', fechaInicio: '', fechaFin: '' };
|
||||
goto('/logs', { replaceState: true });
|
||||
}
|
||||
</script>
|
||||
|
||||
<Tile>
|
||||
<Disclosure summary="Filtros">
|
||||
<Form>
|
||||
<NumberInput fluid labelText="Id de Usuario" min={0} bind:value={filtros.idusu}></NumberInput>
|
||||
<Select fluid labelText="Accion del Log">
|
||||
<Form
|
||||
onsubmit={(e) => {
|
||||
e.preventDefault();
|
||||
aplicarFiltros();
|
||||
}}
|
||||
>
|
||||
<NumberInput fluid labelText="Id de Usuario" min={0} bind:value={filtros.usuarioId} />
|
||||
<Select fluid labelText="Accion del Log" bind:selected={filtros.accion}>
|
||||
<SelectItem text="Todas" value="" />
|
||||
<SelectItem text="Actualizar" value="ACTUALIZAR" />
|
||||
<SelectItem text="Crear" value="CREAR" />
|
||||
<SelectItem text="Eliminar" value="ELIMINAR" />
|
||||
<SelectItem text="Alta" value="ALTA" />
|
||||
</Select>
|
||||
|
||||
<DatePicker fluid datePickerType="range" on:change>
|
||||
<DatePicker
|
||||
fluid
|
||||
datePickerType="range"
|
||||
on:change={(e) => {
|
||||
const dates = e.detail;
|
||||
filtros.fechaInicio = dates.selectedDates[0] ?? '';
|
||||
filtros.fechaFin = dates.selectedDates[1] ?? '';
|
||||
}}
|
||||
>
|
||||
<DatePickerInput labelText="Fecha inicio" placeholder="mm/dd/yyyy" />
|
||||
<DatePickerInput labelText="Fecha fin" placeholder="mm/dd/yyyy" />
|
||||
</DatePicker>
|
||||
|
||||
<div class="mt-4! flex gap-2">
|
||||
<Button type="submit">Buscar</Button>
|
||||
<Button kind="secondary" onclick={limpiarFiltros}>Limpiar</Button>
|
||||
</div>
|
||||
</Form>
|
||||
</Disclosure>
|
||||
</Tile>
|
||||
@@ -10,6 +10,9 @@
|
||||
|
||||
let { logs } = $props();
|
||||
|
||||
/**
|
||||
* @param {string | number | Date} iso
|
||||
*/
|
||||
function formatFecha(iso) {
|
||||
return new Date(iso).toLocaleString('es-AR', {
|
||||
day: '2-digit',
|
||||
@@ -21,7 +24,11 @@
|
||||
}
|
||||
</script>
|
||||
|
||||
<DataTable {headers} rows={logs} expandable>
|
||||
{#if !logs}
|
||||
<p>No hay logs para mostrar</p>
|
||||
{/if}
|
||||
|
||||
<DataTable {headers} rows={logs ?? []} expandable>
|
||||
<svelte:fragment slot="cell" let:row let:cell>
|
||||
{#if cell.key === 'created_at'}
|
||||
{formatFecha(row.created_at)}
|
||||
|
||||
Vendored
+8
-1
@@ -4,7 +4,7 @@ export interface Usuario {
|
||||
name: string;
|
||||
}
|
||||
|
||||
interface CrearRepuestoDto {
|
||||
export interface CrearRepuestoDto {
|
||||
nombre: string;
|
||||
descripcion: string;
|
||||
marca: string;
|
||||
@@ -13,6 +13,13 @@ interface CrearRepuestoDto {
|
||||
stockMinimo: number;
|
||||
}
|
||||
|
||||
export interface BusquedaLogsDto {
|
||||
usuarioId: uint;
|
||||
accion: string;
|
||||
fechaInicio: Date;
|
||||
fechaFin: Date;
|
||||
}
|
||||
|
||||
export interface LogEntry {
|
||||
id: number;
|
||||
usuarioId: number;
|
||||
|
||||
Reference in new issue
Block a user