Private
Public Access
572 lines
17 KiB
Go
572 lines
17 KiB
Go
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
|
|
}
|