Private
Public Access
hecho para poder cargar una reserva desde el facturas venta
Signed-off-by: fede <federico.nicolas.polidoro@gmail.com>
This commit is contained in:
1 parent
1073c69d5c
commit
ab59bd7043
20 files changed
+293
-90
No files matched your search
@@ -5,7 +5,6 @@ import (
|
||||
"strings"
|
||||
|
||||
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||
models_seguridad "repuestera_back/models/seguridad"
|
||||
r "repuestera_back/repositorios"
|
||||
"repuestera_back/utils"
|
||||
|
||||
@@ -14,9 +13,10 @@ import (
|
||||
|
||||
func ActualizarEmpresa(c *gin.Context) {
|
||||
var req struct {
|
||||
Nombre string `json:"nombre"`
|
||||
Slug string `json:"slug"`
|
||||
Cuit string `json:"cuit"`
|
||||
Nombre string `json:"nombre"`
|
||||
Slug string `json:"slug"`
|
||||
Cuit string `json:"cuit"`
|
||||
EmailAlertaStock *[]string `json:"email_alerta_stock"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
@@ -30,10 +30,28 @@ func ActualizarEmpresa(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
input := models_seguridad.Empresa{Nombre: strings.TrimSpace(req.Nombre), Slug: strings.TrimSpace(req.Slug)}
|
||||
if req.Cuit != "" {
|
||||
if strings.TrimSpace(req.Nombre) != "" {
|
||||
empresa.Nombre = strings.TrimSpace(req.Nombre)
|
||||
}
|
||||
if strings.TrimSpace(req.Slug) != "" {
|
||||
empresa.Slug = strings.TrimSpace(req.Slug)
|
||||
}
|
||||
if strings.TrimSpace(req.Cuit) != "" {
|
||||
cuit := strings.TrimSpace(req.Cuit)
|
||||
input.Cuit = &cuit
|
||||
empresa.Cuit = &cuit
|
||||
}
|
||||
if req.EmailAlertaStock != nil {
|
||||
limpios := make([]string, 0, len(*req.EmailAlertaStock))
|
||||
vistos := make(map[string]bool)
|
||||
for _, email := range *req.EmailAlertaStock {
|
||||
email = strings.TrimSpace(email)
|
||||
if email == "" || vistos[email] {
|
||||
continue
|
||||
}
|
||||
vistos[email] = true
|
||||
limpios = append(limpios, email)
|
||||
}
|
||||
empresa.EmailAlertaStock = limpios
|
||||
}
|
||||
|
||||
if err := repo.Empresa.Actualizar(empresa, input); err != nil {
|
||||
|
||||
@@ -18,10 +18,11 @@ func ActualizarEmpresa(c *gin.Context) {
|
||||
}
|
||||
|
||||
var req struct {
|
||||
Nombre string `json:"nombre"`
|
||||
Slug string `json:"slug"`
|
||||
Cuit *string `json:"cuit"`
|
||||
Activa *bool `json:"activa"`
|
||||
Nombre string `json:"nombre"`
|
||||
Slug string `json:"slug"`
|
||||
Cuit *string `json:"cuit"`
|
||||
EmailAlertaStock *[]string `json:"email_alerta_stock"`
|
||||
Activa *bool `json:"activa"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
@@ -49,6 +50,19 @@ func ActualizarEmpresa(c *gin.Context) {
|
||||
empresa.Cuit = &cuit
|
||||
}
|
||||
}
|
||||
if req.EmailAlertaStock != nil {
|
||||
limpios := make([]string, 0, len(*req.EmailAlertaStock))
|
||||
vistos := make(map[string]bool)
|
||||
for _, email := range *req.EmailAlertaStock {
|
||||
email = strings.TrimSpace(email)
|
||||
if email == "" || vistos[email] {
|
||||
continue
|
||||
}
|
||||
vistos[email] = true
|
||||
limpios = append(limpios, email)
|
||||
}
|
||||
empresa.EmailAlertaStock = limpios
|
||||
}
|
||||
if req.Activa != nil {
|
||||
empresa.Activa = *req.Activa
|
||||
}
|
||||
|
||||
@@ -16,12 +16,13 @@ import (
|
||||
|
||||
func CrearEmpresa(c *gin.Context) {
|
||||
var req struct {
|
||||
Nombre string `json:"nombre" binding:"required"`
|
||||
Slug string `json:"slug"`
|
||||
Cuit string `json:"cuit"`
|
||||
OwnerEmail string `json:"owner_email" binding:"required,email"`
|
||||
OwnerName string `json:"owner_name"`
|
||||
OwnerPassword string `json:"owner_password"`
|
||||
Nombre string `json:"nombre" binding:"required"`
|
||||
Slug string `json:"slug"`
|
||||
Cuit string `json:"cuit"`
|
||||
EmailAlertaStock []string `json:"email_alerta_stock"`
|
||||
OwnerEmail string `json:"owner_email" binding:"required,email"`
|
||||
OwnerName string `json:"owner_name"`
|
||||
OwnerPassword string `json:"owner_password"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
@@ -82,6 +83,17 @@ func CrearEmpresa(c *gin.Context) {
|
||||
cuit := strings.TrimSpace(req.Cuit)
|
||||
empresa.Cuit = &cuit
|
||||
}
|
||||
limpios := make([]string, 0, len(req.EmailAlertaStock))
|
||||
vistos := make(map[string]bool)
|
||||
for _, email := range req.EmailAlertaStock {
|
||||
email = strings.TrimSpace(email)
|
||||
if email == "" || vistos[email] {
|
||||
continue
|
||||
}
|
||||
vistos[email] = true
|
||||
limpios = append(limpios, email)
|
||||
}
|
||||
empresa.EmailAlertaStock = limpios
|
||||
|
||||
if err := repo.Empresa.Crear(&empresa, owner.ID); err != nil {
|
||||
if creado {
|
||||
|
||||
@@ -85,6 +85,12 @@ func destinatariosAlertaStock(repo *repositorios.Repositorios, empresaID, usuari
|
||||
return limpiarDestinatarios(strings.Split(raw, ","))
|
||||
}
|
||||
|
||||
if empresaID > 0 {
|
||||
if empresa, err := repo.Empresa.ObtenerPorID(empresaID); err == nil && empresa != nil && len(empresa.EmailAlertaStock) > 0 {
|
||||
return limpiarDestinatarios([]string(empresa.EmailAlertaStock))
|
||||
}
|
||||
}
|
||||
|
||||
var destinatarios []string
|
||||
if empresaID > 0 {
|
||||
miembros, _, err := repo.Empresa.ListarMiembros(empresaID, 0, 100)
|
||||
|
||||
@@ -48,12 +48,13 @@ func (b *EmpresaActualResponseBuilder) Build() (*dto.EmpresaActualResponse, erro
|
||||
}
|
||||
|
||||
return &dto.EmpresaActualResponse{
|
||||
ID: b.empresa.ID,
|
||||
Nombre: b.empresa.Nombre,
|
||||
Slug: b.empresa.Slug,
|
||||
Cuit: b.empresa.Cuit,
|
||||
Activa: b.empresa.Activa,
|
||||
Rol: string(b.rol),
|
||||
MiembrosActivos: b.miembros,
|
||||
ID: b.empresa.ID,
|
||||
Nombre: b.empresa.Nombre,
|
||||
Slug: b.empresa.Slug,
|
||||
Cuit: b.empresa.Cuit,
|
||||
EmailAlertaStock: ListaNoNil([]string(b.empresa.EmailAlertaStock)),
|
||||
Activa: b.empresa.Activa,
|
||||
Rol: string(b.rol),
|
||||
MiembrosActivos: b.miembros,
|
||||
}, nil
|
||||
}
|
||||
@@ -48,13 +48,14 @@ func (b *EmpresaAdminResponseBuilder) Build() (*dto.EmpresaAdminResponse, error)
|
||||
}
|
||||
|
||||
return &dto.EmpresaAdminResponse{
|
||||
ID: b.empresa.ID,
|
||||
Nombre: b.empresa.Nombre,
|
||||
Slug: b.empresa.Slug,
|
||||
Cuit: b.empresa.Cuit,
|
||||
Activa: b.empresa.Activa,
|
||||
Miembros: b.miembros,
|
||||
Owners: b.owners,
|
||||
CreatedAt: b.empresa.CreatedAt,
|
||||
ID: b.empresa.ID,
|
||||
Nombre: b.empresa.Nombre,
|
||||
Slug: b.empresa.Slug,
|
||||
Cuit: b.empresa.Cuit,
|
||||
EmailAlertaStock: ListaNoNil([]string(b.empresa.EmailAlertaStock)),
|
||||
Activa: b.empresa.Activa,
|
||||
Miembros: b.miembros,
|
||||
Owners: b.owners,
|
||||
CreatedAt: b.empresa.CreatedAt,
|
||||
}, nil
|
||||
}
|
||||
@@ -36,12 +36,13 @@ func (b *EmpresaResponseBuilder) Build() (*dto.EmpresaResponse, error) {
|
||||
}
|
||||
|
||||
return &dto.EmpresaResponse{
|
||||
ID: b.empresa.ID,
|
||||
Nombre: b.empresa.Nombre,
|
||||
Slug: b.empresa.Slug,
|
||||
Cuit: b.empresa.Cuit,
|
||||
Activa: b.empresa.Activa,
|
||||
CreatedAt: b.empresa.CreatedAt,
|
||||
UpdatedAt: b.empresa.UpdatedAt,
|
||||
ID: b.empresa.ID,
|
||||
Nombre: b.empresa.Nombre,
|
||||
Slug: b.empresa.Slug,
|
||||
Cuit: b.empresa.Cuit,
|
||||
EmailAlertaStock: ListaNoNil([]string(b.empresa.EmailAlertaStock)),
|
||||
Activa: b.empresa.Activa,
|
||||
CreatedAt: b.empresa.CreatedAt,
|
||||
UpdatedAt: b.empresa.UpdatedAt,
|
||||
}, nil
|
||||
}
|
||||
@@ -8,6 +8,7 @@ type CrearFacturaDto struct {
|
||||
Pagos []PagoFacturaDto `json:"pagos"`
|
||||
EnviarEmail bool `json:"enviarEmail"`
|
||||
Observacion string `json:"observacion"`
|
||||
ReservaID uint `json:"reservaId"`
|
||||
}
|
||||
|
||||
type ItemFacturaDto struct {
|
||||
|
||||
@@ -4,24 +4,26 @@ import "time"
|
||||
|
||||
// EmpresaResponse es la representación pública de una empresa.
|
||||
type EmpresaResponse struct {
|
||||
ID uint `json:"id"`
|
||||
Nombre string `json:"nombre"`
|
||||
Slug string `json:"slug"`
|
||||
Cuit *string `json:"cuit,omitempty"`
|
||||
Activa bool `json:"activa"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
ID uint `json:"id"`
|
||||
Nombre string `json:"nombre"`
|
||||
Slug string `json:"slug"`
|
||||
Cuit *string `json:"cuit,omitempty"`
|
||||
EmailAlertaStock []string `json:"email_alerta_stock,omitempty"`
|
||||
Activa bool `json:"activa"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
// EmpresaActualResponse describe la empresa activa de la sesión.
|
||||
type EmpresaActualResponse struct {
|
||||
ID uint `json:"id"`
|
||||
Nombre string `json:"nombre"`
|
||||
Slug string `json:"slug"`
|
||||
Cuit *string `json:"cuit,omitempty"`
|
||||
Activa bool `json:"activa"`
|
||||
Rol string `json:"rol"`
|
||||
MiembrosActivos int64 `json:"miembros_activos"`
|
||||
ID uint `json:"id"`
|
||||
Nombre string `json:"nombre"`
|
||||
Slug string `json:"slug"`
|
||||
Cuit *string `json:"cuit,omitempty"`
|
||||
EmailAlertaStock []string `json:"email_alerta_stock,omitempty"`
|
||||
Activa bool `json:"activa"`
|
||||
Rol string `json:"rol"`
|
||||
MiembrosActivos int64 `json:"miembros_activos"`
|
||||
}
|
||||
|
||||
// EmpresasResponse es el envelope de empresas del usuario.
|
||||
@@ -81,14 +83,15 @@ type InvitacionCreadaResponse struct {
|
||||
|
||||
// EmpresaAdminResponse es la vista de empresa para plataforma.
|
||||
type EmpresaAdminResponse struct {
|
||||
ID uint `json:"id"`
|
||||
Nombre string `json:"nombre"`
|
||||
Slug string `json:"slug"`
|
||||
Cuit *string `json:"cuit,omitempty"`
|
||||
Activa bool `json:"activa"`
|
||||
Miembros int64 `json:"miembros"`
|
||||
Owners int64 `json:"owners"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
ID uint `json:"id"`
|
||||
Nombre string `json:"nombre"`
|
||||
Slug string `json:"slug"`
|
||||
Cuit *string `json:"cuit,omitempty"`
|
||||
EmailAlertaStock []string `json:"email_alerta_stock,omitempty"`
|
||||
Activa bool `json:"activa"`
|
||||
Miembros int64 `json:"miembros"`
|
||||
Owners int64 `json:"owners"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
// EmpresasAdminListadoResponse es el envelope de empresas de plataforma.
|
||||
|
||||
@@ -3,20 +3,22 @@ package models_seguridad
|
||||
import (
|
||||
"time"
|
||||
|
||||
"gorm.io/datatypes"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// Empresa es el tenant del sistema. Todos los datos de negocio pertenecen a
|
||||
// una empresa y se filtran por EmpresaID.
|
||||
type Empresa struct {
|
||||
ID uint `gorm:"primaryKey" json:"id"`
|
||||
Nombre string `gorm:"type:varchar(120);not null" json:"nombre"`
|
||||
Slug string `gorm:"type:varchar(60);uniqueIndex;not null" json:"slug"`
|
||||
Cuit *string `gorm:"type:varchar(11);uniqueIndex" json:"cuit,omitempty"`
|
||||
Activa bool `gorm:"not null;default:true" json:"activa"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
|
||||
ID uint `gorm:"primaryKey" json:"id"`
|
||||
Nombre string `gorm:"type:varchar(120);not null" json:"nombre"`
|
||||
Slug string `gorm:"type:varchar(60);uniqueIndex;not null" json:"slug"`
|
||||
Cuit *string `gorm:"type:varchar(11);uniqueIndex" json:"cuit,omitempty"`
|
||||
EmailAlertaStock datatypes.JSONSlice[string] `gorm:"type:json" json:"email_alerta_stock,omitempty"`
|
||||
Activa bool `gorm:"not null;default:true" json:"activa"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
|
||||
}
|
||||
|
||||
func (Empresa) TableName() string {
|
||||
|
||||
@@ -130,6 +130,9 @@ func (r *repositorioEmpresa) Actualizar(empresa *models_seguridad.Empresa, input
|
||||
if input.Cuit != nil {
|
||||
empresa.Cuit = input.Cuit
|
||||
}
|
||||
if input.EmailAlertaStock != nil {
|
||||
empresa.EmailAlertaStock = input.EmailAlertaStock
|
||||
}
|
||||
return r.db.Save(empresa).Error
|
||||
}
|
||||
|
||||
|
||||
@@ -97,6 +97,28 @@ func CrearFactura(
|
||||
}
|
||||
}
|
||||
|
||||
// Si se factura a partir de una reserva, validarla y consumirla al confirmar.
|
||||
var reserva *models.Reserva
|
||||
if entrada.ReservaID > 0 {
|
||||
r, err := repo.Reserva.ObtenerPorID(entrada.ReservaID)
|
||||
if err != nil || r == nil {
|
||||
return nil, fmt.Errorf("reserva %d no encontrada", entrada.ReservaID)
|
||||
}
|
||||
if r.Estado != models.ReservaActiva {
|
||||
return nil, fmt.Errorf("la reserva %d no está activa", entrada.ReservaID)
|
||||
}
|
||||
if r.AlmacenID != entrada.AlmacenID {
|
||||
return nil, errors.New("la reserva no corresponde al almacén seleccionado")
|
||||
}
|
||||
if r.ClienteID == nil || *r.ClienteID != entrada.ClienteID {
|
||||
return nil, errors.New("la reserva no corresponde al cliente seleccionado")
|
||||
}
|
||||
if len(items) != 1 || items[0].RepuestoID != uint64(r.RepuestoID) || items[0].Cantidad != r.Cantidad {
|
||||
return nil, errors.New("la reserva no corresponde a los ítems de la factura")
|
||||
}
|
||||
reserva = r
|
||||
}
|
||||
|
||||
// Calcular totales.
|
||||
var subtotal float64
|
||||
detalles := make([]models.FacturaDetalle, 0, len(items))
|
||||
@@ -198,6 +220,12 @@ func CrearFactura(
|
||||
stock := stocksPorRepuesto[item.RepuestoID]
|
||||
saldoAnterior := stock.Cantidad
|
||||
stock.Cantidad = redondearCantidad(stock.Cantidad - item.Cantidad)
|
||||
if reserva != nil && item.RepuestoID == uint64(reserva.RepuestoID) {
|
||||
stock.CantidadReservada = redondearCantidad(stock.CantidadReservada - reserva.Cantidad)
|
||||
if stock.CantidadReservada < 0 {
|
||||
stock.CantidadReservada = 0
|
||||
}
|
||||
}
|
||||
if err := repo.Stock.ActualizarCantidades(tx, stock); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -222,6 +250,18 @@ func CrearFactura(
|
||||
stocks = append(stocks, stock)
|
||||
}
|
||||
|
||||
if reserva != nil {
|
||||
resultado := tx.Model(&models.Reserva{}).
|
||||
Where("id = ? AND estado = ?", reserva.ID, models.ReservaActiva).
|
||||
Update("estado", models.ReservaConsumida)
|
||||
if resultado.Error != nil {
|
||||
return resultado.Error
|
||||
}
|
||||
if resultado.RowsAffected == 0 {
|
||||
return errors.New("la reserva ya no está activa")
|
||||
}
|
||||
}
|
||||
|
||||
if err := RegistrarAsientoVenta(tx, repo, factura, subtotal, descuentoTotal, impuestos, total); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -22,6 +22,7 @@ export interface CrearFacturaPayload {
|
||||
pagos?: PagoFacturaPayload[];
|
||||
enviarEmail?: boolean;
|
||||
observacion?: string;
|
||||
reservaId?: number;
|
||||
}
|
||||
|
||||
export async function crearFactura(payload: CrearFacturaPayload) {
|
||||
|
||||
@@ -38,6 +38,7 @@ export async function actualizarEmpresa(dto: {
|
||||
nombre?: string;
|
||||
slug?: string;
|
||||
cuit?: string;
|
||||
email_alerta_stock?: string[];
|
||||
}): Promise<void> {
|
||||
await apiFetch('/empresa', { method: 'PUT', body: dto });
|
||||
}
|
||||
|
||||
@@ -53,7 +53,7 @@ import { agregarGrupoAUsuario } from '$lib/hooks/agregarGrupoAUsuario';
|
||||
let error = $state('');
|
||||
let exito = $state('');
|
||||
|
||||
let formEmpresa = $state({ nombre: '', slug: '', cuit: '' });
|
||||
let formEmpresa = $state({ nombre: '', slug: '', cuit: '', email_alerta_stock: '' });
|
||||
let guardandoEmpresa = $state(false);
|
||||
|
||||
let modalMiembro = $state(false);
|
||||
@@ -102,7 +102,8 @@ import { agregarGrupoAUsuario } from '$lib/hooks/agregarGrupoAUsuario';
|
||||
formEmpresa = {
|
||||
nombre: empresa.nombre,
|
||||
slug: empresa.slug,
|
||||
cuit: empresa.cuit ?? ''
|
||||
cuit: empresa.cuit ?? '',
|
||||
email_alerta_stock: (empresa.email_alerta_stock ?? []).join(', ')
|
||||
};
|
||||
}
|
||||
|
||||
@@ -148,10 +149,15 @@ import { agregarGrupoAUsuario } from '$lib/hooks/agregarGrupoAUsuario';
|
||||
guardandoEmpresa = true;
|
||||
error = '';
|
||||
try {
|
||||
const emails = formEmpresa.email_alerta_stock
|
||||
.split(',')
|
||||
.map((e) => e.trim())
|
||||
.filter((e) => e !== '');
|
||||
await actualizarEmpresa({
|
||||
nombre: formEmpresa.nombre,
|
||||
slug: formEmpresa.slug,
|
||||
cuit: formEmpresa.cuit
|
||||
cuit: formEmpresa.cuit,
|
||||
email_alerta_stock: emails
|
||||
});
|
||||
await cargarEmpresa();
|
||||
aviso('Datos de la empresa actualizados');
|
||||
@@ -380,6 +386,7 @@ import { agregarGrupoAUsuario } from '$lib/hooks/agregarGrupoAUsuario';
|
||||
<TextInput bind:value={formEmpresa.nombre} labelText="Nombre" />
|
||||
<TextInput bind:value={formEmpresa.slug} labelText="Identificador (slug)" />
|
||||
<TextInput bind:value={formEmpresa.cuit} labelText="CUIT" />
|
||||
<TextInput bind:value={formEmpresa.email_alerta_stock} labelText="Emails de alerta de stock (separados por coma)" />
|
||||
</div>
|
||||
<Button class="mt-4" disabled={guardandoEmpresa} onclick={guardarEmpresa}>
|
||||
{guardandoEmpresa ? 'Guardando...' : 'Guardar datos'}
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
TableRow,
|
||||
Tag
|
||||
} from 'carbon-components-svelte';
|
||||
import { Download, Email } from 'carbon-icons-svelte';
|
||||
import { Download, Email, Inspection } from 'carbon-icons-svelte';
|
||||
import { obtenerComprobante, enviarEmailComprobante } from '$lib/hooks/facturas/comprobante';
|
||||
import type { ComprobanteResponse, PagoResumen } from '../../types';
|
||||
|
||||
@@ -69,9 +69,7 @@
|
||||
}
|
||||
}
|
||||
|
||||
function nombreRepuesto(d: { repuestoId: number; nombre?: string }): string {
|
||||
return d.nombre ?? `Repuesto ${d.repuestoId}`;
|
||||
}
|
||||
|
||||
|
||||
$effect(() => {
|
||||
if (!open) {
|
||||
@@ -195,10 +193,10 @@
|
||||
<TableHeader>Subtotal</TableHeader>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
<TableBody>{$inspect(comprobante)}
|
||||
{#each comprobante.detalles as d}
|
||||
<TableRow>
|
||||
<TableCell>{nombreRepuesto(d)}</TableCell>
|
||||
<TableCell>{`Repuesto ${d.repuestoId}`}</TableCell>
|
||||
<TableCell class="text-right">{d.cantidad}</TableCell>
|
||||
<TableCell class="text-right">{formatMonto(d.precioUnitario)}</TableCell>
|
||||
<TableCell class="text-right font-medium">{formatMonto(d.subtotal)}</TableCell>
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
<script lang="ts">
|
||||
import Header from '$lib/components/Header.svelte';
|
||||
import {
|
||||
Accordion,
|
||||
AccordionItem,
|
||||
Button,
|
||||
InlineNotification,
|
||||
NumberInput,
|
||||
@@ -14,8 +16,9 @@
|
||||
import { crearFactura } from '$lib/hooks/facturas/crearFactura';
|
||||
import { obtenerStockDisponible } from '$lib/hooks/almacenes/obtenerStockDisponible';
|
||||
import StockDisponibleCampo from './StockDisponibleCampo.svelte';
|
||||
import SelectorRepuesto from './SelectorRepuesto.svelte';
|
||||
import ModalBuscarCliente from './ModalBuscarCliente.svelte';
|
||||
import type { Cliente, Repuesto, Almacen, StockDisponible } from '../../../types';
|
||||
import type { Cliente, Repuesto, Almacen, StockDisponible, ReservaStock } from '../../../types';
|
||||
|
||||
let { data } = $props();
|
||||
|
||||
@@ -31,6 +34,7 @@
|
||||
let almacenes = $derived<Almacen[]>(Array.isArray(data.almacenes) ? data.almacenes : []);
|
||||
let descuentos = $derived<any[]>(Array.isArray(data.descuentos) ? data.descuentos : []);
|
||||
let formasPago = $derived<any[]>(Array.isArray(data.formasPago) ? data.formasPago : []);
|
||||
let reservas = $derived<ReservaStock[]>(Array.isArray(data.reservas) ? data.reservas : []);
|
||||
|
||||
let clienteId = $state<number>(0);
|
||||
let almacenId = $state<number>(0);
|
||||
@@ -53,6 +57,7 @@
|
||||
let registrarPago = $state(false);
|
||||
|
||||
let modalClienteAbierto = $state(false);
|
||||
let reservaSeleccionada = $state<number>(0);
|
||||
|
||||
$effect(() => {
|
||||
const id = almacenId;
|
||||
@@ -147,6 +152,16 @@
|
||||
else if (clientes.length > 0) clienteId = clientes[0].ID;
|
||||
}
|
||||
|
||||
function cargarDesdeReserva() {
|
||||
const r = reservas.find((x) => x.ID === reservaSeleccionada);
|
||||
if (!r) return;
|
||||
if (r.cliente_id) clienteId = r.cliente_id;
|
||||
if (r.almacen_id) almacenId = r.almacen_id;
|
||||
if (r.repuesto_id) {
|
||||
items = [{ id: 0, repuestoId: r.repuesto_id, cantidad: r.cantidad || 1 }];
|
||||
}
|
||||
}
|
||||
|
||||
async function enviar(conPago = false) {
|
||||
if (enviando) return;
|
||||
enviando = true;
|
||||
@@ -190,7 +205,8 @@
|
||||
? [{ formaDePagoId: pagoFormaId, importe: pagoImporte }]
|
||||
: undefined,
|
||||
enviarEmail,
|
||||
observacion: observacion.trim() || undefined
|
||||
observacion: observacion.trim() || undefined,
|
||||
reservaId: reservaSeleccionada || undefined
|
||||
};
|
||||
|
||||
const res = await crearFactura(payload);
|
||||
@@ -217,6 +233,25 @@
|
||||
{/if}
|
||||
|
||||
<div class="w-full space-y-4 px-4 md:px-6">
|
||||
<!-- Cargar desde reserva -->
|
||||
<Accordion>
|
||||
<AccordionItem title="Cargar desde reserva">
|
||||
<div class="flex flex-wrap items-end gap-2">
|
||||
<Select labelText="Reserva activa" bind:selected={reservaSeleccionada} class="min-w-64 flex-1">
|
||||
<SelectItem value={0} text="Seleccioná una reserva" />
|
||||
{#each reservas.filter((r) => r.estado === 'activa') as r (r.ID)}
|
||||
<SelectItem
|
||||
value={r.ID}
|
||||
text={`${r.repuesto?.nombre ?? r.repuesto_id} · ${r.cliente?.nombre ?? 'Sin cliente'} · ${r.cantidad}`}
|
||||
/>
|
||||
{/each}
|
||||
</Select>
|
||||
<Button size="small" onclick={cargarDesdeReserva} disabled={!reservaSeleccionada}>
|
||||
Cargar datos
|
||||
</Button>
|
||||
</div>
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
<!-- Aviso stock bajo: solo se muestra cuando hay productos con stock por debajo del umbral -->
|
||||
{#if hayStockBajo}
|
||||
<div class="rounded border border-yellow-300 bg-yellow-50 p-3 text-sm text-yellow-800">
|
||||
@@ -290,12 +325,7 @@
|
||||
<DataTable headers={itemHeaders as any} rows={items} size="compact">
|
||||
<svelte:fragment slot="cell" let:row let:cell>
|
||||
{#if cell.key === 'producto'}
|
||||
<Select hideLabel bind:selected={row.repuestoId} class="w-full">
|
||||
<SelectItem value={0} text="Seleccioná" />
|
||||
{#each repuestos as r (r.ID)}
|
||||
<SelectItem value={r.ID} text={r.nombre} />
|
||||
{/each}
|
||||
</Select>
|
||||
<SelectorRepuesto bind:value={row.repuestoId} {repuestos} />
|
||||
{:else if cell.key === 'cantidad'}
|
||||
<NumberInput hideLabel bind:value={row.cantidad} min={0} step={1} class="w-full" />
|
||||
{:else if cell.key === 'precioUnitario'}
|
||||
|
||||
@@ -4,24 +4,27 @@ import { obtenerRepuestos } from '$lib/hooks/repuestos/obtenerRepuestos';
|
||||
import { obtenerAlmacenes } from '$lib/hooks/almacenes/obtenerAlmacenes';
|
||||
import { obtenerDescuentos } from '$lib/hooks/facturas/obtenerDescuentos';
|
||||
import { obtenerFormasPago } from '$lib/hooks/facturas/obtenerFormasPago';
|
||||
|
||||
import { obtenerReservas } from '$lib/hooks/stock/obtenerReservas';
|
||||
export let ssr = false;
|
||||
|
||||
export async function load({ fetch, depends }) {
|
||||
depends('facturas:nueva:load');
|
||||
const [clientes, repuestos, almacenes, descuentos, formasPago] = await Promise.all([
|
||||
const [clientes, repuestos, almacenes, descuentos, formasPago, reservasRes] = await Promise.all([
|
||||
obtenerClientes(fetch),
|
||||
obtenerRepuestos(fetch),
|
||||
obtenerAlmacenes(fetch),
|
||||
obtenerDescuentos(fetch),
|
||||
obtenerFormasPago(fetch)
|
||||
obtenerFormasPago(fetch),
|
||||
obtenerReservas(fetch, { estado: 'activa' })
|
||||
]);
|
||||
const reservas = Array.isArray(reservasRes) ? reservasRes : [];
|
||||
return {
|
||||
clientes: Array.isArray(clientes) ? clientes : [],
|
||||
repuestos: Array.isArray(repuestos) ? repuestos : [],
|
||||
almacenes: Array.isArray(almacenes) ? almacenes : [],
|
||||
descuentos: Array.isArray(descuentos) ? descuentos : [],
|
||||
formasPago: Array.isArray(formasPago) ? formasPago : [],
|
||||
reservas,
|
||||
errorClientes: typeof clientes === 'string' ? clientes : '',
|
||||
errorRepuestos: typeof repuestos === 'string' ? repuestos : ''
|
||||
};
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
<script lang="ts">
|
||||
import { Button, Modal, TextInput } from 'carbon-components-svelte';
|
||||
import type { Repuesto } from '../../../types';
|
||||
|
||||
let {
|
||||
repuestos = [],
|
||||
value = $bindable(0)
|
||||
}: { repuestos?: Repuesto[]; value?: number } = $props();
|
||||
|
||||
let open = $state(false);
|
||||
let q = $state('');
|
||||
|
||||
const seleccionado = $derived(
|
||||
(repuestos ?? []).find((r) => r.ID === value)
|
||||
);
|
||||
const filtrados = $derived(
|
||||
(repuestos ?? []).filter((r) =>
|
||||
r.nombre.toLowerCase().includes(q.trim().toLowerCase())
|
||||
)
|
||||
);
|
||||
|
||||
function elegir(id: number) {
|
||||
value = id;
|
||||
open = false;
|
||||
q = '';
|
||||
}
|
||||
</script>
|
||||
|
||||
<Button size="small" kind="secondary" onclick={() => (open = true)}>
|
||||
{seleccionado ? seleccionado.nombre : 'Seleccionar producto'}
|
||||
</Button>
|
||||
|
||||
<Modal
|
||||
bind:open
|
||||
modalHeading="Seleccionar producto"
|
||||
primaryButtonText="Cerrar"
|
||||
on:click:button--primary={() => (open = false)}
|
||||
>
|
||||
<TextInput labelText="Buscar" placeholder="Nombre del producto" bind:value={q} />
|
||||
<div class="mt-3 max-h-64 overflow-auto">
|
||||
{#if filtrados.length === 0}
|
||||
<p class="text-sm text-gray-500">Sin resultados</p>
|
||||
{:else}
|
||||
<ul class="space-y-1">
|
||||
{#each filtrados as r (r.ID)}
|
||||
<li>
|
||||
<button
|
||||
class="w-full rounded px-2 py-1 text-left text-sm hover:bg-gray-100"
|
||||
onclick={() => elegir(r.ID)}
|
||||
>
|
||||
{r.nombre}
|
||||
</button>
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
{/if}
|
||||
</div>
|
||||
</Modal>
|
||||
Vendored
+4
-1
@@ -82,6 +82,7 @@ export interface EmpresaActual {
|
||||
nombre: string;
|
||||
slug: string;
|
||||
cuit?: string | null;
|
||||
email_alerta_stock?: string[];
|
||||
activa: boolean;
|
||||
rol: string;
|
||||
miembros_activos: number;
|
||||
@@ -92,6 +93,7 @@ export interface EmpresaPlataforma {
|
||||
nombre: string;
|
||||
slug: string;
|
||||
cuit?: string | null;
|
||||
email_alerta_stock?: string[];
|
||||
activa: boolean;
|
||||
miembros: number;
|
||||
owners: number;
|
||||
@@ -345,7 +347,8 @@ export interface PagoResumen {
|
||||
export interface ComprobanteResponse {
|
||||
ID: number;
|
||||
numero?: string;
|
||||
estado: string;
|
||||
estado: string;
|
||||
nombre: string;
|
||||
total: number;
|
||||
subtotal?: number;
|
||||
descuentoTotal?: number;
|
||||
|
||||
Reference in new issue
Block a user