Private
Public Access
hecha funcionalidad de modificacion/cancelacion de facturas
Signed-off-by: fede <federico.nicolas.polidoro@gmail.com>
This commit is contained in:
1 parent
94a4e292c4
commit
6331e16dc5
39 files changed
+2283
-104
No files matched your search
@@ -1,8 +1,44 @@
|
||||
package factura
|
||||
|
||||
import "github.com/gin-gonic/gin"
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
// Esto tendria que cancelar la factura en caso de que no este pagada y ademas crear una nota de credito
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
dto "repuestera_back/dto/Facturas"
|
||||
"repuestera_back/repositorios"
|
||||
"repuestera_back/services"
|
||||
"repuestera_back/utils"
|
||||
)
|
||||
|
||||
// CancelarFactura anula una factura sin pagos, emite la nota de crédito por el
|
||||
// total y reincorpora el stock vendido.
|
||||
func CancelarFactura(c *gin.Context) {
|
||||
c.Status(200)
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil || id == 0 {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "id inválido"})
|
||||
return
|
||||
}
|
||||
|
||||
var data dto.CancelarFacturaDto
|
||||
if err := c.ShouldBindJSON(&data); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
resultado, err := services.CancelarFactura(
|
||||
repositorios.BaseDeDatos(),
|
||||
repositorios.ObtenerRepositorios(c),
|
||||
utils.EmpresaID(c),
|
||||
c.GetUint("userID"),
|
||||
uint(id),
|
||||
data,
|
||||
)
|
||||
if err != nil {
|
||||
c.JSON(services.CodigoHTTP(err), gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, resultado)
|
||||
}
|
||||
@@ -1,7 +1,44 @@
|
||||
package factura
|
||||
|
||||
import "github.com/gin-gonic/gin"
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
dto "repuestera_back/dto/Facturas"
|
||||
"repuestera_back/repositorios"
|
||||
"repuestera_back/services"
|
||||
"repuestera_back/utils"
|
||||
)
|
||||
|
||||
// ModificarFactura reemplaza los ítems de una factura y emite la nota de
|
||||
// crédito o débito que corresponda según la diferencia de importe.
|
||||
func ModificarFactura(c *gin.Context) {
|
||||
c.Status(200)
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil || id == 0 {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "id inválido"})
|
||||
return
|
||||
}
|
||||
|
||||
var data dto.ModificarFacturaDto
|
||||
if err := c.ShouldBindJSON(&data); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
resultado, err := services.ModificarFactura(
|
||||
repositorios.BaseDeDatos(),
|
||||
repositorios.ObtenerRepositorios(c),
|
||||
utils.EmpresaID(c),
|
||||
c.GetUint("userID"),
|
||||
uint(id),
|
||||
data,
|
||||
)
|
||||
if err != nil {
|
||||
c.JSON(services.CodigoHTTP(err), gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, resultado)
|
||||
}
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||
dto_facturas "repuestera_back/dto/Facturas"
|
||||
r "repuestera_back/repositorios"
|
||||
"repuestera_back/services"
|
||||
)
|
||||
|
||||
// ObtenerComprobante devuelve el detalle de una factura junto con sus pagos,
|
||||
@@ -75,8 +76,15 @@ func ObtenerComprobante(c *gin.Context) {
|
||||
})
|
||||
}
|
||||
|
||||
notas, err := services.ObtenerNotasFactura(repo, factura.ID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, dto_facturas.ComprobanteResponse{
|
||||
FacturaResponse: respuesta,
|
||||
Pagos: pagosResumen,
|
||||
Notas: notas,
|
||||
})
|
||||
}
|
||||
@@ -55,7 +55,7 @@ func registrarDevolucion(db *gorm.DB, repo *repositorios.Repositorios, empresaID
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%w: factura %d", ErrItemNoEncontrado, entrada.FacturaID)
|
||||
}
|
||||
if strings.EqualFold(strings.TrimSpace(factura.Estado), "anulada") {
|
||||
if strings.EqualFold(strings.TrimSpace(factura.Estado), "CANCELADA") {
|
||||
return nil, ErrFacturaAnulada
|
||||
}
|
||||
|
||||
|
||||
@@ -16,6 +16,12 @@ func (d *FacturaDirector) Crear(datos dto_facturas.FacturaCalculada) (*models.Fa
|
||||
return builders.NewCrearFacturaBuilder().ConDatos(datos).Build()
|
||||
}
|
||||
|
||||
// AplicarAjuste actualiza una factura existente con los datos calculados de
|
||||
// una modificación o cancelación y agrega la entrada de historial.
|
||||
func (d *FacturaDirector) AplicarAjuste(factura *models.Factura, datos dto_facturas.FacturaAjusteDto) (*models.Factura, error) {
|
||||
return builders.NewFacturaAjusteBuilder().ConFactura(factura).ConDatos(datos).Build()
|
||||
}
|
||||
|
||||
func (d *FacturaDirector) DesdeFactura(factura *models.Factura) (*dto_facturas.FacturaResponse, error) {
|
||||
return builders.NewFacturaResponseBuilder().ConFactura(factura).Build()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
package directors
|
||||
|
||||
import (
|
||||
builders "repuestera_back/dto/Builders"
|
||||
dto_stock "repuestera_back/dto/Stock"
|
||||
"repuestera_back/models"
|
||||
)
|
||||
|
||||
type MovimientoStockDirector struct{}
|
||||
|
||||
func NewMovimientoStockDirector() *MovimientoStockDirector {
|
||||
return &MovimientoStockDirector{}
|
||||
}
|
||||
|
||||
// Crear construye un movimiento de stock a partir de los datos recibidos.
|
||||
func (d *MovimientoStockDirector) Crear(datos dto_stock.MovimientoStockDto) (*models.MovimientoStock, error) {
|
||||
return builders.NewMovimientoStockBuilder().ConDatos(datos).Build()
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package directors
|
||||
|
||||
import (
|
||||
builders "repuestera_back/dto/Builders"
|
||||
dto_facturas "repuestera_back/dto/Facturas"
|
||||
"repuestera_back/models"
|
||||
)
|
||||
|
||||
type NotaDirector struct{}
|
||||
|
||||
func NewNotaDirector() *NotaDirector {
|
||||
return &NotaDirector{}
|
||||
}
|
||||
|
||||
// DesdeNotaCredito construye el resumen público de una nota de crédito.
|
||||
func (d *NotaDirector) DesdeNotaCredito(nota *models.NotaCredito) (*dto_facturas.NotaResumen, error) {
|
||||
if nota == nil {
|
||||
return nil, nil
|
||||
}
|
||||
return builders.NewNotaCreditoResumenBuilder().ConNota(nota).Build()
|
||||
}
|
||||
|
||||
// DesdeNotaDebito construye el resumen público de una nota de débito.
|
||||
func (d *NotaDirector) DesdeNotaDebito(nota *models.NotaDebito) (*dto_facturas.NotaResumen, error) {
|
||||
if nota == nil {
|
||||
return nil, nil
|
||||
}
|
||||
return builders.NewNotaDebitoResumenBuilder().ConNota(nota).Build()
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package dto_builders
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
dto "repuestera_back/dto/Facturas"
|
||||
"repuestera_back/models"
|
||||
)
|
||||
|
||||
// FacturaAjusteBuilder aplica sobre una factura existente los totales, el
|
||||
// estado y la entrada de historial resultantes de una modificación o
|
||||
// cancelación.
|
||||
type FacturaAjusteBuilder struct {
|
||||
factura *models.Factura
|
||||
datos *dto.FacturaAjusteDto
|
||||
err error
|
||||
}
|
||||
|
||||
var _ IBuilder[models.Factura] = (*FacturaAjusteBuilder)(nil)
|
||||
|
||||
func NewFacturaAjusteBuilder() *FacturaAjusteBuilder {
|
||||
return &FacturaAjusteBuilder{}
|
||||
}
|
||||
|
||||
func (b *FacturaAjusteBuilder) ConFactura(factura *models.Factura) *FacturaAjusteBuilder {
|
||||
if factura == nil {
|
||||
AcumularError(&b.err, "la factura no puede ser nula")
|
||||
return b
|
||||
}
|
||||
b.factura = factura
|
||||
return b
|
||||
}
|
||||
|
||||
func (b *FacturaAjusteBuilder) ConDatos(datos dto.FacturaAjusteDto) *FacturaAjusteBuilder {
|
||||
b.datos = &datos
|
||||
return b
|
||||
}
|
||||
|
||||
func (b *FacturaAjusteBuilder) Build() (*models.Factura, error) {
|
||||
if b.err != nil {
|
||||
return nil, b.err
|
||||
}
|
||||
if b.factura == nil {
|
||||
return nil, errors.New("falta la factura")
|
||||
}
|
||||
if b.datos == nil {
|
||||
return nil, errors.New("faltan los datos del ajuste")
|
||||
}
|
||||
|
||||
datos := b.datos
|
||||
if datos.UsuarioID == 0 {
|
||||
AcumularError(&b.err, "el usuario es obligatorio")
|
||||
}
|
||||
if strings.TrimSpace(datos.Estado) == "" {
|
||||
AcumularError(&b.err, "el estado de la factura es obligatorio")
|
||||
}
|
||||
if strings.TrimSpace(datos.Motivo) == "" {
|
||||
AcumularError(&b.err, "el motivo es obligatorio")
|
||||
}
|
||||
if b.err != nil {
|
||||
return nil, b.err
|
||||
}
|
||||
|
||||
fecha := datos.Fecha
|
||||
if fecha.IsZero() {
|
||||
fecha = time.Now()
|
||||
}
|
||||
usuarioID := datos.UsuarioID
|
||||
|
||||
factura := b.factura
|
||||
factura.Detalles = append([]models.FacturaDetalle{}, datos.Detalles...)
|
||||
factura.Subtotal = datos.Subtotal
|
||||
factura.DescuentoTotal = datos.DescuentoTotal
|
||||
factura.Impuestos = datos.Impuestos
|
||||
factura.Total = datos.Total
|
||||
factura.Saldo = datos.Saldo
|
||||
factura.Estado = datos.Estado
|
||||
factura.Version++
|
||||
factura.EditadaPorID = &usuarioID
|
||||
factura.EditadaAt = &fecha
|
||||
factura.MotivoUltimaEdicion = datos.Motivo
|
||||
factura.Historial = append(factura.Historial, models.FacturaCambio{
|
||||
Fecha: fecha,
|
||||
UsuarioID: usuarioID,
|
||||
Motivo: datos.Motivo,
|
||||
ItemsAnteriores: append([]models.FacturaDetalle{}, datos.ItemsAnteriores...),
|
||||
TotalAnterior: datos.TotalAnterior,
|
||||
ItemsNuevos: append([]models.FacturaDetalle{}, datos.ItemsNuevos...),
|
||||
TotalNuevo: datos.TotalNuevo,
|
||||
NotaTipo: datos.NotaTipo,
|
||||
NotaID: datos.NotaID,
|
||||
})
|
||||
|
||||
return factura, nil
|
||||
}
|
||||
@@ -92,30 +92,32 @@ func (b *FacturaResponseBuilder) Build() (*dto_facturas.FacturaResponse, error)
|
||||
}
|
||||
|
||||
return &dto_facturas.FacturaResponse{
|
||||
ID: b.factura.ID,
|
||||
CreatedAt: b.factura.CreatedAt,
|
||||
UpdatedAt: b.factura.UpdatedAt,
|
||||
DeletedAt: deletedAt,
|
||||
EmpresaID: b.factura.EmpresaID,
|
||||
Numero: b.factura.Numero,
|
||||
Estado: b.factura.Estado,
|
||||
Total: b.factura.Total,
|
||||
Subtotal: b.factura.Subtotal,
|
||||
DescuentoTotal: b.factura.DescuentoTotal,
|
||||
Impuestos: b.factura.Impuestos,
|
||||
AlicuotaIVA: b.factura.AlicuotaIVA,
|
||||
Saldo: b.factura.Saldo,
|
||||
AlmacenID: b.factura.AlmacenID,
|
||||
FechaEmision: b.factura.FechaEmision,
|
||||
Observacion: b.factura.Observacion,
|
||||
Version: b.factura.Version,
|
||||
ClienteID: b.factura.ClienteID,
|
||||
Cliente: cliente,
|
||||
ProveedorID: b.factura.ProveedorID,
|
||||
Proveedor: proveedor,
|
||||
SeAviso: b.factura.SeAviso,
|
||||
Detalles: append([]models.FacturaDetalle{}, b.factura.Detalles...),
|
||||
ResponsableID: b.factura.ResponsableID,
|
||||
Responsable: responsable,
|
||||
ID: b.factura.ID,
|
||||
CreatedAt: b.factura.CreatedAt,
|
||||
UpdatedAt: b.factura.UpdatedAt,
|
||||
DeletedAt: deletedAt,
|
||||
EmpresaID: b.factura.EmpresaID,
|
||||
Numero: b.factura.Numero,
|
||||
Estado: b.factura.Estado,
|
||||
Total: b.factura.Total,
|
||||
Subtotal: b.factura.Subtotal,
|
||||
DescuentoTotal: b.factura.DescuentoTotal,
|
||||
Impuestos: b.factura.Impuestos,
|
||||
AlicuotaIVA: b.factura.AlicuotaIVA,
|
||||
Saldo: b.factura.Saldo,
|
||||
AlmacenID: b.factura.AlmacenID,
|
||||
FechaEmision: b.factura.FechaEmision,
|
||||
Observacion: b.factura.Observacion,
|
||||
Version: b.factura.Version,
|
||||
ClienteID: b.factura.ClienteID,
|
||||
Cliente: cliente,
|
||||
ProveedorID: b.factura.ProveedorID,
|
||||
Proveedor: proveedor,
|
||||
SeAviso: b.factura.SeAviso,
|
||||
Detalles: append([]models.FacturaDetalle{}, b.factura.Detalles...),
|
||||
Historial: append([]models.FacturaCambio{}, b.factura.Historial...),
|
||||
MotivoUltimaEdicion: b.factura.MotivoUltimaEdicion,
|
||||
ResponsableID: b.factura.ResponsableID,
|
||||
Responsable: responsable,
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package dto_builders
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
dto_stock "repuestera_back/dto/Stock"
|
||||
"repuestera_back/models"
|
||||
)
|
||||
|
||||
// MovimientoStockBuilder construye y valida el registro auditable de una
|
||||
// variación de stock.
|
||||
type MovimientoStockBuilder struct {
|
||||
datos *dto_stock.MovimientoStockDto
|
||||
err error
|
||||
}
|
||||
|
||||
var _ IBuilder[models.MovimientoStock] = (*MovimientoStockBuilder)(nil)
|
||||
|
||||
func NewMovimientoStockBuilder() *MovimientoStockBuilder {
|
||||
return &MovimientoStockBuilder{}
|
||||
}
|
||||
|
||||
func (b *MovimientoStockBuilder) ConDatos(datos dto_stock.MovimientoStockDto) *MovimientoStockBuilder {
|
||||
b.datos = &datos
|
||||
return b
|
||||
}
|
||||
|
||||
func (b *MovimientoStockBuilder) Build() (*models.MovimientoStock, error) {
|
||||
if b.datos == nil {
|
||||
return nil, errors.New("faltan los datos del movimiento de stock")
|
||||
}
|
||||
|
||||
datos := b.datos
|
||||
if datos.StockID == 0 {
|
||||
AcumularError(&b.err, "el stock es obligatorio")
|
||||
}
|
||||
if datos.RepuestoID == 0 {
|
||||
AcumularError(&b.err, "el repuesto es obligatorio")
|
||||
}
|
||||
if datos.AlmacenID == 0 {
|
||||
AcumularError(&b.err, "el almacén es obligatorio")
|
||||
}
|
||||
if datos.Tipo == "" {
|
||||
AcumularError(&b.err, "el tipo de movimiento es obligatorio")
|
||||
}
|
||||
if datos.Cantidad <= 0 {
|
||||
AcumularError(&b.err, "la cantidad del movimiento debe ser mayor a cero")
|
||||
}
|
||||
if datos.SaldoAnterior < 0 {
|
||||
AcumularError(&b.err, "el saldo anterior no puede ser negativo")
|
||||
}
|
||||
if datos.SaldoPosterior < 0 {
|
||||
AcumularError(&b.err, "el saldo posterior no puede ser negativo")
|
||||
}
|
||||
if datos.UsuarioID == 0 {
|
||||
AcumularError(&b.err, "el usuario es obligatorio")
|
||||
}
|
||||
if b.err != nil {
|
||||
return nil, b.err
|
||||
}
|
||||
|
||||
referenciaTipo, _ := ValidarTexto(datos.ReferenciaTipo, "el tipo de referencia", &b.err)
|
||||
if b.err != nil {
|
||||
return nil, b.err
|
||||
}
|
||||
|
||||
fecha := datos.Fecha
|
||||
if fecha.IsZero() {
|
||||
fecha = time.Now()
|
||||
}
|
||||
|
||||
return &models.MovimientoStock{
|
||||
StockID: datos.StockID,
|
||||
RepuestoID: datos.RepuestoID,
|
||||
AlmacenID: datos.AlmacenID,
|
||||
Tipo: datos.Tipo,
|
||||
Cantidad: datos.Cantidad,
|
||||
SaldoAnterior: datos.SaldoAnterior,
|
||||
SaldoPosterior: datos.SaldoPosterior,
|
||||
ReferenciaTipo: referenciaTipo,
|
||||
ReferenciaID: datos.ReferenciaID,
|
||||
UsuarioID: datos.UsuarioID,
|
||||
Observacion: datos.Observacion,
|
||||
Fecha: fecha,
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package dto_builders
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
dto "repuestera_back/dto/Facturas"
|
||||
"repuestera_back/models"
|
||||
)
|
||||
|
||||
// NotaCreditoResumenBuilder construye la representación pública de una nota
|
||||
// de crédito.
|
||||
type NotaCreditoResumenBuilder struct {
|
||||
nota *models.NotaCredito
|
||||
err error
|
||||
}
|
||||
|
||||
var _ IBuilder[dto.NotaResumen] = (*NotaCreditoResumenBuilder)(nil)
|
||||
|
||||
func NewNotaCreditoResumenBuilder() *NotaCreditoResumenBuilder {
|
||||
return &NotaCreditoResumenBuilder{}
|
||||
}
|
||||
|
||||
func (b *NotaCreditoResumenBuilder) ConNota(nota *models.NotaCredito) *NotaCreditoResumenBuilder {
|
||||
if nota == nil {
|
||||
AcumularError(&b.err, "la nota de crédito no puede ser nula")
|
||||
return b
|
||||
}
|
||||
b.nota = nota
|
||||
return b
|
||||
}
|
||||
|
||||
func (b *NotaCreditoResumenBuilder) Build() (*dto.NotaResumen, error) {
|
||||
if b.err != nil {
|
||||
return nil, b.err
|
||||
}
|
||||
if b.nota == nil {
|
||||
return nil, errors.New("falta la nota de crédito")
|
||||
}
|
||||
|
||||
nota := b.nota
|
||||
return &dto.NotaResumen{
|
||||
ID: nota.ID,
|
||||
Tipo: "CREDITO",
|
||||
Numero: fmt.Sprintf("NC-%08d", nota.ID),
|
||||
Motivo: nota.Motivo,
|
||||
Importe: nota.Total,
|
||||
Fecha: nota.CreatedAt,
|
||||
FacturaID: nota.FacturaOrigenID,
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package dto_builders
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
dto "repuestera_back/dto/Facturas"
|
||||
"repuestera_back/models"
|
||||
)
|
||||
|
||||
// NotaDebitoResumenBuilder construye la representación pública de una nota de
|
||||
// débito.
|
||||
type NotaDebitoResumenBuilder struct {
|
||||
nota *models.NotaDebito
|
||||
err error
|
||||
}
|
||||
|
||||
var _ IBuilder[dto.NotaResumen] = (*NotaDebitoResumenBuilder)(nil)
|
||||
|
||||
func NewNotaDebitoResumenBuilder() *NotaDebitoResumenBuilder {
|
||||
return &NotaDebitoResumenBuilder{}
|
||||
}
|
||||
|
||||
func (b *NotaDebitoResumenBuilder) ConNota(nota *models.NotaDebito) *NotaDebitoResumenBuilder {
|
||||
if nota == nil {
|
||||
AcumularError(&b.err, "la nota de débito no puede ser nula")
|
||||
return b
|
||||
}
|
||||
b.nota = nota
|
||||
return b
|
||||
}
|
||||
|
||||
func (b *NotaDebitoResumenBuilder) Build() (*dto.NotaResumen, error) {
|
||||
if b.err != nil {
|
||||
return nil, b.err
|
||||
}
|
||||
if b.nota == nil {
|
||||
return nil, errors.New("falta la nota de débito")
|
||||
}
|
||||
|
||||
nota := b.nota
|
||||
return &dto.NotaResumen{
|
||||
ID: nota.ID,
|
||||
Tipo: "DEBITO",
|
||||
Numero: fmt.Sprintf("ND-%08d", nota.ID),
|
||||
Motivo: nota.Motivo,
|
||||
Importe: nota.Total,
|
||||
Fecha: nota.CreatedAt,
|
||||
FacturaID: nota.FacturaOrigenID,
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package dto
|
||||
|
||||
import "repuestera_back/models"
|
||||
|
||||
// AjusteFacturaResponse devuelve la factura actualizada y la nota emitida por
|
||||
// una modificación de ítems. También informa el impacto sobre el saldo y el
|
||||
// stock para que el frontend pueda refrescar la vista sin otra consulta.
|
||||
type AjusteFacturaResponse struct {
|
||||
Factura *FacturaResponse `json:"factura"`
|
||||
Nota *NotaResumen `json:"nota,omitempty"`
|
||||
Diferencia float64 `json:"diferencia"`
|
||||
SaldoAnterior float64 `json:"saldoAnterior"`
|
||||
SaldoNuevo float64 `json:"saldoNuevo"`
|
||||
Stocks []*models.Stock `json:"stocks,omitempty"`
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package dto
|
||||
|
||||
// CancelarFacturaDto contiene el motivo obligatorio de la anulación.
|
||||
type CancelarFacturaDto struct {
|
||||
Motivo string `json:"motivo" binding:"required,max=40"`
|
||||
}
|
||||
@@ -6,4 +6,5 @@ package dto
|
||||
type ComprobanteResponse struct {
|
||||
*FacturaResponse
|
||||
Pagos []PagoResumen `json:"pagos"`
|
||||
Notas []NotaResumen `json:"notas"`
|
||||
}
|
||||
@@ -1,14 +1,14 @@
|
||||
package dto
|
||||
|
||||
type CrearFacturaDto struct {
|
||||
ClienteID uint `json:"clienteId" binding:"required"`
|
||||
AlmacenID uint `json:"almacenId" binding:"required"`
|
||||
Items []ItemFacturaDto `json:"items" binding:"required,min=1"`
|
||||
DescuentoID uint `json:"descuentoId"`
|
||||
Pagos []PagoFacturaDto `json:"pagos"`
|
||||
EnviarEmail bool `json:"enviarEmail"`
|
||||
Observacion string `json:"observacion"`
|
||||
ReservaID uint `json:"reservaId"`
|
||||
ClienteID uint `json:"clienteId" binding:"required"`
|
||||
AlmacenID uint `json:"almacenId" binding:"required"`
|
||||
Items []ItemFacturaDto `json:"items" binding:"required,min=1"`
|
||||
DescuentoID uint `json:"descuentoId"`
|
||||
Pagos []PagoFacturaDto `json:"pagos"`
|
||||
EnviarEmail bool `json:"enviarEmail"`
|
||||
Observacion string `json:"observacion"`
|
||||
ReservaID uint `json:"reservaId"`
|
||||
}
|
||||
|
||||
type ItemFacturaDto struct {
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
package dto
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"repuestera_back/models"
|
||||
)
|
||||
|
||||
// FacturaAjusteDto reúne los datos calculados que se aplican a una factura
|
||||
// existente al modificarla o cancelarla, junto con el detalle de auditoría.
|
||||
type FacturaAjusteDto struct {
|
||||
Detalles []models.FacturaDetalle
|
||||
Subtotal float64
|
||||
DescuentoTotal float64
|
||||
Impuestos float64
|
||||
Total float64
|
||||
Saldo float64
|
||||
Estado string
|
||||
Motivo string
|
||||
UsuarioID uint
|
||||
ItemsAnteriores []models.FacturaDetalle
|
||||
TotalAnterior float64
|
||||
ItemsNuevos []models.FacturaDetalle
|
||||
TotalNuevo float64
|
||||
NotaTipo string
|
||||
NotaID uint
|
||||
Fecha time.Time
|
||||
}
|
||||
@@ -13,29 +13,31 @@ import (
|
||||
// los resúmenes de cliente, proveedor y responsable, pero no las
|
||||
// relaciones internas de esos modelos.
|
||||
type FacturaResponse struct {
|
||||
ID uint `json:"ID"`
|
||||
CreatedAt time.Time `json:"CreatedAt"`
|
||||
UpdatedAt time.Time `json:"UpdatedAt"`
|
||||
DeletedAt *time.Time `json:"DeletedAt"`
|
||||
EmpresaID uint `json:"empresaId"`
|
||||
Numero string `json:"numero"`
|
||||
Estado string `json:"estado"`
|
||||
Total float64 `json:"total"`
|
||||
Subtotal float64 `json:"subtotal"`
|
||||
DescuentoTotal float64 `json:"descuentoTotal"`
|
||||
Impuestos float64 `json:"impuestos"`
|
||||
AlicuotaIVA float64 `json:"alicuotaIva"`
|
||||
Saldo float64 `json:"saldo"`
|
||||
AlmacenID uint `json:"almacenId"`
|
||||
FechaEmision time.Time `json:"fechaEmision"`
|
||||
Observacion string `json:"observacion,omitempty"`
|
||||
Version int `json:"version"`
|
||||
ClienteID uint `json:"ClienteID,omitempty"`
|
||||
Cliente dto_clientes.ClienteResumen `json:"cliente"`
|
||||
ProveedorID *uint `json:"proveedorId,omitempty"`
|
||||
Proveedor *dto_proveedores.ProveedorResumen `json:"proveedor,omitempty"`
|
||||
SeAviso bool `json:"seAviso"`
|
||||
Detalles []models.FacturaDetalle `json:"detalles,omitempty"`
|
||||
ResponsableID uint `json:"ResponsableID,omitempty"`
|
||||
Responsable *dto_base.UsuarioResumen `json:"usuario,omitempty"`
|
||||
ID uint `json:"ID"`
|
||||
CreatedAt time.Time `json:"CreatedAt"`
|
||||
UpdatedAt time.Time `json:"UpdatedAt"`
|
||||
DeletedAt *time.Time `json:"DeletedAt"`
|
||||
EmpresaID uint `json:"empresaId"`
|
||||
Numero string `json:"numero"`
|
||||
Estado string `json:"estado"`
|
||||
Total float64 `json:"total"`
|
||||
Subtotal float64 `json:"subtotal"`
|
||||
DescuentoTotal float64 `json:"descuentoTotal"`
|
||||
Impuestos float64 `json:"impuestos"`
|
||||
AlicuotaIVA float64 `json:"alicuotaIva"`
|
||||
Saldo float64 `json:"saldo"`
|
||||
AlmacenID uint `json:"almacenId"`
|
||||
FechaEmision time.Time `json:"fechaEmision"`
|
||||
Observacion string `json:"observacion,omitempty"`
|
||||
Version int `json:"version"`
|
||||
ClienteID uint `json:"ClienteID,omitempty"`
|
||||
Cliente dto_clientes.ClienteResumen `json:"cliente"`
|
||||
ProveedorID *uint `json:"proveedorId,omitempty"`
|
||||
Proveedor *dto_proveedores.ProveedorResumen `json:"proveedor,omitempty"`
|
||||
SeAviso bool `json:"seAviso"`
|
||||
Detalles []models.FacturaDetalle `json:"detalles,omitempty"`
|
||||
Historial []models.FacturaCambio `json:"historial,omitempty"`
|
||||
MotivoUltimaEdicion string `json:"motivoUltimaEdicion,omitempty"`
|
||||
ResponsableID uint `json:"ResponsableID,omitempty"`
|
||||
Responsable *dto_base.UsuarioResumen `json:"usuario,omitempty"`
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package dto
|
||||
|
||||
// ModificarFacturaDto reemplaza los ítems de una factura existente.
|
||||
// El motivo queda registrado en la auditoría y en la nota de ajuste.
|
||||
type ModificarFacturaDto struct {
|
||||
Items []ItemFacturaDto `json:"items" binding:"required,min=1,dive"`
|
||||
Motivo string `json:"motivo" binding:"required,max=40"`
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package dto
|
||||
|
||||
import "time"
|
||||
|
||||
// NotaResumen es la representación pública de una nota de crédito o débito.
|
||||
// El número se deriva del ID porque el modelo persistido no guarda un número
|
||||
// propio para estos comprobantes.
|
||||
type NotaResumen struct {
|
||||
ID uint `json:"id"`
|
||||
Tipo string `json:"tipo"`
|
||||
Numero string `json:"numero"`
|
||||
Motivo string `json:"motivo"`
|
||||
Importe float64 `json:"importe"`
|
||||
Fecha time.Time `json:"fecha"`
|
||||
FacturaID uint `json:"facturaId"`
|
||||
}
|
||||
@@ -5,11 +5,11 @@ import "time"
|
||||
// PagoResumen es la representación ligera de un pago de factura,
|
||||
// usada para mostrar el historial de pagos en el comprobante.
|
||||
type PagoResumen struct {
|
||||
ID uint `json:"id"`
|
||||
FacturaID uint `json:"facturaId,omitempty"`
|
||||
FormaDePagoID uint `json:"formaDePagoId,omitempty"`
|
||||
FormaDePago string `json:"formaDePago,omitempty"`
|
||||
Importe float64 `json:"importe"`
|
||||
ID uint `json:"id"`
|
||||
FacturaID uint `json:"facturaId,omitempty"`
|
||||
FormaDePagoID uint `json:"formaDePagoId,omitempty"`
|
||||
FormaDePago string `json:"formaDePago,omitempty"`
|
||||
Importe float64 `json:"importe"`
|
||||
Fecha time.Time `json:"fecha"`
|
||||
Observacion string `json:"observacion,omitempty"`
|
||||
Observacion string `json:"observacion,omitempty"`
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package dto
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"repuestera_back/models"
|
||||
)
|
||||
|
||||
// MovimientoStockDto reúne los datos necesarios para construir un movimiento
|
||||
// de stock auditable.
|
||||
type MovimientoStockDto struct {
|
||||
StockID uint64
|
||||
RepuestoID uint64
|
||||
AlmacenID uint
|
||||
Tipo models.TipoMovimientoStock
|
||||
Cantidad float64
|
||||
SaldoAnterior float64
|
||||
SaldoPosterior float64
|
||||
ReferenciaTipo string
|
||||
ReferenciaID uint64
|
||||
UsuarioID uint
|
||||
Observacion string
|
||||
Fecha time.Time
|
||||
}
|
||||
@@ -10,21 +10,23 @@ import (
|
||||
)
|
||||
|
||||
type Repositorios struct {
|
||||
Permiso RepositorioPermiso
|
||||
Usuario RepositorioUsuario
|
||||
Grupo RepositorioGrupo
|
||||
Repuesto RepositorioRepuesto
|
||||
Marca RepositorioMarcas
|
||||
Logs RepositorioLogs
|
||||
Empresa RepositorioEmpresa
|
||||
Almacen RepositorioAlmacen
|
||||
Proveedor RepositorioProveedor
|
||||
Cliente RepositorioCliente
|
||||
Factura RepositorioFactura
|
||||
Pago RepositorioPago
|
||||
Secuencia RepositorioComprobanteSecuencia
|
||||
Descuento RepositorioDescuento
|
||||
FormaDePago RepositorioFormaDePago
|
||||
Permiso RepositorioPermiso
|
||||
Usuario RepositorioUsuario
|
||||
Grupo RepositorioGrupo
|
||||
Repuesto RepositorioRepuesto
|
||||
Marca RepositorioMarcas
|
||||
Logs RepositorioLogs
|
||||
Empresa RepositorioEmpresa
|
||||
Almacen RepositorioAlmacen
|
||||
Proveedor RepositorioProveedor
|
||||
Cliente RepositorioCliente
|
||||
Factura RepositorioFactura
|
||||
NotaCredito RepositorioNotaCredito
|
||||
NotaDebito RepositorioNotaDebito
|
||||
Pago RepositorioPago
|
||||
Secuencia RepositorioComprobanteSecuencia
|
||||
Descuento RepositorioDescuento
|
||||
FormaDePago RepositorioFormaDePago
|
||||
|
||||
Stock RepositorioStock
|
||||
MovimientoStock RepositorioMovimientoStock
|
||||
@@ -92,21 +94,23 @@ func BaseDeDatos() *gorm.DB {
|
||||
|
||||
func nuevoContenedor(db *gorm.DB, empresaID uint) *Repositorios {
|
||||
return &Repositorios{
|
||||
Permiso: &repositorioPermiso{db: db},
|
||||
Usuario: &repositorioUsuario{db: db, empresaID: empresaID},
|
||||
Grupo: &repositorioGrupo{db: dbConEmpresa(db, empresaID), empresaID: empresaID},
|
||||
Repuesto: NuevoRepositorioRepuesto(db, empresaID),
|
||||
Marca: NuevoRepositorioMarcas(db, empresaID),
|
||||
Logs: NuevoRepositorioLogs(db, empresaID),
|
||||
Empresa: &repositorioEmpresa{db: db},
|
||||
Almacen: NuevoRepositorioAlmacen(db, empresaID),
|
||||
Proveedor: NuevoRepositorioProveedor(db, empresaID),
|
||||
Cliente: NuevoRepositorioCliente(db, empresaID),
|
||||
Factura: NuevoRepositorioFactura(db, empresaID),
|
||||
Pago: NuevoRepositorioPago(db, empresaID),
|
||||
Secuencia: NuevoRepositorioComprobanteSecuencia(db, empresaID),
|
||||
Descuento: NuevoRepositorioDescuento(db, empresaID),
|
||||
FormaDePago: NuevoRepositorioFormaDePago(db, empresaID),
|
||||
Permiso: &repositorioPermiso{db: db},
|
||||
Usuario: &repositorioUsuario{db: db, empresaID: empresaID},
|
||||
Grupo: &repositorioGrupo{db: dbConEmpresa(db, empresaID), empresaID: empresaID},
|
||||
Repuesto: NuevoRepositorioRepuesto(db, empresaID),
|
||||
Marca: NuevoRepositorioMarcas(db, empresaID),
|
||||
Logs: NuevoRepositorioLogs(db, empresaID),
|
||||
Empresa: &repositorioEmpresa{db: db},
|
||||
Almacen: NuevoRepositorioAlmacen(db, empresaID),
|
||||
Proveedor: NuevoRepositorioProveedor(db, empresaID),
|
||||
Cliente: NuevoRepositorioCliente(db, empresaID),
|
||||
Factura: NuevoRepositorioFactura(db, empresaID),
|
||||
NotaCredito: NuevoRepositorioNotaCredito(db, empresaID),
|
||||
NotaDebito: NuevoRepositorioNotaDebito(db, empresaID),
|
||||
Pago: NuevoRepositorioPago(db, empresaID),
|
||||
Secuencia: NuevoRepositorioComprobanteSecuencia(db, empresaID),
|
||||
Descuento: NuevoRepositorioDescuento(db, empresaID),
|
||||
FormaDePago: NuevoRepositorioFormaDePago(db, empresaID),
|
||||
|
||||
Stock: NuevoRepositorioStock(db, empresaID),
|
||||
MovimientoStock: NuevoRepositorioMovimientoStock(db, empresaID),
|
||||
|
||||
@@ -13,6 +13,7 @@ type RepositorioFactura interface {
|
||||
Listar(filtros decorator.FiltrosFactura) ([]models.Factura, error)
|
||||
ObtenerConRelaciones(id uint) (*models.Factura, error)
|
||||
CrearConDetalles(tx *gorm.DB, factura *models.Factura) error
|
||||
GuardarAjuste(tx *gorm.DB, factura *models.Factura) error
|
||||
BloquearPorID(tx *gorm.DB, id uint) (*models.Factura, error)
|
||||
ActualizarEstadoSaldo(tx *gorm.DB, id uint, estado string, saldo float64) error
|
||||
ExisteNumero(numero string) (bool, error)
|
||||
@@ -70,6 +71,19 @@ func (r *repositorioFactura) CrearConDetalles(tx *gorm.DB, factura *models.Factu
|
||||
return tx.Create(factura).Error
|
||||
}
|
||||
|
||||
// GuardarAjuste persiste la factura completa después de modificar sus ítems,
|
||||
// totales e historial. Se omiten las asociaciones para que no se reescriban
|
||||
// cliente, almacén ni proveedor.
|
||||
func (r *repositorioFactura) GuardarAjuste(tx *gorm.DB, factura *models.Factura) error {
|
||||
if factura == nil {
|
||||
return gorm.ErrInvalidValue
|
||||
}
|
||||
if r.empresaID > 0 {
|
||||
factura.EmpresaID = r.empresaID
|
||||
}
|
||||
return tx.Omit(clause.Associations).Save(factura).Error
|
||||
}
|
||||
|
||||
func (r *repositorioFactura) BloquearPorID(tx *gorm.DB, id uint) (*models.Factura, error) {
|
||||
var factura models.Factura
|
||||
db := tx
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
package repositorios
|
||||
|
||||
import (
|
||||
"repuestera_back/models"
|
||||
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
// RepositorioNotaCredito persiste las notas de crédito emitidas por los
|
||||
// ajustes de factura y las expone para el comprobante.
|
||||
type RepositorioNotaCredito interface {
|
||||
Crear(tx *gorm.DB, nota *models.NotaCredito) error
|
||||
ListarPorFactura(facturaID uint) ([]models.NotaCredito, error)
|
||||
}
|
||||
|
||||
type repositorioNotaCredito struct {
|
||||
db *gorm.DB
|
||||
empresaID uint
|
||||
}
|
||||
|
||||
func NuevoRepositorioNotaCredito(db *gorm.DB, empresaID uint) RepositorioNotaCredito {
|
||||
return &repositorioNotaCredito{
|
||||
db: dbConEmpresa(db, empresaID),
|
||||
empresaID: empresaID,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *repositorioNotaCredito) Crear(tx *gorm.DB, nota *models.NotaCredito) error {
|
||||
if nota == nil {
|
||||
return gorm.ErrInvalidValue
|
||||
}
|
||||
if r.empresaID > 0 {
|
||||
nota.EmpresaID = r.empresaID
|
||||
}
|
||||
return tx.Omit(clause.Associations).Create(nota).Error
|
||||
}
|
||||
|
||||
func (r *repositorioNotaCredito) ListarPorFactura(facturaID uint) ([]models.NotaCredito, error) {
|
||||
var notas []models.NotaCredito
|
||||
if err := r.db.Where("facturaID = ?", facturaID).Order("created_at ASC").Find(¬as).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return notas, nil
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package repositorios
|
||||
|
||||
import (
|
||||
"repuestera_back/models"
|
||||
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
// RepositorioNotaDebito persiste las notas de débito emitidas por los
|
||||
// ajustes de factura y las expone para el comprobante.
|
||||
type RepositorioNotaDebito interface {
|
||||
Crear(tx *gorm.DB, nota *models.NotaDebito) error
|
||||
ListarPorFactura(facturaID uint) ([]models.NotaDebito, error)
|
||||
}
|
||||
|
||||
type repositorioNotaDebito struct {
|
||||
db *gorm.DB
|
||||
empresaID uint
|
||||
}
|
||||
|
||||
func NuevoRepositorioNotaDebito(db *gorm.DB, empresaID uint) RepositorioNotaDebito {
|
||||
return &repositorioNotaDebito{
|
||||
db: dbConEmpresa(db, empresaID),
|
||||
empresaID: empresaID,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *repositorioNotaDebito) Crear(tx *gorm.DB, nota *models.NotaDebito) error {
|
||||
if nota == nil {
|
||||
return gorm.ErrInvalidValue
|
||||
}
|
||||
if r.empresaID > 0 {
|
||||
nota.EmpresaID = r.empresaID
|
||||
}
|
||||
return tx.Omit(clause.Associations).Create(nota).Error
|
||||
}
|
||||
|
||||
func (r *repositorioNotaDebito) ListarPorFactura(facturaID uint) ([]models.NotaDebito, error) {
|
||||
var notas []models.NotaDebito
|
||||
if err := r.db.Where("facturaID = ?", facturaID).Order("created_at ASC").Find(¬as).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return notas, nil
|
||||
}
|
||||
@@ -25,6 +25,8 @@ func FacturaRoute(r *gin.Engine) {
|
||||
escritura.Use(middleware.AuthMiddleware(15))
|
||||
{
|
||||
escritura.POST("/", factura.CrearFactura)
|
||||
escritura.PUT("/:id", factura.ModificarFactura)
|
||||
escritura.POST("/:id/cancelar", factura.CancelarFactura)
|
||||
escritura.POST("/:id/pagos", factura.RegistrarPago)
|
||||
escritura.POST("/:id/enviar-email", factura.EnviarEmailComprobante)
|
||||
}
|
||||
|
||||
@@ -44,6 +44,91 @@ func RegistrarAsientoVenta(
|
||||
return repo.Contabilidad.CrearAsientoConMovimientos(tx, asiento)
|
||||
}
|
||||
|
||||
// RegistrarAsientoNotaCredito registra el reverso parcial o total de una venta.
|
||||
// El importe de la nota incluye IVA; se separa la base imponible para que las
|
||||
// cuentas de resultado y de IVA queden consistentes.
|
||||
func RegistrarAsientoNotaCredito(
|
||||
tx *gorm.DB,
|
||||
repo *repositorios.Repositorios,
|
||||
nota *models.NotaCredito,
|
||||
alicuota float64,
|
||||
) error {
|
||||
if nota == nil {
|
||||
return gorm.ErrInvalidValue
|
||||
}
|
||||
|
||||
base, impuesto := desglosarImporteConIVA(nota.Total, alicuota)
|
||||
asiento := &contabilidad.AsientoContable{
|
||||
ComprobanteTipo: "NOTA_CREDITO",
|
||||
ComprobanteID: nota.ID,
|
||||
}
|
||||
|
||||
if err := agregarMovimiento(tx, repo, asiento, "Clientes", "activo", 0, nota.Total, "Nota de crédito a clientes"); err != nil {
|
||||
return err
|
||||
}
|
||||
if base > 0 {
|
||||
if err := agregarMovimiento(tx, repo, asiento, "Devoluciones sobre ventas", "resultado", base, 0, "Devolución sobre ventas"); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if impuesto > 0 {
|
||||
if err := agregarMovimiento(tx, repo, asiento, "IVA Débito Fiscal", "pasivo", impuesto, 0, "IVA de nota de crédito"); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return repo.Contabilidad.CrearAsientoConMovimientos(tx, asiento)
|
||||
}
|
||||
|
||||
// RegistrarAsientoNotaDebito registra el incremento de la venta por un ajuste
|
||||
// posterior a la emisión de la factura.
|
||||
func RegistrarAsientoNotaDebito(
|
||||
tx *gorm.DB,
|
||||
repo *repositorios.Repositorios,
|
||||
nota *models.NotaDebito,
|
||||
alicuota float64,
|
||||
) error {
|
||||
if nota == nil {
|
||||
return gorm.ErrInvalidValue
|
||||
}
|
||||
|
||||
base, impuesto := desglosarImporteConIVA(nota.Total, alicuota)
|
||||
asiento := &contabilidad.AsientoContable{
|
||||
ComprobanteTipo: "NOTA_DEBITO",
|
||||
ComprobanteID: nota.ID,
|
||||
}
|
||||
|
||||
if err := agregarMovimiento(tx, repo, asiento, "Clientes", "activo", nota.Total, 0, "Nota de débito a clientes"); err != nil {
|
||||
return err
|
||||
}
|
||||
if base > 0 {
|
||||
if err := agregarMovimiento(tx, repo, asiento, "Ventas", "resultado", 0, base, "Ingreso adicional por ventas"); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if impuesto > 0 {
|
||||
if err := agregarMovimiento(tx, repo, asiento, "IVA Débito Fiscal", "pasivo", 0, impuesto, "IVA de nota de débito"); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return repo.Contabilidad.CrearAsientoConMovimientos(tx, asiento)
|
||||
}
|
||||
|
||||
// desglosarImporteConIVA separa un importe final en base imponible e IVA.
|
||||
func desglosarImporteConIVA(total, alicuota float64) (base, impuesto float64) {
|
||||
if total <= 0 {
|
||||
return 0, 0
|
||||
}
|
||||
if alicuota < 0 {
|
||||
alicuota = 0
|
||||
}
|
||||
divisor := 1 + alicuota/100
|
||||
base = redondearMonto(total / divisor)
|
||||
impuesto = redondearMonto(total - base)
|
||||
return base, impuesto
|
||||
}
|
||||
|
||||
func agregarMovimiento(
|
||||
tx *gorm.DB,
|
||||
repo *repositorios.Repositorios,
|
||||
|
||||
@@ -18,11 +18,12 @@ import (
|
||||
)
|
||||
|
||||
const (
|
||||
estadoFacturaEmitida = "EMITIDA"
|
||||
estadoFacturaParcial = "PARCIAL"
|
||||
estadoFacturaPagada = "PAGADA"
|
||||
)
|
||||
|
||||
var errCantidadInvalida = errors.New("la cantidad debe ser mayor a cero")
|
||||
var ErrCantidadInvalidaFactura = errors.New("la cantidad debe ser mayor a cero")
|
||||
|
||||
// CrearFactura valida los datos, emite la factura y registra sus efectos
|
||||
// (stock, contabilidad y pagos) dentro de una misma transacción.
|
||||
@@ -350,7 +351,7 @@ func registrarLogFactura(
|
||||
|
||||
func validarCantidad(cantidad float64) error {
|
||||
if math.IsNaN(cantidad) || math.IsInf(cantidad, 0) || cantidad <= 0 {
|
||||
return errCantidadInvalida
|
||||
return ErrCantidadInvalidaFactura
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,571 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"net/http"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"gorm.io/gorm"
|
||||
|
||||
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||
dto "repuestera_back/dto/Facturas"
|
||||
dto_stock "repuestera_back/dto/Stock"
|
||||
"repuestera_back/models"
|
||||
models_logs "repuestera_back/models/logs"
|
||||
"repuestera_back/repositorios"
|
||||
)
|
||||
|
||||
const motivoAjusteMaximo = 40
|
||||
|
||||
// Errores de dominio del ajuste de facturas.
|
||||
var (
|
||||
ErrFacturaPagoParcial = errors.New("la factura tiene un pago parcial y no admite modificaciones")
|
||||
ErrFacturaSinCambios = errors.New("la modificación no produce cambios")
|
||||
ErrMotivoRequeridoFactura = errors.New("el motivo es obligatorio")
|
||||
ErrMotivoFacturaLargo = errors.New("el motivo no puede superar los 40 caracteres")
|
||||
ErrRepuestoNoEncontradoAjuste = errors.New("el repuesto no existe o no pertenece a la empresa")
|
||||
ErrStockInsuficienteAjuste = errors.New("stock insuficiente")
|
||||
ErrImporteNotaInvalido = errors.New("el importe de la nota debe ser mayor a cero")
|
||||
ErrItemDuplicadoAjuste = errors.New("el repuesto está repetido en la factura")
|
||||
ErrPrecioUnitarioInvalido = errors.New("el precio unitario es inválido")
|
||||
ErrFacturaEstadoNoAjustable = errors.New("la factura no se encuentra en un estado modificable")
|
||||
)
|
||||
|
||||
// CodigoHTTP traduce un error de dominio de facturación al código HTTP que
|
||||
// debe devolver el controller.
|
||||
func CodigoHTTP(err error) int {
|
||||
switch {
|
||||
case errors.Is(err, gorm.ErrRecordNotFound),
|
||||
errors.Is(err, ErrFacturaNoEncontrada),
|
||||
errors.Is(err, ErrRepuestoNoEncontradoAjuste):
|
||||
return http.StatusNotFound
|
||||
case errors.Is(err, ErrFacturaCancelada),
|
||||
errors.Is(err, ErrFacturaPagoParcial),
|
||||
errors.Is(err, ErrFacturaEstadoNoAjustable),
|
||||
errors.Is(err, ErrFacturaCancelacionConPagos),
|
||||
errors.Is(err, ErrFacturaEstadoNoCancelable):
|
||||
return http.StatusConflict
|
||||
case errors.Is(err, ErrStockInsuficienteAjuste):
|
||||
return http.StatusUnprocessableEntity
|
||||
case errors.Is(err, ErrFacturaSinCambios),
|
||||
errors.Is(err, ErrMotivoRequeridoFactura),
|
||||
errors.Is(err, ErrMotivoFacturaLargo),
|
||||
errors.Is(err, ErrImporteNotaInvalido),
|
||||
errors.Is(err, ErrItemDuplicadoAjuste),
|
||||
errors.Is(err, ErrPrecioUnitarioInvalido),
|
||||
errors.Is(err, ErrCantidadInvalidaFactura):
|
||||
return http.StatusBadRequest
|
||||
default:
|
||||
return http.StatusInternalServerError
|
||||
}
|
||||
}
|
||||
|
||||
type cambioStockAjuste struct {
|
||||
stock *models.Stock
|
||||
delta float64
|
||||
saldoAnterior float64
|
||||
}
|
||||
|
||||
// ModificarFactura reemplaza los ítems de una factura activa y emite
|
||||
// automáticamente la nota de crédito o débito que respalda la diferencia.
|
||||
// La factura, el stock, la nota y la contabilidad se actualizan en una única
|
||||
// transacción.
|
||||
func ModificarFactura(
|
||||
db *gorm.DB,
|
||||
repo *repositorios.Repositorios,
|
||||
empresaID, usuarioID, facturaID uint,
|
||||
entrada dto.ModificarFacturaDto,
|
||||
) (*dto.AjusteFacturaResponse, error) {
|
||||
motivo, err := validarMotivoAjuste(entrada.Motivo)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(entrada.Items) == 0 {
|
||||
return nil, errors.New("la factura debe tener al menos un ítem")
|
||||
}
|
||||
|
||||
items := append([]dto.ItemFacturaDto(nil), entrada.Items...)
|
||||
sort.Slice(items, func(i, j int) bool { return items[i].RepuestoID < items[j].RepuestoID })
|
||||
|
||||
repuestos := make(map[uint64]*models.Repuesto, len(items))
|
||||
nombres := make(map[uint64]string, len(items))
|
||||
vistos := make(map[uint64]bool, len(items))
|
||||
for i := range items {
|
||||
item := &items[i]
|
||||
if item.RepuestoID == 0 {
|
||||
return nil, fmt.Errorf("%w: repuesto inválido", ErrRepuestoNoEncontradoAjuste)
|
||||
}
|
||||
if vistos[item.RepuestoID] {
|
||||
return nil, fmt.Errorf("%w: %d", ErrItemDuplicadoAjuste, item.RepuestoID)
|
||||
}
|
||||
vistos[item.RepuestoID] = true
|
||||
|
||||
if err := validarCantidad(item.Cantidad); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
item.Cantidad = redondearCantidad(item.Cantidad)
|
||||
|
||||
repuestoPtr, err := repo.Repuesto.ObtenerPorID(uint(item.RepuestoID))
|
||||
if err != nil || repuestoPtr == nil || *repuestoPtr == nil {
|
||||
return nil, fmt.Errorf("%w: %d", ErrRepuestoNoEncontradoAjuste, item.RepuestoID)
|
||||
}
|
||||
repuesto := *repuestoPtr
|
||||
if repuesto.DeletedAt.Valid {
|
||||
return nil, fmt.Errorf("%w: %d", ErrRepuestoNoEncontradoAjuste, item.RepuestoID)
|
||||
}
|
||||
if item.PrecioUnitario <= 0 {
|
||||
item.PrecioUnitario = repuesto.Precio
|
||||
}
|
||||
if item.PrecioUnitario < 0 || math.IsNaN(item.PrecioUnitario) || math.IsInf(item.PrecioUnitario, 0) {
|
||||
return nil, ErrPrecioUnitarioInvalido
|
||||
}
|
||||
|
||||
repuestos[item.RepuestoID] = repuesto
|
||||
nombres[item.RepuestoID] = repuesto.Nombre
|
||||
}
|
||||
|
||||
var (
|
||||
factura *models.Factura
|
||||
notaTipo string
|
||||
notaResumen *dto.NotaResumen
|
||||
diferencia float64
|
||||
saldoAnterior float64
|
||||
saldoNuevo float64
|
||||
totalAnterior float64
|
||||
stocksAfectados []*models.Stock
|
||||
stocksConsumidos []*models.Stock
|
||||
saldosAnteriores = make(map[uint64]float64)
|
||||
)
|
||||
|
||||
err = db.Transaction(func(tx *gorm.DB) error {
|
||||
f, err := repo.Factura.BloquearPorID(tx, facturaID)
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return ErrFacturaNoEncontrada
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
factura = f
|
||||
saldoAnterior = redondearMonto(f.Saldo)
|
||||
totalAnterior = redondearMonto(f.Total)
|
||||
|
||||
if err := validarFacturaModificable(f); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
cantidadesAnteriores := make(map[uint64]float64, len(f.Detalles))
|
||||
for _, detalle := range f.Detalles {
|
||||
cantidadesAnteriores[detalle.RepuestoID] = redondearCantidad(
|
||||
cantidadesAnteriores[detalle.RepuestoID] + detalle.Cantidad,
|
||||
)
|
||||
}
|
||||
itemsAnteriores := append([]models.FacturaDetalle{}, f.Detalles...)
|
||||
|
||||
cantidadesNuevas := make(map[uint64]float64, len(items))
|
||||
detalles := make([]models.FacturaDetalle, 0, len(items))
|
||||
subtotal := 0.0
|
||||
for _, item := range items {
|
||||
sub := redondearMonto(item.Cantidad * item.PrecioUnitario)
|
||||
subtotal = redondearMonto(subtotal + sub)
|
||||
cantidadesNuevas[item.RepuestoID] = item.Cantidad
|
||||
detalles = append(detalles, models.FacturaDetalle{
|
||||
RepuestoID: item.RepuestoID,
|
||||
RepuestoNombre: nombres[item.RepuestoID],
|
||||
Cantidad: item.Cantidad,
|
||||
DescuentoID: f.DescuentoID,
|
||||
PrecioUnitario: item.PrecioUnitario,
|
||||
Subtotal: sub,
|
||||
AlicuotaIVA: f.AlicuotaIVA,
|
||||
})
|
||||
}
|
||||
|
||||
// Se conserva la proporción de descuento vigente en la factura para no
|
||||
// alterar el acuerdo comercial al cambiar únicamente los ítems.
|
||||
descuentoTotal := 0.0
|
||||
if f.Subtotal > 0 && f.DescuentoTotal > 0 {
|
||||
descuentoTotal = redondearMonto(subtotal * (f.DescuentoTotal / f.Subtotal))
|
||||
if descuentoTotal > subtotal {
|
||||
descuentoTotal = subtotal
|
||||
}
|
||||
}
|
||||
|
||||
alicuota := f.AlicuotaIVA
|
||||
if alicuota <= 0 {
|
||||
alicuota = 21
|
||||
}
|
||||
baseImponible := redondearMonto(subtotal - descuentoTotal)
|
||||
impuestos := redondearMonto(baseImponible * alicuota / 100)
|
||||
nuevoTotal := redondearMonto(baseImponible + impuestos)
|
||||
diferencia = redondearMonto(nuevoTotal - totalAnterior)
|
||||
if math.Abs(diferencia) < toleranciaCentavos {
|
||||
return ErrFacturaSinCambios
|
||||
}
|
||||
|
||||
cambios, err := prepararCambiosStock(tx, repo, f.AlmacenID, cantidadesAnteriores, cantidadesNuevas)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
notaID := uint(0)
|
||||
if diferencia < 0 {
|
||||
nota, err := crearNotaCreditoTx(tx, repo, empresaID, usuarioID, f, math.Abs(diferencia), motivo)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
notaTipo = "CREDITO"
|
||||
notaID = nota.ID
|
||||
notaResumen, err = dto_directors.NewNotaDirector().DesdeNotaCredito(nota)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
nota, err := crearNotaDebitoTx(tx, repo, empresaID, usuarioID, f, diferencia, motivo)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
notaTipo = "DEBITO"
|
||||
notaID = nota.ID
|
||||
notaResumen, err = dto_directors.NewNotaDirector().DesdeNotaDebito(nota)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
for _, cambio := range cambios {
|
||||
cambio.stock.Cantidad = redondearCantidad(cambio.stock.Cantidad + cambio.delta)
|
||||
if err := repo.Stock.ActualizarCantidades(tx, cambio.stock); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
tipoMovimiento := models.MovimientoVenta
|
||||
referencia := "NOTA_DEBITO"
|
||||
if cambio.delta < 0 {
|
||||
tipoMovimiento = models.MovimientoDevolucion
|
||||
referencia = "NOTA_CREDITO"
|
||||
}
|
||||
|
||||
movimiento, err := dto_directors.NewMovimientoStockDirector().Crear(dto_stock.MovimientoStockDto{
|
||||
StockID: cambio.stock.ID,
|
||||
RepuestoID: cambio.stock.RepuestoID,
|
||||
AlmacenID: cambio.stock.AlmacenID,
|
||||
Tipo: tipoMovimiento,
|
||||
Cantidad: redondearCantidad(math.Abs(cambio.delta)),
|
||||
SaldoAnterior: redondearCantidad(cambio.saldoAnterior),
|
||||
SaldoPosterior: redondearCantidad(cambio.stock.Cantidad),
|
||||
ReferenciaTipo: referencia,
|
||||
ReferenciaID: uint64(notaID),
|
||||
UsuarioID: usuarioID,
|
||||
Observacion: motivo,
|
||||
Fecha: time.Now(),
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := repo.MovimientoStock.Registrar(tx, movimiento); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
stocksAfectados = append(stocksAfectados, cambio.stock)
|
||||
if cambio.delta > 0 {
|
||||
stocksConsumidos = append(stocksConsumidos, cambio.stock)
|
||||
saldosAnteriores[cambio.stock.ID] = cambio.saldoAnterior
|
||||
}
|
||||
}
|
||||
|
||||
pagado := importePagadoFactura(f)
|
||||
saldoNuevo = redondearMonto(nuevoTotal - pagado)
|
||||
if saldoNuevo < toleranciaCentavos {
|
||||
saldoNuevo = 0
|
||||
}
|
||||
|
||||
nuevoEstado := estadoFacturaEmitida
|
||||
if saldoNuevo == 0 {
|
||||
nuevoEstado = estadoFacturaPagada
|
||||
} else if pagado > toleranciaCentavos {
|
||||
nuevoEstado = estadoFacturaParcial
|
||||
}
|
||||
|
||||
f, err = dto_directors.NewFacturaDirector().AplicarAjuste(f, dto.FacturaAjusteDto{
|
||||
Detalles: detalles,
|
||||
Subtotal: subtotal,
|
||||
DescuentoTotal: descuentoTotal,
|
||||
Impuestos: impuestos,
|
||||
Total: nuevoTotal,
|
||||
Saldo: saldoNuevo,
|
||||
Estado: nuevoEstado,
|
||||
Motivo: motivo,
|
||||
UsuarioID: usuarioID,
|
||||
ItemsAnteriores: itemsAnteriores,
|
||||
TotalAnterior: totalAnterior,
|
||||
ItemsNuevos: detalles,
|
||||
TotalNuevo: nuevoTotal,
|
||||
NotaTipo: notaTipo,
|
||||
NotaID: notaID,
|
||||
Fecha: time.Now(),
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := repo.Factura.GuardarAjuste(tx, f); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
registrarLogFactura(repo, empresaID, usuarioID, "MODIFICAR_FACTURA", []models_logs.LogDetalle{
|
||||
{NombreTabla: "factura", Columna: "facturaId", ValorNuevo: fmt.Sprintf("%d", factura.ID)},
|
||||
{NombreTabla: "factura", Columna: "numero", ValorNuevo: factura.Numero},
|
||||
{NombreTabla: "factura", Columna: "total", ValorAnterior: fmt.Sprintf("%.2f", totalAnterior), ValorNuevo: fmt.Sprintf("%.2f", factura.Total)},
|
||||
{NombreTabla: "factura", Columna: "saldo", ValorAnterior: fmt.Sprintf("%.2f", saldoAnterior), ValorNuevo: fmt.Sprintf("%.2f", factura.Saldo)},
|
||||
{NombreTabla: "nota", Columna: "tipo", ValorNuevo: notaTipo},
|
||||
{NombreTabla: "nota", Columna: "notaId", ValorNuevo: fmt.Sprintf("%d", notaResumen.ID)},
|
||||
{NombreTabla: "nota", Columna: "importe", ValorNuevo: fmt.Sprintf("%.2f", notaResumen.Importe)},
|
||||
})
|
||||
for _, stock := range stocksConsumidos {
|
||||
repuesto := repuestos[stock.RepuestoID]
|
||||
if repuesto == nil {
|
||||
continue
|
||||
}
|
||||
NotificarStockBajo(repo, empresaID, usuarioID, stock, repuesto, saldosAnteriores[stock.ID])
|
||||
}
|
||||
|
||||
respuesta, err := dto_directors.NewFacturaDirector().DesdeFactura(factura)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &dto.AjusteFacturaResponse{
|
||||
Factura: respuesta,
|
||||
Nota: notaResumen,
|
||||
Diferencia: diferencia,
|
||||
SaldoAnterior: saldoAnterior,
|
||||
SaldoNuevo: saldoNuevo,
|
||||
Stocks: stocksAfectados,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// prepararCambiosStock bloquea en orden estable las filas de stock que cambian
|
||||
// y valida la disponibilidad de los incrementos antes de aplicar la nota.
|
||||
func prepararCambiosStock(
|
||||
tx *gorm.DB,
|
||||
repo *repositorios.Repositorios,
|
||||
almacenID uint,
|
||||
anteriores, nuevas map[uint64]float64,
|
||||
) ([]cambioStockAjuste, error) {
|
||||
ids := make([]uint64, 0, len(anteriores)+len(nuevas))
|
||||
vistos := make(map[uint64]bool, len(anteriores)+len(nuevas))
|
||||
for id := range anteriores {
|
||||
if !vistos[id] {
|
||||
vistos[id] = true
|
||||
ids = append(ids, id)
|
||||
}
|
||||
}
|
||||
for id := range nuevas {
|
||||
if !vistos[id] {
|
||||
vistos[id] = true
|
||||
ids = append(ids, id)
|
||||
}
|
||||
}
|
||||
sort.Slice(ids, func(i, j int) bool { return ids[i] < ids[j] })
|
||||
|
||||
cambios := make([]cambioStockAjuste, 0, len(ids))
|
||||
for _, repuestoID := range ids {
|
||||
delta := redondearCantidad(nuevas[repuestoID] - anteriores[repuestoID])
|
||||
if delta == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
if delta > 0 {
|
||||
stock, err := repo.Stock.BloquearPorRepuestoAlmacen(tx, repuestoID, almacenID)
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, fmt.Errorf("%w: repuesto %d, disponible 0.000, solicitado %.3f", ErrStockInsuficienteAjuste, repuestoID, delta)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
disponible := redondearCantidad(stock.Cantidad - stock.CantidadReservada)
|
||||
if disponible+toleranciaCentavos < delta {
|
||||
return nil, fmt.Errorf("%w: repuesto %d, disponible %.3f, solicitado %.3f", ErrStockInsuficienteAjuste, repuestoID, disponible, delta)
|
||||
}
|
||||
cambios = append(cambios, cambioStockAjuste{
|
||||
stock: stock,
|
||||
delta: delta,
|
||||
saldoAnterior: stock.Cantidad,
|
||||
})
|
||||
continue
|
||||
}
|
||||
|
||||
stock, err := repo.Stock.BloquearOCrearPorRepuestoAlmacen(tx, repuestoID, almacenID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cambios = append(cambios, cambioStockAjuste{
|
||||
stock: stock,
|
||||
delta: delta,
|
||||
saldoAnterior: stock.Cantidad,
|
||||
})
|
||||
}
|
||||
|
||||
return cambios, nil
|
||||
}
|
||||
|
||||
func validarFacturaModificable(factura *models.Factura) error {
|
||||
if factura == nil {
|
||||
return ErrFacturaNoEncontrada
|
||||
}
|
||||
|
||||
estado := strings.ToUpper(strings.TrimSpace(factura.Estado))
|
||||
if estado == "CANCELADA" {
|
||||
return ErrFacturaCancelada
|
||||
}
|
||||
if estado != estadoFacturaEmitida && estado != estadoFacturaPagada {
|
||||
return ErrFacturaEstadoNoAjustable
|
||||
}
|
||||
|
||||
pagado := importePagadoFactura(factura)
|
||||
total := redondearMonto(factura.Total)
|
||||
|
||||
// Se contrasta el estado con los pagos reales para no habilitar ajustes
|
||||
// sobre facturas cuyo saldo quedó inconsistente.
|
||||
if pagado > toleranciaCentavos && pagado < total-toleranciaCentavos {
|
||||
return ErrFacturaPagoParcial
|
||||
}
|
||||
if estado == estadoFacturaEmitida && pagado > toleranciaCentavos {
|
||||
return ErrFacturaPagoParcial
|
||||
}
|
||||
if estado == estadoFacturaPagada && pagado < total-toleranciaCentavos {
|
||||
return ErrFacturaPagoParcial
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func importePagadoFactura(factura *models.Factura) float64 {
|
||||
if factura == nil {
|
||||
return 0
|
||||
}
|
||||
pagado := redondearMonto(factura.Total - factura.Saldo)
|
||||
if pagado < 0 {
|
||||
return 0
|
||||
}
|
||||
return pagado
|
||||
}
|
||||
|
||||
func validarMotivoAjuste(raw string) (string, error) {
|
||||
motivo := strings.TrimSpace(raw)
|
||||
if motivo == "" {
|
||||
return "", ErrMotivoRequeridoFactura
|
||||
}
|
||||
if utf8.RuneCountInString(motivo) > motivoAjusteMaximo {
|
||||
return "", ErrMotivoFacturaLargo
|
||||
}
|
||||
return motivo, nil
|
||||
}
|
||||
|
||||
func crearNotaCreditoTx(
|
||||
tx *gorm.DB,
|
||||
repo *repositorios.Repositorios,
|
||||
empresaID, usuarioID uint,
|
||||
factura *models.Factura,
|
||||
importe float64,
|
||||
motivo string,
|
||||
) (*models.NotaCredito, error) {
|
||||
if factura == nil {
|
||||
return nil, ErrFacturaNoEncontrada
|
||||
}
|
||||
if math.IsNaN(importe) || math.IsInf(importe, 0) || importe <= 0 {
|
||||
return nil, ErrImporteNotaInvalido
|
||||
}
|
||||
|
||||
nota := &models.NotaCredito{Motivo: motivo}
|
||||
nota.EmpresaID = empresaID
|
||||
nota.Estado = estadoFacturaEmitida
|
||||
nota.Total = redondearMonto(importe)
|
||||
nota.ResponsableID = usuarioID
|
||||
nota.FacturaOrigenID = factura.ID
|
||||
|
||||
if err := repo.NotaCredito.Crear(tx, nota); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := RegistrarAsientoNotaCredito(tx, repo, nota, factura.AlicuotaIVA); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return nota, nil
|
||||
}
|
||||
|
||||
func crearNotaDebitoTx(
|
||||
tx *gorm.DB,
|
||||
repo *repositorios.Repositorios,
|
||||
empresaID, usuarioID uint,
|
||||
factura *models.Factura,
|
||||
importe float64,
|
||||
motivo string,
|
||||
) (*models.NotaDebito, error) {
|
||||
if factura == nil {
|
||||
return nil, ErrFacturaNoEncontrada
|
||||
}
|
||||
if math.IsNaN(importe) || math.IsInf(importe, 0) || importe <= 0 {
|
||||
return nil, ErrImporteNotaInvalido
|
||||
}
|
||||
|
||||
nota := &models.NotaDebito{Motivo: motivo}
|
||||
nota.EmpresaID = empresaID
|
||||
nota.Estado = estadoFacturaEmitida
|
||||
nota.Total = redondearMonto(importe)
|
||||
nota.ResponsableID = usuarioID
|
||||
nota.FacturaOrigenID = factura.ID
|
||||
|
||||
if err := repo.NotaDebito.Crear(tx, nota); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := RegistrarAsientoNotaDebito(tx, repo, nota, factura.AlicuotaIVA); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return nota, nil
|
||||
}
|
||||
|
||||
// ObtenerNotasFactura devuelve las notas de crédito y débito asociadas a una
|
||||
// factura, ordenadas cronológicamente para mostrarlas en el comprobante.
|
||||
func ObtenerNotasFactura(repo *repositorios.Repositorios, facturaID uint) ([]dto.NotaResumen, error) {
|
||||
creditos, err := repo.NotaCredito.ListarPorFactura(facturaID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
debitos, err := repo.NotaDebito.ListarPorFactura(facturaID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
notas := make([]dto.NotaResumen, 0, len(creditos)+len(debitos))
|
||||
director := dto_directors.NewNotaDirector()
|
||||
for i := range creditos {
|
||||
resumen, err := director.DesdeNotaCredito(&creditos[i])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resumen != nil {
|
||||
notas = append(notas, *resumen)
|
||||
}
|
||||
}
|
||||
for i := range debitos {
|
||||
resumen, err := director.DesdeNotaDebito(&debitos[i])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resumen != nil {
|
||||
notas = append(notas, *resumen)
|
||||
}
|
||||
}
|
||||
sort.SliceStable(notas, func(i, j int) bool {
|
||||
return notas[i].Fecha.Before(notas[j].Fecha)
|
||||
})
|
||||
return notas, nil
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
|
||||
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||
dto "repuestera_back/dto/Facturas"
|
||||
dto_stock "repuestera_back/dto/Stock"
|
||||
"repuestera_back/models"
|
||||
models_logs "repuestera_back/models/logs"
|
||||
"repuestera_back/repositorios"
|
||||
)
|
||||
|
||||
// Errores de dominio de la cancelación de facturas.
|
||||
var (
|
||||
ErrFacturaCancelacionConPagos = errors.New("la factura no puede cancelarse porque ya tiene pagos registrados")
|
||||
ErrFacturaEstadoNoCancelable = errors.New("la factura no se encuentra en un estado cancelable")
|
||||
)
|
||||
|
||||
type reposicionStock struct {
|
||||
stock *models.Stock
|
||||
cantidad float64
|
||||
saldoAnterior float64
|
||||
}
|
||||
|
||||
// CancelarFactura anula una factura activa sin pagos, emite la nota de crédito
|
||||
// por el total y reincorpora el stock vendido. Todo se ejecuta en una única
|
||||
// transacción para que la factura, la nota, el stock y la contabilidad queden
|
||||
// consistentes.
|
||||
func CancelarFactura(
|
||||
db *gorm.DB,
|
||||
repo *repositorios.Repositorios,
|
||||
empresaID, usuarioID, facturaID uint,
|
||||
entrada dto.CancelarFacturaDto,
|
||||
) (*dto.AjusteFacturaResponse, error) {
|
||||
motivo, err := validarMotivoAjuste(entrada.Motivo)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var (
|
||||
factura *models.Factura
|
||||
notaResumen *dto.NotaResumen
|
||||
totalAnterior float64
|
||||
saldoAnterior float64
|
||||
stocks []*models.Stock
|
||||
)
|
||||
|
||||
err = db.Transaction(func(tx *gorm.DB) error {
|
||||
f, err := repo.Factura.BloquearPorID(tx, facturaID)
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return ErrFacturaNoEncontrada
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
factura = f
|
||||
totalAnterior = redondearMonto(f.Total)
|
||||
saldoAnterior = redondearMonto(f.Saldo)
|
||||
|
||||
if err := validarFacturaCancelable(f); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
cantidades := make(map[uint64]float64, len(f.Detalles))
|
||||
for _, detalle := range f.Detalles {
|
||||
cantidades[detalle.RepuestoID] = redondearCantidad(
|
||||
cantidades[detalle.RepuestoID] + detalle.Cantidad,
|
||||
)
|
||||
}
|
||||
|
||||
notaID := uint(0)
|
||||
if totalAnterior > toleranciaCentavos {
|
||||
nota, err := crearNotaCreditoTx(tx, repo, empresaID, usuarioID, f, totalAnterior, motivo)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
notaID = nota.ID
|
||||
notaResumen, err = dto_directors.NewNotaDirector().DesdeNotaCredito(nota)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
repuestos := make([]uint64, 0, len(cantidades))
|
||||
for repuestoID := range cantidades {
|
||||
repuestos = append(repuestos, repuestoID)
|
||||
}
|
||||
sort.Slice(repuestos, func(i, j int) bool { return repuestos[i] < repuestos[j] })
|
||||
|
||||
referenciaTipo := "CANCELACION_FACTURA"
|
||||
if notaID > 0 {
|
||||
referenciaTipo = "NOTA_CREDITO"
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
for _, repuestoID := range repuestos {
|
||||
cantidad := cantidades[repuestoID]
|
||||
if cantidad <= 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
stock, err := repo.Stock.BloquearOCrearPorRepuestoAlmacen(tx, repuestoID, f.AlmacenID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
saldoStock := redondearCantidad(stock.Cantidad)
|
||||
stock.Cantidad = redondearCantidad(stock.Cantidad + cantidad)
|
||||
if err := repo.Stock.ActualizarCantidades(tx, stock); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
movimiento, err := dto_directors.NewMovimientoStockDirector().Crear(dto_stock.MovimientoStockDto{
|
||||
StockID: stock.ID,
|
||||
RepuestoID: stock.RepuestoID,
|
||||
AlmacenID: stock.AlmacenID,
|
||||
Tipo: models.MovimientoDevolucion,
|
||||
Cantidad: cantidad,
|
||||
SaldoAnterior: saldoStock,
|
||||
SaldoPosterior: stock.Cantidad,
|
||||
ReferenciaTipo: referenciaTipo,
|
||||
ReferenciaID: uint64(notaID),
|
||||
UsuarioID: usuarioID,
|
||||
Observacion: motivo,
|
||||
Fecha: now,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := repo.MovimientoStock.Registrar(tx, movimiento); err != nil {
|
||||
return err
|
||||
}
|
||||
stocks = append(stocks, stock)
|
||||
}
|
||||
|
||||
f, err = dto_directors.NewFacturaDirector().AplicarAjuste(f, dto.FacturaAjusteDto{
|
||||
Detalles: f.Detalles,
|
||||
Subtotal: f.Subtotal,
|
||||
DescuentoTotal: f.DescuentoTotal,
|
||||
Impuestos: f.Impuestos,
|
||||
Total: f.Total,
|
||||
Saldo: 0,
|
||||
Estado: "CANCELADA",
|
||||
Motivo: motivo,
|
||||
UsuarioID: usuarioID,
|
||||
ItemsAnteriores: f.Detalles,
|
||||
TotalAnterior: totalAnterior,
|
||||
TotalNuevo: 0,
|
||||
NotaTipo: "CREDITO",
|
||||
NotaID: notaID,
|
||||
Fecha: now,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return repo.Factura.GuardarAjuste(tx, f)
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
detallesLog := []models_logs.LogDetalle{
|
||||
{NombreTabla: "factura", Columna: "facturaId", ValorNuevo: fmt.Sprintf("%d", factura.ID)},
|
||||
{NombreTabla: "factura", Columna: "numero", ValorNuevo: factura.Numero},
|
||||
{NombreTabla: "factura", Columna: "estado", ValorAnterior: "EMITIDA", ValorNuevo: factura.Estado},
|
||||
{NombreTabla: "factura", Columna: "saldo", ValorAnterior: fmt.Sprintf("%.2f", saldoAnterior), ValorNuevo: fmt.Sprintf("%.2f", factura.Saldo)},
|
||||
}
|
||||
if notaResumen != nil {
|
||||
detallesLog = append(detallesLog,
|
||||
models_logs.LogDetalle{NombreTabla: "nota", Columna: "tipo", ValorNuevo: "CREDITO"},
|
||||
models_logs.LogDetalle{NombreTabla: "nota", Columna: "notaId", ValorNuevo: fmt.Sprintf("%d", notaResumen.ID)},
|
||||
models_logs.LogDetalle{NombreTabla: "nota", Columna: "importe", ValorNuevo: fmt.Sprintf("%.2f", notaResumen.Importe)},
|
||||
)
|
||||
}
|
||||
registrarLogFactura(repo, empresaID, usuarioID, "CANCELAR_FACTURA", detallesLog)
|
||||
|
||||
respuesta, err := dto_directors.NewFacturaDirector().DesdeFactura(factura)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &dto.AjusteFacturaResponse{
|
||||
Factura: respuesta,
|
||||
Nota: notaResumen,
|
||||
Diferencia: -totalAnterior,
|
||||
SaldoAnterior: saldoAnterior,
|
||||
SaldoNuevo: 0,
|
||||
Stocks: stocks,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func validarFacturaCancelable(factura *models.Factura) error {
|
||||
if factura == nil {
|
||||
return ErrFacturaNoEncontrada
|
||||
}
|
||||
|
||||
estado := strings.ToUpper(strings.TrimSpace(factura.Estado))
|
||||
if estado == "CANCELADA" {
|
||||
return ErrFacturaCancelada
|
||||
}
|
||||
if estado != estadoFacturaEmitida {
|
||||
return ErrFacturaEstadoNoCancelable
|
||||
}
|
||||
if importePagadoFactura(factura) > toleranciaCentavos {
|
||||
return ErrFacturaCancelacionConPagos
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { API_URL } from '$lib/env';
|
||||
import { getToken } from '../token';
|
||||
|
||||
export async function cancelarFactura(facturaId: number, motivo: string) {
|
||||
try {
|
||||
const req = await fetch(`${API_URL}/facturas/${facturaId}/cancelar`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${getToken()}` },
|
||||
body: JSON.stringify({ motivo })
|
||||
});
|
||||
const data = await req.json();
|
||||
if (req.ok) return data;
|
||||
return data.error ?? 'No se pudo cancelar la factura';
|
||||
} catch {
|
||||
return 'No se pudo alcanzar el servidor';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { API_URL } from '$lib/env';
|
||||
import { getToken } from '../token';
|
||||
|
||||
export interface ItemModificarFactura {
|
||||
repuestoId: number;
|
||||
cantidad: number;
|
||||
precioUnitario: number;
|
||||
}
|
||||
|
||||
export interface ModificarFacturaPayload {
|
||||
items: ItemModificarFactura[];
|
||||
motivo: string;
|
||||
}
|
||||
|
||||
export async function modificarFactura(facturaId: number, payload: ModificarFacturaPayload) {
|
||||
try {
|
||||
const req = await fetch(`${API_URL}/facturas/${facturaId}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${getToken()}` },
|
||||
body: JSON.stringify(payload)
|
||||
});
|
||||
const data = await req.json();
|
||||
if (req.ok) return data;
|
||||
return data.error ?? 'No se pudo modificar la factura';
|
||||
} catch {
|
||||
return 'No se pudo alcanzar el servidor';
|
||||
}
|
||||
}
|
||||
@@ -24,6 +24,7 @@
|
||||
import type { Factura } from '../../types';
|
||||
import ModalVerComprobante from './ModalVerComprobante.svelte';
|
||||
import RegistrarPagoModal from './RegistrarPagoModal.svelte';
|
||||
import CancelarFacturaModal from './CancelarFacturaModal.svelte';
|
||||
|
||||
let { data } = $props();
|
||||
|
||||
@@ -59,6 +60,8 @@
|
||||
let openVer = $state(false);
|
||||
let facturaPago = $state<Factura | null>(null);
|
||||
let openPago = $state(false);
|
||||
let facturaCancelar = $state<Factura | null>(null);
|
||||
let openCancelar = $state(false);
|
||||
|
||||
function buscar() {
|
||||
const params = new URLSearchParams();
|
||||
@@ -237,7 +240,8 @@
|
||||
kind="ghost"
|
||||
size="small"
|
||||
icon={Edit}
|
||||
disabled={f.estado === 'CANCELADA' || f.estado === 'PAGADA'}>Modificar</Button
|
||||
disabled={f.estado !== 'EMITIDA' && f.estado !== 'PAGADA'}
|
||||
onclick={() => goto(`/facturas/${f.ID}/modificar`)}>Modificar</Button
|
||||
>
|
||||
<Button
|
||||
kind="ghost"
|
||||
@@ -255,7 +259,11 @@
|
||||
kind="danger-ghost"
|
||||
size="small"
|
||||
icon={Close}
|
||||
disabled={f.estado === 'CANCELADA' || f.estado === 'PAGADA'}>Cancelar</Button
|
||||
disabled={f.estado !== 'EMITIDA'}
|
||||
onclick={() => {
|
||||
facturaCancelar = f;
|
||||
openCancelar = true;
|
||||
}}>Cancelar</Button
|
||||
>
|
||||
</div>
|
||||
</TableCell>
|
||||
@@ -274,3 +282,14 @@
|
||||
factura={facturaPago}
|
||||
onClose={() => (facturaPago = null)}
|
||||
/>
|
||||
<CancelarFacturaModal
|
||||
bind:open={openCancelar}
|
||||
factura={facturaCancelar}
|
||||
onClose={() => (facturaCancelar = null)}
|
||||
onCancelada={(resultado) => {
|
||||
info = resultado.nota
|
||||
? `Factura cancelada. Se emitió ${resultado.nota.numero} por ${formatMonto(resultado.nota.importe)}.`
|
||||
: 'Factura cancelada correctamente.';
|
||||
facturaCancelar = null;
|
||||
}}
|
||||
/>
|
||||
@@ -0,0 +1,145 @@
|
||||
<script lang="ts">
|
||||
import { Button, InlineNotification, Modal, TextInput } from 'carbon-components-svelte';
|
||||
import { invalidate } from '$app/navigation';
|
||||
import { cancelarFactura } from '$lib/hooks/facturas/cancelarFactura';
|
||||
import { obtenerAlmacenes } from '$lib/hooks/almacenes/obtenerAlmacenes';
|
||||
import type { AjusteFacturaResponse, Almacen, Factura } from '../../types';
|
||||
|
||||
let {
|
||||
open = $bindable(),
|
||||
factura = null,
|
||||
onCancelada,
|
||||
onClose
|
||||
}: {
|
||||
open?: boolean;
|
||||
factura?: Factura | null;
|
||||
onCancelada?: (resultado: AjusteFacturaResponse) => void;
|
||||
onClose?: () => void;
|
||||
} = $props();
|
||||
|
||||
let motivo = $state('');
|
||||
let enviando = $state(false);
|
||||
let error = $state('');
|
||||
let almacenes = $state<Almacen[]>([]);
|
||||
|
||||
let cliente = $derived(factura?.cliente?.nombre ?? '-');
|
||||
let total = $derived(Number(factura?.total ?? 0));
|
||||
let almacen = $derived(almacenes.find((item) => item.id === factura?.almacenId));
|
||||
let almacenTexto = $derived(
|
||||
almacen
|
||||
? `${almacen.codigo}${almacen.ubicacion ? ` · ${almacen.ubicacion}` : ''}`
|
||||
: factura?.almacenId
|
||||
? `Almacén ${factura.almacenId}`
|
||||
: '-'
|
||||
);
|
||||
|
||||
function formatMonto(valor?: number): string {
|
||||
if (valor === undefined || valor === null) return '-';
|
||||
return valor.toLocaleString('es-AR', { style: 'currency', currency: 'ARS' });
|
||||
}
|
||||
|
||||
function cerrar() {
|
||||
open = false;
|
||||
onClose?.();
|
||||
}
|
||||
|
||||
async function cargarAlmacenes() {
|
||||
const res = await obtenerAlmacenes(fetch);
|
||||
almacenes = Array.isArray(res) ? res : [];
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
if (!open) return;
|
||||
motivo = '';
|
||||
error = '';
|
||||
enviando = false;
|
||||
void cargarAlmacenes();
|
||||
});
|
||||
|
||||
async function confirmar() {
|
||||
if (enviando || !factura) return;
|
||||
error = '';
|
||||
|
||||
const motivoLimpio = motivo.trim();
|
||||
if (!motivoLimpio) {
|
||||
error = 'Ingresá el motivo de la cancelación.';
|
||||
return;
|
||||
}
|
||||
if (motivoLimpio.length > 40) {
|
||||
error = 'El motivo no puede superar los 40 caracteres.';
|
||||
return;
|
||||
}
|
||||
|
||||
enviando = true;
|
||||
const respuesta = await cancelarFactura(factura.ID, motivoLimpio);
|
||||
enviando = false;
|
||||
|
||||
if (typeof respuesta === 'string') {
|
||||
error = respuesta;
|
||||
return;
|
||||
}
|
||||
|
||||
await invalidate('facturas:load');
|
||||
open = false;
|
||||
onCancelada?.(respuesta as AjusteFacturaResponse);
|
||||
}
|
||||
</script>
|
||||
|
||||
<form
|
||||
id="cancelar-factura-form"
|
||||
onsubmit={(event) => {
|
||||
event.preventDefault();
|
||||
confirmar();
|
||||
}}
|
||||
>
|
||||
<Modal
|
||||
bind:open
|
||||
modalHeading={`Cancelar Factura ${factura?.numero ?? ''}`}
|
||||
secondaryButtonText="Volver"
|
||||
primaryButtonText={enviando ? 'Cancelando...' : 'Confirmar Cancelación'}
|
||||
primaryButtonDisabled={enviando}
|
||||
formId="cancelar-factura-form"
|
||||
hasForm
|
||||
on:click:button--secondary={cerrar}
|
||||
danger
|
||||
>
|
||||
<div class="space-y-4">
|
||||
<InlineNotification
|
||||
kind="warning"
|
||||
title="Atención"
|
||||
subtitle="Esta acción generará automáticamente una Nota de Crédito asociada a esta factura."
|
||||
hideCloseButton
|
||||
/>
|
||||
|
||||
{#if error}
|
||||
<InlineNotification kind="error" title="Error" subtitle={error} hideCloseButton />
|
||||
{/if}
|
||||
|
||||
<div class="grid grid-cols-1 gap-3 md:grid-cols-2">
|
||||
<div>
|
||||
<span class="block text-sm font-medium">Cliente</span>
|
||||
<span class="block py-2">{cliente}</span>
|
||||
</div>
|
||||
<div>
|
||||
<span class="block text-sm font-medium">Total</span>
|
||||
<span class="block py-2">{formatMonto(total)}</span>
|
||||
</div>
|
||||
<div>
|
||||
<span class="block text-sm font-medium">Almacén de devolución</span>
|
||||
<span class="block py-2">{almacenTexto}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<TextInput
|
||||
labelText="Motivo de Cancelación"
|
||||
bind:value={motivo}
|
||||
maxlength={40}
|
||||
placeholder="Detallá el motivo de la cancelación"
|
||||
disabled={enviando}
|
||||
/>
|
||||
<p class="mt-1 text-xs text-gray-500">{motivo.length}/40</p>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
</form>
|
||||
@@ -229,6 +229,36 @@
|
||||
</Table>
|
||||
</TableContainer>
|
||||
|
||||
<!-- Notas de crédito y débito asociadas -->
|
||||
{#if comprobante.notas && comprobante.notas.length > 0}
|
||||
<div class="space-y-2">
|
||||
<TableContainer title="Notas de ajuste">
|
||||
<Table size="compact">
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
<TableHeader>Fecha</TableHeader>
|
||||
<TableHeader>Nota</TableHeader>
|
||||
<TableHeader>Motivo</TableHeader>
|
||||
<TableHeader>Importe</TableHeader>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
{#each comprobante.notas as nota (nota.id)}
|
||||
<TableRow>
|
||||
<TableCell>{formatFecha(nota.fecha)}</TableCell>
|
||||
<TableCell>
|
||||
<Tag type={nota.tipo === 'CREDITO' ? 'red' : 'green'}>{nota.numero}</Tag>
|
||||
</TableCell>
|
||||
<TableCell class="text-gray-500">{nota.motivo}</TableCell>
|
||||
<TableCell class="text-right font-medium">{formatMonto(nota.importe)}</TableCell>
|
||||
</TableRow>
|
||||
{/each}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</TableContainer>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<!-- Pagos realizados usando Carbon Table -->
|
||||
<div class="space-y-2">
|
||||
<TableContainer>
|
||||
|
||||
@@ -0,0 +1,352 @@
|
||||
<script lang="ts">
|
||||
import Header from '$lib/components/Header.svelte';
|
||||
import {
|
||||
Button,
|
||||
Checkbox,
|
||||
DataTable,
|
||||
InlineNotification,
|
||||
NumberInput,
|
||||
TextInput,
|
||||
Tag
|
||||
} from 'carbon-components-svelte';
|
||||
import { ArrowLeft, Save } from 'carbon-icons-svelte';
|
||||
import { goto } from '$app/navigation';
|
||||
import { untrack } from 'svelte';
|
||||
import { modificarFactura } from '$lib/hooks/facturas/modificarFactura';
|
||||
import type { AjusteFacturaResponse, Almacen, ComprobanteResponse } from '../../../../types';
|
||||
|
||||
let { data } = $props();
|
||||
|
||||
interface Fila {
|
||||
key: number;
|
||||
repuestoId: number;
|
||||
nombre: string;
|
||||
cantidadOriginal: number;
|
||||
precioOriginal: number;
|
||||
incluir: boolean;
|
||||
cantidad: number;
|
||||
precio: number;
|
||||
}
|
||||
|
||||
let comprobante = $derived<ComprobanteResponse | null>(data.comprobante ?? null);
|
||||
let almacenes = $derived<Almacen[]>(Array.isArray(data.almacenes) ? data.almacenes : []);
|
||||
let almacenActual = $derived(almacenes.find((almacen) => almacen.id === comprobante?.almacenId));
|
||||
let error = $state('');
|
||||
let info = $state('');
|
||||
let enviando = $state(false);
|
||||
let resultado = $state<AjusteFacturaResponse | null>(null);
|
||||
let motivo = $state('');
|
||||
|
||||
let filas = $state<Fila[]>(
|
||||
untrack(() =>
|
||||
(data.comprobante?.detalles ?? []).map((detalle, indice) => ({
|
||||
key: indice,
|
||||
repuestoId: Number(detalle.repuestoId),
|
||||
nombre: detalle.repuestoNombre ?? `Repuesto ${detalle.repuestoId}`,
|
||||
cantidadOriginal: Number(detalle.cantidad),
|
||||
precioOriginal: Number(detalle.precioUnitario),
|
||||
incluir: false,
|
||||
cantidad: Number(detalle.cantidad),
|
||||
precio:
|
||||
data.preciosActuales?.[Number(detalle.repuestoId)] ??
|
||||
Number(detalle.precioUnitario)
|
||||
}))
|
||||
)
|
||||
);
|
||||
|
||||
function redondear(valor: number): number {
|
||||
return Math.round((valor + Number.EPSILON) * 100) / 100;
|
||||
}
|
||||
|
||||
function formatFecha(iso?: string): string {
|
||||
if (!iso) return '-';
|
||||
try {
|
||||
return new Date(iso).toLocaleDateString('es-AR');
|
||||
} catch {
|
||||
return iso;
|
||||
}
|
||||
}
|
||||
|
||||
function formatMonto(valor?: number): string {
|
||||
if (valor === undefined || valor === null) return '-';
|
||||
return valor.toLocaleString('es-AR', { style: 'currency', currency: 'ARS' });
|
||||
}
|
||||
|
||||
const headers = [
|
||||
{ key: 'ajustar', value: 'Ajustar', empty: false },
|
||||
{ key: 'nombre', value: 'Ítem', empty: false },
|
||||
{ key: 'cantidadOriginal', value: 'Cant. Original', empty: false },
|
||||
{ key: 'cantidadAjustada', value: 'Cant. Ajustada', empty: false },
|
||||
{ key: 'precioOriginal', value: 'Precio Unit. Original', empty: false },
|
||||
{ key: 'precioAjustado', value: 'Precio Unit. Ajustado', empty: false },
|
||||
{ key: 'subtotal', value: 'Subtotal del Ajuste', empty: false }
|
||||
];
|
||||
|
||||
const headersDatos = [
|
||||
{ key: 'campo', value: 'Campo' },
|
||||
{ key: 'valor', value: 'Valor' }
|
||||
];
|
||||
|
||||
let filasDatos = $derived.by(() => {
|
||||
if (!comprobante) return [];
|
||||
const filas = [
|
||||
{ id: 'cliente', campo: 'Cliente', valor: comprobante.cliente?.nombre ?? '-' },
|
||||
{ id: 'fecha', campo: 'Fecha', valor: formatFecha(comprobante.FechaEmision) },
|
||||
{
|
||||
id: 'almacen',
|
||||
campo: 'Almacén',
|
||||
valor: almacenActual
|
||||
? `${almacenActual.codigo}${almacenActual.ubicacion ? ` · ${almacenActual.ubicacion}` : ''}`
|
||||
: comprobante.almacenId
|
||||
? `Almacén ${comprobante.almacenId}`
|
||||
: '-'
|
||||
},
|
||||
{ id: 'total', campo: 'Total', valor: formatMonto(comprobante.total) },
|
||||
{ id: 'estado', campo: 'Estado', valor: comprobante.estado }
|
||||
];
|
||||
if (comprobante.motivoUltimaEdicion) {
|
||||
filas.push({
|
||||
id: 'ultima-edicion',
|
||||
campo: 'Última edición',
|
||||
valor: comprobante.motivoUltimaEdicion
|
||||
});
|
||||
}
|
||||
return filas;
|
||||
});
|
||||
|
||||
const headersResumen = [
|
||||
{ key: 'concepto', value: 'Concepto', empty: false },
|
||||
{ key: 'monto', value: 'Monto', empty: false }
|
||||
];
|
||||
|
||||
let filasResumen = $derived.by(() => [
|
||||
{ id: 'subtotal', concepto: 'Subtotal', monto: formatMonto(subtotalNuevo) },
|
||||
{ id: 'descuento', concepto: 'Descuento', monto: formatMonto(descuentoNuevo) },
|
||||
{ id: 'iva', concepto: `IVA (${alicuota}%)`, monto: formatMonto(impuestosNuevos) },
|
||||
{ id: 'total', concepto: 'Total nuevo', monto: formatMonto(totalNuevo) }
|
||||
]);
|
||||
|
||||
function subtotalAjuste(fila: Fila): number {
|
||||
if (!fila.incluir) return 0;
|
||||
return redondear(fila.cantidad * fila.precio - fila.cantidadOriginal * fila.precioOriginal);
|
||||
}
|
||||
|
||||
let subtotalOriginal = $derived(
|
||||
redondear(
|
||||
(comprobante?.detalles ?? []).reduce(
|
||||
(acc, detalle) => acc + Number(detalle.cantidad) * Number(detalle.precioUnitario),
|
||||
0
|
||||
)
|
||||
)
|
||||
);
|
||||
|
||||
let subtotalNuevo = $derived(
|
||||
redondear(
|
||||
filas.reduce((acc, fila) => {
|
||||
if (!fila.incluir) return acc + fila.cantidadOriginal * fila.precioOriginal;
|
||||
return acc + fila.cantidad * fila.precio;
|
||||
}, 0)
|
||||
)
|
||||
);
|
||||
|
||||
let descuentoOriginal = $derived(Number(comprobante?.descuentoTotal ?? 0));
|
||||
|
||||
// El backend conserva la proporción de descuento vigente; se replica para
|
||||
// que el monto proyectado en pantalla coincida con el que se persistirá.
|
||||
let descuentoNuevo = $derived.by(() => {
|
||||
const baseOriginal = Number(comprobante?.subtotal ?? subtotalOriginal);
|
||||
if (baseOriginal <= 0 || descuentoOriginal <= 0) return 0;
|
||||
const proporcionado = subtotalNuevo * (descuentoOriginal / baseOriginal);
|
||||
return redondear(Math.min(proporcionado, subtotalNuevo));
|
||||
});
|
||||
|
||||
let alicuota = $derived(Number(comprobante?.alicuotaIva ?? 21));
|
||||
let baseNueva = $derived(redondear(subtotalNuevo - descuentoNuevo));
|
||||
let impuestosNuevos = $derived(redondear((baseNueva * alicuota) / 100));
|
||||
let totalNuevo = $derived(redondear(baseNueva + impuestosNuevos));
|
||||
let totalActual = $derived(Number(comprobante?.total ?? 0));
|
||||
let diferencia = $derived(redondear(totalNuevo - totalActual));
|
||||
|
||||
let tipoNota = $derived(
|
||||
diferencia < -0.004
|
||||
? 'Nota de Crédito (Bajar Monto)'
|
||||
: diferencia > 0.004
|
||||
? 'Nota de Débito (Subir Monto)'
|
||||
: 'Sin cambios'
|
||||
);
|
||||
|
||||
let filasSeleccionadas = $derived(filas.filter((fila) => fila.incluir).length);
|
||||
|
||||
async function guardar() {
|
||||
if (enviando) return;
|
||||
error = '';
|
||||
|
||||
if (!comprobante) {
|
||||
error = 'No se pudo cargar la factura.';
|
||||
return;
|
||||
}
|
||||
if (filasSeleccionadas === 0) {
|
||||
error = 'Tildá al menos un ítem para ajustar.';
|
||||
return;
|
||||
}
|
||||
const motivoLimpio = motivo.trim();
|
||||
if (!motivoLimpio) {
|
||||
error = 'Ingresá el motivo de la modificación.';
|
||||
return;
|
||||
}
|
||||
if (motivoLimpio.length > 40) {
|
||||
error = 'El motivo no puede superar los 40 caracteres.';
|
||||
return;
|
||||
}
|
||||
if (Math.abs(diferencia) < 0.005) {
|
||||
error = 'La modificación no produce cambios de importe.';
|
||||
return;
|
||||
}
|
||||
for (const fila of filas) {
|
||||
if (!fila.incluir) continue;
|
||||
if (!(fila.cantidad > 0)) {
|
||||
error = `La cantidad de "${fila.nombre}" debe ser mayor a cero.`;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
enviando = true;
|
||||
const respuesta = await modificarFactura(comprobante.ID, {
|
||||
items: filas.map((fila) => ({
|
||||
repuestoId: fila.repuestoId,
|
||||
cantidad: fila.incluir ? fila.cantidad : fila.cantidadOriginal,
|
||||
precioUnitario: fila.incluir ? fila.precio : fila.precioOriginal
|
||||
})),
|
||||
motivo: motivoLimpio
|
||||
});
|
||||
enviando = false;
|
||||
|
||||
if (typeof respuesta === 'string') {
|
||||
error = respuesta;
|
||||
return;
|
||||
}
|
||||
|
||||
resultado = respuesta as AjusteFacturaResponse;
|
||||
info = resultado.nota
|
||||
? `Factura modificada. Se emitió ${resultado.nota.numero} por ${formatMonto(resultado.nota.importe)}.`
|
||||
: 'Factura modificada correctamente.';
|
||||
}
|
||||
</script>
|
||||
|
||||
<Header />
|
||||
|
||||
<div class="page-container">
|
||||
<div class="mb-4 flex items-center gap-2">
|
||||
<Button kind="ghost" icon={ArrowLeft} onclick={() => goto('/facturas')}>Volver</Button>
|
||||
<h1 class="page-title">
|
||||
Modificar Factura {comprobante?.numero ?? ''}
|
||||
</h1>
|
||||
</div>
|
||||
|
||||
{#if error}
|
||||
<InlineNotification kind="error" title="Error" subtitle={error} hideCloseButton />
|
||||
{/if}
|
||||
{#if info}
|
||||
<InlineNotification kind="success" title="Modificación exitosa" subtitle={info} hideCloseButton />
|
||||
{/if}
|
||||
|
||||
{#if !comprobante}
|
||||
<InlineNotification
|
||||
kind="error"
|
||||
title="Factura no disponible"
|
||||
subtitle={data.error || 'No se pudo cargar la factura solicitada.'}
|
||||
hideCloseButton
|
||||
/>
|
||||
{:else}
|
||||
<div class="w-full space-y-4 px-4 md:px-6">
|
||||
<!-- Datos actuales -->
|
||||
<div class="rounded border p-4">
|
||||
<h2 class="mb-3 text-lg font-semibold">Datos Actuales</h2>
|
||||
<DataTable size="compact" headers={headersDatos} rows={filasDatos as any} />
|
||||
</div>
|
||||
|
||||
<!-- Ítems -->
|
||||
<div class="rounded border p-4">
|
||||
<div class="mb-3 flex flex-wrap items-center justify-between gap-2">
|
||||
<h2 class="text-lg font-semibold">Ítems de la Factura</h2>
|
||||
<p class="text-sm text-gray-600">Tildá los ítems que se ajustan</p>
|
||||
</div>
|
||||
<DataTable size="compact" {headers} rows={filas as any}>
|
||||
<svelte:fragment slot="cell" let:row let:cell>
|
||||
{@const fila = row as unknown as Fila}
|
||||
{#if cell.key === 'ajustar'}
|
||||
<Checkbox hideLabel labelText="Ajustar" bind:checked={fila.incluir} />
|
||||
{:else if cell.key === 'nombre'}
|
||||
{fila.nombre}
|
||||
{:else if cell.key === 'cantidadOriginal'}
|
||||
{fila.cantidadOriginal}
|
||||
{:else if cell.key === 'cantidadAjustada'}
|
||||
<NumberInput
|
||||
hideLabel
|
||||
labelText="Cantidad ajustada"
|
||||
bind:value={fila.cantidad}
|
||||
min={0}
|
||||
step={1}
|
||||
disabled={!fila.incluir}
|
||||
class="w-full"
|
||||
/>
|
||||
{:else if cell.key === 'precioOriginal'}
|
||||
{formatMonto(fila.precioOriginal)}
|
||||
{:else if cell.key === 'precioAjustado'}
|
||||
{formatMonto(fila.precio)}
|
||||
{:else if cell.key === 'subtotal'}
|
||||
{formatMonto(subtotalAjuste(fila))}
|
||||
{/if}
|
||||
</svelte:fragment>
|
||||
</DataTable>
|
||||
<p class="mt-2 text-xs text-gray-500">
|
||||
El precio unitario ajustado se toma del precio actual del producto y no es editable.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<!-- Nota de ajuste -->
|
||||
<div class="rounded border p-4">
|
||||
<h2 class="mb-3 text-lg font-semibold">Tipo de Nota</h2>
|
||||
<div class="space-y-3">
|
||||
<div>
|
||||
<span class="block text-sm font-medium">Tipo</span>
|
||||
<span class="block py-2">{tipoNota}</span>
|
||||
<p class="text-sm text-gray-600">
|
||||
El tipo se determina automáticamente según el signo de la diferencia.
|
||||
</p>
|
||||
</div>
|
||||
<div class="grid grid-cols-1 gap-3 md:grid-cols-2">
|
||||
<div>
|
||||
<span class="block text-sm font-medium">Monto Total del Ajuste (calculado)</span>
|
||||
<span class="block py-2">{formatMonto(diferencia)}</span>
|
||||
</div>
|
||||
<div class="space-y-1 text-sm">
|
||||
<DataTable size="compact" headers={headersResumen} rows={filasResumen as any} />
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<TextInput
|
||||
labelText="Motivo General"
|
||||
bind:value={motivo}
|
||||
maxlength={40}
|
||||
placeholder="Detallá el motivo de la modificación"
|
||||
disabled={!!resultado}
|
||||
/>
|
||||
<p class="mt-1 text-xs text-gray-500">{motivo.length}/40</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex justify-end gap-2 pt-2">
|
||||
<Button kind="secondary" onclick={() => goto('/facturas')} disabled={enviando}>
|
||||
{resultado ? 'Volver al listado' : 'Cancelar'}
|
||||
</Button>
|
||||
{#if !resultado}
|
||||
<Button icon={Save} onclick={guardar} disabled={enviando}>
|
||||
{enviando ? 'Guardando...' : 'Guardar Cambios'}
|
||||
</Button>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
@@ -0,0 +1,52 @@
|
||||
import { obtenerComprobante } from '$lib/hooks/facturas/comprobante';
|
||||
import { obtenerRepuestos } from '$lib/hooks/repuestos/obtenerRepuestos';
|
||||
import { obtenerAlmacenes } from '$lib/hooks/almacenes/obtenerAlmacenes';
|
||||
import type { Almacen, ComprobanteResponse, Repuesto } from '../../../../types';
|
||||
|
||||
export let ssr = false;
|
||||
|
||||
export async function load({ fetch, params, depends }) {
|
||||
depends('facturas:modificar:load');
|
||||
|
||||
const id = Number(params.id);
|
||||
if (!id || Number.isNaN(id)) {
|
||||
return {
|
||||
comprobante: null,
|
||||
preciosActuales: {} as Record<number, number>,
|
||||
almacenes: [] as Almacen[],
|
||||
error: 'Factura inválida'
|
||||
};
|
||||
}
|
||||
|
||||
const [comprobante, repuestosRes, almacenesRes] = await Promise.all([
|
||||
obtenerComprobante(fetch, id),
|
||||
obtenerRepuestos(fetch),
|
||||
obtenerAlmacenes(fetch)
|
||||
]);
|
||||
|
||||
if (typeof comprobante === 'string') {
|
||||
return {
|
||||
comprobante: null,
|
||||
preciosActuales: {} as Record<number, number>,
|
||||
almacenes: [] as Almacen[],
|
||||
error: comprobante
|
||||
};
|
||||
}
|
||||
|
||||
const repuestos = Array.isArray(repuestosRes) ? (repuestosRes as Repuesto[]) : [];
|
||||
const preciosActuales: Record<number, number> = {};
|
||||
for (const repuesto of repuestos) {
|
||||
const precio = Number(repuesto.precio);
|
||||
if (Number.isFinite(precio)) {
|
||||
preciosActuales[Number(repuesto.ID)] = precio;
|
||||
}
|
||||
}
|
||||
const almacenes = Array.isArray(almacenesRes) ? (almacenesRes as Almacen[]) : [];
|
||||
|
||||
return {
|
||||
comprobante: comprobante as ComprobanteResponse,
|
||||
preciosActuales,
|
||||
almacenes,
|
||||
error: ''
|
||||
};
|
||||
}
|
||||
Vendored
+32
@@ -326,6 +326,7 @@ export interface Factura {
|
||||
Observacion?: string;
|
||||
Version?: number;
|
||||
ClienteID?: number;
|
||||
almacenId?: number;
|
||||
cliente?: Cliente;
|
||||
ProveedorID?: number | null;
|
||||
proveedor?: Proveedor | null;
|
||||
@@ -345,6 +346,25 @@ export interface PagoResumen {
|
||||
observacion?: string;
|
||||
}
|
||||
|
||||
export interface NotaResumen {
|
||||
id: number;
|
||||
tipo: 'CREDITO' | 'DEBITO';
|
||||
numero: string;
|
||||
motivo: string;
|
||||
importe: number;
|
||||
fecha: string;
|
||||
facturaId: number;
|
||||
}
|
||||
|
||||
export interface AjusteFacturaResponse {
|
||||
factura: Factura;
|
||||
nota?: NotaResumen;
|
||||
diferencia: number;
|
||||
saldoAnterior: number;
|
||||
saldoNuevo: number;
|
||||
stocks?: StockDisponible[];
|
||||
}
|
||||
|
||||
export interface ComprobanteResponse {
|
||||
ID: number;
|
||||
numero?: string;
|
||||
@@ -358,6 +378,7 @@ export interface ComprobanteResponse {
|
||||
saldo?: number;
|
||||
FechaEmision?: string;
|
||||
Observacion?: string;
|
||||
almacenId?: number;
|
||||
cliente?: {
|
||||
ID: number;
|
||||
nombre: string;
|
||||
@@ -366,6 +387,17 @@ export interface ComprobanteResponse {
|
||||
};
|
||||
detalles?: FacturaDetalle[];
|
||||
pagos: PagoResumen[];
|
||||
notas?: NotaResumen[];
|
||||
historial?: Array<{
|
||||
fecha: string;
|
||||
usuarioId: number;
|
||||
motivo: string;
|
||||
totalAnterior: number;
|
||||
totalNuevo: number;
|
||||
notaTipo?: string;
|
||||
notaId?: number;
|
||||
}>;
|
||||
motivoUltimaEdicion?: string;
|
||||
}
|
||||
|
||||
export interface FacturaResumen {
|
||||
|
||||
Reference in new issue
Block a user