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
+227
-24
No files matched your search
@@ -5,7 +5,6 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
dto_directors "repuestera_back/dto/Builders/Directors"
|
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||||
models_seguridad "repuestera_back/models/seguridad"
|
|
||||||
r "repuestera_back/repositorios"
|
r "repuestera_back/repositorios"
|
||||||
"repuestera_back/utils"
|
"repuestera_back/utils"
|
||||||
|
|
||||||
@@ -17,6 +16,7 @@ func ActualizarEmpresa(c *gin.Context) {
|
|||||||
Nombre string `json:"nombre"`
|
Nombre string `json:"nombre"`
|
||||||
Slug string `json:"slug"`
|
Slug string `json:"slug"`
|
||||||
Cuit string `json:"cuit"`
|
Cuit string `json:"cuit"`
|
||||||
|
EmailAlertaStock *[]string `json:"email_alerta_stock"`
|
||||||
}
|
}
|
||||||
if err := c.ShouldBindJSON(&req); err != nil {
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
@@ -30,10 +30,28 @@ func ActualizarEmpresa(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
input := models_seguridad.Empresa{Nombre: strings.TrimSpace(req.Nombre), Slug: strings.TrimSpace(req.Slug)}
|
if strings.TrimSpace(req.Nombre) != "" {
|
||||||
if req.Cuit != "" {
|
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)
|
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 {
|
if err := repo.Empresa.Actualizar(empresa, input); err != nil {
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ func ActualizarEmpresa(c *gin.Context) {
|
|||||||
Nombre string `json:"nombre"`
|
Nombre string `json:"nombre"`
|
||||||
Slug string `json:"slug"`
|
Slug string `json:"slug"`
|
||||||
Cuit *string `json:"cuit"`
|
Cuit *string `json:"cuit"`
|
||||||
|
EmailAlertaStock *[]string `json:"email_alerta_stock"`
|
||||||
Activa *bool `json:"activa"`
|
Activa *bool `json:"activa"`
|
||||||
}
|
}
|
||||||
if err := c.ShouldBindJSON(&req); err != nil {
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
@@ -49,6 +50,19 @@ func ActualizarEmpresa(c *gin.Context) {
|
|||||||
empresa.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 req.Activa != nil {
|
if req.Activa != nil {
|
||||||
empresa.Activa = *req.Activa
|
empresa.Activa = *req.Activa
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -19,6 +19,7 @@ func CrearEmpresa(c *gin.Context) {
|
|||||||
Nombre string `json:"nombre" binding:"required"`
|
Nombre string `json:"nombre" binding:"required"`
|
||||||
Slug string `json:"slug"`
|
Slug string `json:"slug"`
|
||||||
Cuit string `json:"cuit"`
|
Cuit string `json:"cuit"`
|
||||||
|
EmailAlertaStock []string `json:"email_alerta_stock"`
|
||||||
OwnerEmail string `json:"owner_email" binding:"required,email"`
|
OwnerEmail string `json:"owner_email" binding:"required,email"`
|
||||||
OwnerName string `json:"owner_name"`
|
OwnerName string `json:"owner_name"`
|
||||||
OwnerPassword string `json:"owner_password"`
|
OwnerPassword string `json:"owner_password"`
|
||||||
@@ -82,6 +83,17 @@ func CrearEmpresa(c *gin.Context) {
|
|||||||
cuit := strings.TrimSpace(req.Cuit)
|
cuit := strings.TrimSpace(req.Cuit)
|
||||||
empresa.Cuit = &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 err := repo.Empresa.Crear(&empresa, owner.ID); err != nil {
|
||||||
if creado {
|
if creado {
|
||||||
|
|||||||
@@ -85,6 +85,12 @@ func destinatariosAlertaStock(repo *repositorios.Repositorios, empresaID, usuari
|
|||||||
return limpiarDestinatarios(strings.Split(raw, ","))
|
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
|
var destinatarios []string
|
||||||
if empresaID > 0 {
|
if empresaID > 0 {
|
||||||
miembros, _, err := repo.Empresa.ListarMiembros(empresaID, 0, 100)
|
miembros, _, err := repo.Empresa.ListarMiembros(empresaID, 0, 100)
|
||||||
|
|||||||
@@ -52,6 +52,7 @@ func (b *EmpresaActualResponseBuilder) Build() (*dto.EmpresaActualResponse, erro
|
|||||||
Nombre: b.empresa.Nombre,
|
Nombre: b.empresa.Nombre,
|
||||||
Slug: b.empresa.Slug,
|
Slug: b.empresa.Slug,
|
||||||
Cuit: b.empresa.Cuit,
|
Cuit: b.empresa.Cuit,
|
||||||
|
EmailAlertaStock: ListaNoNil([]string(b.empresa.EmailAlertaStock)),
|
||||||
Activa: b.empresa.Activa,
|
Activa: b.empresa.Activa,
|
||||||
Rol: string(b.rol),
|
Rol: string(b.rol),
|
||||||
MiembrosActivos: b.miembros,
|
MiembrosActivos: b.miembros,
|
||||||
|
|||||||
@@ -52,6 +52,7 @@ func (b *EmpresaAdminResponseBuilder) Build() (*dto.EmpresaAdminResponse, error)
|
|||||||
Nombre: b.empresa.Nombre,
|
Nombre: b.empresa.Nombre,
|
||||||
Slug: b.empresa.Slug,
|
Slug: b.empresa.Slug,
|
||||||
Cuit: b.empresa.Cuit,
|
Cuit: b.empresa.Cuit,
|
||||||
|
EmailAlertaStock: ListaNoNil([]string(b.empresa.EmailAlertaStock)),
|
||||||
Activa: b.empresa.Activa,
|
Activa: b.empresa.Activa,
|
||||||
Miembros: b.miembros,
|
Miembros: b.miembros,
|
||||||
Owners: b.owners,
|
Owners: b.owners,
|
||||||
|
|||||||
@@ -40,6 +40,7 @@ func (b *EmpresaResponseBuilder) Build() (*dto.EmpresaResponse, error) {
|
|||||||
Nombre: b.empresa.Nombre,
|
Nombre: b.empresa.Nombre,
|
||||||
Slug: b.empresa.Slug,
|
Slug: b.empresa.Slug,
|
||||||
Cuit: b.empresa.Cuit,
|
Cuit: b.empresa.Cuit,
|
||||||
|
EmailAlertaStock: ListaNoNil([]string(b.empresa.EmailAlertaStock)),
|
||||||
Activa: b.empresa.Activa,
|
Activa: b.empresa.Activa,
|
||||||
CreatedAt: b.empresa.CreatedAt,
|
CreatedAt: b.empresa.CreatedAt,
|
||||||
UpdatedAt: b.empresa.UpdatedAt,
|
UpdatedAt: b.empresa.UpdatedAt,
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ type CrearFacturaDto struct {
|
|||||||
Pagos []PagoFacturaDto `json:"pagos"`
|
Pagos []PagoFacturaDto `json:"pagos"`
|
||||||
EnviarEmail bool `json:"enviarEmail"`
|
EnviarEmail bool `json:"enviarEmail"`
|
||||||
Observacion string `json:"observacion"`
|
Observacion string `json:"observacion"`
|
||||||
|
ReservaID uint `json:"reservaId"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type ItemFacturaDto struct {
|
type ItemFacturaDto struct {
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ type EmpresaResponse struct {
|
|||||||
Nombre string `json:"nombre"`
|
Nombre string `json:"nombre"`
|
||||||
Slug string `json:"slug"`
|
Slug string `json:"slug"`
|
||||||
Cuit *string `json:"cuit,omitempty"`
|
Cuit *string `json:"cuit,omitempty"`
|
||||||
|
EmailAlertaStock []string `json:"email_alerta_stock,omitempty"`
|
||||||
Activa bool `json:"activa"`
|
Activa bool `json:"activa"`
|
||||||
CreatedAt time.Time `json:"created_at"`
|
CreatedAt time.Time `json:"created_at"`
|
||||||
UpdatedAt time.Time `json:"updated_at"`
|
UpdatedAt time.Time `json:"updated_at"`
|
||||||
@@ -19,6 +20,7 @@ type EmpresaActualResponse struct {
|
|||||||
Nombre string `json:"nombre"`
|
Nombre string `json:"nombre"`
|
||||||
Slug string `json:"slug"`
|
Slug string `json:"slug"`
|
||||||
Cuit *string `json:"cuit,omitempty"`
|
Cuit *string `json:"cuit,omitempty"`
|
||||||
|
EmailAlertaStock []string `json:"email_alerta_stock,omitempty"`
|
||||||
Activa bool `json:"activa"`
|
Activa bool `json:"activa"`
|
||||||
Rol string `json:"rol"`
|
Rol string `json:"rol"`
|
||||||
MiembrosActivos int64 `json:"miembros_activos"`
|
MiembrosActivos int64 `json:"miembros_activos"`
|
||||||
@@ -85,6 +87,7 @@ type EmpresaAdminResponse struct {
|
|||||||
Nombre string `json:"nombre"`
|
Nombre string `json:"nombre"`
|
||||||
Slug string `json:"slug"`
|
Slug string `json:"slug"`
|
||||||
Cuit *string `json:"cuit,omitempty"`
|
Cuit *string `json:"cuit,omitempty"`
|
||||||
|
EmailAlertaStock []string `json:"email_alerta_stock,omitempty"`
|
||||||
Activa bool `json:"activa"`
|
Activa bool `json:"activa"`
|
||||||
Miembros int64 `json:"miembros"`
|
Miembros int64 `json:"miembros"`
|
||||||
Owners int64 `json:"owners"`
|
Owners int64 `json:"owners"`
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ package models_seguridad
|
|||||||
import (
|
import (
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"gorm.io/datatypes"
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -13,6 +14,7 @@ type Empresa struct {
|
|||||||
Nombre string `gorm:"type:varchar(120);not null" json:"nombre"`
|
Nombre string `gorm:"type:varchar(120);not null" json:"nombre"`
|
||||||
Slug string `gorm:"type:varchar(60);uniqueIndex;not null" json:"slug"`
|
Slug string `gorm:"type:varchar(60);uniqueIndex;not null" json:"slug"`
|
||||||
Cuit *string `gorm:"type:varchar(11);uniqueIndex" json:"cuit,omitempty"`
|
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"`
|
Activa bool `gorm:"not null;default:true" json:"activa"`
|
||||||
CreatedAt time.Time `json:"created_at"`
|
CreatedAt time.Time `json:"created_at"`
|
||||||
UpdatedAt time.Time `json:"updated_at"`
|
UpdatedAt time.Time `json:"updated_at"`
|
||||||
|
|||||||
@@ -130,6 +130,9 @@ func (r *repositorioEmpresa) Actualizar(empresa *models_seguridad.Empresa, input
|
|||||||
if input.Cuit != nil {
|
if input.Cuit != nil {
|
||||||
empresa.Cuit = input.Cuit
|
empresa.Cuit = input.Cuit
|
||||||
}
|
}
|
||||||
|
if input.EmailAlertaStock != nil {
|
||||||
|
empresa.EmailAlertaStock = input.EmailAlertaStock
|
||||||
|
}
|
||||||
return r.db.Save(empresa).Error
|
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.
|
// Calcular totales.
|
||||||
var subtotal float64
|
var subtotal float64
|
||||||
detalles := make([]models.FacturaDetalle, 0, len(items))
|
detalles := make([]models.FacturaDetalle, 0, len(items))
|
||||||
@@ -198,6 +220,12 @@ func CrearFactura(
|
|||||||
stock := stocksPorRepuesto[item.RepuestoID]
|
stock := stocksPorRepuesto[item.RepuestoID]
|
||||||
saldoAnterior := stock.Cantidad
|
saldoAnterior := stock.Cantidad
|
||||||
stock.Cantidad = redondearCantidad(stock.Cantidad - item.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 {
|
if err := repo.Stock.ActualizarCantidades(tx, stock); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -222,6 +250,18 @@ func CrearFactura(
|
|||||||
stocks = append(stocks, stock)
|
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 {
|
if err := RegistrarAsientoVenta(tx, repo, factura, subtotal, descuentoTotal, impuestos, total); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -22,6 +22,7 @@ export interface CrearFacturaPayload {
|
|||||||
pagos?: PagoFacturaPayload[];
|
pagos?: PagoFacturaPayload[];
|
||||||
enviarEmail?: boolean;
|
enviarEmail?: boolean;
|
||||||
observacion?: string;
|
observacion?: string;
|
||||||
|
reservaId?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function crearFactura(payload: CrearFacturaPayload) {
|
export async function crearFactura(payload: CrearFacturaPayload) {
|
||||||
|
|||||||
@@ -38,6 +38,7 @@ export async function actualizarEmpresa(dto: {
|
|||||||
nombre?: string;
|
nombre?: string;
|
||||||
slug?: string;
|
slug?: string;
|
||||||
cuit?: string;
|
cuit?: string;
|
||||||
|
email_alerta_stock?: string[];
|
||||||
}): Promise<void> {
|
}): Promise<void> {
|
||||||
await apiFetch('/empresa', { method: 'PUT', body: dto });
|
await apiFetch('/empresa', { method: 'PUT', body: dto });
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -53,7 +53,7 @@ import { agregarGrupoAUsuario } from '$lib/hooks/agregarGrupoAUsuario';
|
|||||||
let error = $state('');
|
let error = $state('');
|
||||||
let exito = $state('');
|
let exito = $state('');
|
||||||
|
|
||||||
let formEmpresa = $state({ nombre: '', slug: '', cuit: '' });
|
let formEmpresa = $state({ nombre: '', slug: '', cuit: '', email_alerta_stock: '' });
|
||||||
let guardandoEmpresa = $state(false);
|
let guardandoEmpresa = $state(false);
|
||||||
|
|
||||||
let modalMiembro = $state(false);
|
let modalMiembro = $state(false);
|
||||||
@@ -102,7 +102,8 @@ import { agregarGrupoAUsuario } from '$lib/hooks/agregarGrupoAUsuario';
|
|||||||
formEmpresa = {
|
formEmpresa = {
|
||||||
nombre: empresa.nombre,
|
nombre: empresa.nombre,
|
||||||
slug: empresa.slug,
|
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;
|
guardandoEmpresa = true;
|
||||||
error = '';
|
error = '';
|
||||||
try {
|
try {
|
||||||
|
const emails = formEmpresa.email_alerta_stock
|
||||||
|
.split(',')
|
||||||
|
.map((e) => e.trim())
|
||||||
|
.filter((e) => e !== '');
|
||||||
await actualizarEmpresa({
|
await actualizarEmpresa({
|
||||||
nombre: formEmpresa.nombre,
|
nombre: formEmpresa.nombre,
|
||||||
slug: formEmpresa.slug,
|
slug: formEmpresa.slug,
|
||||||
cuit: formEmpresa.cuit
|
cuit: formEmpresa.cuit,
|
||||||
|
email_alerta_stock: emails
|
||||||
});
|
});
|
||||||
await cargarEmpresa();
|
await cargarEmpresa();
|
||||||
aviso('Datos de la empresa actualizados');
|
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.nombre} labelText="Nombre" />
|
||||||
<TextInput bind:value={formEmpresa.slug} labelText="Identificador (slug)" />
|
<TextInput bind:value={formEmpresa.slug} labelText="Identificador (slug)" />
|
||||||
<TextInput bind:value={formEmpresa.cuit} labelText="CUIT" />
|
<TextInput bind:value={formEmpresa.cuit} labelText="CUIT" />
|
||||||
|
<TextInput bind:value={formEmpresa.email_alerta_stock} labelText="Emails de alerta de stock (separados por coma)" />
|
||||||
</div>
|
</div>
|
||||||
<Button class="mt-4" disabled={guardandoEmpresa} onclick={guardarEmpresa}>
|
<Button class="mt-4" disabled={guardandoEmpresa} onclick={guardarEmpresa}>
|
||||||
{guardandoEmpresa ? 'Guardando...' : 'Guardar datos'}
|
{guardandoEmpresa ? 'Guardando...' : 'Guardar datos'}
|
||||||
|
|||||||
@@ -12,7 +12,7 @@
|
|||||||
TableRow,
|
TableRow,
|
||||||
Tag
|
Tag
|
||||||
} from 'carbon-components-svelte';
|
} 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 { obtenerComprobante, enviarEmailComprobante } from '$lib/hooks/facturas/comprobante';
|
||||||
import type { ComprobanteResponse, PagoResumen } from '../../types';
|
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(() => {
|
$effect(() => {
|
||||||
if (!open) {
|
if (!open) {
|
||||||
@@ -195,10 +193,10 @@
|
|||||||
<TableHeader>Subtotal</TableHeader>
|
<TableHeader>Subtotal</TableHeader>
|
||||||
</TableRow>
|
</TableRow>
|
||||||
</TableHead>
|
</TableHead>
|
||||||
<TableBody>
|
<TableBody>{$inspect(comprobante)}
|
||||||
{#each comprobante.detalles as d}
|
{#each comprobante.detalles as d}
|
||||||
<TableRow>
|
<TableRow>
|
||||||
<TableCell>{nombreRepuesto(d)}</TableCell>
|
<TableCell>{`Repuesto ${d.repuestoId}`}</TableCell>
|
||||||
<TableCell class="text-right">{d.cantidad}</TableCell>
|
<TableCell class="text-right">{d.cantidad}</TableCell>
|
||||||
<TableCell class="text-right">{formatMonto(d.precioUnitario)}</TableCell>
|
<TableCell class="text-right">{formatMonto(d.precioUnitario)}</TableCell>
|
||||||
<TableCell class="text-right font-medium">{formatMonto(d.subtotal)}</TableCell>
|
<TableCell class="text-right font-medium">{formatMonto(d.subtotal)}</TableCell>
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import Header from '$lib/components/Header.svelte';
|
import Header from '$lib/components/Header.svelte';
|
||||||
import {
|
import {
|
||||||
|
Accordion,
|
||||||
|
AccordionItem,
|
||||||
Button,
|
Button,
|
||||||
InlineNotification,
|
InlineNotification,
|
||||||
NumberInput,
|
NumberInput,
|
||||||
@@ -14,8 +16,9 @@
|
|||||||
import { crearFactura } from '$lib/hooks/facturas/crearFactura';
|
import { crearFactura } from '$lib/hooks/facturas/crearFactura';
|
||||||
import { obtenerStockDisponible } from '$lib/hooks/almacenes/obtenerStockDisponible';
|
import { obtenerStockDisponible } from '$lib/hooks/almacenes/obtenerStockDisponible';
|
||||||
import StockDisponibleCampo from './StockDisponibleCampo.svelte';
|
import StockDisponibleCampo from './StockDisponibleCampo.svelte';
|
||||||
|
import SelectorRepuesto from './SelectorRepuesto.svelte';
|
||||||
import ModalBuscarCliente from './ModalBuscarCliente.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();
|
let { data } = $props();
|
||||||
|
|
||||||
@@ -31,6 +34,7 @@
|
|||||||
let almacenes = $derived<Almacen[]>(Array.isArray(data.almacenes) ? data.almacenes : []);
|
let almacenes = $derived<Almacen[]>(Array.isArray(data.almacenes) ? data.almacenes : []);
|
||||||
let descuentos = $derived<any[]>(Array.isArray(data.descuentos) ? data.descuentos : []);
|
let descuentos = $derived<any[]>(Array.isArray(data.descuentos) ? data.descuentos : []);
|
||||||
let formasPago = $derived<any[]>(Array.isArray(data.formasPago) ? data.formasPago : []);
|
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 clienteId = $state<number>(0);
|
||||||
let almacenId = $state<number>(0);
|
let almacenId = $state<number>(0);
|
||||||
@@ -53,6 +57,7 @@
|
|||||||
let registrarPago = $state(false);
|
let registrarPago = $state(false);
|
||||||
|
|
||||||
let modalClienteAbierto = $state(false);
|
let modalClienteAbierto = $state(false);
|
||||||
|
let reservaSeleccionada = $state<number>(0);
|
||||||
|
|
||||||
$effect(() => {
|
$effect(() => {
|
||||||
const id = almacenId;
|
const id = almacenId;
|
||||||
@@ -147,6 +152,16 @@
|
|||||||
else if (clientes.length > 0) clienteId = clientes[0].ID;
|
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) {
|
async function enviar(conPago = false) {
|
||||||
if (enviando) return;
|
if (enviando) return;
|
||||||
enviando = true;
|
enviando = true;
|
||||||
@@ -190,7 +205,8 @@
|
|||||||
? [{ formaDePagoId: pagoFormaId, importe: pagoImporte }]
|
? [{ formaDePagoId: pagoFormaId, importe: pagoImporte }]
|
||||||
: undefined,
|
: undefined,
|
||||||
enviarEmail,
|
enviarEmail,
|
||||||
observacion: observacion.trim() || undefined
|
observacion: observacion.trim() || undefined,
|
||||||
|
reservaId: reservaSeleccionada || undefined
|
||||||
};
|
};
|
||||||
|
|
||||||
const res = await crearFactura(payload);
|
const res = await crearFactura(payload);
|
||||||
@@ -217,6 +233,25 @@
|
|||||||
{/if}
|
{/if}
|
||||||
|
|
||||||
<div class="w-full space-y-4 px-4 md:px-6">
|
<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 -->
|
<!-- Aviso stock bajo: solo se muestra cuando hay productos con stock por debajo del umbral -->
|
||||||
{#if hayStockBajo}
|
{#if hayStockBajo}
|
||||||
<div class="rounded border border-yellow-300 bg-yellow-50 p-3 text-sm text-yellow-800">
|
<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">
|
<DataTable headers={itemHeaders as any} rows={items} size="compact">
|
||||||
<svelte:fragment slot="cell" let:row let:cell>
|
<svelte:fragment slot="cell" let:row let:cell>
|
||||||
{#if cell.key === 'producto'}
|
{#if cell.key === 'producto'}
|
||||||
<Select hideLabel bind:selected={row.repuestoId} class="w-full">
|
<SelectorRepuesto bind:value={row.repuestoId} {repuestos} />
|
||||||
<SelectItem value={0} text="Seleccioná" />
|
|
||||||
{#each repuestos as r (r.ID)}
|
|
||||||
<SelectItem value={r.ID} text={r.nombre} />
|
|
||||||
{/each}
|
|
||||||
</Select>
|
|
||||||
{:else if cell.key === 'cantidad'}
|
{:else if cell.key === 'cantidad'}
|
||||||
<NumberInput hideLabel bind:value={row.cantidad} min={0} step={1} class="w-full" />
|
<NumberInput hideLabel bind:value={row.cantidad} min={0} step={1} class="w-full" />
|
||||||
{:else if cell.key === 'precioUnitario'}
|
{:else if cell.key === 'precioUnitario'}
|
||||||
|
|||||||
@@ -4,24 +4,27 @@ import { obtenerRepuestos } from '$lib/hooks/repuestos/obtenerRepuestos';
|
|||||||
import { obtenerAlmacenes } from '$lib/hooks/almacenes/obtenerAlmacenes';
|
import { obtenerAlmacenes } from '$lib/hooks/almacenes/obtenerAlmacenes';
|
||||||
import { obtenerDescuentos } from '$lib/hooks/facturas/obtenerDescuentos';
|
import { obtenerDescuentos } from '$lib/hooks/facturas/obtenerDescuentos';
|
||||||
import { obtenerFormasPago } from '$lib/hooks/facturas/obtenerFormasPago';
|
import { obtenerFormasPago } from '$lib/hooks/facturas/obtenerFormasPago';
|
||||||
|
import { obtenerReservas } from '$lib/hooks/stock/obtenerReservas';
|
||||||
export let ssr = false;
|
export let ssr = false;
|
||||||
|
|
||||||
export async function load({ fetch, depends }) {
|
export async function load({ fetch, depends }) {
|
||||||
depends('facturas:nueva:load');
|
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),
|
obtenerClientes(fetch),
|
||||||
obtenerRepuestos(fetch),
|
obtenerRepuestos(fetch),
|
||||||
obtenerAlmacenes(fetch),
|
obtenerAlmacenes(fetch),
|
||||||
obtenerDescuentos(fetch),
|
obtenerDescuentos(fetch),
|
||||||
obtenerFormasPago(fetch)
|
obtenerFormasPago(fetch),
|
||||||
|
obtenerReservas(fetch, { estado: 'activa' })
|
||||||
]);
|
]);
|
||||||
|
const reservas = Array.isArray(reservasRes) ? reservasRes : [];
|
||||||
return {
|
return {
|
||||||
clientes: Array.isArray(clientes) ? clientes : [],
|
clientes: Array.isArray(clientes) ? clientes : [],
|
||||||
repuestos: Array.isArray(repuestos) ? repuestos : [],
|
repuestos: Array.isArray(repuestos) ? repuestos : [],
|
||||||
almacenes: Array.isArray(almacenes) ? almacenes : [],
|
almacenes: Array.isArray(almacenes) ? almacenes : [],
|
||||||
descuentos: Array.isArray(descuentos) ? descuentos : [],
|
descuentos: Array.isArray(descuentos) ? descuentos : [],
|
||||||
formasPago: Array.isArray(formasPago) ? formasPago : [],
|
formasPago: Array.isArray(formasPago) ? formasPago : [],
|
||||||
|
reservas,
|
||||||
errorClientes: typeof clientes === 'string' ? clientes : '',
|
errorClientes: typeof clientes === 'string' ? clientes : '',
|
||||||
errorRepuestos: typeof repuestos === 'string' ? repuestos : ''
|
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
+3
@@ -82,6 +82,7 @@ export interface EmpresaActual {
|
|||||||
nombre: string;
|
nombre: string;
|
||||||
slug: string;
|
slug: string;
|
||||||
cuit?: string | null;
|
cuit?: string | null;
|
||||||
|
email_alerta_stock?: string[];
|
||||||
activa: boolean;
|
activa: boolean;
|
||||||
rol: string;
|
rol: string;
|
||||||
miembros_activos: number;
|
miembros_activos: number;
|
||||||
@@ -92,6 +93,7 @@ export interface EmpresaPlataforma {
|
|||||||
nombre: string;
|
nombre: string;
|
||||||
slug: string;
|
slug: string;
|
||||||
cuit?: string | null;
|
cuit?: string | null;
|
||||||
|
email_alerta_stock?: string[];
|
||||||
activa: boolean;
|
activa: boolean;
|
||||||
miembros: number;
|
miembros: number;
|
||||||
owners: number;
|
owners: number;
|
||||||
@@ -346,6 +348,7 @@ export interface ComprobanteResponse {
|
|||||||
ID: number;
|
ID: number;
|
||||||
numero?: string;
|
numero?: string;
|
||||||
estado: string;
|
estado: string;
|
||||||
|
nombre: string;
|
||||||
total: number;
|
total: number;
|
||||||
subtotal?: number;
|
subtotal?: number;
|
||||||
descuentoTotal?: number;
|
descuentoTotal?: number;
|
||||||
|
|||||||
Reference in new issue
Block a user