Private
Public Access
hecho poder ver la cantidad de stock disponible
Signed-off-by: fede <federico.nicolas.polidoro@gmail.com>
This commit is contained in:
1 parent
09830e15ec
commit
6ffc398b19
8 files changed
+214
-14
No files matched your search
@@ -0,0 +1,54 @@
|
||||
package factura
|
||||
|
||||
import (
|
||||
"math"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
dto "repuestera_back/dto/Facturas"
|
||||
r "repuestera_back/repositorios"
|
||||
)
|
||||
|
||||
// ObtenerStockDisponible devuelve por repuesto y almacén cuánto stock se puede
|
||||
// vender. Se usa en el alta de factura para mostrar la disponibilidad antes de
|
||||
// vender. Si no se pasa almacenId, devuelve el stock de toda la empresa.
|
||||
func ObtenerStockDisponible(c *gin.Context) {
|
||||
almacenID := uint(0)
|
||||
if raw := c.Query("almacenId"); raw != "" {
|
||||
id, err := strconv.ParseUint(raw, 10, 64)
|
||||
if err != nil || id == 0 {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "almacenId inválido"})
|
||||
return
|
||||
}
|
||||
almacenID = uint(id)
|
||||
}
|
||||
|
||||
stocks, err := r.ObtenerRepositorios(c).Stock.ListarStockPorAlmacen(almacenID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
respuesta := make([]dto.StockDisponibleResponse, 0, len(stocks))
|
||||
for _, stock := range stocks {
|
||||
disponible := stock.Cantidad - stock.CantidadReservada
|
||||
if disponible < 0 {
|
||||
disponible = 0
|
||||
}
|
||||
respuesta = append(respuesta, dto.StockDisponibleResponse{
|
||||
RepuestoID: stock.RepuestoID,
|
||||
AlmacenID: stock.AlmacenID,
|
||||
Cantidad: redondearStock(stock.Cantidad),
|
||||
CantidadReservada: redondearStock(stock.CantidadReservada),
|
||||
Disponible: redondearStock(disponible),
|
||||
})
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, respuesta)
|
||||
}
|
||||
|
||||
func redondearStock(valor float64) float64 {
|
||||
return math.Round(valor*1000) / 1000
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package dto
|
||||
|
||||
// StockDisponible resume, por repuesto y almacén, cuántas unidades se pueden
|
||||
// vender (cantidad menos las reservadas). Es la información que muestra el
|
||||
// alta de factura para avisar cuánto stock hay antes de vender.
|
||||
type StockDisponibleResponse struct {
|
||||
RepuestoID uint64 `json:"repuestoId"`
|
||||
AlmacenID uint `json:"almacenId"`
|
||||
Cantidad float64 `json:"cantidad"`
|
||||
CantidadReservada float64 `json:"cantidadReservada"`
|
||||
Disponible float64 `json:"disponible"`
|
||||
}
|
||||
@@ -23,6 +23,7 @@ type FiltrosStock struct {
|
||||
type RepositorioStock interface {
|
||||
IRepositorio[models.Stock]
|
||||
Listar(filtros FiltrosStock) ([]models.Stock, error)
|
||||
ListarStockPorAlmacen(almacenID uint) ([]models.Stock, error)
|
||||
ObtenerPorRepuestoAlmacen(repuestoID uint64, almacenID uint) (*models.Stock, error)
|
||||
BuscarPorRepuestoAlmacen(tx *gorm.DB, repuestoID uint64, almacenID uint) (*models.Stock, error)
|
||||
BloquearOCrearPorRepuestoAlmacen(tx *gorm.DB, repuestoID uint64, almacenID uint) (*models.Stock, error)
|
||||
@@ -85,6 +86,25 @@ func (r *repositorioStock) Listar(filtros FiltrosStock) ([]models.Stock, error)
|
||||
return stocks, nil
|
||||
}
|
||||
|
||||
// ListarStockPorAlmacen devuelve todas las filas de stock de un almacén (o de
|
||||
// toda la empresa si almacenID es 0) sin paginar. Lo usamos para mostrar la
|
||||
// disponibilidad al armar una factura, donde hay que conocer todos los
|
||||
// repuestos y no sólo una página.
|
||||
func (r *repositorioStock) ListarStockPorAlmacen(almacenID uint) ([]models.Stock, error) {
|
||||
query := r.db.
|
||||
Select("stock.id", "stock.repuesto_id", "stock.almacen_id", "stock.cantidad", "stock.cantidad_reservada").
|
||||
Order("stock.repuesto_id ASC")
|
||||
if almacenID > 0 {
|
||||
query = query.Where("stock.almacen_id = ?", almacenID)
|
||||
}
|
||||
|
||||
var stocks []models.Stock
|
||||
if err := query.Find(&stocks).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return stocks, nil
|
||||
}
|
||||
|
||||
func (r *repositorioStock) ObtenerPorRepuestoAlmacen(repuestoID uint64, almacenID uint) (*models.Stock, error) {
|
||||
var stock models.Stock
|
||||
if err := r.db.
|
||||
|
||||
@@ -14,6 +14,7 @@ func FacturaRoute(r *gin.Engine) {
|
||||
grupo.Use(middleware.AuthMiddleware(9, 15))
|
||||
{
|
||||
grupo.GET("/", factura.ObtenerFacturas)
|
||||
grupo.GET("/stock-disponible", factura.ObtenerStockDisponible)
|
||||
grupo.GET("/:id", factura.ObtenerFactura)
|
||||
grupo.GET("/:id/comprobante", factura.ObtenerComprobante)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import { API_URL } from '$lib/env';
|
||||
import type { StockDisponible } from '../../../types';
|
||||
import { getToken } from '../token';
|
||||
|
||||
export async function obtenerStockDisponible(
|
||||
fetch2?: Function,
|
||||
almacenid: number = 0
|
||||
): Promise<StockDisponible[] | string> {
|
||||
const fetchfn = fetch2 ? fetch2 : fetch;
|
||||
try {
|
||||
const params = new URLSearchParams();
|
||||
if (!almacenid) return 'No se especifico almacen';
|
||||
params.append('almacenId', String(almacenid));
|
||||
|
||||
const req = await fetchfn(`${API_URL}/facturas/stock-disponible?${params.toString()}`, {
|
||||
method: 'GET',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${getToken()}` }
|
||||
});
|
||||
const data = await req.json();
|
||||
if (req.ok) return data;
|
||||
return data.error ?? 'No se pudieron obtener los datos';
|
||||
} catch {
|
||||
return 'No se pudo alcanzar el servidor';
|
||||
}
|
||||
}
|
||||
@@ -12,8 +12,10 @@
|
||||
import { Add, TrashCan, ArrowLeft, Search } from 'carbon-icons-svelte';
|
||||
import { goto, invalidate } from '$app/navigation';
|
||||
import { crearFactura } from '$lib/hooks/facturas/crearFactura';
|
||||
import { obtenerStockDisponible } from '$lib/hooks/almacenes/obtenerStockDisponible';
|
||||
import StockDisponibleCampo from './StockDisponibleCampo.svelte';
|
||||
import ModalBuscarCliente from './ModalBuscarCliente.svelte';
|
||||
import type { Cliente, Repuesto, Almacen } from '../../../types';
|
||||
import type { Cliente, Repuesto, Almacen, StockDisponible } from '../../../types';
|
||||
|
||||
let { data } = $props();
|
||||
|
||||
@@ -32,6 +34,8 @@
|
||||
|
||||
let clienteId = $state<number>(0);
|
||||
let almacenId = $state<number>(0);
|
||||
let stockPorRepuesto = $state<Record<number, number>>({});
|
||||
let stockCargado = $state(false);
|
||||
let descuentoId = $state<number>(0);
|
||||
let enviarEmail = $state(false);
|
||||
let observacion = $state('');
|
||||
@@ -50,6 +54,40 @@
|
||||
|
||||
let modalClienteAbierto = $state(false);
|
||||
|
||||
$effect(() => {
|
||||
const id = almacenId;
|
||||
if (!id) {
|
||||
stockPorRepuesto = {};
|
||||
stockCargado = false;
|
||||
return;
|
||||
}
|
||||
stockCargado = false;
|
||||
let cancelado = false;
|
||||
obtenerStockDisponible(fetch, id).then((res) => {
|
||||
if (cancelado) return;
|
||||
if (Array.isArray(res)) {
|
||||
const mapa: Record<number, number> = {};
|
||||
for (const s of res as StockDisponible[]) {
|
||||
mapa[Number(s.repuestoId)] = s.disponible;
|
||||
}
|
||||
stockPorRepuesto = mapa;
|
||||
stockCargado = true;
|
||||
} else {
|
||||
stockPorRepuesto = {};
|
||||
stockCargado = true;
|
||||
}
|
||||
});
|
||||
return () => {
|
||||
cancelado = true;
|
||||
};
|
||||
});
|
||||
|
||||
function stockDisponible(repuestoId: number): number | null {
|
||||
if (!almacenId || repuestoId <= 0) return null;
|
||||
if (!stockCargado) return null;
|
||||
return stockPorRepuesto[repuestoId] ?? 0;
|
||||
}
|
||||
|
||||
let clienteSeleccionado = $derived(clientes.find((c) => c.ID === clienteId));
|
||||
|
||||
const itemHeaders = [
|
||||
@@ -57,6 +95,7 @@
|
||||
{ key: 'cantidad', value: 'Cantidad', empty: false },
|
||||
{ key: 'precioUnitario', value: 'Precio Unit.', empty: false },
|
||||
{ key: 'subtotal', value: 'Subtotal', empty: false },
|
||||
{ key: 'stock', value: 'Stock disp.', empty: false },
|
||||
{ key: 'acciones', value: '', empty: false }
|
||||
];
|
||||
|
||||
@@ -196,10 +235,14 @@
|
||||
hideLabel
|
||||
readonly
|
||||
placeholder="Sin cliente seleccionado"
|
||||
value={clienteSeleccionado ? `${clienteSeleccionado.nombre} (${clienteSeleccionado.cuit ?? ''})` : ''}
|
||||
class="min-w-64 flex-1 border-none focus:ring-0 focus:border-transparent bg-transparent px-3 py-2 text-sm"
|
||||
value={clienteSeleccionado
|
||||
? `${clienteSeleccionado.nombre} (${clienteSeleccionado.cuit ?? ''})`
|
||||
: ''}
|
||||
class="min-w-64 flex-1 border-none bg-transparent px-3 py-2 text-sm focus:border-transparent focus:ring-0"
|
||||
/>
|
||||
<Button size="small" icon={Search} onclick={() => (modalClienteAbierto = true)}>Buscar Cliente</Button>
|
||||
<Button size="small" icon={Search} onclick={() => (modalClienteAbierto = true)}
|
||||
>Buscar Cliente</Button
|
||||
>
|
||||
<Button size="small" kind="secondary" onclick={clienteDefault}>Cliente Default</Button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -210,7 +253,7 @@
|
||||
hideLabel
|
||||
readonly
|
||||
value={clienteSeleccionado?.email ?? '-'}
|
||||
class="border-none focus:ring-0 focus:border-transparent bg-transparent px-3 py-2 text-sm"
|
||||
class="border-none bg-transparent px-3 py-2 text-sm focus:border-transparent focus:ring-0"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
@@ -219,7 +262,7 @@
|
||||
hideLabel
|
||||
readonly
|
||||
value={clienteSeleccionado?.cuit ?? '-'}
|
||||
class="border-none focus:ring-0 focus:border-transparent bg-transparent px-3 py-2 text-sm"
|
||||
class="border-none bg-transparent px-3 py-2 text-sm focus:border-transparent focus:ring-0"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
@@ -256,11 +299,28 @@
|
||||
{:else if cell.key === 'cantidad'}
|
||||
<NumberInput hideLabel bind:value={row.cantidad} min={0} step={1} class="w-full" />
|
||||
{:else if cell.key === 'precioUnitario'}
|
||||
<TextInput hideLabel readonly value={formatMonto(precioRepuesto(row.repuestoId))} class="w-full text-right" />
|
||||
<TextInput
|
||||
hideLabel
|
||||
readonly
|
||||
value={formatMonto(precioRepuesto(row.repuestoId))}
|
||||
class="w-full text-right"
|
||||
/>
|
||||
{:else if cell.key === 'subtotal'}
|
||||
<TextInput hideLabel readonly value={formatMonto(row.cantidad * precioRepuesto(row.repuestoId))} class="w-full text-right" />
|
||||
<TextInput
|
||||
hideLabel
|
||||
readonly
|
||||
value={formatMonto(row.cantidad * precioRepuesto(row.repuestoId))}
|
||||
class="w-full text-right"
|
||||
/>
|
||||
{:else if cell.key === 'stock'}
|
||||
<StockDisponibleCampo value={stockDisponible(row.repuestoId)} />
|
||||
{:else if cell.key === 'acciones'}
|
||||
<Button kind="danger-ghost" size="small" icon={TrashCan} onclick={() => quitarItem(row.id)} />
|
||||
<Button
|
||||
kind="danger-ghost"
|
||||
size="small"
|
||||
icon={TrashCan}
|
||||
onclick={() => quitarItem(row.id)}
|
||||
/>
|
||||
{/if}
|
||||
</svelte:fragment>
|
||||
</DataTable>
|
||||
@@ -275,16 +335,27 @@
|
||||
<Select hideLabel labelText="Descuento" bind:selected={descuentoId}>
|
||||
<SelectItem value={0} text="Sin descuento" />
|
||||
{#each descuentos as d (d.ID)}
|
||||
<SelectItem value={d.ID} text={`${d.nombre} (${d.tipo === 'PORCENTAJE' ? d.valor + '%' : '$' + d.valor})`} />
|
||||
<SelectItem
|
||||
value={d.ID}
|
||||
text={`${d.nombre} (${d.tipo === 'PORCENTAJE' ? d.valor + '%' : '$' + d.valor})`}
|
||||
/>
|
||||
{/each}
|
||||
</Select>
|
||||
</div>
|
||||
<div class="flex flex-col justify-end">
|
||||
<div class="space-y-1 text-sm">
|
||||
<div class="flex justify-between"><span>Subtotal</span><span>{formatMonto(subtotal)}</span></div>
|
||||
<div class="flex justify-between"><span>Descuento</span><span>{formatMonto(descuentoTotal)}</span></div>
|
||||
<div class="flex justify-between"><span>IVA (21%)</span><span>{formatMonto(impuestos)}</span></div>
|
||||
<div class="flex justify-between text-lg font-bold"><span>Total</span><span>{formatMonto(total)}</span></div>
|
||||
<div class="flex justify-between">
|
||||
<span>Subtotal</span><span>{formatMonto(subtotal)}</span>
|
||||
</div>
|
||||
<div class="flex justify-between">
|
||||
<span>Descuento</span><span>{formatMonto(descuentoTotal)}</span>
|
||||
</div>
|
||||
<div class="flex justify-between">
|
||||
<span>IVA (21%)</span><span>{formatMonto(impuestos)}</span>
|
||||
</div>
|
||||
<div class="flex justify-between text-lg font-bold">
|
||||
<span>Total</span><span>{formatMonto(total)}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
<script lang="ts">
|
||||
import { TextInput } from 'carbon-components-svelte';
|
||||
|
||||
let { value = null }: { value?: number | null } = $props();
|
||||
|
||||
let display = $derived(value == null ? '-' : Number(value).toLocaleString('es-AR'));
|
||||
</script>
|
||||
|
||||
<TextInput hideLabel readonly value={display} class="w-full text-right" />
|
||||
Vendored
+8
@@ -247,6 +247,14 @@ export interface StockItem {
|
||||
DeletedAt?: string | null;
|
||||
}
|
||||
|
||||
export interface StockDisponible {
|
||||
repuestoId: number;
|
||||
almacenId: number;
|
||||
cantidad: number;
|
||||
cantidadReservada: number;
|
||||
disponible: number;
|
||||
}
|
||||
|
||||
export interface Cliente {
|
||||
ID: number;
|
||||
CreatedAt?: string;
|
||||
|
||||
Reference in new issue
Block a user