Private
Public Access
feat: hecha funcionalidad del cu-12
Signed-off-by: fede <federico.nicolas.polidoro@gmail.com>
This commit is contained in:
1 parent
5a8d4bc2d6
commit
37d357357a
14 files changed
+672
-116
No files matched your search
@@ -1,21 +1,53 @@
|
||||
package stock
|
||||
|
||||
import (
|
||||
applog "log"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
dto "repuestera_back/dto/Stock"
|
||||
"repuestera_back/models"
|
||||
r "repuestera_back/repositorios"
|
||||
)
|
||||
|
||||
func ObtenerReservas(c *gin.Context) {
|
||||
filtros := r.FiltrosReserva{}
|
||||
_ = filtros
|
||||
var q dto.FiltrosReservaQuery
|
||||
if err := c.ShouldBindQuery(&q); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
if !estadoReservaValido(q.Estado) {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "estado de reserva inválido"})
|
||||
return
|
||||
}
|
||||
|
||||
reservas, err := r.ObtenerRepositorios(c).Reserva.ListarActivas(filtros)
|
||||
repo := r.ObtenerRepositorios(c)
|
||||
|
||||
// D9: las reservas vencidas se procesan de forma lazy al consultar.
|
||||
if err := marcarReservasVencidas(r.BaseDeDatos(), repo, c.GetUint("userID"), time.Now()); err != nil {
|
||||
applog.Printf("stock: no se pudieron procesar las reservas vencidas: %v", err)
|
||||
}
|
||||
|
||||
reservas, err := repo.Reserva.ListarActivas(q)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, reservas)
|
||||
}
|
||||
|
||||
func estadoReservaValido(estado string) bool {
|
||||
switch strings.ToLower(strings.TrimSpace(estado)) {
|
||||
case "", "todas",
|
||||
string(models.ReservaActiva),
|
||||
string(models.ReservaVencida),
|
||||
string(models.ReservaLiberada),
|
||||
string(models.ReservaConsumida):
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package stock
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"math"
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
|
||||
"repuestera_back/models"
|
||||
"repuestera_back/repositorios"
|
||||
)
|
||||
|
||||
// marcarReservasVencidas pasa a vencidas las reservas activas cuya fecha ya
|
||||
// paso y devuelve al disponible la cantidad que tenian reservada. Se ejecuta de
|
||||
// forma lazy al consultar reservas (D9) para no depender de un cron.
|
||||
func marcarReservasVencidas(db *gorm.DB, repo *repositorios.Repositorios, usuarioID uint, ahora time.Time) error {
|
||||
if db == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
return db.Transaction(func(tx *gorm.DB) error {
|
||||
vencidas, err := repo.Reserva.BloquearVencidas(tx, ahora)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for _, reserva := range vencidas {
|
||||
stock, err := repo.Stock.BloquearPorRepuestoAlmacen(tx, uint64(reserva.RepuestoID), reserva.AlmacenID)
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
// La reserva igual debe dejar de figurar como activa.
|
||||
if _, err := repo.Reserva.MarcarVencida(tx, reserva.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
liberar := math.Min(reserva.Cantidad, stock.CantidadReservada)
|
||||
if liberar > 0 {
|
||||
saldoAnterior := stock.CantidadReservada
|
||||
stock.CantidadReservada = redondearCantidad(stock.CantidadReservada - liberar)
|
||||
if err := repo.Stock.ActualizarCantidades(tx, stock); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := registrarMovimiento(tx, repo, usuarioID, stock, models.MovimientoLiberacion, -liberar, saldoAnterior, stock.CantidadReservada, "RESERVA", uint64(reserva.ID), "Vencimiento de reserva"); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
marcada, err := repo.Reserva.MarcarVencida(tx, reserva.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !marcada {
|
||||
return ErrReservaYaLiberada
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package dto
|
||||
|
||||
// FiltrosReservaQuery acota el listado de reservas de stock.
|
||||
type FiltrosReservaQuery struct {
|
||||
RepuestoID uint `form:"repuestoId"`
|
||||
AlmacenID uint `form:"almacenId"`
|
||||
ClienteID uint `form:"clienteId"`
|
||||
Texto string `form:"q"`
|
||||
Cliente string `form:"cliente"`
|
||||
Estado string `form:"estado"`
|
||||
Pagina int `form:"pagina"`
|
||||
PorPagina int `form:"porPagina"`
|
||||
}
|
||||
@@ -1,30 +1,23 @@
|
||||
package repositorios
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
dto "repuestera_back/dto/Stock"
|
||||
"repuestera_back/models"
|
||||
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
// FiltrosReserva acota el listado de reservas.
|
||||
type FiltrosReserva struct {
|
||||
RepuestoID uint
|
||||
AlmacenID uint
|
||||
ClienteID uint
|
||||
VencenAntesDe *time.Time
|
||||
IncluirVencidas bool
|
||||
Pagina int
|
||||
PorPagina int
|
||||
}
|
||||
|
||||
type RepositorioReserva interface {
|
||||
IRepositorio[models.Reserva]
|
||||
ListarActivas(filtros FiltrosReserva) ([]models.Reserva, error)
|
||||
ListarActivas(filtros dto.FiltrosReservaQuery) ([]models.Reserva, error)
|
||||
CrearTx(tx *gorm.DB, reserva *models.Reserva) error
|
||||
Liberar(tx *gorm.DB, id uint) (bool, error)
|
||||
MarcarVencidas(ahora time.Time) (int64, error)
|
||||
BloquearVencidas(tx *gorm.DB, ahora time.Time) ([]models.Reserva, error)
|
||||
MarcarVencida(tx *gorm.DB, id uint) (bool, error)
|
||||
}
|
||||
|
||||
type repositorioReserva struct {
|
||||
@@ -41,17 +34,22 @@ func NuevoRepositorioReserva(db *gorm.DB, empresaID uint) RepositorioReserva {
|
||||
}
|
||||
}
|
||||
|
||||
func (r *repositorioReserva) ListarActivas(filtros FiltrosReserva) ([]models.Reserva, error) {
|
||||
func (r *repositorioReserva) ListarActivas(filtros dto.FiltrosReservaQuery) ([]models.Reserva, error) {
|
||||
query := r.db.Model(&models.Reserva{}).
|
||||
Preload("Repuesto").
|
||||
Preload("Almacen").
|
||||
Preload("Cliente")
|
||||
|
||||
estados := []models.EstadoReserva{models.ReservaActiva}
|
||||
if filtros.IncluirVencidas {
|
||||
estados = append(estados, models.ReservaVencida)
|
||||
estado := strings.ToLower(strings.TrimSpace(filtros.Estado))
|
||||
switch estado {
|
||||
case "todas":
|
||||
// Sin filtro de estado.
|
||||
case "", "activa":
|
||||
// Por defecto solo se muestran las reservas vigentes.
|
||||
query = query.Where("estado = ?", models.ReservaActiva)
|
||||
default:
|
||||
query = query.Where("estado = ?", models.EstadoReserva(estado))
|
||||
}
|
||||
query = query.Where("estado IN ?", estados)
|
||||
|
||||
if filtros.RepuestoID > 0 {
|
||||
query = query.Where("repuesto_id = ?", filtros.RepuestoID)
|
||||
@@ -62,8 +60,19 @@ func (r *repositorioReserva) ListarActivas(filtros FiltrosReserva) ([]models.Res
|
||||
if filtros.ClienteID > 0 {
|
||||
query = query.Where("cliente_id = ?", filtros.ClienteID)
|
||||
}
|
||||
if filtros.VencenAntesDe != nil {
|
||||
query = query.Where("fecha_vencimiento <= ?", *filtros.VencenAntesDe)
|
||||
if filtros.Texto != "" {
|
||||
like := "%" + strings.TrimSpace(filtros.Texto) + "%"
|
||||
query = query.Where(
|
||||
"repuesto_id IN (SELECT id FROM repuesto WHERE nombre LIKE ? OR descripcion LIKE ?)",
|
||||
like, like,
|
||||
)
|
||||
}
|
||||
if filtros.ClienteNombre != "" {
|
||||
like := "%" + strings.TrimSpace(filtros.ClienteNombre) + "%"
|
||||
query = query.Where(
|
||||
"cliente_id IN (SELECT id FROM clientes WHERE nombre LIKE ?)",
|
||||
like,
|
||||
)
|
||||
}
|
||||
|
||||
pagina, porPagina := normalizarPagina(filtros.Pagina, filtros.PorPagina)
|
||||
@@ -105,14 +114,34 @@ func (r *repositorioReserva) Liberar(tx *gorm.DB, id uint) (bool, error) {
|
||||
return resultado.RowsAffected > 0, nil
|
||||
}
|
||||
|
||||
// MarcarVencidas pasa a vencida todas las reservas activas cuya fecha ya paso.
|
||||
func (r *repositorioReserva) MarcarVencidas(ahora time.Time) (int64, error) {
|
||||
query := r.db.Model(&models.Reserva{}).
|
||||
Where("estado = ? AND fecha_vencimiento < ?", models.ReservaActiva, ahora)
|
||||
// BloquearVencidas devuelve las reservas activas cuya fecha ya paso, con
|
||||
// FOR UPDATE para poder liberar su cantidad reservada sin carreras.
|
||||
func (r *repositorioReserva) BloquearVencidas(tx *gorm.DB, ahora time.Time) ([]models.Reserva, error) {
|
||||
query := tx.Clauses(clause.Locking{Strength: "UPDATE"}).
|
||||
Where("estado = ? AND fecha_vencimiento IS NOT NULL AND fecha_vencimiento < ?", models.ReservaActiva, ahora)
|
||||
if r.empresaID > 0 {
|
||||
query = query.Where("empresa_id = ?", r.empresaID)
|
||||
}
|
||||
|
||||
var reservas []models.Reserva
|
||||
if err := query.Order("id ASC").Find(&reservas).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return reservas, nil
|
||||
}
|
||||
|
||||
// MarcarVencida pasa a vencida una reserva que seguia activa.
|
||||
// Devuelve false cuando ya no estaba activa.
|
||||
func (r *repositorioReserva) MarcarVencida(tx *gorm.DB, id uint) (bool, error) {
|
||||
query := tx.Model(&models.Reserva{}).
|
||||
Where("id = ? AND estado = ?", id, models.ReservaActiva)
|
||||
if r.empresaID > 0 {
|
||||
query = query.Where("empresa_id = ?", r.empresaID)
|
||||
}
|
||||
|
||||
resultado := query.Update("estado", models.ReservaVencida)
|
||||
return resultado.RowsAffected, resultado.Error
|
||||
if resultado.Error != nil {
|
||||
return false, resultado.Error
|
||||
}
|
||||
return resultado.RowsAffected > 0, nil
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package stock
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
ctrl "repuestera_back/controllers/stock"
|
||||
)
|
||||
|
||||
func TestObtenerReservas_EstadoInvalido(t *testing.T) {
|
||||
context, recorder := newStockContext(t, "GET", "/stock/reservas?estado=invalido", nil, nil)
|
||||
ctrl.ObtenerReservas(context)
|
||||
|
||||
if recorder.Code != 400 {
|
||||
t.Fatalf("estado inválido: esperado 400, obtenido %d: %s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestObtenerReservas_Filtros(t *testing.T) {
|
||||
context, recorder := newIntegrationContext(
|
||||
t,
|
||||
"GET",
|
||||
"/stock/reservas?estado=activa&q=bujia&cliente=garcia&almacenId=1&pagina=1&porPagina=20",
|
||||
nil,
|
||||
nil,
|
||||
)
|
||||
ctrl.ObtenerReservas(context)
|
||||
|
||||
if recorder.Code != 200 {
|
||||
t.Fatalf("reservas con filtros: esperado 200, obtenido %d: %s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
if !json.Valid(recorder.Body.Bytes()) {
|
||||
t.Fatalf("reservas con filtros: respuesta no es JSON válido: %s", recorder.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestObtenerReservas_TodasLasEstados(t *testing.T) {
|
||||
context, recorder := newIntegrationContext(t, "GET", "/stock/reservas?estado=todas", nil, nil)
|
||||
ctrl.ObtenerReservas(context)
|
||||
|
||||
if recorder.Code != 200 {
|
||||
t.Fatalf("reservas de todos los estados: esperado 200, obtenido %d: %s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,30 @@
|
||||
import { API_URL } from '$lib/env';
|
||||
import { getToken } from '../token';
|
||||
|
||||
export async function obtenerReservas(fetch2?: Function) {
|
||||
export interface FiltrosReserva {
|
||||
q?: string;
|
||||
cliente?: string;
|
||||
almacenId?: number;
|
||||
estado?: string;
|
||||
pagina?: number;
|
||||
porPagina?: number;
|
||||
}
|
||||
|
||||
export async function obtenerReservas(fetch2?: Function, filtros: FiltrosReserva = {}) {
|
||||
const fetchfn = fetch2 ? fetch2 : fetch;
|
||||
const params = new URLSearchParams();
|
||||
|
||||
if (filtros.q) params.set('q', filtros.q);
|
||||
if (filtros.cliente) params.set('cliente', filtros.cliente);
|
||||
if (filtros.almacenId) params.set('almacenId', String(filtros.almacenId));
|
||||
if (filtros.estado) params.set('estado', filtros.estado);
|
||||
if (filtros.pagina) params.set('pagina', String(filtros.pagina));
|
||||
if (filtros.porPagina) params.set('porPagina', String(filtros.porPagina));
|
||||
|
||||
const query = params.toString();
|
||||
|
||||
try {
|
||||
const req = await fetchfn(`${API_URL}/stock/reservas`, {
|
||||
const req = await fetchfn(`${API_URL}/stock/reservas${query ? `?${query}` : ''}`, {
|
||||
method: 'GET',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${getToken()}` }
|
||||
});
|
||||
|
||||
@@ -1,19 +1,8 @@
|
||||
<script lang="ts">
|
||||
import Header from '$lib/components/Header.svelte';
|
||||
import {
|
||||
Button,
|
||||
DataTableSkeleton,
|
||||
InlineNotification,
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableContainer,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow
|
||||
} from 'carbon-components-svelte';
|
||||
import { InventoryManagement, Play, Return } from 'carbon-icons-svelte';
|
||||
import { goto, invalidate } from '$app/navigation';
|
||||
import { Button, DataTableSkeleton, InlineNotification } from 'carbon-components-svelte';
|
||||
import { InventoryManagement, Return, Time } from 'carbon-icons-svelte';
|
||||
import { goto } from '$app/navigation';
|
||||
import ModalStructured from '$lib/components/ModalStructured.svelte';
|
||||
import FiltrosStock from './FiltrosStock.svelte';
|
||||
import TablaStock from './TablaStock.svelte';
|
||||
@@ -24,8 +13,7 @@
|
||||
import IngresarStockForm from './IngresarStockForm.svelte';
|
||||
import DevolucionStockForm from './DevolucionStockForm.svelte';
|
||||
import { formatearCantidad } from './formatoCantidad';
|
||||
import { liberarReserva } from '$lib/hooks/stock/liberarReserva';
|
||||
import type { Almacen, Cliente, ReservaStock, StockItem } from '../../types';
|
||||
import type { Almacen, Cliente, StockItem } from '../../types';
|
||||
|
||||
let { data } = $props();
|
||||
|
||||
@@ -38,7 +26,6 @@
|
||||
let stock = $derived<StockItem[]>(Array.isArray(data.stock) ? data.stock : []);
|
||||
let almacenes = $derived<Almacen[]>(Array.isArray(data.almacenes) ? data.almacenes : []);
|
||||
let clientes = $derived<Cliente[]>(Array.isArray(data.clientes) ? data.clientes : []);
|
||||
let reservas = $derived<ReservaStock[]>(Array.isArray(data.reservas) ? data.reservas : []);
|
||||
let filtros = $derived(data.filtros ?? { q: '', almacenId: 0, estado: '' });
|
||||
let cargando = $derived(data.stock === undefined || data.stock === null);
|
||||
|
||||
@@ -92,21 +79,6 @@
|
||||
};
|
||||
openInfo = true;
|
||||
}
|
||||
|
||||
async function liberar(r: ReservaStock) {
|
||||
const res = await liberarReserva(r.ID);
|
||||
if (typeof res === 'string') {
|
||||
error = res;
|
||||
return;
|
||||
}
|
||||
await invalidate('stock:load');
|
||||
}
|
||||
|
||||
function fecha(v?: string) {
|
||||
if (!v) return '-';
|
||||
const d = new Date(v);
|
||||
return Number.isNaN(d.getTime()) ? '-' : d.toLocaleDateString();
|
||||
}
|
||||
</script>
|
||||
|
||||
<Header />
|
||||
@@ -121,6 +93,7 @@
|
||||
<Button kind="tertiary" icon={Return} onclick={() => (openDevolucion = true)}>
|
||||
Registrar Devolución
|
||||
</Button>
|
||||
<Button kind="tertiary" icon={Time} onclick={() => goto('/stock/reservas')}>Reservas</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -154,54 +127,6 @@
|
||||
onVer={verRegistro}
|
||||
/>
|
||||
{/if}
|
||||
|
||||
{#if data.reservasError}
|
||||
<InlineNotification
|
||||
kind="error"
|
||||
title="Reservas"
|
||||
subtitle={data.reservasError}
|
||||
hideCloseButton
|
||||
/>
|
||||
{/if}
|
||||
|
||||
{#if !cargando}
|
||||
<TableContainer title="Reservas activas">
|
||||
<Table>
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
<TableHeader>Repuesto</TableHeader>
|
||||
<TableHeader>Almacén</TableHeader>
|
||||
<TableHeader>Cantidad</TableHeader>
|
||||
<TableHeader>Cliente</TableHeader>
|
||||
<TableHeader>Vencimiento</TableHeader>
|
||||
<TableHeader>Acciones</TableHeader>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
{#if reservas.length === 0}
|
||||
<TableRow>
|
||||
<TableCell colspan={6}>No hay reservas activas.</TableCell>
|
||||
</TableRow>
|
||||
{:else}
|
||||
{#each reservas as r (r.ID)}
|
||||
<TableRow>
|
||||
<TableCell>{r.repuesto?.nombre ?? r.repuesto_id}</TableCell>
|
||||
<TableCell>{r.almacen?.codigo ?? r.almacen_id}</TableCell>
|
||||
<TableCell>{formatearCantidad(r.cantidad)}</TableCell>
|
||||
<TableCell>{r.cliente?.nombre ?? '-'}</TableCell>
|
||||
<TableCell>{fecha(r.fecha_vencimiento)}</TableCell>
|
||||
<TableCell class="acciones-cell">
|
||||
<Button kind="ghost" size="small" icon={Play} onclick={() => liberar(r)}>
|
||||
Liberar
|
||||
</Button>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
{/each}
|
||||
{/if}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</TableContainer>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<IngresarStockForm bind:open={openIngreso} {almacenes} onClose={() => (openIngreso = false)} />
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { obtenerStock } from '$lib/hooks/stock/obtenerStock';
|
||||
import { obtenerAlmacenes } from '$lib/hooks/almacenes/obtenerAlmacenes';
|
||||
import { obtenerClientes } from '$lib/hooks/clientes/obtenerClientes';
|
||||
import { obtenerReservas } from '$lib/hooks/stock/obtenerReservas';
|
||||
|
||||
export let ssr = false;
|
||||
|
||||
@@ -15,19 +14,16 @@ export async function load({ fetch, depends, url }) {
|
||||
estado: url.searchParams.get('estado') ?? ''
|
||||
};
|
||||
|
||||
const [stock, almacenes, clientes, reservas] = await Promise.all([
|
||||
const [stock, almacenes, clientes] = await Promise.all([
|
||||
obtenerStock(fetch, filtros),
|
||||
obtenerAlmacenes(fetch),
|
||||
obtenerClientes(fetch),
|
||||
obtenerReservas(fetch)
|
||||
obtenerClientes(fetch)
|
||||
]);
|
||||
|
||||
return {
|
||||
stock,
|
||||
almacenes: Array.isArray(almacenes) ? almacenes : [],
|
||||
clientes: Array.isArray(clientes) ? clientes : [],
|
||||
reservas: Array.isArray(reservas) ? reservas : [],
|
||||
reservasError: typeof reservas === 'string' ? reservas : '',
|
||||
error: typeof stock === 'string' ? stock : '',
|
||||
filtros
|
||||
};
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
<script lang="ts">
|
||||
import Header from '$lib/components/Header.svelte';
|
||||
import { Button, DataTableSkeleton, InlineNotification } from 'carbon-components-svelte';
|
||||
import { Add, ArrowLeft } from 'carbon-icons-svelte';
|
||||
import { goto } from '$app/navigation';
|
||||
import ModalStructured from '$lib/components/ModalStructured.svelte';
|
||||
import FiltrosReservas from './FiltrosReservas.svelte';
|
||||
import TablaReservas from './TablaReservas.svelte';
|
||||
import LiberarReservaForm from './LiberarReservaForm.svelte';
|
||||
import { formatearCantidad } from '../formatoCantidad';
|
||||
import type { Almacen, ReservaStock } from '../../../types';
|
||||
|
||||
let { data } = $props();
|
||||
|
||||
let error = $state('');
|
||||
|
||||
$effect(() => {
|
||||
if (data.error) error = data.error;
|
||||
});
|
||||
|
||||
let reservas = $derived<ReservaStock[]>(Array.isArray(data.reservas) ? data.reservas : []);
|
||||
let almacenes = $derived<Almacen[]>(Array.isArray(data.almacenes) ? data.almacenes : []);
|
||||
let filtros = $derived(data.filtros ?? { q: '', cliente: '', almacenId: 0, estado: '' });
|
||||
let cargando = $derived(data.reservas === undefined || data.reservas === null);
|
||||
|
||||
const headers = [
|
||||
{ key: 'repuesto', value: 'Producto' },
|
||||
{ key: 'descripcion', value: 'Descripción' },
|
||||
{ key: 'almacen', value: 'Almacén' },
|
||||
{ key: 'cantidad', value: 'Cant. reservada' },
|
||||
{ key: 'cliente', value: 'Reservado para' },
|
||||
{ key: 'fecha', value: 'Fecha reserva' },
|
||||
{ key: 'vence', value: 'Vence' },
|
||||
{ key: 'estado', value: 'Estado' }
|
||||
];
|
||||
|
||||
let openInfo = $state(false);
|
||||
let openLiberar = $state(false);
|
||||
let reservaInfo = $state<Record<string, unknown> | null>(null);
|
||||
let reservaLiberar = $state<ReservaStock | null>(null);
|
||||
|
||||
function buscar(f: { q: string; cliente: string; almacenId: number; estado: string }) {
|
||||
const params = new URLSearchParams();
|
||||
if (f.q) params.set('q', f.q);
|
||||
if (f.cliente) params.set('cliente', f.cliente);
|
||||
if (f.almacenId) params.set('almacenId', String(f.almacenId));
|
||||
if (f.estado) params.set('estado', f.estado);
|
||||
const query = params.toString();
|
||||
void goto(`/stock/reservas${query ? `?${query}` : ''}`, { keepFocus: true, noScroll: true });
|
||||
}
|
||||
|
||||
function limpiarFiltros() {
|
||||
void goto('/stock/reservas', { keepFocus: true, noScroll: true });
|
||||
}
|
||||
|
||||
function fecha(valor?: string | null) {
|
||||
if (!valor) return '-';
|
||||
const d = new Date(valor);
|
||||
return Number.isNaN(d.getTime()) ? '-' : d.toLocaleDateString();
|
||||
}
|
||||
|
||||
function ver(reserva: ReservaStock) {
|
||||
reservaInfo = {
|
||||
Producto: reserva.repuesto?.nombre ?? reserva.repuesto_id,
|
||||
Descripción: reserva.repuesto?.descripcion || '-',
|
||||
Almacén: reserva.almacen?.codigo ?? reserva.almacen_id,
|
||||
'Cantidad reservada': formatearCantidad(reserva.cantidad),
|
||||
'Reservado para': reserva.cliente?.nombre ?? '-',
|
||||
'Fecha reserva': fecha(reserva.CreatedAt),
|
||||
Vence: fecha(reserva.fecha_vencimiento),
|
||||
Estado: reserva.estado,
|
||||
Observación: reserva.observacion || '-'
|
||||
};
|
||||
openInfo = true;
|
||||
}
|
||||
</script>
|
||||
|
||||
<Header />
|
||||
|
||||
<div class="page-container">
|
||||
<div class="flex flex-wrap justify-between gap-4">
|
||||
<h1 class="page-title">Reservas de stock</h1>
|
||||
<div class="flex flex-wrap justify-end gap-2">
|
||||
<Button kind="ghost" icon={ArrowLeft} onclick={() => goto('/stock')}>Volver a stock</Button>
|
||||
<Button kind="tertiary" icon={Add} onclick={() => goto('/stock')}>Nueva reserva</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<FiltrosReservas {almacenes} valores={filtros} onBuscar={buscar} onLimpiar={limpiarFiltros} />
|
||||
|
||||
{#if error}
|
||||
<InlineNotification kind="error" title="Error" subtitle={error} hideCloseButton />
|
||||
{/if}
|
||||
|
||||
{#if cargando}
|
||||
<DataTableSkeleton {headers} rows={5} size="compact" showHeader={false} showToolbar={false} />
|
||||
{:else}
|
||||
<TablaReservas
|
||||
{reservas}
|
||||
onVer={ver}
|
||||
onLiberar={(r) => {
|
||||
reservaLiberar = r;
|
||||
openLiberar = true;
|
||||
}}
|
||||
/>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<ModalStructured objeto={reservaInfo} bind:open={openInfo} />
|
||||
|
||||
<LiberarReservaForm
|
||||
bind:open={openLiberar}
|
||||
reserva={reservaLiberar}
|
||||
onClose={() => {
|
||||
openLiberar = false;
|
||||
reservaLiberar = null;
|
||||
}}
|
||||
/>
|
||||
@@ -0,0 +1,28 @@
|
||||
import { obtenerReservas } from '$lib/hooks/stock/obtenerReservas';
|
||||
import { obtenerAlmacenes } from '$lib/hooks/almacenes/obtenerAlmacenes';
|
||||
|
||||
export let ssr = false;
|
||||
|
||||
export async function load({ fetch, depends, url }) {
|
||||
depends('reservas:load');
|
||||
|
||||
const almacenParam = url.searchParams.get('almacenId');
|
||||
const filtros = {
|
||||
q: url.searchParams.get('q') ?? '',
|
||||
cliente: url.searchParams.get('cliente') ?? '',
|
||||
almacenId: almacenParam ? Number(almacenParam) || undefined : undefined,
|
||||
estado: url.searchParams.get('estado') ?? ''
|
||||
};
|
||||
|
||||
const [reservas, almacenes] = await Promise.all([
|
||||
obtenerReservas(fetch, filtros),
|
||||
obtenerAlmacenes(fetch)
|
||||
]);
|
||||
|
||||
return {
|
||||
reservas,
|
||||
almacenes: Array.isArray(almacenes) ? almacenes : [],
|
||||
error: typeof reservas === 'string' ? reservas : '',
|
||||
filtros
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
<script lang="ts">
|
||||
import { Tag } from 'carbon-components-svelte';
|
||||
|
||||
let { estado = '' } = $props();
|
||||
|
||||
const valor = $derived((estado ?? '').toLowerCase());
|
||||
const etiqueta = $derived(
|
||||
valor === 'activa'
|
||||
? 'Activa'
|
||||
: valor === 'vencida'
|
||||
? 'Vencida'
|
||||
: valor === 'liberada'
|
||||
? 'Liberada'
|
||||
: valor === 'consumida'
|
||||
? 'Consumida'
|
||||
: estado || '-'
|
||||
);
|
||||
</script>
|
||||
|
||||
{#if valor === 'activa'}
|
||||
<Tag type="green">{etiqueta}</Tag>
|
||||
{:else if valor === 'vencida'}
|
||||
<Tag type="magenta">{etiqueta}</Tag>
|
||||
{:else if valor === 'liberada'}
|
||||
<Tag type="gray">{etiqueta}</Tag>
|
||||
{:else}
|
||||
<Tag type="blue">{etiqueta}</Tag>
|
||||
{/if}
|
||||
@@ -0,0 +1,65 @@
|
||||
<script lang="ts">
|
||||
import { Button, Select, SelectItem, TextInput } from 'carbon-components-svelte';
|
||||
import { Close, Search } from 'carbon-icons-svelte';
|
||||
import type { Almacen } from '../../../types';
|
||||
|
||||
let {
|
||||
almacenes = [],
|
||||
valores = { q: '', cliente: '', almacenId: 0, estado: '' },
|
||||
onBuscar,
|
||||
onLimpiar
|
||||
}: {
|
||||
almacenes?: Almacen[];
|
||||
valores?: { q?: string; cliente?: string; almacenId?: number; estado?: string };
|
||||
onBuscar?: (filtros: { q: string; cliente: string; almacenId: number; estado: string }) => void;
|
||||
onLimpiar?: () => void;
|
||||
} = $props();
|
||||
|
||||
let q = $state('');
|
||||
let cliente = $state('');
|
||||
let almacenId = $state<number>(0);
|
||||
let estado = $state('');
|
||||
|
||||
$effect(() => {
|
||||
q = valores.q ?? '';
|
||||
cliente = valores.cliente ?? '';
|
||||
almacenId = valores.almacenId ?? 0;
|
||||
estado = valores.estado ?? '';
|
||||
});
|
||||
</script>
|
||||
|
||||
<form
|
||||
class="mb-6 flex flex-wrap items-end gap-4"
|
||||
onsubmit={(e) => {
|
||||
e.preventDefault();
|
||||
onBuscar?.({ q, cliente, almacenId: Number(almacenId) || 0, estado });
|
||||
}}
|
||||
>
|
||||
<div class="min-w-60 flex-1">
|
||||
<TextInput labelText="Buscar producto" placeholder="Nombre o descripción" bind:value={q} />
|
||||
</div>
|
||||
|
||||
<div class="min-w-60 flex-1">
|
||||
<TextInput labelText="Cliente" placeholder="Buscar nombre del cliente" bind:value={cliente} />
|
||||
</div>
|
||||
|
||||
<Select labelText="Almacén" bind:selected={almacenId}>
|
||||
<SelectItem value={0} text="Todos los almacenes" />
|
||||
{#each almacenes as a (a.id)}
|
||||
<SelectItem value={a.id} text={a.ubicacion ? `${a.codigo} · ${a.ubicacion}` : a.codigo} />
|
||||
{/each}
|
||||
</Select>
|
||||
|
||||
<Select labelText="Estado" bind:selected={estado}>
|
||||
<SelectItem value="" text="Activas" />
|
||||
<SelectItem value="todas" text="Todas" />
|
||||
<SelectItem value="activa" text="Activa" />
|
||||
<SelectItem value="vencida" text="Vencida" />
|
||||
<SelectItem value="liberada" text="Liberada" />
|
||||
</Select>
|
||||
|
||||
<div class="flex gap-2">
|
||||
<Button type="submit" icon={Search}>Buscar</Button>
|
||||
<Button kind="ghost" icon={Close} onclick={() => onLimpiar?.()}>Limpiar</Button>
|
||||
</div>
|
||||
</form>
|
||||
@@ -0,0 +1,107 @@
|
||||
<script lang="ts">
|
||||
import { InlineNotification, Modal } from 'carbon-components-svelte';
|
||||
import { invalidate } from '$app/navigation';
|
||||
import { liberarReserva } from '$lib/hooks/stock/liberarReserva';
|
||||
import { formatearCantidad } from '../formatoCantidad';
|
||||
import type { ReservaStock } from '../../../types';
|
||||
|
||||
let {
|
||||
open = $bindable(),
|
||||
onClose,
|
||||
reserva = null
|
||||
}: {
|
||||
open?: boolean;
|
||||
onClose?: () => void;
|
||||
reserva?: ReservaStock | null;
|
||||
} = $props();
|
||||
|
||||
let error = $state('');
|
||||
let enviando = $state(false);
|
||||
|
||||
$effect(() => {
|
||||
if (open) {
|
||||
error = '';
|
||||
enviando = false;
|
||||
}
|
||||
});
|
||||
|
||||
function handleClose() {
|
||||
onClose?.();
|
||||
}
|
||||
|
||||
function fecha(valor?: string | null) {
|
||||
if (!valor) return '-';
|
||||
const d = new Date(valor);
|
||||
return Number.isNaN(d.getTime()) ? '-' : d.toLocaleDateString();
|
||||
}
|
||||
|
||||
async function confirmar() {
|
||||
if (enviando || !reserva) return;
|
||||
enviando = true;
|
||||
error = '';
|
||||
|
||||
const res = await liberarReserva(reserva.ID);
|
||||
if (typeof res === 'string') {
|
||||
error = res;
|
||||
} else {
|
||||
await invalidate('reservas:load');
|
||||
handleClose();
|
||||
}
|
||||
enviando = false;
|
||||
}
|
||||
</script>
|
||||
|
||||
<form
|
||||
id="liberarReservaForm"
|
||||
onsubmit={(e) => {
|
||||
e.preventDefault();
|
||||
void confirmar();
|
||||
}}
|
||||
>
|
||||
<Modal
|
||||
formId="liberarReservaForm"
|
||||
bind:open
|
||||
size="sm"
|
||||
modalHeading="Liberar reserva"
|
||||
primaryButtonText="Confirmar liberación"
|
||||
primaryButtonDisabled={enviando}
|
||||
secondaryButtonText="Cancelar"
|
||||
on:click:button--secondary={handleClose}
|
||||
>
|
||||
{#if error}
|
||||
<div class="mb-4">
|
||||
<InlineNotification kind="error" title="Error" subtitle={error} hideCloseButton />
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="mb-4 grid grid-cols-1 gap-3">
|
||||
<div>
|
||||
<p class="text-sm text-gray-400">Producto</p>
|
||||
<p class="font-semibold">{reserva?.repuesto?.nombre ?? reserva?.repuesto_id ?? '-'}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p class="text-sm text-gray-400">Cantidad reservada</p>
|
||||
<p class="font-semibold">{formatearCantidad(reserva?.cantidad ?? 0)}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p class="text-sm text-gray-400">Reservado para</p>
|
||||
<p class="font-semibold">{reserva?.cliente?.nombre ?? '-'}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p class="text-sm text-gray-400">Fecha de reserva</p>
|
||||
<p class="font-semibold">{fecha(reserva?.CreatedAt)}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p class="text-sm text-gray-400">Vence</p>
|
||||
<p class="font-semibold">{fecha(reserva?.fecha_vencimiento)}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<InlineNotification
|
||||
kind="warning"
|
||||
title="Atención"
|
||||
subtitle="Esta acción liberará el stock reservado y quedará disponible nuevamente para la venta."
|
||||
hideCloseButton
|
||||
/>
|
||||
</Modal>
|
||||
</form>
|
||||
@@ -0,0 +1,88 @@
|
||||
<script lang="ts">
|
||||
import {
|
||||
Button,
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableContainer,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow
|
||||
} from 'carbon-components-svelte';
|
||||
import { Information, Play } from 'carbon-icons-svelte';
|
||||
import EstadoReservaTag from './EstadoReservaTag.svelte';
|
||||
import { formatearCantidad } from '../formatoCantidad';
|
||||
import type { ReservaStock } from '../../../types';
|
||||
|
||||
let {
|
||||
reservas = [],
|
||||
onVer,
|
||||
onLiberar
|
||||
}: {
|
||||
reservas?: ReservaStock[];
|
||||
onVer?: (r: ReservaStock) => void;
|
||||
onLiberar?: (r: ReservaStock) => void;
|
||||
} = $props();
|
||||
|
||||
function fecha(valor?: string | null) {
|
||||
if (!valor) return '-';
|
||||
const d = new Date(valor);
|
||||
return Number.isNaN(d.getTime()) ? '-' : d.toLocaleDateString();
|
||||
}
|
||||
|
||||
function activa(reserva: ReservaStock) {
|
||||
return (reserva.estado ?? '').toLowerCase() === 'activa';
|
||||
}
|
||||
</script>
|
||||
|
||||
<TableContainer title="Reservas de stock">
|
||||
<Table>
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
<TableHeader>Producto</TableHeader>
|
||||
<TableHeader>Descripción</TableHeader>
|
||||
<TableHeader>Almacén</TableHeader>
|
||||
<TableHeader>Cant. reservada</TableHeader>
|
||||
<TableHeader>Reservado para</TableHeader>
|
||||
<TableHeader>Fecha reserva</TableHeader>
|
||||
<TableHeader>Vence</TableHeader>
|
||||
<TableHeader>Estado</TableHeader>
|
||||
<TableHeader>Acciones</TableHeader>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
{#if reservas.length === 0}
|
||||
<TableRow>
|
||||
<TableCell colspan={9}>
|
||||
No hay reservas para mostrar con los filtros seleccionados.
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
{:else}
|
||||
{#each reservas as r (r.ID)}
|
||||
<TableRow>
|
||||
<TableCell>{r.repuesto?.nombre ?? r.repuesto_id}</TableCell>
|
||||
<TableCell title={r.repuesto?.descripcion ?? ''}
|
||||
>{r.repuesto?.descripcion || '-'}</TableCell
|
||||
>
|
||||
<TableCell>{r.almacen?.codigo ?? r.almacen_id}</TableCell>
|
||||
<TableCell>{formatearCantidad(r.cantidad)}</TableCell>
|
||||
<TableCell>{r.cliente?.nombre ?? '-'}</TableCell>
|
||||
<TableCell>{fecha(r.CreatedAt)}</TableCell>
|
||||
<TableCell>{fecha(r.fecha_vencimiento)}</TableCell>
|
||||
<TableCell><EstadoReservaTag estado={r.estado} /></TableCell>
|
||||
<TableCell>
|
||||
<Button kind="ghost" size="small" icon={Information} onclick={() => onVer?.(r)}>
|
||||
Ver
|
||||
</Button>
|
||||
{#if activa(r)}
|
||||
<Button kind="ghost" size="small" icon={Play} onclick={() => onLiberar?.(r)}>
|
||||
Liberar
|
||||
</Button>
|
||||
{/if}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
{/each}
|
||||
{/if}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</TableContainer>
|
||||
Reference in new issue
Block a user