Private
Public Access
funcionalidad de logs andando
This commit is contained in:
1 parent
06ed4a518b
commit
aac88856ac
21 files changed
+627
-31
No files matched your search
+2
-2
@@ -6,8 +6,8 @@ COPY go.mod go.sum ./
|
||||
RUN go mod download
|
||||
|
||||
COPY . .
|
||||
RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o server .
|
||||
|
||||
RUN CGO_ENABLED=0 GOOS=linux go build -o server .
|
||||
# -ldflags="-s -w"
|
||||
# ---
|
||||
FROM scratch
|
||||
|
||||
|
||||
@@ -0,0 +1,198 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
"reflect"
|
||||
"repuestera_back/models/logs"
|
||||
|
||||
"gorm.io/datatypes"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func SetupAuditoria(db *gorm.DB) {
|
||||
if err := db.Callback().Update().Before("gorm:update").Register("auditoria:capturar_anterior", capturarEstadoAnterior); err != nil {
|
||||
log.Println("ERROR registrando capturar_anterior:", err)
|
||||
}
|
||||
if err := db.Callback().Update().After("gorm:update").Register("auditoria:log_update", generarLogUpdate); err != nil {
|
||||
log.Println("ERROR registrando log_update:", err)
|
||||
}
|
||||
if err := db.Callback().Create().After("gorm:create").Register("auditoria:log_create", generarLogCreate); err != nil {
|
||||
log.Println("ERROR registrando log_create:", err)
|
||||
}
|
||||
if err := db.Callback().Delete().Before("gorm:delete").Register("auditoria:log_delete", generarLogDelete); err != nil {
|
||||
log.Println("ERROR registrando log_delete:", err)
|
||||
}
|
||||
}
|
||||
|
||||
func capturarEstadoAnterior(tx *gorm.DB) {
|
||||
if tx.Statement.Schema == nil || auditoriaDeshabilitada(tx) {
|
||||
return
|
||||
}
|
||||
|
||||
pkField := tx.Statement.Schema.PrioritizedPrimaryField
|
||||
if pkField == nil {
|
||||
return
|
||||
}
|
||||
|
||||
reflectValue := tx.Statement.ReflectValue
|
||||
if !reflectValue.IsValid() {
|
||||
return
|
||||
}
|
||||
|
||||
pkValue, isZero := pkField.ValueOf(context.Background(), reflectValue)
|
||||
if isZero {
|
||||
return
|
||||
}
|
||||
|
||||
modeloAnterior := reflect.New(tx.Statement.Schema.ModelType).Interface()
|
||||
|
||||
if err := tx.Session(&gorm.Session{NewDB: true}).
|
||||
Model(modeloAnterior).
|
||||
First(modeloAnterior, pkValue).Error; err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
tx.Set("auditoria:anterior", modeloAnterior)
|
||||
}
|
||||
|
||||
func generarLogUpdate(tx *gorm.DB) {
|
||||
if tx.Statement.Schema == nil || auditoriaDeshabilitada(tx) {
|
||||
return
|
||||
}
|
||||
|
||||
anteriorVal, ok := tx.Get("auditoria:anterior")
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
nuevo := tx.Statement.Dest
|
||||
detalles := generarDetalles(tx.Statement.Table, anteriorVal, nuevo)
|
||||
|
||||
if len(detalles) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
guardarLog(tx, "ACTUALIZAR", detalles)
|
||||
}
|
||||
|
||||
func generarLogCreate(tx *gorm.DB) {
|
||||
if tx.Statement.Schema == nil || auditoriaDeshabilitada(tx) {
|
||||
return
|
||||
}
|
||||
|
||||
detalles := []logs.LogDetalle{
|
||||
{
|
||||
NombreTabla: tx.Statement.Table,
|
||||
Columna: "*",
|
||||
ValorNuevo: fmt.Sprintf("Registro creado (ID: %v)", obtenerID(tx.Statement.Dest)),
|
||||
},
|
||||
}
|
||||
|
||||
guardarLog(tx, "CREAR", detalles)
|
||||
}
|
||||
|
||||
func generarLogDelete(tx *gorm.DB) {
|
||||
if tx.Statement.Schema == nil || auditoriaDeshabilitada(tx) {
|
||||
return
|
||||
}
|
||||
|
||||
detalles := []logs.LogDetalle{
|
||||
{
|
||||
NombreTabla: tx.Statement.Table,
|
||||
Columna: "*",
|
||||
ValorAnterior: fmt.Sprintf("Registro eliminado (ID: %v)", obtenerID(tx.Statement.Dest)),
|
||||
},
|
||||
}
|
||||
|
||||
guardarLog(tx, "ELIMINAR", detalles)
|
||||
}
|
||||
|
||||
func generarDetalles(tabla string, anterior, nuevo interface{}) []logs.LogDetalle {
|
||||
var detalles []logs.LogDetalle
|
||||
|
||||
valAnterior := reflect.ValueOf(anterior)
|
||||
valNuevo := reflect.ValueOf(nuevo)
|
||||
|
||||
for valAnterior.Kind() == reflect.Ptr {
|
||||
valAnterior = valAnterior.Elem()
|
||||
}
|
||||
for valNuevo.Kind() == reflect.Ptr {
|
||||
valNuevo = valNuevo.Elem()
|
||||
}
|
||||
|
||||
if valAnterior.Kind() != reflect.Struct || valNuevo.Kind() != reflect.Struct {
|
||||
return detalles
|
||||
}
|
||||
|
||||
tipo := valAnterior.Type()
|
||||
|
||||
for i := 0; i < tipo.NumField(); i++ {
|
||||
campo := tipo.Field(i)
|
||||
|
||||
if campo.PkgPath != "" { // campo no exportado
|
||||
continue
|
||||
}
|
||||
if campo.Name == "CreatedAt" || campo.Name == "UpdatedAt" || campo.Name == "DeletedAt" {
|
||||
continue
|
||||
}
|
||||
|
||||
campoNuevo := valNuevo.FieldByName(campo.Name)
|
||||
if !campoNuevo.IsValid() {
|
||||
continue
|
||||
}
|
||||
|
||||
vAnt := fmt.Sprintf("%v", valAnterior.Field(i).Interface())
|
||||
vNue := fmt.Sprintf("%v", campoNuevo.Interface())
|
||||
|
||||
if vAnt != vNue {
|
||||
detalles = append(detalles, logs.LogDetalle{
|
||||
NombreTabla: tabla,
|
||||
Columna: campo.Name,
|
||||
ValorAnterior: vAnt,
|
||||
ValorNuevo: vNue,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return detalles
|
||||
}
|
||||
|
||||
func guardarLog(tx *gorm.DB, accion string, detalles []logs.LogDetalle) {
|
||||
usuarioID, okUsuario := tx.Get("auditoria:usuario_id")
|
||||
|
||||
if !okUsuario {
|
||||
log.Printf("ADVERTENCIA: Operación '%s' en tabla '%s' no auditada: falta 'auditoria:usuario_id' en contexto GORM", accion, tx.Statement.Table)
|
||||
return
|
||||
}
|
||||
|
||||
logEntry := logs.Log{
|
||||
UsuarioID: usuarioID.(uint),
|
||||
Accion: accion,
|
||||
Detalles: datatypes.JSONSlice[logs.LogDetalle](detalles),
|
||||
}
|
||||
|
||||
if err := DB.Create(&logEntry).Error; err != nil {
|
||||
log.Printf("ERROR guardarLog: falló al crear entrada de log: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func auditoriaDeshabilitada(tx *gorm.DB) bool {
|
||||
return tx.Statement.Table == "logs"
|
||||
}
|
||||
|
||||
func obtenerID(dest interface{}) interface{} {
|
||||
val := reflect.ValueOf(dest)
|
||||
for val.Kind() == reflect.Ptr {
|
||||
val = val.Elem()
|
||||
}
|
||||
if val.Kind() != reflect.Struct {
|
||||
return nil
|
||||
}
|
||||
campoID := val.FieldByName("ID")
|
||||
if campoID.IsValid() {
|
||||
return campoID.Interface()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package logs
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
r "repuestera_back/repositorios"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func ObtenerLog(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
|
||||
}
|
||||
|
||||
logs, err := r.ObtenerRepositorios().Logs.ObtenerPorPaginas(uint(pag))
|
||||
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, logs)
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package logs
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
r "repuestera_back/repositorios"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func ObtenerLogs(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
|
||||
}
|
||||
repo := r.ObtenerRepositorios().Logs
|
||||
|
||||
logs, err := repo.ObtenerPorPaginas(uint(pag))
|
||||
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
cantpags, err := repo.CantPaginas()
|
||||
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"logs": logs,
|
||||
"maxlenght": cantpags,
|
||||
})
|
||||
}
|
||||
@@ -46,7 +46,8 @@ func ActualizarRepuesto(c *gin.Context){
|
||||
return
|
||||
}
|
||||
|
||||
if err := r.ObtenerRepositorios().Repuesto.Actualizar(entity, &repuesto); err != nil {
|
||||
uid, _ := c.Get("userID")
|
||||
if err := r.ObtenerRepositorios().Repuesto.Actualizar(entity, &repuesto, uid.(uint)); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -32,7 +32,8 @@ func CrearRepuesto(c *gin.Context){
|
||||
ConMarca(marca.ID).
|
||||
Build()
|
||||
|
||||
if err := r.ObtenerRepositorios().Repuesto.Crear(&repuesto); err != nil {
|
||||
uid, _ := c.Get("userID")
|
||||
if err := r.ObtenerRepositorios().Repuesto.Crear(&repuesto, uid.(uint)); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -20,7 +20,9 @@ func EliminarRepuesto(c *gin.Context){
|
||||
return
|
||||
}
|
||||
|
||||
if err := r.ObtenerRepositorios().Repuesto.Eliminar(uint(id)); err != nil {
|
||||
|
||||
uid, _ := c.Get("userID")
|
||||
if err := r.ObtenerRepositorios().Repuesto.Eliminar(uint(id), uid.(uint)); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
package logs
|
||||
|
||||
import "gorm.io/gorm"
|
||||
|
||||
func DBConAuditoria(db *gorm.DB, usuarioID uint) *gorm.DB {
|
||||
return db.Set("auditoria:usuario_id", usuarioID)
|
||||
}
|
||||
+8
-15
@@ -4,24 +4,17 @@ import (
|
||||
"time"
|
||||
|
||||
models_seguridad "repuestera_back/models/seguridad"
|
||||
|
||||
"gorm.io/datatypes"
|
||||
)
|
||||
|
||||
type LogDetalle struct {
|
||||
NombreTabla string `json:"nombreTabla"`
|
||||
Columna string `json:"columna"`
|
||||
ValorAnterior string `json:"valorAnterior,omitempty"`
|
||||
ValorNuevo string `json:"valorNuevo,omitempty"`
|
||||
}
|
||||
|
||||
type Log struct {
|
||||
ID uint64 `gorm:"primaryKey" json:"id"`
|
||||
EmpresaID string `gorm:"type:varchar(3);index;not null" json:"empresaId"`
|
||||
UsuarioID uint `gorm:"index;not null" json:"usuarioId"`
|
||||
Accion string `gorm:"type:varchar(50);not null" json:"accion"`
|
||||
Detalles []LogDetalle `gorm:"type:json" json:"detalles,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
// Empresa models_seguridad.Empresa `gorm:"foreignKey:EmpresaID" json:"empresa,omitempty"`
|
||||
Usuario models_seguridad.Usuario `gorm:"foreignKey:UsuarioID" json:"usuario,omitempty"`
|
||||
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[LogDetalle] `gorm:"type:json" json:"detalles,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
Usuario models_seguridad.Usuario `gorm:"foreignKey:UsuarioID" json:"usuario,omitempty"`
|
||||
}
|
||||
|
||||
func (Log) TableName() string {
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
package logs
|
||||
|
||||
type LogDetalle struct {
|
||||
NombreTabla string `json:"nombreTabla"`
|
||||
Columna string `json:"columna"`
|
||||
ValorAnterior string `json:"valorAnterior,omitempty"`
|
||||
ValorNuevo string `json:"valorNuevo,omitempty"`
|
||||
}
|
||||
@@ -12,6 +12,7 @@ type Repositorios struct {
|
||||
Grupo RepositorioGrupo
|
||||
Repuesto RepositorioRepuesto
|
||||
Marca RepositorioMarcas
|
||||
Logs RepositorioLogs
|
||||
}
|
||||
|
||||
var (
|
||||
@@ -28,6 +29,7 @@ func InicializarRepositorios(db *gorm.DB) {
|
||||
Grupo: &repositorioGrupo{db: db},
|
||||
Repuesto: NuevoRepositorioRepuesto(db),
|
||||
Marca: NuevoRepositorioMarcas(db),
|
||||
Logs: NuevoRepositorioLogs(db),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package repositorios
|
||||
|
||||
import (
|
||||
"repuestera_back/logs"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
@@ -8,9 +10,9 @@ type IRepositorio[T any] interface {
|
||||
Guardar(entidad *T) error
|
||||
ObtenerTodos() ([]T, error)
|
||||
ObtenerPorID(id uint) (*T, error)
|
||||
Crear(entidad T) error
|
||||
Actualizar(entidad *T, input T) error
|
||||
Eliminar(id uint) error
|
||||
Crear(entidad T, usuarioID uint) error
|
||||
Actualizar(entidad *T, input T, usuarioID uint) error
|
||||
Eliminar(id uint, usuarioID uint) error
|
||||
}
|
||||
|
||||
type RepositorioBase[T any] struct {
|
||||
@@ -21,6 +23,10 @@ func NewRepositorioBase[T any](db *gorm.DB) *RepositorioBase[T] {
|
||||
return &RepositorioBase[T]{db: db}
|
||||
}
|
||||
|
||||
func (r *RepositorioBase[T]) dbConAuditoria(usuarioID uint) *gorm.DB {
|
||||
return logs.DBConAuditoria(r.db, usuarioID)
|
||||
}
|
||||
|
||||
func (r *RepositorioBase[T]) Guardar(entidad *T) error {
|
||||
return r.db.Save(entidad).Error
|
||||
}
|
||||
@@ -41,15 +47,15 @@ func (r *RepositorioBase[T]) ObtenerPorID(id uint) (*T, error) {
|
||||
return &entidad, nil
|
||||
}
|
||||
|
||||
func (r *RepositorioBase[T]) Crear(entidad T) error {
|
||||
return r.db.Create(&entidad).Error
|
||||
func (r *RepositorioBase[T]) Crear(entidad T, usuarioID uint) error {
|
||||
return r.dbConAuditoria(usuarioID).Create(&entidad).Error
|
||||
}
|
||||
|
||||
func (r *RepositorioBase[T]) Actualizar(entidad *T, input T) error {
|
||||
return r.db.Model(entidad).Updates(input).Error
|
||||
func (r *RepositorioBase[T]) Actualizar(entidad *T, input T, usuarioID uint) error {
|
||||
return r.dbConAuditoria(usuarioID).Model(entidad).Updates(input).Error
|
||||
}
|
||||
|
||||
func (r *RepositorioBase[T]) Eliminar(id uint) error {
|
||||
func (r *RepositorioBase[T]) Eliminar(id uint, usuarioID uint) error {
|
||||
var entidad T
|
||||
return r.db.Delete(&entidad, id).Error
|
||||
return r.dbConAuditoria(usuarioID).Delete(&entidad, id).Error
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package repositorios
|
||||
|
||||
import (
|
||||
"repuestera_back/models/logs"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type RepositorioLogs interface {
|
||||
IRepositorio[*logs.Log]
|
||||
ObtenerPorPaginas(pag uint) ([]logs.Log, error)
|
||||
CantPaginas() (int64, error)
|
||||
}
|
||||
|
||||
type repositorioLogs struct {
|
||||
*RepositorioBase[*logs.Log]
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NuevoRepositorioLogs(db *gorm.DB) RepositorioLogs {
|
||||
baseRepo := NewRepositorioBase[*logs.Log](db)
|
||||
return &repositorioLogs{
|
||||
RepositorioBase: baseRepo,
|
||||
db: db,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *repositorioLogs) ObtenerPorPaginas(pag uint) ([]logs.Log, error) {
|
||||
var logs []logs.Log
|
||||
if err := r.db.Limit(10).Offset(int(pag) * 10).Find(&logs).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return logs, nil
|
||||
}
|
||||
|
||||
func (r *repositorioLogs) CantPaginas() (int64, error) {
|
||||
var pags int64
|
||||
err := r.db.Model(&logs.Log{}).Count(&pags).Error
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return pags, nil
|
||||
}
|
||||
@@ -39,9 +39,12 @@ func main() {
|
||||
|
||||
fmt.Println("Database connected and migrated successfully")
|
||||
|
||||
config.SetupAuditoria(config.DB)
|
||||
|
||||
repositorios.InicializarRepositorios(config.DB)
|
||||
config.InitPermisos()
|
||||
|
||||
|
||||
r := gin.Default()
|
||||
|
||||
routes.AuthRoute(r)
|
||||
@@ -49,6 +52,9 @@ func main() {
|
||||
routes.GroupRoute(r)
|
||||
routes.UserRoute(r)
|
||||
routes.RepuestoRoute(r)
|
||||
routes.LogsRoute(r)
|
||||
|
||||
fmt.Println("callback registrado:", config.DB.Callback().Create().Get("auditoria:log_create") != nil)
|
||||
|
||||
r.Run(":8080")
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package routes
|
||||
|
||||
import (
|
||||
"repuestera_back/controllers/logs"
|
||||
"repuestera_back/middleware"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func LogsRoute(r *gin.Engine) {
|
||||
repuestoGrupo := r.Group("/logs")
|
||||
repuestoGrupo.Use(middleware.AuthMiddleware(), middleware.PermisoMiddleware(5))
|
||||
{
|
||||
repuestoGrupo.GET("/:p/", logs.ObtenerLogs)
|
||||
|
||||
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,15 @@
|
||||
import { API_URL } from '$lib/env';
|
||||
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}/`, {
|
||||
headers: {
|
||||
Authorization: `Bearer ${getToken()}`
|
||||
}
|
||||
});
|
||||
if (!res.ok) throw new Error(`No se pudieron cargar los logs (${res.status})`);
|
||||
const data = await res.json();
|
||||
return { logs: data.logs, maxPagina: data.maxLenght };
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
<script lang="ts">
|
||||
import Header from '$lib/components/Header.svelte';
|
||||
import {
|
||||
DataTable,
|
||||
PaginationNav,
|
||||
InlineLoading,
|
||||
Tag,
|
||||
Tile,
|
||||
Button
|
||||
} from 'carbon-components-svelte';
|
||||
import Renew from 'carbon-icons-svelte/lib/Renew.svelte';
|
||||
import { LogsCache, type RespuestaPagina } from './LogsEstado.svelte';
|
||||
import type { LogEntry } from '../../types';
|
||||
import { obtenerLogs } from '$lib/hooks/logs/obtenerLogs';
|
||||
|
||||
const cache = new LogsCache<LogEntry>();
|
||||
|
||||
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';
|
||||
}
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
irAPagina(0);
|
||||
});
|
||||
|
||||
const headers = [
|
||||
{ key: 'created_at', value: 'Fecha' },
|
||||
{ key: 'empresaId', value: 'Empresa' },
|
||||
{ key: 'usuario', value: 'Usuario' },
|
||||
{ key: 'accion', value: 'Acción' }
|
||||
];
|
||||
|
||||
function formatFecha(iso: string) {
|
||||
return new Date(iso).toLocaleString('es-AR', {
|
||||
day: '2-digit',
|
||||
month: '2-digit',
|
||||
year: 'numeric',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit'
|
||||
});
|
||||
}
|
||||
|
||||
const cargandoActual = $derived(() => cache.estaCargando(cache.paginaActual()));
|
||||
</script>
|
||||
|
||||
<Header />
|
||||
<div class="page-container">
|
||||
<div class="flex items-center justify-between">
|
||||
<h2 class="text-lg font-semibold">Logs</h2>
|
||||
<Button
|
||||
kind="ghost"
|
||||
size="small"
|
||||
icon={Renew}
|
||||
iconDescription="Recargar página actual"
|
||||
disabled={cargandoActual()}
|
||||
onclick={() => irAPagina(cache.paginaActual(), true)}
|
||||
>
|
||||
Recargar
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{#if error}
|
||||
<Tile>
|
||||
<p class="mb-2 text-red-600">{error}</p>
|
||||
<Button size="small" onclick={() => irAPagina(cache.paginaActual(), true)}>Reintentar</Button>
|
||||
</Tile>
|
||||
{:else if cargandoActual() && logs.length === 0}
|
||||
<InlineLoading description="Cargando logs…" />
|
||||
{:else if logs.length === 0}
|
||||
<Tile>
|
||||
<p>No hay logs en esta página.</p>
|
||||
</Tile>
|
||||
{:else}
|
||||
<DataTable {headers} rows={logs} expandable>
|
||||
<svelte:fragment slot="cell" let:row let:cell>
|
||||
{#if cell.key === 'created_at'}
|
||||
{formatFecha(row.created_at)}
|
||||
{:else if cell.key === 'usuario'}
|
||||
{row.usuario?.nombre ?? `#${row.usuarioId}`}
|
||||
{:else if cell.key === 'accion'}
|
||||
<Tag type="blue">{row.accion}</Tag>
|
||||
{:else}
|
||||
{cell.value}
|
||||
{/if}
|
||||
</svelte:fragment>
|
||||
|
||||
<svelte:fragment slot="expanded-row" let:row>
|
||||
{#if row.detalles && row.detalles.length > 0}
|
||||
<div class="flex flex-col gap-2 py-2">
|
||||
{#each row.detalles as d}
|
||||
<div class="grid grid-cols-4 gap-2 text-sm">
|
||||
<span class="font-medium">{d.nombreTabla}</span>
|
||||
<span>{d.columna}</span>
|
||||
<span class="text-red-600 line-through">{d.valorAnterior ?? '—'}</span>
|
||||
<span class="text-green-600">{d.valorNuevo ?? '—'}</span>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
{:else}
|
||||
<p class="py-2 text-sm text-gray-500">Sin detalles registrados.</p>
|
||||
{/if}
|
||||
</svelte:fragment>
|
||||
</DataTable>
|
||||
{/if}
|
||||
|
||||
<div class="flex items-center gap-3">
|
||||
<PaginationNav
|
||||
page={cache.paginaActual()}
|
||||
total={cache.paginaMaxima() + 1}
|
||||
on:change={(e) => irAPagina(e.detail)}
|
||||
/>
|
||||
{#if cache.ultimoFueCache()}
|
||||
<span class="text-xs text-gray-500">desde caché</span>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,86 @@
|
||||
// logs-cache.svelte.ts
|
||||
import { SvelteMap, SvelteSet } from 'svelte/reactivity';
|
||||
|
||||
export interface RespuestaPagina<T> {
|
||||
logs: T[];
|
||||
maxPagina: number;
|
||||
}
|
||||
|
||||
export class LogsCache<T = unknown> {
|
||||
#cache = new SvelteMap<number, T[]>();
|
||||
#cargando = new SvelteSet<number>();
|
||||
#enVuelo = new Map<number, Promise<T[]>>();
|
||||
#pagina = $state(0);
|
||||
#maxPagina = $state(0);
|
||||
|
||||
#ultimoHit = $state(true);
|
||||
ultimoFueCache = $derived(() => this.#ultimoHit);
|
||||
paginaActual = $derived(() => this.#pagina);
|
||||
paginaMaxima = $derived(() => this.#maxPagina);
|
||||
paginaActMax = $derived(() => `${this.#pagina}/${this.#maxPagina}`);
|
||||
|
||||
tieneCache(pagina: number): boolean {
|
||||
return this.#cache.has(pagina);
|
||||
}
|
||||
|
||||
obtenerLogs(pagina: number): T[] | undefined {
|
||||
return this.#cache.get(pagina);
|
||||
}
|
||||
|
||||
estaCargando(pagina: number): boolean {
|
||||
return this.#cargando.has(pagina);
|
||||
}
|
||||
|
||||
async cargarPagina(
|
||||
pagina: number,
|
||||
fetcher: (pagina: number) => Promise<RespuestaPagina<T>>,
|
||||
forzar = false
|
||||
): Promise<T[]> {
|
||||
this.#pagina = pagina;
|
||||
|
||||
if (!forzar && this.#cache.has(pagina)) {
|
||||
this.#ultimoHit = true;
|
||||
return this.#cache.get(pagina)!;
|
||||
}
|
||||
|
||||
if (this.#enVuelo.has(pagina)) {
|
||||
return this.#enVuelo.get(pagina)!;
|
||||
}
|
||||
|
||||
this.#ultimoHit = false;
|
||||
this.#cargando.add(pagina);
|
||||
const promesa = fetcher(pagina)
|
||||
.then(({ logs, maxPagina }) => {
|
||||
this.#cache.set(pagina, logs);
|
||||
this.#maxPagina = maxPagina;
|
||||
return logs;
|
||||
})
|
||||
.finally(() => {
|
||||
this.#cargando.delete(pagina);
|
||||
this.#enVuelo.delete(pagina);
|
||||
});
|
||||
|
||||
this.#enVuelo.set(pagina, promesa);
|
||||
return promesa;
|
||||
}
|
||||
|
||||
invalidar(pagina?: number) {
|
||||
if (pagina === undefined) {
|
||||
this.#cache.clear();
|
||||
} else {
|
||||
this.#cache.delete(pagina);
|
||||
}
|
||||
}
|
||||
|
||||
paginasCacheadas(): number[] {
|
||||
return Array.from(this.#cache.keys());
|
||||
}
|
||||
|
||||
get puedeAvanzar(): boolean {
|
||||
return this.#pagina < this.#maxPagina;
|
||||
}
|
||||
|
||||
get puedeRetroceder(): boolean {
|
||||
return this.#pagina > 0;
|
||||
}
|
||||
}
|
||||
@@ -142,6 +142,6 @@
|
||||
openEditar = false;
|
||||
repuestoEditar = { id: 0 };
|
||||
}}
|
||||
repuesto={repuestoEditar}
|
||||
bind:repuesto={repuestoEditar}
|
||||
></EditarRepuestoForm>
|
||||
<ModalStructured objeto={repuestoInfo} bind:open={openInfo} />
|
||||
@@ -7,7 +7,7 @@
|
||||
let {
|
||||
open = $bindable(),
|
||||
onClose,
|
||||
repuesto
|
||||
repuesto = $bindable()
|
||||
}: { open: boolean; onClose: Function; repuesto: ActualizarRepuestoDto } = $props();
|
||||
|
||||
let error = $state('');
|
||||
|
||||
Vendored
+16
@@ -13,6 +13,22 @@ interface CrearRepuestoDto {
|
||||
stockMinimo: number;
|
||||
}
|
||||
|
||||
export interface LogEntry {
|
||||
id: number;
|
||||
usuarioId: number;
|
||||
accion: string;
|
||||
detalles?: LogDetalle[];
|
||||
created_at: string;
|
||||
usuario?: Usuario;
|
||||
}
|
||||
|
||||
export interface LogDetalle {
|
||||
nombreTabla: string;
|
||||
columna: string;
|
||||
valorAnterior?: string;
|
||||
valorNuevo?: string;
|
||||
}
|
||||
|
||||
interface ActualizarRepuestoDto {
|
||||
id: number;
|
||||
nombre: string;
|
||||
|
||||
Reference in new issue
Block a user