Private
Public Access
hecha la parte del cu-02 falta test
Signed-off-by: fede <federico.nicolas.polidoro@gmail.com>
This commit is contained in:
1 parent
42bf987ffc
commit
cc80dd1467
20 files changed
+940
-7
No files matched your search
@@ -0,0 +1,18 @@
|
||||
package descuento
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
r "repuestera_back/repositorios"
|
||||
)
|
||||
|
||||
func ObtenerDescuentos(c *gin.Context) {
|
||||
descuentos, err := r.ObtenerRepositorios(c).Descuento.ListarActivos()
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, descuentos)
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package factura
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
dto "repuestera_back/dto/Facturas"
|
||||
"repuestera_back/repositorios"
|
||||
"repuestera_back/services"
|
||||
"repuestera_back/utils"
|
||||
)
|
||||
|
||||
func CrearFactura(c *gin.Context) {
|
||||
var data dto.CrearFacturaDto
|
||||
if err := c.ShouldBindJSON(&data); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
resultado, err := services.CrearFactura(
|
||||
repositorios.BaseDeDatos(),
|
||||
repositorios.ObtenerRepositorios(c),
|
||||
utils.EmpresaID(c),
|
||||
c.GetUint("userID"),
|
||||
data,
|
||||
)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, resultado)
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package formapago
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
r "repuestera_back/repositorios"
|
||||
)
|
||||
|
||||
func ObtenerFormasPago(c *gin.Context) {
|
||||
formas, err := r.ObtenerRepositorios(c).FormaDePago.ObtenerTodos()
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, formas)
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package dto_builders
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
|
||||
dto "repuestera_back/dto/Facturas"
|
||||
"repuestera_back/models"
|
||||
)
|
||||
|
||||
type CrearFacturaBuilder struct {
|
||||
datos *dto.FacturaCalculada
|
||||
err error
|
||||
}
|
||||
|
||||
var _ IBuilder[models.Factura] = (*CrearFacturaBuilder)(nil)
|
||||
|
||||
func NewCrearFacturaBuilder() *CrearFacturaBuilder {
|
||||
return &CrearFacturaBuilder{}
|
||||
}
|
||||
|
||||
func (b *CrearFacturaBuilder) ConDatos(datos dto.FacturaCalculada) *CrearFacturaBuilder {
|
||||
b.datos = &datos
|
||||
return b
|
||||
}
|
||||
|
||||
func (b *CrearFacturaBuilder) Build() (*models.Factura, error) {
|
||||
if b.datos == nil {
|
||||
return nil, errors.New("faltan los datos de la factura")
|
||||
}
|
||||
|
||||
datos := b.datos
|
||||
if strings.TrimSpace(datos.Numero) == "" {
|
||||
AcumularError(&b.err, "el número de factura es obligatorio")
|
||||
}
|
||||
if datos.ClienteID == 0 {
|
||||
AcumularError(&b.err, "el cliente es obligatorio")
|
||||
}
|
||||
if datos.AlmacenID == 0 {
|
||||
AcumularError(&b.err, "el almacén es obligatorio")
|
||||
}
|
||||
if datos.ResponsableID == 0 {
|
||||
AcumularError(&b.err, "el responsable es obligatorio")
|
||||
}
|
||||
if datos.FechaEmision.IsZero() {
|
||||
AcumularError(&b.err, "la fecha de emisión es obligatoria")
|
||||
}
|
||||
if len(datos.Detalles) == 0 {
|
||||
AcumularError(&b.err, "la factura debe tener al menos un detalle")
|
||||
}
|
||||
if datos.Subtotal < 0 {
|
||||
AcumularError(&b.err, "el subtotal no puede ser negativo")
|
||||
}
|
||||
if datos.DescuentoTotal < 0 {
|
||||
AcumularError(&b.err, "el descuento no puede ser negativo")
|
||||
}
|
||||
if datos.Impuestos < 0 {
|
||||
AcumularError(&b.err, "los impuestos no pueden ser negativos")
|
||||
}
|
||||
if datos.AlicuotaIVA < 0 {
|
||||
AcumularError(&b.err, "la alícuota de IVA no puede ser negativa")
|
||||
}
|
||||
if datos.Total < 0 {
|
||||
AcumularError(&b.err, "el total no puede ser negativo")
|
||||
}
|
||||
if datos.Saldo < 0 {
|
||||
AcumularError(&b.err, "el saldo no puede ser negativo")
|
||||
}
|
||||
if b.err != nil {
|
||||
return nil, b.err
|
||||
}
|
||||
|
||||
factura := &models.Factura{
|
||||
Numero: strings.TrimSpace(datos.Numero),
|
||||
ClienteID: datos.ClienteID,
|
||||
AlmacenID: datos.AlmacenID,
|
||||
FechaEmision: datos.FechaEmision,
|
||||
Subtotal: datos.Subtotal,
|
||||
DescuentoID: datos.DescuentoID,
|
||||
DescuentoTotal: datos.DescuentoTotal,
|
||||
Impuestos: datos.Impuestos,
|
||||
AlicuotaIVA: datos.AlicuotaIVA,
|
||||
Saldo: datos.Saldo,
|
||||
Detalles: append([]models.FacturaDetalle{}, datos.Detalles...),
|
||||
Observacion: strings.TrimSpace(datos.Observacion),
|
||||
Version: 1,
|
||||
}
|
||||
factura.EmpresaID = datos.EmpresaID
|
||||
factura.Estado = "EMITIDA"
|
||||
factura.Total = datos.Total
|
||||
factura.ResponsableID = datos.ResponsableID
|
||||
|
||||
return factura, nil
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package directors
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
builders "repuestera_back/dto/Builders"
|
||||
dto_email "repuestera_back/dto/Email"
|
||||
"repuestera_back/models"
|
||||
)
|
||||
|
||||
type EmailDirector struct{}
|
||||
|
||||
func NewEmailDirector() *EmailDirector {
|
||||
return &EmailDirector{}
|
||||
}
|
||||
|
||||
// ComprobanteVenta arma el email que se envía al cliente después de emitir
|
||||
// una factura.
|
||||
func (d *EmailDirector) ComprobanteVenta(factura *models.Factura, destinatario string) (*dto_email.MensajeEmail, error) {
|
||||
if factura == nil {
|
||||
return nil, errors.New("la factura no puede ser nula")
|
||||
}
|
||||
if strings.TrimSpace(destinatario) == "" {
|
||||
return nil, errors.New("el destinatario es obligatorio")
|
||||
}
|
||||
|
||||
descripcion := fmt.Sprintf("<p>Factura %s por %.2f</p>", factura.Numero, factura.Total)
|
||||
return builders.NewMensajeEmailBuilder().
|
||||
ConTitulo("Comprobante de venta " + factura.Numero).
|
||||
ConDescripcion(descripcion).
|
||||
ConItems([]string{}).
|
||||
ConDestinatarios([]string{destinatario}).
|
||||
Build()
|
||||
}
|
||||
@@ -12,6 +12,10 @@ func NewFacturaDirector() *FacturaDirector {
|
||||
return &FacturaDirector{}
|
||||
}
|
||||
|
||||
func (d *FacturaDirector) Crear(datos dto_facturas.FacturaCalculada) (*models.Factura, error) {
|
||||
return builders.NewCrearFacturaBuilder().ConDatos(datos).Build()
|
||||
}
|
||||
|
||||
func (d *FacturaDirector) DesdeFactura(factura *models.Factura) (*dto_facturas.FacturaResponse, error) {
|
||||
return builders.NewFacturaResponseBuilder().ConFactura(factura).Build()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
package dto_builders
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
|
||||
dto_email "repuestera_back/dto/Email"
|
||||
)
|
||||
|
||||
type MensajeEmailBuilder struct {
|
||||
mensaje dto_email.MensajeEmail
|
||||
err error
|
||||
}
|
||||
|
||||
var _ IBuilder[dto_email.MensajeEmail] = (*MensajeEmailBuilder)(nil)
|
||||
|
||||
func NewMensajeEmailBuilder() *MensajeEmailBuilder {
|
||||
return &MensajeEmailBuilder{}
|
||||
}
|
||||
|
||||
func (b *MensajeEmailBuilder) ConTitulo(titulo string) *MensajeEmailBuilder {
|
||||
titulo = strings.TrimSpace(titulo)
|
||||
if titulo == "" {
|
||||
AcumularError(&b.err, "el título del email no puede ser nulo o vacío")
|
||||
return b
|
||||
}
|
||||
b.mensaje.Titulo = titulo
|
||||
return b
|
||||
}
|
||||
|
||||
func (b *MensajeEmailBuilder) ConDescripcion(descripcion string) *MensajeEmailBuilder {
|
||||
descripcion = strings.TrimSpace(descripcion)
|
||||
if descripcion == "" {
|
||||
AcumularError(&b.err, "la descripción del email no puede ser nula o vacía")
|
||||
return b
|
||||
}
|
||||
b.mensaje.Descripcion = descripcion
|
||||
return b
|
||||
}
|
||||
|
||||
func (b *MensajeEmailBuilder) ConItems(items []string) *MensajeEmailBuilder {
|
||||
b.mensaje.Items = items
|
||||
return b
|
||||
}
|
||||
|
||||
func (b *MensajeEmailBuilder) ConDestinatarios(destinatarios []string) *MensajeEmailBuilder {
|
||||
b.mensaje.Destinatarios = normalizarDestinatarios(destinatarios)
|
||||
return b
|
||||
}
|
||||
|
||||
func (b *MensajeEmailBuilder) Build() (*dto_email.MensajeEmail, error) {
|
||||
if b.err != nil {
|
||||
return nil, b.err
|
||||
}
|
||||
if strings.TrimSpace(b.mensaje.Titulo) == "" {
|
||||
return nil, errors.New("falta el título del email")
|
||||
}
|
||||
if strings.TrimSpace(b.mensaje.Descripcion) == "" {
|
||||
return nil, errors.New("falta la descripción del email")
|
||||
}
|
||||
|
||||
b.mensaje.Items = ListaNoNil(b.mensaje.Items)
|
||||
b.mensaje.Destinatarios = ListaNoNil(b.mensaje.Destinatarios)
|
||||
return &b.mensaje, nil
|
||||
}
|
||||
|
||||
func normalizarDestinatarios(destinatarios []string) []string {
|
||||
vistos := make(map[string]bool, len(destinatarios))
|
||||
limpios := make([]string, 0, len(destinatarios))
|
||||
for _, destinatario := range destinatarios {
|
||||
destinatario = strings.TrimSpace(destinatario)
|
||||
if destinatario == "" || vistos[destinatario] {
|
||||
continue
|
||||
}
|
||||
vistos[destinatario] = true
|
||||
limpios = append(limpios, destinatario)
|
||||
}
|
||||
return limpios
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package dto_email
|
||||
|
||||
// MensajeEmail es el contrato que espera el servicio comms en POST /email.
|
||||
type MensajeEmail struct {
|
||||
Titulo string
|
||||
Descripcion string
|
||||
Items []string
|
||||
Destinatarios []string
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
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"`
|
||||
}
|
||||
|
||||
type ItemFacturaDto struct {
|
||||
RepuestoID uint64 `json:"repuestoId" binding:"required"`
|
||||
Cantidad float64 `json:"cantidad" binding:"required,gt=0"`
|
||||
PrecioUnitario float64 `json:"precioUnitario" binding:"gte=0"`
|
||||
}
|
||||
|
||||
type PagoFacturaDto struct {
|
||||
FormaDePagoID uint `json:"formaDePagoId" binding:"required"`
|
||||
Importe float64 `json:"importe" binding:"required,gt=0"`
|
||||
Fecha string `json:"fecha"`
|
||||
Observacion string `json:"observacion"`
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package dto
|
||||
|
||||
import "repuestera_back/models"
|
||||
|
||||
// CrearFacturaResponse es la respuesta de la emisión de una factura.
|
||||
type CrearFacturaResponse struct {
|
||||
Factura *FacturaResponse `json:"factura"`
|
||||
Stocks []*models.Stock `json:"stocks"`
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package dto
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"repuestera_back/models"
|
||||
)
|
||||
|
||||
// FacturaCalculada reúne los datos ya validados y calculados que necesita el
|
||||
// builder para construir el modelo de factura.
|
||||
type FacturaCalculada struct {
|
||||
EmpresaID uint
|
||||
Numero string
|
||||
ClienteID uint
|
||||
AlmacenID uint
|
||||
FechaEmision time.Time
|
||||
Subtotal float64
|
||||
DescuentoID uint
|
||||
DescuentoTotal float64
|
||||
Impuestos float64
|
||||
AlicuotaIVA float64
|
||||
Total float64
|
||||
Saldo float64
|
||||
Detalles []models.FacturaDetalle
|
||||
Observacion string
|
||||
ResponsableID uint
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package models
|
||||
|
||||
import "gorm.io/gorm"
|
||||
|
||||
// ComprobanteSecuencia lleva el último número emitido por empresa y tipo.
|
||||
type ComprobanteSecuencia struct {
|
||||
gorm.Model
|
||||
EmpresaID uint `gorm:"not null;index;uniqueIndex:uq_seq_empresa_tipo,priority:1" json:"empresaId"`
|
||||
Tipo string `gorm:"type:varchar(20);not null;uniqueIndex:uq_seq_empresa_tipo,priority:2" json:"tipo"`
|
||||
UltimoNumero uint `gorm:"not null;default:0" json:"ultimoNumero"`
|
||||
}
|
||||
|
||||
func (ComprobanteSecuencia) TableName() string {
|
||||
return "comprobante_secuencia"
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package models
|
||||
|
||||
import "time"
|
||||
|
||||
// FacturaCambio registra una modificación sobre una factura (auditoría).
|
||||
type FacturaCambio struct {
|
||||
Fecha time.Time `json:"fecha"`
|
||||
UsuarioID uint `json:"usuarioId"`
|
||||
Motivo string `json:"motivo"`
|
||||
ItemsAnteriores []FacturaDetalle `json:"itemsAnteriores"`
|
||||
TotalAnterior float64 `json:"totalAnterior"`
|
||||
ItemsNuevos []FacturaDetalle `json:"itemsNuevos"`
|
||||
TotalNuevo float64 `json:"totalNuevo"`
|
||||
NotaTipo string `json:"notaTipo,omitempty"`
|
||||
NotaID uint `json:"notaId,omitempty"`
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package repositorios
|
||||
|
||||
import (
|
||||
"repuestera_back/models"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type RepositorioComprobanteSecuencia interface {
|
||||
Siguiente(tx *gorm.DB, empresaID uint, tipo string) (uint, error)
|
||||
}
|
||||
|
||||
type repositorioComprobanteSecuencia struct {
|
||||
db *gorm.DB
|
||||
empresaID uint
|
||||
}
|
||||
|
||||
func NuevoRepositorioComprobanteSecuencia(db *gorm.DB, empresaID uint) RepositorioComprobanteSecuencia {
|
||||
return &repositorioComprobanteSecuencia{
|
||||
db: dbConEmpresa(db, empresaID),
|
||||
empresaID: empresaID,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *repositorioComprobanteSecuencia) Siguiente(tx *gorm.DB, empresaID uint, tipo string) (uint, error) {
|
||||
var seq models.ComprobanteSecuencia
|
||||
db := tx
|
||||
if empresaID > 0 {
|
||||
db = db.Where("empresa_id = ?", empresaID)
|
||||
}
|
||||
if err := db.Where("tipo = ?", tipo).First(&seq).Error; err != nil {
|
||||
if err != gorm.ErrRecordNotFound {
|
||||
return 0, err
|
||||
}
|
||||
seq = models.ComprobanteSecuencia{
|
||||
EmpresaID: empresaID,
|
||||
Tipo: tipo,
|
||||
UltimoNumero: 0,
|
||||
}
|
||||
if err := tx.Create(&seq).Error; err != nil {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
seq.UltimoNumero++
|
||||
if err := tx.Model(&seq).Update("ultimo_numero", seq.UltimoNumero).Error; err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return seq.UltimoNumero, nil
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package repositorios
|
||||
|
||||
import (
|
||||
"repuestera_back/models"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type RepositorioDescuento interface {
|
||||
IRepositorio[models.Descuento]
|
||||
ListarActivos() ([]models.Descuento, error)
|
||||
}
|
||||
|
||||
type repositorioDescuento struct {
|
||||
*RepositorioBase[models.Descuento]
|
||||
db *gorm.DB
|
||||
empresaID uint
|
||||
}
|
||||
|
||||
func NuevoRepositorioDescuento(db *gorm.DB, empresaID uint) RepositorioDescuento {
|
||||
return &repositorioDescuento{
|
||||
RepositorioBase: NewRepositorioBase[models.Descuento](db, empresaID),
|
||||
db: dbConEmpresa(db, empresaID),
|
||||
empresaID: empresaID,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *repositorioDescuento) ListarActivos() ([]models.Descuento, error) {
|
||||
var ds []models.Descuento
|
||||
if err := r.db.Unscoped().Where("activo = ?", true).Find(&ds).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ds, nil
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package repositorios
|
||||
|
||||
import (
|
||||
"repuestera_back/models"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type RepositorioFormaDePago interface {
|
||||
IRepositorio[models.FormaDePago]
|
||||
}
|
||||
|
||||
type repositorioFormaDePago struct {
|
||||
*RepositorioBase[models.FormaDePago]
|
||||
db *gorm.DB
|
||||
empresaID uint
|
||||
}
|
||||
|
||||
func NuevoRepositorioFormaDePago(db *gorm.DB, empresaID uint) RepositorioFormaDePago {
|
||||
return &repositorioFormaDePago{
|
||||
RepositorioBase: NewRepositorioBase[models.FormaDePago](db, empresaID),
|
||||
db: dbConEmpresa(db, empresaID),
|
||||
empresaID: empresaID,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package repositorios
|
||||
|
||||
import (
|
||||
"repuestera_back/models"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type RepositorioPago interface {
|
||||
IRepositorio[models.Pago]
|
||||
Registrar(tx *gorm.DB, pago *models.Pago) error
|
||||
ListarPorFactura(facturaID uint) ([]models.Pago, error)
|
||||
SumarPorFactura(facturaID uint) (float64, error)
|
||||
}
|
||||
|
||||
type repositorioPago struct {
|
||||
*RepositorioBase[models.Pago]
|
||||
db *gorm.DB
|
||||
empresaID uint
|
||||
}
|
||||
|
||||
func NuevoRepositorioPago(db *gorm.DB, empresaID uint) RepositorioPago {
|
||||
return &repositorioPago{
|
||||
RepositorioBase: NewRepositorioBase[models.Pago](db, empresaID),
|
||||
db: dbConEmpresa(db, empresaID),
|
||||
empresaID: empresaID,
|
||||
}
|
||||
}
|
||||
|
||||
// Registrar persiste un pago dentro de una transacción y le asigna la empresa activa.
|
||||
func (r *repositorioPago) Registrar(tx *gorm.DB, pago *models.Pago) error {
|
||||
if pago == nil {
|
||||
return gorm.ErrInvalidValue
|
||||
}
|
||||
if r.empresaID > 0 {
|
||||
pago.EmpresaID = r.empresaID
|
||||
}
|
||||
return tx.Create(pago).Error
|
||||
}
|
||||
|
||||
func (r *repositorioPago) ListarPorFactura(facturaID uint) ([]models.Pago, error) {
|
||||
var pagos []models.Pago
|
||||
if err := r.db.Where("factura_id = ?", facturaID).Find(&pagos).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return pagos, nil
|
||||
}
|
||||
|
||||
func (r *repositorioPago) SumarPorFactura(facturaID uint) (float64, error) {
|
||||
var total float64
|
||||
if err := r.db.Model(&models.Pago{}).Where("factura_id = ?", facturaID).Select("COALESCE(SUM(importe),0)").Scan(&total).Error; err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return total, nil
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"gorm.io/gorm"
|
||||
|
||||
"repuestera_back/models"
|
||||
"repuestera_back/models/contabilidad"
|
||||
"repuestera_back/repositorios"
|
||||
)
|
||||
|
||||
// RegistrarAsientoVenta registra el asiento contable de una venta.
|
||||
func RegistrarAsientoVenta(
|
||||
tx *gorm.DB,
|
||||
repo *repositorios.Repositorios,
|
||||
factura *models.Factura,
|
||||
subtotal, descuento, impuestos, total float64,
|
||||
) error {
|
||||
if factura == nil {
|
||||
return gorm.ErrInvalidValue
|
||||
}
|
||||
|
||||
base := redondearCantidad(subtotal - descuento)
|
||||
if base <= 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
asiento := &contabilidad.AsientoContable{
|
||||
ComprobanteTipo: "FACTURA",
|
||||
ComprobanteID: factura.ID,
|
||||
}
|
||||
|
||||
if err := agregarMovimiento(tx, repo, asiento, "Clientes", "activo", total, 0, "Venta a clientes"); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := agregarMovimiento(tx, repo, asiento, "Ventas", "resultado", 0, base, "Ingreso por ventas"); err != nil {
|
||||
return err
|
||||
}
|
||||
if impuestos > 0 {
|
||||
if err := agregarMovimiento(tx, repo, asiento, "IVA Débito Fiscal", "pasivo", 0, impuestos, "IVA sobre ventas"); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return repo.Contabilidad.CrearAsientoConMovimientos(tx, asiento)
|
||||
}
|
||||
|
||||
func agregarMovimiento(
|
||||
tx *gorm.DB,
|
||||
repo *repositorios.Repositorios,
|
||||
asiento *contabilidad.AsientoContable,
|
||||
nombre, tipo string,
|
||||
debe, haber float64,
|
||||
descripcion string,
|
||||
) error {
|
||||
cuenta := &contabilidad.CuentaContable{Nombre: nombre, Tipo: tipo}
|
||||
if err := repo.Contabilidad.GuardarCuenta(tx, cuenta); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
asiento.Movimientos = append(asiento.Movimientos, contabilidad.MovimientoContable{
|
||||
CuentaID: cuenta.ID,
|
||||
Debe: redondearCantidad(debe),
|
||||
Haber: redondearCantidad(haber),
|
||||
Descripcion: descripcion,
|
||||
})
|
||||
return nil
|
||||
}
|
||||
@@ -9,16 +9,13 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
dto_email "repuestera_back/dto/Email"
|
||||
"repuestera_back/jwtutils"
|
||||
)
|
||||
|
||||
// MensajeEmail es el contrato que espera el servicio comms en POST /email.
|
||||
type MensajeEmail struct {
|
||||
Titulo string
|
||||
Descripcion string
|
||||
Items []string
|
||||
Destinatarios []string
|
||||
}
|
||||
// MensajeEmail se mantiene como alias para no romper a los consumidores que
|
||||
// ya lo usaban desde el paquete services.
|
||||
type MensajeEmail = dto_email.MensajeEmail
|
||||
|
||||
// EnviarEmail publica un mensaje en el servicio comms. Devuelve false si no
|
||||
// hay destinatarios, si comms no responde o si rechaza el envío.
|
||||
|
||||
@@ -0,0 +1,323 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
applog "log"
|
||||
"math"
|
||||
"sort"
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
|
||||
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||
dto "repuestera_back/dto/Facturas"
|
||||
"repuestera_back/models"
|
||||
models_logs "repuestera_back/models/logs"
|
||||
"repuestera_back/repositorios"
|
||||
)
|
||||
|
||||
const (
|
||||
estadoFacturaParcial = "PARCIAL"
|
||||
estadoFacturaPagada = "PAGADA"
|
||||
)
|
||||
|
||||
var errCantidadInvalida = 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.
|
||||
func CrearFactura(
|
||||
db *gorm.DB,
|
||||
repo *repositorios.Repositorios,
|
||||
empresaID, usuarioID uint,
|
||||
entrada dto.CrearFacturaDto,
|
||||
) (*dto.CrearFacturaResponse, error) {
|
||||
if len(entrada.Items) == 0 {
|
||||
return nil, errors.New("la factura debe tener al menos un ítem")
|
||||
}
|
||||
|
||||
cliente, err := repo.Cliente.ObtenerPorID(entrada.ClienteID)
|
||||
if err != nil || cliente == nil {
|
||||
return nil, fmt.Errorf("cliente %d no encontrado", entrada.ClienteID)
|
||||
}
|
||||
|
||||
if _, err := repo.Almacen.ObtenerPorID(entrada.AlmacenID); err != nil {
|
||||
return nil, fmt.Errorf("almacén %d no encontrado", entrada.AlmacenID)
|
||||
}
|
||||
|
||||
var descuento *models.Descuento
|
||||
if entrada.DescuentoID > 0 {
|
||||
d, err := repo.Descuento.ObtenerPorID(entrada.DescuentoID)
|
||||
if err != nil || d == nil {
|
||||
return nil, fmt.Errorf("descuento %d no encontrado", entrada.DescuentoID)
|
||||
}
|
||||
if !d.Activo {
|
||||
return nil, errors.New("el descuento no está activo")
|
||||
}
|
||||
descuento = d
|
||||
}
|
||||
|
||||
// Ordenar ítems por repuesto para bloquear en orden estable.
|
||||
items := append([]dto.ItemFacturaDto(nil), entrada.Items...)
|
||||
sort.Slice(items, func(i, j int) bool { return items[i].RepuestoID < items[j].RepuestoID })
|
||||
|
||||
// Validar repuestos y cantidades, y detectar duplicados.
|
||||
vistos := make(map[uint64]bool, len(items))
|
||||
for i := range items {
|
||||
item := &items[i]
|
||||
if item.RepuestoID == 0 {
|
||||
return nil, errors.New("repuesto inválido")
|
||||
}
|
||||
if vistos[item.RepuestoID] {
|
||||
return nil, fmt.Errorf("el repuesto %d está repetido", item.RepuestoID)
|
||||
}
|
||||
vistos[item.RepuestoID] = true
|
||||
if err := validarCantidad(item.Cantidad); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
repuesto, err := repo.Repuesto.ObtenerPorID(uint(item.RepuestoID))
|
||||
if err != nil || repuesto == nil || *repuesto == nil {
|
||||
return nil, fmt.Errorf("repuesto %d no encontrado", item.RepuestoID)
|
||||
}
|
||||
if item.PrecioUnitario <= 0 {
|
||||
item.PrecioUnitario = (*repuesto).Precio
|
||||
}
|
||||
}
|
||||
|
||||
// Validar pagos.
|
||||
for _, pago := range entrada.Pagos {
|
||||
if err := validarCantidad(pago.Importe); err != nil {
|
||||
return nil, fmt.Errorf("importe de pago inválido: %w", err)
|
||||
}
|
||||
if _, err := repo.FormaDePago.ObtenerPorID(pago.FormaDePagoID); err != nil {
|
||||
return nil, fmt.Errorf("forma de pago %d no encontrada", pago.FormaDePagoID)
|
||||
}
|
||||
}
|
||||
|
||||
// Calcular totales.
|
||||
var subtotal float64
|
||||
detalles := make([]models.FacturaDetalle, 0, len(items))
|
||||
for _, item := range items {
|
||||
sub := redondearCantidad(item.Cantidad * item.PrecioUnitario)
|
||||
subtotal = redondearCantidad(subtotal + sub)
|
||||
detalles = append(detalles, models.FacturaDetalle{
|
||||
RepuestoID: item.RepuestoID,
|
||||
Cantidad: item.Cantidad,
|
||||
DescuentoID: entrada.DescuentoID,
|
||||
PrecioUnitario: item.PrecioUnitario,
|
||||
Subtotal: sub,
|
||||
AlicuotaIVA: 21,
|
||||
})
|
||||
}
|
||||
|
||||
descuentoTotal := 0.0
|
||||
if descuento != nil {
|
||||
switch descuento.Tipo {
|
||||
case models.Porcentaje:
|
||||
descuentoTotal = redondearCantidad(subtotal * descuento.Valor / 100)
|
||||
case models.Fijo:
|
||||
descuentoTotal = redondearCantidad(descuento.Valor)
|
||||
}
|
||||
if descuentoTotal > subtotal {
|
||||
descuentoTotal = subtotal
|
||||
}
|
||||
}
|
||||
|
||||
baseImponible := redondearCantidad(subtotal - descuentoTotal)
|
||||
alicuota := 21.0
|
||||
impuestos := redondearCantidad(baseImponible * alicuota / 100)
|
||||
total := redondearCantidad(baseImponible + impuestos)
|
||||
|
||||
var sumaPagos float64
|
||||
for _, pago := range entrada.Pagos {
|
||||
sumaPagos = redondearCantidad(sumaPagos + pago.Importe)
|
||||
}
|
||||
if sumaPagos > total {
|
||||
return nil, errors.New("los pagos superan el total de la factura")
|
||||
}
|
||||
|
||||
var facturaCreada *models.Factura
|
||||
stocks := make([]*models.Stock, 0, len(items))
|
||||
|
||||
err = db.Transaction(func(tx *gorm.DB) error {
|
||||
// Bloquear stock y validar disponibilidad.
|
||||
stocksPorRepuesto := make(map[uint64]*models.Stock, len(items))
|
||||
for _, item := range items {
|
||||
stock, err := repo.Stock.BloquearPorRepuestoAlmacen(tx, item.RepuestoID, entrada.AlmacenID)
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return fmt.Errorf("stock insuficiente: repuesto %d", item.RepuestoID)
|
||||
}
|
||||
return err
|
||||
}
|
||||
disponible := redondearCantidad(stock.Cantidad - stock.CantidadReservada)
|
||||
if disponible < redondearCantidad(item.Cantidad) {
|
||||
return fmt.Errorf(
|
||||
"stock insuficiente: repuesto %d, disponible %.3f, solicitado %.3f",
|
||||
item.RepuestoID, disponible, item.Cantidad,
|
||||
)
|
||||
}
|
||||
stocksPorRepuesto[item.RepuestoID] = stock
|
||||
}
|
||||
|
||||
numero, err := repo.Secuencia.Siguiente(tx, empresaID, "FACTURA")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
factura, err := dto_directors.NewFacturaDirector().Crear(dto.FacturaCalculada{
|
||||
EmpresaID: empresaID,
|
||||
Numero: fmt.Sprintf("F-%08d", numero),
|
||||
ClienteID: entrada.ClienteID,
|
||||
AlmacenID: entrada.AlmacenID,
|
||||
FechaEmision: time.Now(),
|
||||
Subtotal: subtotal,
|
||||
DescuentoID: entrada.DescuentoID,
|
||||
DescuentoTotal: descuentoTotal,
|
||||
Impuestos: impuestos,
|
||||
AlicuotaIVA: alicuota,
|
||||
Total: total,
|
||||
Saldo: total,
|
||||
Detalles: detalles,
|
||||
Observacion: entrada.Observacion,
|
||||
ResponsableID: usuarioID,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := repo.Factura.CrearConDetalles(tx, factura); err != nil {
|
||||
return err
|
||||
}
|
||||
facturaCreada = factura
|
||||
|
||||
// Descontar stock y registrar el movimiento.
|
||||
for _, item := range items {
|
||||
stock := stocksPorRepuesto[item.RepuestoID]
|
||||
saldoAnterior := stock.Cantidad
|
||||
stock.Cantidad = redondearCantidad(stock.Cantidad - item.Cantidad)
|
||||
if err := repo.Stock.ActualizarCantidades(tx, stock); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
movimiento := &models.MovimientoStock{
|
||||
StockID: stock.ID,
|
||||
RepuestoID: stock.RepuestoID,
|
||||
AlmacenID: stock.AlmacenID,
|
||||
Tipo: models.MovimientoVenta,
|
||||
Cantidad: redondearCantidad(item.Cantidad),
|
||||
SaldoAnterior: redondearCantidad(saldoAnterior),
|
||||
SaldoPosterior: redondearCantidad(stock.Cantidad),
|
||||
ReferenciaTipo: "FACTURA",
|
||||
ReferenciaID: uint64(factura.ID),
|
||||
UsuarioID: usuarioID,
|
||||
Observacion: entrada.Observacion,
|
||||
Fecha: time.Now(),
|
||||
}
|
||||
if err := repo.MovimientoStock.Registrar(tx, movimiento); err != nil {
|
||||
return err
|
||||
}
|
||||
stocks = append(stocks, stock)
|
||||
}
|
||||
|
||||
if err := RegistrarAsientoVenta(tx, repo, factura, subtotal, descuentoTotal, impuestos, total); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Pagos inmediatos.
|
||||
for _, pagoEntrada := range entrada.Pagos {
|
||||
fecha := time.Now()
|
||||
if pagoEntrada.Fecha != "" {
|
||||
if f, err := time.Parse("2006-01-02", pagoEntrada.Fecha); err == nil {
|
||||
fecha = f
|
||||
}
|
||||
}
|
||||
|
||||
pago := &models.Pago{
|
||||
FacturaID: factura.ID,
|
||||
FormaDePagoID: pagoEntrada.FormaDePagoID,
|
||||
Importe: pagoEntrada.Importe,
|
||||
Fecha: fecha,
|
||||
Observacion: pagoEntrada.Observacion,
|
||||
}
|
||||
if err := repo.Pago.Registrar(tx, pago); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if sumaPagos > 0 {
|
||||
nuevoSaldo := redondearCantidad(total - sumaPagos)
|
||||
nuevoEstado := estadoFacturaParcial
|
||||
if nuevoSaldo <= 0 {
|
||||
nuevoEstado = estadoFacturaPagada
|
||||
nuevoSaldo = 0
|
||||
}
|
||||
if err := repo.Factura.ActualizarEstadoSaldo(tx, factura.ID, nuevoEstado, nuevoSaldo); err != nil {
|
||||
return err
|
||||
}
|
||||
factura.Estado = nuevoEstado
|
||||
factura.Saldo = nuevoSaldo
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Email post-commit: un fallo no revierte la factura.
|
||||
if entrada.EnviarEmail && cliente.Email != "" {
|
||||
mensaje, err := dto_directors.NewEmailDirector().ComprobanteVenta(facturaCreada, cliente.Email)
|
||||
if err != nil {
|
||||
applog.Printf("facturas: no se pudo construir el email de la factura %s: %v", facturaCreada.Numero, err)
|
||||
} else if EnviarEmail(*mensaje, usuarioID) {
|
||||
facturaCreada.SeAviso = true
|
||||
}
|
||||
}
|
||||
|
||||
// Auditoría.
|
||||
registrarLogFactura(repo, empresaID, usuarioID, "CREAR_FACTURA", []models_logs.LogDetalle{
|
||||
{NombreTabla: "factura", Columna: "facturaId", ValorNuevo: fmt.Sprintf("%d", facturaCreada.ID)},
|
||||
{NombreTabla: "factura", Columna: "numero", ValorNuevo: facturaCreada.Numero},
|
||||
{NombreTabla: "factura", Columna: "total", ValorNuevo: fmt.Sprintf("%.2f", total)},
|
||||
})
|
||||
|
||||
facturaCreada.Cliente = *cliente
|
||||
respuestaFactura, err := dto_directors.NewFacturaDirector().DesdeFactura(facturaCreada)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &dto.CrearFacturaResponse{
|
||||
Factura: respuestaFactura,
|
||||
Stocks: stocks,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func registrarLogFactura(
|
||||
repo *repositorios.Repositorios,
|
||||
empresaID, usuarioID uint,
|
||||
accion string,
|
||||
detalles []models_logs.LogDetalle,
|
||||
) {
|
||||
log, err := dto_directors.NewLogDirector().Custom(usuarioID, accion, detalles)
|
||||
if err != nil {
|
||||
applog.Printf("facturas: no se pudo construir el log de %s: %v", accion, err)
|
||||
return
|
||||
}
|
||||
log.EmpresaID = empresaID
|
||||
if err := repo.Logs.Crear(log, usuarioID); err != nil {
|
||||
applog.Printf("facturas: no se pudo registrar el log de %s: %v", accion, err)
|
||||
}
|
||||
}
|
||||
|
||||
func validarCantidad(cantidad float64) error {
|
||||
if math.IsNaN(cantidad) || math.IsInf(cantidad, 0) || cantidad <= 0 {
|
||||
return errCantidadInvalida
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func redondearCantidad(valor float64) float64 {
|
||||
return math.Round(valor*1000) / 1000
|
||||
}
|
||||
Reference in new issue
Block a user