Private
Public Access
bueno es parte del plan de implementacion para el caso de uso de gestion
de stock
This commit is contained in:
1 parent
24e746b1b7
commit
6ed8805e21
40 files changed
+2726
-9
No files matched your search
@@ -16,6 +16,7 @@ var tablasTenant = []string{
|
|||||||
"marca",
|
"marca",
|
||||||
"repuesto",
|
"repuesto",
|
||||||
"stock",
|
"stock",
|
||||||
|
"movimiento_stock",
|
||||||
"clientes",
|
"clientes",
|
||||||
"descuentos",
|
"descuentos",
|
||||||
"forma_de_pago",
|
"forma_de_pago",
|
||||||
@@ -26,6 +27,7 @@ var tablasTenant = []string{
|
|||||||
"factura",
|
"factura",
|
||||||
"recibo",
|
"recibo",
|
||||||
"remitos",
|
"remitos",
|
||||||
|
"diferencia_remito",
|
||||||
"nota_credito",
|
"nota_credito",
|
||||||
"nota_debito",
|
"nota_debito",
|
||||||
"orden_compra",
|
"orden_compra",
|
||||||
|
|||||||
@@ -0,0 +1,363 @@
|
|||||||
|
package config
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"log"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"repuestera_back/models"
|
||||||
|
models_seguridad "repuestera_back/models/seguridad"
|
||||||
|
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
// columnasDecimalesStock son las columnas de stock que deben ser decimales.
|
||||||
|
// GORM no las convierte solo con AutoMigrate porque su heuristica de
|
||||||
|
// MigrateColumn no detecta el cambio de tipo cuando el default coincide.
|
||||||
|
var columnasDecimalesStock = map[string]bool{
|
||||||
|
"cantidad": true,
|
||||||
|
"cantidad_reservada": true,
|
||||||
|
}
|
||||||
|
|
||||||
|
// columnasMovimientosLegado son las columnas JSON historicas de stock.
|
||||||
|
// "movmientos" es el typo original y "movimientos" el nombre corregido.
|
||||||
|
var columnasMovimientosLegado = []string{"movmientos", "movimientos"}
|
||||||
|
|
||||||
|
// MigrarStock completa la preparacion de datos posterior a AutoMigrate:
|
||||||
|
// - garantiza los almacenes por defecto por empresa;
|
||||||
|
// - convierte las cantidades de stock a decimal;
|
||||||
|
// - migra el JSON historico de stock a la tabla movimiento_stock;
|
||||||
|
// - elimina la columna con el typo historico.
|
||||||
|
//
|
||||||
|
// Es idempotente: las filas ya migradas quedan con movimientos = NULL y la
|
||||||
|
// columna legada se elimina una sola vez.
|
||||||
|
func MigrarStock() error {
|
||||||
|
if !DB.Migrator().HasTable("stock") {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := sembrarAlmacenDefault(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := migrarTiposStock(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := migrarMovimientosLegado(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := migrarDetallesDevolucion(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return eliminarColumnaMovmientos()
|
||||||
|
}
|
||||||
|
|
||||||
|
func sembrarAlmacenDefault() error {
|
||||||
|
if _, err := empresaDefault(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
var empresas []models_seguridad.Empresa
|
||||||
|
if err := DB.Find(&empresas).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, empresa := range empresas {
|
||||||
|
almacenes := []models.Almacen{
|
||||||
|
{Codigo: "A1", Ubicacion: "Deposito principal"},
|
||||||
|
{Codigo: "A2", Ubicacion: "Deposito secundario"},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, almacen := range almacenes {
|
||||||
|
var count int64
|
||||||
|
if err := DB.Model(&models.Almacen{}).
|
||||||
|
Where("empresa_id = ? AND codigo = ?", empresa.ID, almacen.Codigo).
|
||||||
|
Count(&count).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if count > 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
almacen.EmpresaID = empresa.ID
|
||||||
|
if err := DB.Create(&almacen).Error; err != nil {
|
||||||
|
return fmt.Errorf("crear almacen %s de empresa %d: %w", almacen.Codigo, empresa.ID, err)
|
||||||
|
}
|
||||||
|
log.Printf("stock: almacen %s creado para empresa %d", almacen.Codigo, empresa.ID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// migrarTiposStock convierte a decimal las columnas de cantidad si quedaron
|
||||||
|
// como enteros de una version anterior.
|
||||||
|
func migrarTiposStock() error {
|
||||||
|
columnas, err := DB.Migrator().ColumnTypes(&models.Stock{})
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("leer columnas de stock: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, columna := range columnas {
|
||||||
|
if !columnasDecimalesStock[columna.Name()] {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if strings.EqualFold(columna.DatabaseTypeName(), "decimal") {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := DB.Migrator().AlterColumn(&models.Stock{}, columna.Name()); err != nil {
|
||||||
|
return fmt.Errorf("convertir stock.%s a decimal: %w", columna.Name(), err)
|
||||||
|
}
|
||||||
|
log.Printf("stock: columna stock.%s convertida a decimal", columna.Name())
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func migrarMovimientosLegado() error {
|
||||||
|
if !DB.Migrator().HasTable("movimiento_stock") {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
columnas := columnasLegadoExistentes()
|
||||||
|
if len(columnas) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type stockLegado struct {
|
||||||
|
ID uint64
|
||||||
|
EmpresaID uint64
|
||||||
|
RepuestoID uint64
|
||||||
|
AlmacenID uint
|
||||||
|
Movmientos []byte
|
||||||
|
Movimientos []byte
|
||||||
|
}
|
||||||
|
|
||||||
|
condiciones := make([]string, len(columnas))
|
||||||
|
for i, columna := range columnas {
|
||||||
|
condiciones[i] = columna + " IS NOT NULL"
|
||||||
|
}
|
||||||
|
|
||||||
|
var filas []stockLegado
|
||||||
|
if err := DB.Table("stock").
|
||||||
|
Select("id, empresa_id, repuesto_id, almacen_id, " + strings.Join(columnas, ", ")).
|
||||||
|
Where(strings.Join(condiciones, " OR ")).
|
||||||
|
Scan(&filas).Error; err != nil {
|
||||||
|
return fmt.Errorf("leer movimientos legados de stock: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
migradas := 0
|
||||||
|
for _, fila := range filas {
|
||||||
|
movs, err := parsearMovimientosLegados(fila.Movmientos)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("stock %d (movmientos): %w", fila.ID, err)
|
||||||
|
}
|
||||||
|
otros, err := parsearMovimientosLegados(fila.Movimientos)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("stock %d (movimientos): %w", fila.ID, err)
|
||||||
|
}
|
||||||
|
movs = append(movs, otros...)
|
||||||
|
|
||||||
|
if len(movs) == 0 {
|
||||||
|
if err := limpiarMovimientosLegados(DB, fila.ID, columnas); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := migrarFilaMovimientos(fila.ID, fila.EmpresaID, fila.RepuestoID, fila.AlmacenID, columnas, movs); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
migradas++
|
||||||
|
}
|
||||||
|
|
||||||
|
if migradas > 0 {
|
||||||
|
log.Printf("stock: %d filas con movimientos migradas a movimiento_stock", migradas)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func columnasLegadoExistentes() []string {
|
||||||
|
var columnas []string
|
||||||
|
for _, columna := range columnasMovimientosLegado {
|
||||||
|
if DB.Migrator().HasColumn("stock", columna) {
|
||||||
|
columnas = append(columnas, columna)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return columnas
|
||||||
|
}
|
||||||
|
|
||||||
|
func parsearMovimientosLegados(raw []byte) ([]models.MovimientoStockLegacy, error) {
|
||||||
|
if len(raw) == 0 || string(raw) == "null" {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
var movs []models.MovimientoStockLegacy
|
||||||
|
if err := json.Unmarshal(raw, &movs); err != nil {
|
||||||
|
return nil, fmt.Errorf("json de movimientos invalido: %w", err)
|
||||||
|
}
|
||||||
|
return movs, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func migrarFilaMovimientos(stockID, empresaID, repuestoID uint64, almacenID uint, columnas []string, movs []models.MovimientoStockLegacy) error {
|
||||||
|
return DB.Transaction(func(tx *gorm.DB) error {
|
||||||
|
var pendientes int64
|
||||||
|
condiciones := make([]string, len(columnas))
|
||||||
|
for i, columna := range columnas {
|
||||||
|
condiciones[i] = columna + " IS NOT NULL"
|
||||||
|
}
|
||||||
|
if err := tx.Table("stock").
|
||||||
|
Where("id = ? AND ("+strings.Join(condiciones, " OR ")+")", stockID).
|
||||||
|
Count(&pendientes).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if pendientes == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
empresa := empresaID
|
||||||
|
if empresa == 0 {
|
||||||
|
empresa = 1
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, legado := range movs {
|
||||||
|
tipo := strings.ToUpper(strings.TrimSpace(legado.Tipo))
|
||||||
|
if tipo == "" {
|
||||||
|
tipo = string(models.MovimientoLegado)
|
||||||
|
}
|
||||||
|
|
||||||
|
fecha := legado.Fecha
|
||||||
|
if fecha.IsZero() {
|
||||||
|
fecha = time.Now()
|
||||||
|
}
|
||||||
|
|
||||||
|
movimiento := models.MovimientoStock{
|
||||||
|
EmpresaID: empresa,
|
||||||
|
StockID: stockID,
|
||||||
|
RepuestoID: repuestoID,
|
||||||
|
AlmacenID: almacenID,
|
||||||
|
Tipo: models.TipoMovimientoStock(tipo),
|
||||||
|
Cantidad: legado.Cantidad,
|
||||||
|
ReferenciaTipo: "LEGACY",
|
||||||
|
ReferenciaID: stockID,
|
||||||
|
UsuarioID: legado.UsuarioID,
|
||||||
|
Observacion: "Migrado desde stock.movimientos (JSON legado)",
|
||||||
|
Fecha: fecha,
|
||||||
|
CreatedAt: fecha,
|
||||||
|
}
|
||||||
|
if err := tx.Create(&movimiento).Error; err != nil {
|
||||||
|
return fmt.Errorf("stock %d: crear movimiento: %w", stockID, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return limpiarMovimientosLegados(tx, stockID, columnas)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// migrarDetallesDevolucion pasa los renglones de la tabla devolucion_detalle
|
||||||
|
// a la columna JSON devolucion.detalles y elimina la tabla vieja.
|
||||||
|
func migrarDetallesDevolucion() error {
|
||||||
|
if !DB.Migrator().HasTable("devolucion") || !DB.Migrator().HasColumn("devolucion", "detalles") {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if !DB.Migrator().HasTable("devolucion_detalle") {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type filaDetalle struct {
|
||||||
|
DevolucionID uint
|
||||||
|
RepuestoID uint64
|
||||||
|
Cantidad float64
|
||||||
|
PrecioUnitario float64
|
||||||
|
Subtotal float64
|
||||||
|
}
|
||||||
|
|
||||||
|
var filas []filaDetalle
|
||||||
|
if err := DB.Table("devolucion_detalle").
|
||||||
|
Select("devolucion_id, repuesto_id, cantidad, precio_unitario, subtotal").
|
||||||
|
Order("devolucion_id ASC, id ASC").
|
||||||
|
Scan(&filas).Error; err != nil {
|
||||||
|
return fmt.Errorf("leer devolucion_detalle: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
agrupadas := make(map[uint][]models.DevolucionDetalle)
|
||||||
|
for _, fila := range filas {
|
||||||
|
agrupadas[fila.DevolucionID] = append(agrupadas[fila.DevolucionID], models.DevolucionDetalle{
|
||||||
|
RepuestoID: fila.RepuestoID,
|
||||||
|
Cantidad: fila.Cantidad,
|
||||||
|
PrecioUnitario: fila.PrecioUnitario,
|
||||||
|
Subtotal: fila.Subtotal,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
migradas := 0
|
||||||
|
for devolucionID, detalles := range agrupadas {
|
||||||
|
var actual string
|
||||||
|
if err := DB.Table("devolucion").
|
||||||
|
Select("COALESCE(detalles, '[]')").
|
||||||
|
Where("id = ?", devolucionID).
|
||||||
|
Scan(&actual).Error; err != nil {
|
||||||
|
return fmt.Errorf("leer devolucion %d: %w", devolucionID, err)
|
||||||
|
}
|
||||||
|
if actual != "" && actual != "[]" && actual != "null" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
jsonDetalles, err := json.Marshal(detalles)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("serializar detalles de devolucion %d: %w", devolucionID, err)
|
||||||
|
}
|
||||||
|
if err := DB.Exec("UPDATE devolucion SET detalles = ? WHERE id = ?", string(jsonDetalles), devolucionID).Error; err != nil {
|
||||||
|
return fmt.Errorf("actualizar devolucion %d: %w", devolucionID, err)
|
||||||
|
}
|
||||||
|
migradas++
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := DB.Migrator().DropTable("devolucion_detalle"); err != nil {
|
||||||
|
return fmt.Errorf("eliminar tabla devolucion_detalle: %w", err)
|
||||||
|
}
|
||||||
|
if migradas > 0 {
|
||||||
|
log.Printf("stock: %d devoluciones migradas a detalles JSON", migradas)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func limpiarMovimientosLegados(tx *gorm.DB, stockID uint64, columnas []string) error {
|
||||||
|
asignaciones := make([]string, len(columnas))
|
||||||
|
for i, columna := range columnas {
|
||||||
|
asignaciones[i] = columna + " = NULL"
|
||||||
|
}
|
||||||
|
return tx.Exec(
|
||||||
|
"UPDATE stock SET "+strings.Join(asignaciones, ", ")+" WHERE id = ?",
|
||||||
|
stockID,
|
||||||
|
).Error
|
||||||
|
}
|
||||||
|
|
||||||
|
// eliminarColumnaMovmientos borra la columna con el typo historico una vez
|
||||||
|
// que sus datos ya fueron migrados a movimiento_stock.
|
||||||
|
func eliminarColumnaMovmientos() error {
|
||||||
|
const columna = "movmientos"
|
||||||
|
if !DB.Migrator().HasColumn("stock", columna) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
var pendientes int64
|
||||||
|
if err := DB.Table("stock").Where(columna + " IS NOT NULL").Count(&pendientes).Error; err != nil {
|
||||||
|
return fmt.Errorf("verificar stock.%s antes de eliminarla: %w", columna, err)
|
||||||
|
}
|
||||||
|
if pendientes > 0 {
|
||||||
|
return fmt.Errorf("stock.%s tiene %d filas sin migrar; no se elimina", columna, pendientes)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := DB.Migrator().DropColumn(&models.Stock{}, columna); err != nil {
|
||||||
|
return fmt.Errorf("eliminar columna stock.%s: %w", columna, err)
|
||||||
|
}
|
||||||
|
log.Printf("stock: columna stock.%s eliminada", columna)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -25,6 +25,10 @@ var permisosSemilla = []permisoSemilla{
|
|||||||
{6, "Gestión de Logs", "logs", "Consultar la auditoría de la empresa."},
|
{6, "Gestión de Logs", "logs", "Consultar la auditoría de la empresa."},
|
||||||
{7, "Gestión de Empresa", "empresa", "Editar los datos de la empresa y sus miembros."},
|
{7, "Gestión de Empresa", "empresa", "Editar los datos de la empresa y sus miembros."},
|
||||||
{8, "Administración de Plataforma", "plataforma", "Administrar empresas y administradores globales."},
|
{8, "Administración de Plataforma", "plataforma", "Administrar empresas y administradores globales."},
|
||||||
|
{9, "Gestión de Stock", "stock", "Consultar y operar el stock de la empresa."},
|
||||||
|
{10, "Gestión de Almacenes", "almacenes", "Consultar y administrar los almacenes de la empresa."},
|
||||||
|
{11, "Gestión de Proveedores", "proveedores", "Consultar y administrar los proveedores de la empresa."},
|
||||||
|
{12, "Gestión de Clientes", "clientes", "Consultar y administrar los clientes de la empresa."},
|
||||||
}
|
}
|
||||||
|
|
||||||
// InitPermisos crea el catálogo global de permisos y garantiza que cada
|
// InitPermisos crea el catálogo global de permisos y garantiza que cada
|
||||||
@@ -77,6 +81,10 @@ func AsegurarGruposEmpresa(db *gorm.DB, empresaID uint) (uint, uint, error) {
|
|||||||
models_seguridad.PermisoGestionLogs,
|
models_seguridad.PermisoGestionLogs,
|
||||||
models_seguridad.PermisoGestionMarcas,
|
models_seguridad.PermisoGestionMarcas,
|
||||||
models_seguridad.PermisoGestionEmpresa,
|
models_seguridad.PermisoGestionEmpresa,
|
||||||
|
models_seguridad.PermisoGestionStock,
|
||||||
|
models_seguridad.PermisoGestionAlmacenes,
|
||||||
|
models_seguridad.PermisoGestionProveedores,
|
||||||
|
models_seguridad.PermisoGestionClientes,
|
||||||
}
|
}
|
||||||
if err := asignarPermisosFaltantes(db, admin.ID, permisosAdmin); err != nil {
|
if err := asignarPermisosFaltantes(db, admin.ID, permisosAdmin); err != nil {
|
||||||
return 0, 0, err
|
return 0, 0, err
|
||||||
@@ -85,6 +93,10 @@ func AsegurarGruposEmpresa(db *gorm.DB, empresaID uint) (uint, uint, error) {
|
|||||||
permisosUsuario := []uint{
|
permisosUsuario := []uint{
|
||||||
models_seguridad.PermisoGestionRepuestos,
|
models_seguridad.PermisoGestionRepuestos,
|
||||||
models_seguridad.PermisoGestionMarcas,
|
models_seguridad.PermisoGestionMarcas,
|
||||||
|
models_seguridad.PermisoGestionStock,
|
||||||
|
models_seguridad.PermisoGestionAlmacenes,
|
||||||
|
models_seguridad.PermisoGestionProveedores,
|
||||||
|
models_seguridad.PermisoGestionClientes,
|
||||||
}
|
}
|
||||||
if err := asignarPermisosFaltantes(db, usuario.ID, permisosUsuario); err != nil {
|
if err := asignarPermisosFaltantes(db, usuario.ID, permisosUsuario); err != nil {
|
||||||
return 0, 0, err
|
return 0, 0, err
|
||||||
|
|||||||
@@ -0,0 +1,44 @@
|
|||||||
|
package almacen
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
|
||||||
|
dto "repuestera_back/dto/Almacenes"
|
||||||
|
"repuestera_back/models"
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
)
|
||||||
|
|
||||||
|
func CrearAlmacen(c *gin.Context) {
|
||||||
|
var data dto.CrearAlmacenDto
|
||||||
|
if err := c.ShouldBindJSON(&data); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
repo := r.ObtenerRepositorios(c).Almacen
|
||||||
|
if _, err := repo.BuscarPorCodigo(data.Codigo); err == nil {
|
||||||
|
c.JSON(http.StatusConflict, gin.H{"error": "ya existe un almacén con ese código"})
|
||||||
|
return
|
||||||
|
} else if !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
almacen := models.Almacen{Codigo: data.Codigo, Ubicacion: data.Ubicacion}
|
||||||
|
if err := repo.Crear(almacen, c.GetUint("userID")); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
creado, err := repo.BuscarPorCodigo(data.Codigo)
|
||||||
|
if err != nil {
|
||||||
|
c.Status(http.StatusCreated)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusCreated, creado)
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
package almacen
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
)
|
||||||
|
|
||||||
|
func ObtenerAlmacenes(c *gin.Context) {
|
||||||
|
almacenes, err := r.ObtenerRepositorios(c).Almacen.Listar()
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, almacenes)
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
package cliente
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
)
|
||||||
|
|
||||||
|
func ObtenerClientes(c *gin.Context) {
|
||||||
|
clientes, err := r.ObtenerRepositorios(c).Cliente.Listar(c.Query("q"))
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, clientes)
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
package factura
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
)
|
||||||
|
|
||||||
|
func ObtenerFactura(c *gin.Context) {
|
||||||
|
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "id inválido"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
factura, err := r.ObtenerRepositorios(c).Factura.ObtenerConRelaciones(uint(id))
|
||||||
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
c.JSON(http.StatusNotFound, gin.H{"error": "factura no encontrada"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, factura)
|
||||||
|
}
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
package factura
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
)
|
||||||
|
|
||||||
|
func ObtenerFacturas(c *gin.Context) {
|
||||||
|
filtros := r.FiltrosFactura{
|
||||||
|
Numero: c.Query("numero"),
|
||||||
|
Cliente: c.Query("cliente"),
|
||||||
|
}
|
||||||
|
|
||||||
|
if raw := c.Query("clienteId"); raw != "" {
|
||||||
|
id, err := strconv.ParseUint(raw, 10, 64)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "clienteId inválido"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
filtros.ClienteID = uint(id)
|
||||||
|
}
|
||||||
|
|
||||||
|
desde, err := fechaQuery(c.Query("desde"))
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "desde inválido, se espera YYYY-MM-DD"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
hasta, err := fechaQuery(c.Query("hasta"))
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "hasta inválido, se espera YYYY-MM-DD"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
filtros.Desde = desde
|
||||||
|
filtros.Hasta = hasta
|
||||||
|
|
||||||
|
facturas, err := r.ObtenerRepositorios(c).Factura.Listar(filtros)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, facturas)
|
||||||
|
}
|
||||||
|
|
||||||
|
func fechaQuery(valor string) (*time.Time, error) {
|
||||||
|
if valor == "" {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
fecha, err := time.Parse("2006-01-02", valor)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &fecha, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
package proveedor
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
|
||||||
|
dto "repuestera_back/dto/Proveedores"
|
||||||
|
"repuestera_back/models"
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
)
|
||||||
|
|
||||||
|
func CrearProveedor(c *gin.Context) {
|
||||||
|
var data dto.CrearProveedorDto
|
||||||
|
if err := c.ShouldBindJSON(&data); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
repo := r.ObtenerRepositorios(c).Proveedor
|
||||||
|
if _, err := repo.BuscarPorNombre(data.Nombre); err == nil {
|
||||||
|
c.JSON(http.StatusConflict, gin.H{"error": "ya existe un proveedor con ese nombre"})
|
||||||
|
return
|
||||||
|
} else if !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
proveedor := models.Proveedor{
|
||||||
|
Nombre: data.Nombre,
|
||||||
|
Cuit: data.Cuit,
|
||||||
|
Email: data.Email,
|
||||||
|
Telefono: data.Telefono,
|
||||||
|
}
|
||||||
|
if err := repo.Crear(proveedor, c.GetUint("userID")); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
creado, err := repo.BuscarPorNombre(data.Nombre)
|
||||||
|
if err != nil {
|
||||||
|
c.Status(http.StatusCreated)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusCreated, creado)
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
package proveedor
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
)
|
||||||
|
|
||||||
|
func ObtenerProveedores(c *gin.Context) {
|
||||||
|
proveedores, err := r.ObtenerRepositorios(c).Proveedor.Listar(c.Query("q"))
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, proveedores)
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
package dto
|
||||||
|
|
||||||
|
type CrearAlmacenDto struct {
|
||||||
|
Codigo string `json:"codigo" binding:"required,max=5"`
|
||||||
|
Ubicacion string `json:"ubicacion" binding:"max=40"`
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
package dto
|
||||||
|
|
||||||
|
type CrearProveedorDto struct {
|
||||||
|
Nombre string `json:"nombre" binding:"required,max=40"`
|
||||||
|
Cuit string `json:"cuit" binding:"max=11"`
|
||||||
|
Email string `json:"email" binding:"omitempty,email,max=80"`
|
||||||
|
Telefono string `json:"telefono" binding:"max=30"`
|
||||||
|
}
|
||||||
@@ -1,10 +1,14 @@
|
|||||||
package models
|
package models
|
||||||
|
|
||||||
|
import "gorm.io/datatypes"
|
||||||
|
|
||||||
type Devolucion struct {
|
type Devolucion struct {
|
||||||
Comprobante
|
Comprobante
|
||||||
Motivo string `gorm:"type:varchar(200);not null" json:"motivo"`
|
Motivo string `gorm:"type:varchar(200);not null" json:"motivo"`
|
||||||
FacturaOrigen Factura `gorm:"foreignKey:FacturaOrigenID" json:"facturaOrigen"`
|
FacturaOrigen Factura `gorm:"foreignKey:FacturaOrigenID" json:"facturaOrigen"`
|
||||||
FacturaOrigenID uint `gorm:"column:facturaOrigenID;not null" json:"facturaOrigenId"`
|
FacturaOrigenID uint `gorm:"column:facturaOrigenID;not null" json:"facturaOrigenId"`
|
||||||
|
|
||||||
|
Detalles datatypes.JSONSlice[DevolucionDetalle] `gorm:"type:json" json:"detalles,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (Devolucion) TableName() string {
|
func (Devolucion) TableName() string {
|
||||||
|
|||||||
@@ -0,0 +1,10 @@
|
|||||||
|
package models
|
||||||
|
|
||||||
|
// DevolucionDetalle es un renglon de devolucion.
|
||||||
|
// Se persiste como JSON dentro de Devolucion.Detalles.
|
||||||
|
type DevolucionDetalle struct {
|
||||||
|
RepuestoID uint64 `json:"repuestoId"`
|
||||||
|
Cantidad float64 `json:"cantidad"`
|
||||||
|
PrecioUnitario float64 `json:"precioUnitario"`
|
||||||
|
Subtotal float64 `json:"subtotal"`
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
package models
|
||||||
|
|
||||||
|
import "time"
|
||||||
|
|
||||||
|
// DiferenciaRemito registra una diferencia entre lo declarado en el remito
|
||||||
|
// y lo efectivamente recibido.
|
||||||
|
type DiferenciaRemito struct {
|
||||||
|
ID uint64 `gorm:"primaryKey" json:"id"`
|
||||||
|
EmpresaID uint64 `gorm:"not null;default:1;index" json:"empresaId"`
|
||||||
|
|
||||||
|
RemitoID uint `gorm:"not null;index" json:"remitoId"`
|
||||||
|
Remito Remito `gorm:"foreignKey:RemitoID" json:"-"`
|
||||||
|
|
||||||
|
RepuestoID uint64 `gorm:"not null;index" json:"repuestoId"`
|
||||||
|
Repuesto Repuesto `gorm:"foreignKey:RepuestoID" json:"repuesto,omitempty"`
|
||||||
|
|
||||||
|
CantidadEsperada float64 `gorm:"type:decimal(15,3);not null;default:0" json:"cantidadEsperada"`
|
||||||
|
CantidadRecibida float64 `gorm:"type:decimal(15,3);not null;default:0" json:"cantidadRecibida"`
|
||||||
|
Diferencia float64 `gorm:"type:decimal(15,3);not null;default:0" json:"diferencia"`
|
||||||
|
|
||||||
|
UsuarioID uint `gorm:"index" json:"usuarioId"`
|
||||||
|
Observacion string `gorm:"type:varchar(255)" json:"observacion,omitempty"`
|
||||||
|
NotificadaAt *time.Time `json:"notificadaAt,omitempty"`
|
||||||
|
|
||||||
|
CreatedAt time.Time `json:"createdAt"`
|
||||||
|
UpdatedAt time.Time `json:"updatedAt"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (DiferenciaRemito) TableName() string {
|
||||||
|
return "diferencia_remito"
|
||||||
|
}
|
||||||
@@ -2,6 +2,7 @@ package models
|
|||||||
|
|
||||||
type Factura struct {
|
type Factura struct {
|
||||||
Comprobante
|
Comprobante
|
||||||
|
Numero string `gorm:"type:varchar(30);index" json:"numero"`
|
||||||
ClienteID uint `gorm:"column:ClienteID"`
|
ClienteID uint `gorm:"column:ClienteID"`
|
||||||
Cliente Cliente `gorm:"foreignKey:ClienteID" json:"cliente"`
|
Cliente Cliente `gorm:"foreignKey:ClienteID" json:"cliente"`
|
||||||
ProveedorID *uint `json:"proveedorId,omitempty"`
|
ProveedorID *uint `json:"proveedorId,omitempty"`
|
||||||
|
|||||||
@@ -0,0 +1,51 @@
|
|||||||
|
package models
|
||||||
|
|
||||||
|
import "time"
|
||||||
|
|
||||||
|
// TipoMovimientoStock identifica la naturaleza de una variación de stock.
|
||||||
|
type TipoMovimientoStock string
|
||||||
|
|
||||||
|
const (
|
||||||
|
MovimientoIngreso TipoMovimientoStock = "INGRESO"
|
||||||
|
MovimientoAjuste TipoMovimientoStock = "AJUSTE"
|
||||||
|
MovimientoTrasladoSalida TipoMovimientoStock = "TRASLADO_SALIDA"
|
||||||
|
MovimientoTrasladoEntrada TipoMovimientoStock = "TRASLADO_ENTRADA"
|
||||||
|
MovimientoReserva TipoMovimientoStock = "RESERVA"
|
||||||
|
MovimientoLiberacion TipoMovimientoStock = "LIBERACION"
|
||||||
|
MovimientoDevolucion TipoMovimientoStock = "DEVOLUCION"
|
||||||
|
MovimientoVenta TipoMovimientoStock = "VENTA"
|
||||||
|
MovimientoLegado TipoMovimientoStock = "LEGACY"
|
||||||
|
)
|
||||||
|
|
||||||
|
// MovimientoStock es el registro auditable de cada variación de stock.
|
||||||
|
// Reemplaza al JSON historico embebido en Stock.
|
||||||
|
type MovimientoStock struct {
|
||||||
|
ID uint64 `gorm:"primaryKey" json:"id"`
|
||||||
|
EmpresaID uint64 `gorm:"not null;default:1;index;index:idx_mov_empresa_fecha,priority:1;index:idx_mov_empresa_repuesto_almacen,priority:1;index:idx_mov_empresa_tipo,priority:1" json:"empresaId"`
|
||||||
|
|
||||||
|
StockID uint64 `gorm:"not null;index" json:"stockId"`
|
||||||
|
Stock Stock `gorm:"foreignKey:StockID" json:"-"`
|
||||||
|
|
||||||
|
RepuestoID uint64 `gorm:"not null;index:idx_mov_empresa_repuesto_almacen,priority:2" json:"repuestoId"`
|
||||||
|
Repuesto Repuesto `gorm:"foreignKey:RepuestoID" json:"repuesto,omitempty"`
|
||||||
|
|
||||||
|
AlmacenID uint `gorm:"not null;index:idx_mov_empresa_repuesto_almacen,priority:3" json:"almacenId"`
|
||||||
|
Almacen Almacen `gorm:"foreignKey:AlmacenID" json:"almacen,omitempty"`
|
||||||
|
|
||||||
|
Tipo TipoMovimientoStock `gorm:"type:varchar(30);not null;index:idx_mov_empresa_tipo,priority:2" json:"tipo"`
|
||||||
|
Cantidad float64 `gorm:"type:decimal(15,3);not null" json:"cantidad"`
|
||||||
|
SaldoAnterior float64 `gorm:"type:decimal(15,3);not null;default:0" json:"saldoAnterior"`
|
||||||
|
SaldoPosterior float64 `gorm:"type:decimal(15,3);not null;default:0" json:"saldoPosterior"`
|
||||||
|
|
||||||
|
ReferenciaTipo string `gorm:"type:varchar(20);index" json:"referenciaTipo,omitempty"`
|
||||||
|
ReferenciaID uint64 `gorm:"index" json:"referenciaId,omitempty"`
|
||||||
|
|
||||||
|
UsuarioID uint `gorm:"index" json:"usuarioId"`
|
||||||
|
Observacion string `gorm:"type:varchar(255)" json:"observacion,omitempty"`
|
||||||
|
Fecha time.Time `gorm:"not null;index;index:idx_mov_empresa_fecha,priority:2" json:"fecha"`
|
||||||
|
CreatedAt time.Time `json:"createdAt"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (MovimientoStock) TableName() string {
|
||||||
|
return "movimiento_stock"
|
||||||
|
}
|
||||||
@@ -6,5 +6,8 @@ type Proveedor struct {
|
|||||||
gorm.Model
|
gorm.Model
|
||||||
EmpresaID uint `gorm:"not null;default:1;index" json:"empresaId"`
|
EmpresaID uint `gorm:"not null;default:1;index" json:"empresaId"`
|
||||||
Nombre string `gorm:"type:varchar(40)" json:"nombre"`
|
Nombre string `gorm:"type:varchar(40)" json:"nombre"`
|
||||||
|
Cuit string `gorm:"type:varchar(11);index" json:"cuit,omitempty"`
|
||||||
|
Email string `gorm:"type:varchar(80)" json:"email,omitempty"`
|
||||||
|
Telefono string `gorm:"type:varchar(30)" json:"telefono,omitempty"`
|
||||||
Facturas []Factura `gorm:"foreignKey:ProveedorID" json:"facturas,omitempty"`
|
Facturas []Factura `gorm:"foreignKey:ProveedorID" json:"facturas,omitempty"`
|
||||||
}
|
}
|
||||||
@@ -8,14 +8,24 @@ import (
|
|||||||
|
|
||||||
type Remito struct {
|
type Remito struct {
|
||||||
Comprobante
|
Comprobante
|
||||||
|
Numero string `gorm:"type:varchar(30);index" json:"numero"`
|
||||||
FechaEmision time.Time `gorm:"not null" json:"fechaEmision"`
|
FechaEmision time.Time `gorm:"not null" json:"fechaEmision"`
|
||||||
TipoOperacion TipoOperacion `gorm:"type:varchar(20);not null" json:"tipoOperacion"`
|
TipoOperacion TipoOperacion `gorm:"type:varchar(20);not null" json:"tipoOperacion"`
|
||||||
EmisorID uint `gorm:"not null" json:"emisorId"`
|
EmisorID uint `gorm:"not null" json:"emisorId"`
|
||||||
ReceptorID uint `gorm:"not null" json:"receptorId"`
|
ReceptorID uint `gorm:"not null" json:"receptorId"`
|
||||||
|
|
||||||
|
ProveedorID *uint `gorm:"index" json:"proveedorId,omitempty"`
|
||||||
|
Proveedor *Proveedor `gorm:"foreignKey:ProveedorID" json:"proveedor,omitempty"`
|
||||||
|
|
||||||
AlmacenOrigenID *uint `gorm:"column:almacen_origen_id" json:"almacenOrigenId,omitempty"`
|
AlmacenOrigenID *uint `gorm:"column:almacen_origen_id" json:"almacenOrigenId,omitempty"`
|
||||||
AlmacenOrigen *Almacen `gorm:"foreignKey:AlmacenOrigenID" json:"almacenOrigen,omitempty"`
|
AlmacenOrigen *Almacen `gorm:"foreignKey:AlmacenOrigenID" json:"almacenOrigen,omitempty"`
|
||||||
|
|
||||||
|
AlmacenDestinoID *uint `gorm:"column:almacen_destino_id" json:"almacenDestinoId,omitempty"`
|
||||||
|
AlmacenDestino *Almacen `gorm:"foreignKey:AlmacenDestinoID" json:"almacenDestino,omitempty"`
|
||||||
|
|
||||||
|
ArchivoURL string `gorm:"type:varchar(500)" json:"archivoUrl,omitempty"`
|
||||||
|
Observacion string `gorm:"type:varchar(255)" json:"observacion,omitempty"`
|
||||||
|
|
||||||
Detalles datatypes.JSONSlice[RemitoDetalle] `gorm:"type:json" json:"detalles,omitempty"`
|
Detalles datatypes.JSONSlice[RemitoDetalle] `gorm:"type:json" json:"detalles,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -8,17 +8,19 @@ import (
|
|||||||
|
|
||||||
type Reserva struct {
|
type Reserva struct {
|
||||||
gorm.Model
|
gorm.Model
|
||||||
EmpresaID uint `gorm:"not null;default:1;index;index:idx_reserva_empresa_repuesto_almacen,priority:1" json:"empresaId"`
|
EmpresaID uint `gorm:"not null;default:1;index;index:idx_reserva_empresa_repuesto_almacen,priority:1;index:idx_reserva_empresa_estado_vencimiento,priority:1" json:"empresaId"`
|
||||||
|
|
||||||
RepuestoID uint `gorm:"not null;index:idx_reserva_empresa_repuesto_almacen,priority:2" json:"repuesto_id"`
|
RepuestoID uint `gorm:"not null;index:idx_reserva_empresa_repuesto_almacen,priority:2" json:"repuesto_id"`
|
||||||
Repuesto Repuesto `gorm:"foreignKey:RepuestoID" json:"repuesto,omitempty"`
|
Repuesto Repuesto `gorm:"foreignKey:RepuestoID" json:"repuesto,omitempty"`
|
||||||
AlmacenID uint `gorm:"not null;index:idx_reserva_empresa_repuesto_almacen,priority:3" json:"almacen_id"`
|
AlmacenID uint `gorm:"not null;index:idx_reserva_empresa_repuesto_almacen,priority:3" json:"almacen_id"`
|
||||||
Almacen Almacen `gorm:"foreignKey:AlmacenID" json:"almacen,omitempty"`
|
Almacen Almacen `gorm:"foreignKey:AlmacenID" json:"almacen,omitempty"`
|
||||||
Cantidad float64 `gorm:"not null;check:cantidad > 0" json:"cantidad"`
|
Cantidad float64 `gorm:"type:decimal(15,3);not null;check:cantidad > 0" json:"cantidad"`
|
||||||
Estado EstadoReserva `gorm:"type:varchar(20);not null;default:'activa';index" json:"estado"`
|
Estado EstadoReserva `gorm:"type:varchar(20);not null;default:'activa';index;index:idx_reserva_empresa_estado_vencimiento,priority:2" json:"estado"`
|
||||||
ClienteID *uint `json:"cliente_id,omitempty"`
|
ClienteID *uint `json:"cliente_id,omitempty"`
|
||||||
Cliente *Cliente `gorm:"foreignKey:ClienteID" json:"cliente,omitempty"`
|
Cliente *Cliente `gorm:"foreignKey:ClienteID" json:"cliente,omitempty"`
|
||||||
FechaVencimiento time.Time `gorm:"index" json:"fecha_vencimiento,omitempty"`
|
FechaVencimiento time.Time `gorm:"index;index:idx_reserva_empresa_estado_vencimiento,priority:3" json:"fecha_vencimiento,omitempty"`
|
||||||
|
CreadoPorID uint `gorm:"index" json:"creadoPorId,omitempty"`
|
||||||
|
Observacion string `gorm:"type:varchar(255)" json:"observacion,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type EstadoReserva string
|
type EstadoReserva string
|
||||||
|
|||||||
@@ -11,6 +11,10 @@ const (
|
|||||||
PermisoGestionMarcas uint = 5
|
PermisoGestionMarcas uint = 5
|
||||||
PermisoGestionEmpresa uint = 7
|
PermisoGestionEmpresa uint = 7
|
||||||
PermisoPlataforma uint = 8
|
PermisoPlataforma uint = 8
|
||||||
|
PermisoGestionStock uint = 9
|
||||||
|
PermisoGestionAlmacenes uint = 10
|
||||||
|
PermisoGestionProveedores uint = 11
|
||||||
|
PermisoGestionClientes uint = 12
|
||||||
)
|
)
|
||||||
|
|
||||||
// PermisosDeEmpresa son los permisos que puede recibir una empresa. Los
|
// PermisosDeEmpresa son los permisos que puede recibir una empresa. Los
|
||||||
@@ -23,6 +27,10 @@ func PermisosDeEmpresa() []uint {
|
|||||||
PermisoGestionLogs,
|
PermisoGestionLogs,
|
||||||
PermisoGestionMarcas,
|
PermisoGestionMarcas,
|
||||||
PermisoGestionEmpresa,
|
PermisoGestionEmpresa,
|
||||||
|
PermisoGestionStock,
|
||||||
|
PermisoGestionAlmacenes,
|
||||||
|
PermisoGestionProveedores,
|
||||||
|
PermisoGestionClientes,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+14
-4
@@ -4,24 +4,34 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"gorm.io/datatypes"
|
"gorm.io/datatypes"
|
||||||
|
"gorm.io/gorm"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Stock struct {
|
type Stock struct {
|
||||||
ID uint64 `gorm:"primaryKey" json:"id"`
|
ID uint64 `gorm:"primaryKey" json:"id"`
|
||||||
EmpresaID uint64 `gorm:"not null;default:1;index;uniqueIndex:uq_stock_empresa_repuesto_almacen,priority:1" json:"empresaId"`
|
EmpresaID uint64 `gorm:"not null;default:1;index;uniqueIndex:uq_stock_empresa_repuesto_almacen,priority:1" json:"empresaId"`
|
||||||
|
|
||||||
Cantidad uint `gorm:"not null;default:0" json:"cantidad"`
|
Cantidad float64 `gorm:"type:decimal(15,3);not null;default:0;check:cantidad >= 0" json:"cantidad"`
|
||||||
CantidadReservada uint `gorm:"not null;default:0" json:"cantidadReservada"`
|
CantidadReservada float64 `gorm:"type:decimal(15,3);not null;default:0;check:cantidad_reservada >= 0" json:"cantidadReservada"`
|
||||||
RepuestoID uint64 `gorm:"not null;uniqueIndex:uq_stock_empresa_repuesto_almacen,priority:2" json:"repuestoId"`
|
RepuestoID uint64 `gorm:"not null;uniqueIndex:uq_stock_empresa_repuesto_almacen,priority:2" json:"repuestoId"`
|
||||||
Repuesto Repuesto `gorm:"foreignKey:RepuestoID" json:"repuesto"`
|
Repuesto Repuesto `gorm:"foreignKey:RepuestoID" json:"repuesto"`
|
||||||
AlmacenID uint `gorm:"not null;uniqueIndex:uq_stock_empresa_repuesto_almacen,priority:3" json:"almacenId"`
|
AlmacenID uint `gorm:"not null;uniqueIndex:uq_stock_empresa_repuesto_almacen,priority:3" json:"almacenId"`
|
||||||
Almacen Almacen `gorm:"foreignKey:AlmacenID" json:"almacen,omitempty"`
|
Almacen Almacen `gorm:"foreignKey:AlmacenID" json:"almacen,omitempty"`
|
||||||
Observacion string `gorm:"type:varchar(60)" json:"observacion"`
|
Observacion string `gorm:"type:varchar(60)" json:"observacion"`
|
||||||
|
|
||||||
Movmientos datatypes.JSONSlice[MovimientoStock] `gorm:"type:json" json:"movimientos,omitempty"`
|
// MovimientosLegacy conserva el JSON histórico de la versión anterior.
|
||||||
|
// La fuente de verdad pasa a ser la tabla movimiento_stock.
|
||||||
|
MovimientosLegacy datatypes.JSONSlice[MovimientoStockLegacy] `gorm:"column:movimientos;type:json" json:"movimientosLegacy,omitempty"`
|
||||||
|
Movimientos []MovimientoStock `gorm:"foreignKey:StockID" json:"-"`
|
||||||
|
|
||||||
|
CreatedAt time.Time `json:"createdAt"`
|
||||||
|
UpdatedAt time.Time `json:"updatedAt"`
|
||||||
|
DeletedAt gorm.DeletedAt `gorm:"index" json:"deletedAt,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type MovimientoStock struct {
|
// MovimientoStockLegacy es el formato anterior embebido en stock.movimientos.
|
||||||
|
// Solo se usa para migrar datos existentes.
|
||||||
|
type MovimientoStockLegacy struct {
|
||||||
Fecha time.Time `json:"fecha"`
|
Fecha time.Time `json:"fecha"`
|
||||||
Tipo string `json:"tipo"`
|
Tipo string `json:"tipo"`
|
||||||
Cantidad float64 `json:"cantidad"`
|
Cantidad float64 `json:"cantidad"`
|
||||||
|
|||||||
@@ -17,6 +17,18 @@ type Repositorios struct {
|
|||||||
Marca RepositorioMarcas
|
Marca RepositorioMarcas
|
||||||
Logs RepositorioLogs
|
Logs RepositorioLogs
|
||||||
Empresa RepositorioEmpresa
|
Empresa RepositorioEmpresa
|
||||||
|
Almacen RepositorioAlmacen
|
||||||
|
Proveedor RepositorioProveedor
|
||||||
|
Cliente RepositorioCliente
|
||||||
|
Factura RepositorioFactura
|
||||||
|
|
||||||
|
Stock RepositorioStock
|
||||||
|
MovimientoStock RepositorioMovimientoStock
|
||||||
|
Reserva RepositorioReserva
|
||||||
|
Remito RepositorioRemito
|
||||||
|
Devolucion RepositorioDevolucion
|
||||||
|
DiferenciaRemito RepositorioDiferenciaRemito
|
||||||
|
Contabilidad RepositorioContabilidad
|
||||||
}
|
}
|
||||||
|
|
||||||
var (
|
var (
|
||||||
@@ -62,6 +74,18 @@ func ObtenerRepositorios(contextos ...*gin.Context) *Repositorios {
|
|||||||
return repo
|
return repo
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// NuevoContenedor arma un contenedor de repositorios para una empresa sin
|
||||||
|
// depender de un contexto de Gin. Lo usan servicios y tests.
|
||||||
|
func NuevoContenedor(db *gorm.DB, empresaID uint) *Repositorios {
|
||||||
|
return nuevoContenedor(db, empresaID)
|
||||||
|
}
|
||||||
|
|
||||||
|
// BaseDeDatos expone la conexion inicializada para servicios que necesitan
|
||||||
|
// abrir transacciones.
|
||||||
|
func BaseDeDatos() *gorm.DB {
|
||||||
|
return dbGlobal
|
||||||
|
}
|
||||||
|
|
||||||
func nuevoContenedor(db *gorm.DB, empresaID uint) *Repositorios {
|
func nuevoContenedor(db *gorm.DB, empresaID uint) *Repositorios {
|
||||||
return &Repositorios{
|
return &Repositorios{
|
||||||
Permiso: &repositorioPermiso{db: db},
|
Permiso: &repositorioPermiso{db: db},
|
||||||
@@ -71,6 +95,18 @@ func nuevoContenedor(db *gorm.DB, empresaID uint) *Repositorios {
|
|||||||
Marca: NuevoRepositorioMarcas(db, empresaID),
|
Marca: NuevoRepositorioMarcas(db, empresaID),
|
||||||
Logs: NuevoRepositorioLogs(db, empresaID),
|
Logs: NuevoRepositorioLogs(db, empresaID),
|
||||||
Empresa: &repositorioEmpresa{db: db},
|
Empresa: &repositorioEmpresa{db: db},
|
||||||
|
Almacen: NuevoRepositorioAlmacen(db, empresaID),
|
||||||
|
Proveedor: NuevoRepositorioProveedor(db, empresaID),
|
||||||
|
Cliente: NuevoRepositorioCliente(db, empresaID),
|
||||||
|
Factura: NuevoRepositorioFactura(db, empresaID),
|
||||||
|
|
||||||
|
Stock: NuevoRepositorioStock(db, empresaID),
|
||||||
|
MovimientoStock: NuevoRepositorioMovimientoStock(db, empresaID),
|
||||||
|
Reserva: NuevoRepositorioReserva(db, empresaID),
|
||||||
|
Remito: NuevoRepositorioRemito(db, empresaID),
|
||||||
|
Devolucion: NuevoRepositorioDevolucion(db, empresaID),
|
||||||
|
DiferenciaRemito: NuevoRepositorioDiferenciaRemito(db, empresaID),
|
||||||
|
Contabilidad: NuevoRepositorioContabilidad(db, empresaID),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -78,5 +114,8 @@ func dbConEmpresa(db *gorm.DB, empresaID uint) *gorm.DB {
|
|||||||
if empresaID == 0 {
|
if empresaID == 0 {
|
||||||
return db
|
return db
|
||||||
}
|
}
|
||||||
return db.Where("empresa_id = ?", empresaID)
|
// Session asegura que cada consulta derive de un clon limpio. Sin esto,
|
||||||
|
// un First que devuelve ErrRecordNotFound deja el error pegado al *gorm.DB
|
||||||
|
// y la siguiente consulta del mismo repositorio falla sin ejecutar SQL.
|
||||||
|
return db.Where("empresa_id = ?", empresaID).Session(&gorm.Session{})
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
package repositorios
|
||||||
|
|
||||||
|
import (
|
||||||
|
"repuestera_back/models"
|
||||||
|
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
type RepositorioAlmacen interface {
|
||||||
|
IRepositorio[models.Almacen]
|
||||||
|
Listar() ([]models.Almacen, error)
|
||||||
|
BuscarPorCodigo(codigo string) (*models.Almacen, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
type repositorioAlmacen struct {
|
||||||
|
*RepositorioBase[models.Almacen]
|
||||||
|
db *gorm.DB
|
||||||
|
empresaID uint
|
||||||
|
}
|
||||||
|
|
||||||
|
func NuevoRepositorioAlmacen(db *gorm.DB, empresaID uint) RepositorioAlmacen {
|
||||||
|
return &repositorioAlmacen{
|
||||||
|
RepositorioBase: NewRepositorioBase[models.Almacen](db, empresaID),
|
||||||
|
db: dbConEmpresa(db, empresaID),
|
||||||
|
empresaID: empresaID,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *repositorioAlmacen) Listar() ([]models.Almacen, error) {
|
||||||
|
var almacenes []models.Almacen
|
||||||
|
if err := r.db.Order("codigo ASC").Find(&almacenes).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return almacenes, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *repositorioAlmacen) BuscarPorCodigo(codigo string) (*models.Almacen, error) {
|
||||||
|
var almacen models.Almacen
|
||||||
|
if err := r.db.Where("codigo = ?", codigo).First(&almacen).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &almacen, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
package repositorios
|
||||||
|
|
||||||
|
import (
|
||||||
|
"repuestera_back/models"
|
||||||
|
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
type RepositorioCliente interface {
|
||||||
|
IRepositorio[models.Cliente]
|
||||||
|
Listar(q string) ([]models.Cliente, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
type repositorioCliente struct {
|
||||||
|
*RepositorioBase[models.Cliente]
|
||||||
|
db *gorm.DB
|
||||||
|
empresaID uint
|
||||||
|
}
|
||||||
|
|
||||||
|
func NuevoRepositorioCliente(db *gorm.DB, empresaID uint) RepositorioCliente {
|
||||||
|
return &repositorioCliente{
|
||||||
|
RepositorioBase: NewRepositorioBase[models.Cliente](db, empresaID),
|
||||||
|
db: dbConEmpresa(db, empresaID),
|
||||||
|
empresaID: empresaID,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *repositorioCliente) Listar(q string) ([]models.Cliente, error) {
|
||||||
|
var clientes []models.Cliente
|
||||||
|
query := r.db.Order("nombre ASC")
|
||||||
|
if q != "" {
|
||||||
|
like := "%" + q + "%"
|
||||||
|
query = query.Where("nombre LIKE ? OR cuit LIKE ?", like, like)
|
||||||
|
}
|
||||||
|
if err := query.Find(&clientes).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return clientes, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
package repositorios
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
|
||||||
|
"repuestera_back/models/contabilidad"
|
||||||
|
|
||||||
|
"gorm.io/gorm"
|
||||||
|
"gorm.io/gorm/clause"
|
||||||
|
)
|
||||||
|
|
||||||
|
type RepositorioContabilidad interface {
|
||||||
|
CrearAsientoConMovimientos(tx *gorm.DB, asiento *contabilidad.AsientoContable) error
|
||||||
|
ObtenerCuentaPorCodigo(tx *gorm.DB, codigo string) (*contabilidad.CuentaContable, error)
|
||||||
|
GuardarCuenta(tx *gorm.DB, cuenta *contabilidad.CuentaContable) error
|
||||||
|
ListarCuentas() ([]contabilidad.CuentaContable, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
type repositorioContabilidad struct {
|
||||||
|
db *gorm.DB
|
||||||
|
empresaID uint
|
||||||
|
}
|
||||||
|
|
||||||
|
func NuevoRepositorioContabilidad(db *gorm.DB, empresaID uint) RepositorioContabilidad {
|
||||||
|
return &repositorioContabilidad{
|
||||||
|
db: dbConEmpresa(db, empresaID),
|
||||||
|
empresaID: empresaID,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// CrearAsientoConMovimientos persiste el asiento y cada una de sus lineas.
|
||||||
|
func (r *repositorioContabilidad) CrearAsientoConMovimientos(tx *gorm.DB, asiento *contabilidad.AsientoContable) error {
|
||||||
|
if asiento == nil {
|
||||||
|
return gorm.ErrInvalidValue
|
||||||
|
}
|
||||||
|
if r.empresaID > 0 {
|
||||||
|
asiento.EmpresaID = r.empresaID
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := tx.Omit(clause.Associations).Create(asiento).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
for i := range asiento.Movimientos {
|
||||||
|
asiento.Movimientos[i].AsientoID = asiento.ID
|
||||||
|
if r.empresaID > 0 {
|
||||||
|
asiento.Movimientos[i].EmpresaID = r.empresaID
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(asiento.Movimientos) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return tx.Create(&asiento.Movimientos).Error
|
||||||
|
}
|
||||||
|
|
||||||
|
// ObtenerCuentaPorCodigo busca la cuenta por su nombre/codigo contable.
|
||||||
|
func (r *repositorioContabilidad) ObtenerCuentaPorCodigo(tx *gorm.DB, codigo string) (*contabilidad.CuentaContable, error) {
|
||||||
|
var cuenta contabilidad.CuentaContable
|
||||||
|
query := tx.Where("nombre = ?", codigo)
|
||||||
|
if r.empresaID > 0 {
|
||||||
|
query = query.Where("empresa_id = ?", r.empresaID)
|
||||||
|
}
|
||||||
|
if err := query.First(&cuenta).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &cuenta, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// GuardarCuenta crea la cuenta si no existe para la empresa.
|
||||||
|
func (r *repositorioContabilidad) GuardarCuenta(tx *gorm.DB, cuenta *contabilidad.CuentaContable) error {
|
||||||
|
if cuenta == nil {
|
||||||
|
return gorm.ErrInvalidValue
|
||||||
|
}
|
||||||
|
if r.empresaID > 0 {
|
||||||
|
cuenta.EmpresaID = r.empresaID
|
||||||
|
}
|
||||||
|
|
||||||
|
existente, err := r.ObtenerCuentaPorCodigo(tx, cuenta.Nombre)
|
||||||
|
if err == nil {
|
||||||
|
cuenta.ID = existente.ID
|
||||||
|
query := tx.Model(&contabilidad.CuentaContable{}).Where("id = ?", existente.ID)
|
||||||
|
if r.empresaID > 0 {
|
||||||
|
query = query.Where("empresa_id = ?", r.empresaID)
|
||||||
|
}
|
||||||
|
return query.Update("tipo", cuenta.Tipo).Error
|
||||||
|
}
|
||||||
|
if !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return tx.Create(cuenta).Error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *repositorioContabilidad) ListarCuentas() ([]contabilidad.CuentaContable, error) {
|
||||||
|
var cuentas []contabilidad.CuentaContable
|
||||||
|
if err := r.db.Order("nombre ASC").Find(&cuentas).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return cuentas, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
package repositorios
|
||||||
|
|
||||||
|
import (
|
||||||
|
"repuestera_back/models"
|
||||||
|
|
||||||
|
"gorm.io/gorm"
|
||||||
|
"gorm.io/gorm/clause"
|
||||||
|
)
|
||||||
|
|
||||||
|
type RepositorioDevolucion interface {
|
||||||
|
IRepositorio[models.Devolucion]
|
||||||
|
CrearConDetalles(tx *gorm.DB, devolucion *models.Devolucion) error
|
||||||
|
ListarPorFactura(facturaID uint) ([]models.Devolucion, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
type repositorioDevolucion struct {
|
||||||
|
*RepositorioBase[models.Devolucion]
|
||||||
|
db *gorm.DB
|
||||||
|
empresaID uint
|
||||||
|
}
|
||||||
|
|
||||||
|
func NuevoRepositorioDevolucion(db *gorm.DB, empresaID uint) RepositorioDevolucion {
|
||||||
|
return &repositorioDevolucion{
|
||||||
|
RepositorioBase: NewRepositorioBase[models.Devolucion](db, empresaID),
|
||||||
|
db: dbConEmpresa(db, empresaID),
|
||||||
|
empresaID: empresaID,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// CrearConDetalles persiste la devolucion con sus renglones en la columna JSON.
|
||||||
|
func (r *repositorioDevolucion) CrearConDetalles(tx *gorm.DB, devolucion *models.Devolucion) error {
|
||||||
|
if devolucion == nil {
|
||||||
|
return gorm.ErrInvalidValue
|
||||||
|
}
|
||||||
|
if r.empresaID > 0 {
|
||||||
|
devolucion.EmpresaID = r.empresaID
|
||||||
|
}
|
||||||
|
// FacturaOrigen es una relacion; los detalles ya viajan como JSON.
|
||||||
|
return tx.Omit(clause.Associations).Create(devolucion).Error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *repositorioDevolucion) ListarPorFactura(facturaID uint) ([]models.Devolucion, error) {
|
||||||
|
var devoluciones []models.Devolucion
|
||||||
|
if err := r.db.
|
||||||
|
Where("`facturaOrigenID` = ?", facturaID).
|
||||||
|
Order("created_at DESC").
|
||||||
|
Find(&devoluciones).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return devoluciones, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
package repositorios
|
||||||
|
|
||||||
|
import (
|
||||||
|
"repuestera_back/models"
|
||||||
|
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
type RepositorioDiferenciaRemito interface {
|
||||||
|
IRepositorio[models.DiferenciaRemito]
|
||||||
|
Registrar(tx *gorm.DB, diferencia *models.DiferenciaRemito) error
|
||||||
|
ListarPorRemito(remitoID uint) ([]models.DiferenciaRemito, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
type repositorioDiferenciaRemito struct {
|
||||||
|
*RepositorioBase[models.DiferenciaRemito]
|
||||||
|
db *gorm.DB
|
||||||
|
empresaID uint
|
||||||
|
}
|
||||||
|
|
||||||
|
func NuevoRepositorioDiferenciaRemito(db *gorm.DB, empresaID uint) RepositorioDiferenciaRemito {
|
||||||
|
return &repositorioDiferenciaRemito{
|
||||||
|
RepositorioBase: NewRepositorioBase[models.DiferenciaRemito](db, empresaID),
|
||||||
|
db: dbConEmpresa(db, empresaID),
|
||||||
|
empresaID: empresaID,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *repositorioDiferenciaRemito) Registrar(tx *gorm.DB, diferencia *models.DiferenciaRemito) error {
|
||||||
|
if diferencia == nil {
|
||||||
|
return gorm.ErrInvalidValue
|
||||||
|
}
|
||||||
|
if r.empresaID > 0 {
|
||||||
|
diferencia.EmpresaID = uint64(r.empresaID)
|
||||||
|
}
|
||||||
|
return tx.Create(diferencia).Error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *repositorioDiferenciaRemito) ListarPorRemito(remitoID uint) ([]models.DiferenciaRemito, error) {
|
||||||
|
var diferencias []models.DiferenciaRemito
|
||||||
|
if err := r.db.
|
||||||
|
Preload("Repuesto").
|
||||||
|
Where("remito_id = ?", remitoID).
|
||||||
|
Order("id ASC").
|
||||||
|
Find(&diferencias).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return diferencias, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
package repositorios
|
||||||
|
|
||||||
|
import (
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"repuestera_back/models"
|
||||||
|
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
type FiltrosFactura struct {
|
||||||
|
Numero string
|
||||||
|
ClienteID uint
|
||||||
|
Cliente string
|
||||||
|
Desde *time.Time
|
||||||
|
Hasta *time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
type RepositorioFactura interface {
|
||||||
|
IRepositorio[models.Factura]
|
||||||
|
Listar(filtros FiltrosFactura) ([]models.Factura, error)
|
||||||
|
ObtenerConRelaciones(id uint) (*models.Factura, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
type repositorioFactura struct {
|
||||||
|
*RepositorioBase[models.Factura]
|
||||||
|
db *gorm.DB
|
||||||
|
empresaID uint
|
||||||
|
}
|
||||||
|
|
||||||
|
func NuevoRepositorioFactura(db *gorm.DB, empresaID uint) RepositorioFactura {
|
||||||
|
return &repositorioFactura{
|
||||||
|
RepositorioBase: NewRepositorioBase[models.Factura](db, empresaID),
|
||||||
|
db: dbConEmpresa(db, empresaID),
|
||||||
|
empresaID: empresaID,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *repositorioFactura) Listar(filtros FiltrosFactura) ([]models.Factura, error) {
|
||||||
|
var facturas []models.Factura
|
||||||
|
|
||||||
|
query := r.db.Model(&models.Factura{}).Preload("Cliente")
|
||||||
|
if filtros.Numero != "" {
|
||||||
|
query = query.Where("numero LIKE ?", "%"+filtros.Numero+"%")
|
||||||
|
}
|
||||||
|
if filtros.ClienteID > 0 {
|
||||||
|
query = query.Where("`ClienteID` = ?", filtros.ClienteID)
|
||||||
|
}
|
||||||
|
if filtros.Cliente != "" {
|
||||||
|
query = query.Joins("JOIN clientes ON clientes.id = factura.`ClienteID`").
|
||||||
|
Where("clientes.nombre LIKE ?", "%"+filtros.Cliente+"%")
|
||||||
|
}
|
||||||
|
if filtros.Desde != nil {
|
||||||
|
query = query.Where("factura.created_at >= ?", *filtros.Desde)
|
||||||
|
}
|
||||||
|
if filtros.Hasta != nil {
|
||||||
|
query = query.Where("factura.created_at < ?", filtros.Hasta.AddDate(0, 0, 1))
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := query.Order("factura.created_at DESC").Find(&facturas).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return facturas, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *repositorioFactura) ObtenerConRelaciones(id uint) (*models.Factura, error) {
|
||||||
|
var factura models.Factura
|
||||||
|
if err := r.db.Preload("Cliente").First(&factura, id).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &factura, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,112 @@
|
|||||||
|
package repositorios
|
||||||
|
|
||||||
|
import (
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"repuestera_back/models"
|
||||||
|
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
// FiltrosMovimiento acota la consulta del historial de movimientos.
|
||||||
|
type FiltrosMovimiento struct {
|
||||||
|
StockID uint64
|
||||||
|
RepuestoID uint64
|
||||||
|
AlmacenID uint
|
||||||
|
Tipo models.TipoMovimientoStock
|
||||||
|
Desde *time.Time
|
||||||
|
Hasta *time.Time
|
||||||
|
Pagina int
|
||||||
|
PorPagina int
|
||||||
|
}
|
||||||
|
|
||||||
|
// ResumenMovimiento agrupa cantidades por tipo para reportes.
|
||||||
|
type ResumenMovimiento struct {
|
||||||
|
Tipo models.TipoMovimientoStock
|
||||||
|
Cantidad float64
|
||||||
|
}
|
||||||
|
|
||||||
|
type RepositorioMovimientoStock interface {
|
||||||
|
IRepositorio[models.MovimientoStock]
|
||||||
|
Registrar(tx *gorm.DB, movimiento *models.MovimientoStock) error
|
||||||
|
ListarPorRango(filtros FiltrosMovimiento) ([]models.MovimientoStock, error)
|
||||||
|
Sumarizar(filtros FiltrosMovimiento) ([]ResumenMovimiento, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
type repositorioMovimientoStock struct {
|
||||||
|
*RepositorioBase[models.MovimientoStock]
|
||||||
|
db *gorm.DB
|
||||||
|
empresaID uint
|
||||||
|
}
|
||||||
|
|
||||||
|
func NuevoRepositorioMovimientoStock(db *gorm.DB, empresaID uint) RepositorioMovimientoStock {
|
||||||
|
return &repositorioMovimientoStock{
|
||||||
|
RepositorioBase: NewRepositorioBase[models.MovimientoStock](db, empresaID),
|
||||||
|
db: dbConEmpresa(db, empresaID),
|
||||||
|
empresaID: empresaID,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *repositorioMovimientoStock) Registrar(tx *gorm.DB, movimiento *models.MovimientoStock) error {
|
||||||
|
if movimiento == nil {
|
||||||
|
return gorm.ErrInvalidValue
|
||||||
|
}
|
||||||
|
if r.empresaID > 0 {
|
||||||
|
movimiento.EmpresaID = uint64(r.empresaID)
|
||||||
|
}
|
||||||
|
if movimiento.Fecha.IsZero() {
|
||||||
|
movimiento.Fecha = time.Now()
|
||||||
|
}
|
||||||
|
return tx.Create(movimiento).Error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *repositorioMovimientoStock) ListarPorRango(filtros FiltrosMovimiento) ([]models.MovimientoStock, error) {
|
||||||
|
query := r.aplicarFiltros(r.db.Model(&models.MovimientoStock{}).Preload("Repuesto"), filtros)
|
||||||
|
pagina, porPagina := normalizarPagina(filtros.Pagina, filtros.PorPagina)
|
||||||
|
|
||||||
|
var movimientos []models.MovimientoStock
|
||||||
|
if err := query.
|
||||||
|
Order("fecha DESC, id DESC").
|
||||||
|
Offset((pagina - 1) * porPagina).
|
||||||
|
Limit(porPagina).
|
||||||
|
Find(&movimientos).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return movimientos, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *repositorioMovimientoStock) Sumarizar(filtros FiltrosMovimiento) ([]ResumenMovimiento, error) {
|
||||||
|
query := r.aplicarFiltros(r.db.Model(&models.MovimientoStock{}), filtros)
|
||||||
|
|
||||||
|
var resumen []ResumenMovimiento
|
||||||
|
if err := query.
|
||||||
|
Select("tipo, SUM(cantidad) AS cantidad").
|
||||||
|
Group("tipo").
|
||||||
|
Order("tipo ASC").
|
||||||
|
Scan(&resumen).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return resumen, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *repositorioMovimientoStock) aplicarFiltros(query *gorm.DB, filtros FiltrosMovimiento) *gorm.DB {
|
||||||
|
if filtros.StockID > 0 {
|
||||||
|
query = query.Where("stock_id = ?", filtros.StockID)
|
||||||
|
}
|
||||||
|
if filtros.RepuestoID > 0 {
|
||||||
|
query = query.Where("repuesto_id = ?", filtros.RepuestoID)
|
||||||
|
}
|
||||||
|
if filtros.AlmacenID > 0 {
|
||||||
|
query = query.Where("almacen_id = ?", filtros.AlmacenID)
|
||||||
|
}
|
||||||
|
if filtros.Tipo != "" {
|
||||||
|
query = query.Where("tipo = ?", filtros.Tipo)
|
||||||
|
}
|
||||||
|
if filtros.Desde != nil {
|
||||||
|
query = query.Where("fecha >= ?", *filtros.Desde)
|
||||||
|
}
|
||||||
|
if filtros.Hasta != nil {
|
||||||
|
query = query.Where("fecha < ?", filtros.Hasta.AddDate(0, 0, 1))
|
||||||
|
}
|
||||||
|
return query
|
||||||
|
}
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
package repositorios
|
||||||
|
|
||||||
|
import (
|
||||||
|
"repuestera_back/models"
|
||||||
|
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
type RepositorioProveedor interface {
|
||||||
|
IRepositorio[models.Proveedor]
|
||||||
|
Listar(q string) ([]models.Proveedor, error)
|
||||||
|
BuscarPorNombre(nombre string) (*models.Proveedor, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
type repositorioProveedor struct {
|
||||||
|
*RepositorioBase[models.Proveedor]
|
||||||
|
db *gorm.DB
|
||||||
|
empresaID uint
|
||||||
|
}
|
||||||
|
|
||||||
|
func NuevoRepositorioProveedor(db *gorm.DB, empresaID uint) RepositorioProveedor {
|
||||||
|
return &repositorioProveedor{
|
||||||
|
RepositorioBase: NewRepositorioBase[models.Proveedor](db, empresaID),
|
||||||
|
db: dbConEmpresa(db, empresaID),
|
||||||
|
empresaID: empresaID,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *repositorioProveedor) Listar(q string) ([]models.Proveedor, error) {
|
||||||
|
var proveedores []models.Proveedor
|
||||||
|
query := r.db.Order("nombre ASC")
|
||||||
|
if q != "" {
|
||||||
|
like := "%" + q + "%"
|
||||||
|
query = query.Where("nombre LIKE ? OR cuit LIKE ?", like, like)
|
||||||
|
}
|
||||||
|
if err := query.Find(&proveedores).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return proveedores, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *repositorioProveedor) BuscarPorNombre(nombre string) (*models.Proveedor, error) {
|
||||||
|
var proveedor models.Proveedor
|
||||||
|
if err := r.db.Where("nombre = ?", nombre).First(&proveedor).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &proveedor, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
package repositorios
|
||||||
|
|
||||||
|
import (
|
||||||
|
"repuestera_back/models"
|
||||||
|
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
type RepositorioRemito interface {
|
||||||
|
IRepositorio[models.Remito]
|
||||||
|
CrearConDetalles(tx *gorm.DB, remito *models.Remito) error
|
||||||
|
ObtenerConDetalles(id uint) (*models.Remito, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
type repositorioRemito struct {
|
||||||
|
*RepositorioBase[models.Remito]
|
||||||
|
db *gorm.DB
|
||||||
|
empresaID uint
|
||||||
|
}
|
||||||
|
|
||||||
|
func NuevoRepositorioRemito(db *gorm.DB, empresaID uint) RepositorioRemito {
|
||||||
|
return &repositorioRemito{
|
||||||
|
RepositorioBase: NewRepositorioBase[models.Remito](db, empresaID),
|
||||||
|
db: dbConEmpresa(db, empresaID),
|
||||||
|
empresaID: empresaID,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// CrearConDetalles persiste el remito junto con su JSON de detalles.
|
||||||
|
func (r *repositorioRemito) CrearConDetalles(tx *gorm.DB, remito *models.Remito) error {
|
||||||
|
if remito == nil {
|
||||||
|
return gorm.ErrInvalidValue
|
||||||
|
}
|
||||||
|
if r.empresaID > 0 {
|
||||||
|
remito.EmpresaID = r.empresaID
|
||||||
|
}
|
||||||
|
return tx.Create(remito).Error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *repositorioRemito) ObtenerConDetalles(id uint) (*models.Remito, error) {
|
||||||
|
var remito models.Remito
|
||||||
|
if err := r.db.
|
||||||
|
Preload("Proveedor").
|
||||||
|
Preload("AlmacenOrigen").
|
||||||
|
Preload("AlmacenDestino").
|
||||||
|
First(&remito, id).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &remito, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,106 @@
|
|||||||
|
package repositorios
|
||||||
|
|
||||||
|
import (
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"repuestera_back/models"
|
||||||
|
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
// FiltrosReserva acota el listado de reservas.
|
||||||
|
type FiltrosReserva struct {
|
||||||
|
RepuestoID uint
|
||||||
|
AlmacenID uint
|
||||||
|
ClienteID uint
|
||||||
|
VencenAntesDe *time.Time
|
||||||
|
IncluirVencidas bool
|
||||||
|
Pagina int
|
||||||
|
PorPagina int
|
||||||
|
}
|
||||||
|
|
||||||
|
type RepositorioReserva interface {
|
||||||
|
IRepositorio[models.Reserva]
|
||||||
|
ListarActivas(filtros FiltrosReserva) ([]models.Reserva, error)
|
||||||
|
Liberar(tx *gorm.DB, id uint) (bool, error)
|
||||||
|
MarcarVencidas(ahora time.Time) (int64, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
type repositorioReserva struct {
|
||||||
|
*RepositorioBase[models.Reserva]
|
||||||
|
db *gorm.DB
|
||||||
|
empresaID uint
|
||||||
|
}
|
||||||
|
|
||||||
|
func NuevoRepositorioReserva(db *gorm.DB, empresaID uint) RepositorioReserva {
|
||||||
|
return &repositorioReserva{
|
||||||
|
RepositorioBase: NewRepositorioBase[models.Reserva](db, empresaID),
|
||||||
|
db: dbConEmpresa(db, empresaID),
|
||||||
|
empresaID: empresaID,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *repositorioReserva) ListarActivas(filtros FiltrosReserva) ([]models.Reserva, error) {
|
||||||
|
query := r.db.Model(&models.Reserva{}).
|
||||||
|
Preload("Repuesto").
|
||||||
|
Preload("Almacen").
|
||||||
|
Preload("Cliente")
|
||||||
|
|
||||||
|
estados := []models.EstadoReserva{models.ReservaActiva}
|
||||||
|
if filtros.IncluirVencidas {
|
||||||
|
estados = append(estados, models.ReservaVencida)
|
||||||
|
}
|
||||||
|
query = query.Where("estado IN ?", estados)
|
||||||
|
|
||||||
|
if filtros.RepuestoID > 0 {
|
||||||
|
query = query.Where("repuesto_id = ?", filtros.RepuestoID)
|
||||||
|
}
|
||||||
|
if filtros.AlmacenID > 0 {
|
||||||
|
query = query.Where("almacen_id = ?", filtros.AlmacenID)
|
||||||
|
}
|
||||||
|
if filtros.ClienteID > 0 {
|
||||||
|
query = query.Where("cliente_id = ?", filtros.ClienteID)
|
||||||
|
}
|
||||||
|
if filtros.VencenAntesDe != nil {
|
||||||
|
query = query.Where("fecha_vencimiento <= ?", *filtros.VencenAntesDe)
|
||||||
|
}
|
||||||
|
|
||||||
|
pagina, porPagina := normalizarPagina(filtros.Pagina, filtros.PorPagina)
|
||||||
|
var reservas []models.Reserva
|
||||||
|
if err := query.
|
||||||
|
Order("fecha_vencimiento ASC, id ASC").
|
||||||
|
Offset((pagina - 1) * porPagina).
|
||||||
|
Limit(porPagina).
|
||||||
|
Find(&reservas).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return reservas, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Liberar marca la reserva como liberada si seguia activa.
|
||||||
|
// Devuelve false cuando la reserva ya no estaba activa.
|
||||||
|
func (r *repositorioReserva) Liberar(tx *gorm.DB, id uint) (bool, error) {
|
||||||
|
query := tx.Model(&models.Reserva{}).
|
||||||
|
Where("id = ? AND estado = ?", id, models.ReservaActiva)
|
||||||
|
if r.empresaID > 0 {
|
||||||
|
query = query.Where("empresa_id = ?", r.empresaID)
|
||||||
|
}
|
||||||
|
|
||||||
|
resultado := query.Update("estado", models.ReservaLiberada)
|
||||||
|
if resultado.Error != nil {
|
||||||
|
return false, resultado.Error
|
||||||
|
}
|
||||||
|
return resultado.RowsAffected > 0, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// MarcarVencidas pasa a vencida todas las reservas activas cuya fecha ya paso.
|
||||||
|
func (r *repositorioReserva) MarcarVencidas(ahora time.Time) (int64, error) {
|
||||||
|
query := r.db.Model(&models.Reserva{}).
|
||||||
|
Where("estado = ? AND fecha_vencimiento < ?", models.ReservaActiva, ahora)
|
||||||
|
if r.empresaID > 0 {
|
||||||
|
query = query.Where("empresa_id = ?", r.empresaID)
|
||||||
|
}
|
||||||
|
|
||||||
|
resultado := query.Update("estado", models.ReservaVencida)
|
||||||
|
return resultado.RowsAffected, resultado.Error
|
||||||
|
}
|
||||||
@@ -0,0 +1,177 @@
|
|||||||
|
package repositorios
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"repuestera_back/models"
|
||||||
|
|
||||||
|
"gorm.io/gorm"
|
||||||
|
"gorm.io/gorm/clause"
|
||||||
|
)
|
||||||
|
|
||||||
|
// FiltrosStock acota el listado de items de stock.
|
||||||
|
type FiltrosStock struct {
|
||||||
|
RepuestoID uint64
|
||||||
|
AlmacenID uint
|
||||||
|
Texto string
|
||||||
|
SoloBajoMinimo bool
|
||||||
|
Pagina int
|
||||||
|
PorPagina int
|
||||||
|
}
|
||||||
|
|
||||||
|
type RepositorioStock interface {
|
||||||
|
IRepositorio[models.Stock]
|
||||||
|
Listar(filtros FiltrosStock) ([]models.Stock, error)
|
||||||
|
ObtenerPorRepuestoAlmacen(repuestoID uint64, almacenID uint) (*models.Stock, error)
|
||||||
|
CrearSiNoExiste(stock *models.Stock) error
|
||||||
|
BloquearPorID(tx *gorm.DB, id uint64) (*models.Stock, error)
|
||||||
|
BloquearPorRepuestoAlmacen(tx *gorm.DB, repuestoID uint64, almacenID uint) (*models.Stock, error)
|
||||||
|
ActualizarCantidades(tx *gorm.DB, stock *models.Stock) error
|
||||||
|
ActualizarObservacion(tx *gorm.DB, id uint64, texto string) error
|
||||||
|
}
|
||||||
|
|
||||||
|
type repositorioStock struct {
|
||||||
|
*RepositorioBase[models.Stock]
|
||||||
|
db *gorm.DB
|
||||||
|
empresaID uint
|
||||||
|
}
|
||||||
|
|
||||||
|
func NuevoRepositorioStock(db *gorm.DB, empresaID uint) RepositorioStock {
|
||||||
|
return &repositorioStock{
|
||||||
|
RepositorioBase: NewRepositorioBase[models.Stock](db, empresaID),
|
||||||
|
db: dbConEmpresa(db, empresaID),
|
||||||
|
empresaID: empresaID,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *repositorioStock) Listar(filtros FiltrosStock) ([]models.Stock, error) {
|
||||||
|
query := r.db.Model(&models.Stock{}).
|
||||||
|
Preload("Repuesto").
|
||||||
|
Preload("Almacen")
|
||||||
|
|
||||||
|
if filtros.RepuestoID > 0 {
|
||||||
|
query = query.Where("stock.repuesto_id = ?", filtros.RepuestoID)
|
||||||
|
}
|
||||||
|
if filtros.AlmacenID > 0 {
|
||||||
|
query = query.Where("stock.almacen_id = ?", filtros.AlmacenID)
|
||||||
|
}
|
||||||
|
// Se usan subconsultas en lugar de JOIN para no volver ambiguo el filtro
|
||||||
|
// empresa_id que ya trae el repositorio.
|
||||||
|
if filtros.Texto != "" {
|
||||||
|
like := "%" + strings.TrimSpace(filtros.Texto) + "%"
|
||||||
|
query = query.Where(
|
||||||
|
"stock.repuesto_id IN (SELECT id FROM repuesto WHERE nombre LIKE ? OR descripcion LIKE ?)",
|
||||||
|
like, like,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
if filtros.SoloBajoMinimo {
|
||||||
|
query = query.Where(
|
||||||
|
"stock.cantidad < (SELECT stock_minimo FROM repuesto WHERE repuesto.id = stock.repuesto_id)",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
pagina, porPagina := normalizarPagina(filtros.Pagina, filtros.PorPagina)
|
||||||
|
var stocks []models.Stock
|
||||||
|
if err := query.
|
||||||
|
Order("stock.id ASC").
|
||||||
|
Offset((pagina - 1) * porPagina).
|
||||||
|
Limit(porPagina).
|
||||||
|
Find(&stocks).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return stocks, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *repositorioStock) ObtenerPorRepuestoAlmacen(repuestoID uint64, almacenID uint) (*models.Stock, error) {
|
||||||
|
var stock models.Stock
|
||||||
|
if err := r.db.
|
||||||
|
Preload("Repuesto").
|
||||||
|
Preload("Almacen").
|
||||||
|
Where("repuesto_id = ? AND almacen_id = ?", repuestoID, almacenID).
|
||||||
|
First(&stock).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &stock, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *repositorioStock) CrearSiNoExiste(stock *models.Stock) error {
|
||||||
|
if stock == nil {
|
||||||
|
return errors.New("stock nil")
|
||||||
|
}
|
||||||
|
|
||||||
|
existente, err := r.ObtenerPorRepuestoAlmacen(stock.RepuestoID, stock.AlmacenID)
|
||||||
|
if err == nil {
|
||||||
|
*stock = *existente
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if r.empresaID > 0 {
|
||||||
|
stock.EmpresaID = uint64(r.empresaID)
|
||||||
|
}
|
||||||
|
return r.db.Create(stock).Error
|
||||||
|
}
|
||||||
|
|
||||||
|
// BloquearPorID toma la fila con FOR UPDATE dentro de una transaccion.
|
||||||
|
func (r *repositorioStock) BloquearPorID(tx *gorm.DB, id uint64) (*models.Stock, error) {
|
||||||
|
var stock models.Stock
|
||||||
|
query := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Where("id = ?", id)
|
||||||
|
if r.empresaID > 0 {
|
||||||
|
query = query.Where("empresa_id = ?", r.empresaID)
|
||||||
|
}
|
||||||
|
if err := query.First(&stock).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &stock, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *repositorioStock) ActualizarCantidades(tx *gorm.DB, stock *models.Stock) error {
|
||||||
|
query := tx.Model(&models.Stock{}).Where("id = ?", stock.ID)
|
||||||
|
if r.empresaID > 0 {
|
||||||
|
query = query.Where("empresa_id = ?", r.empresaID)
|
||||||
|
}
|
||||||
|
return query.Updates(map[string]any{
|
||||||
|
"cantidad": stock.Cantidad,
|
||||||
|
"cantidad_reservada": stock.CantidadReservada,
|
||||||
|
}).Error
|
||||||
|
}
|
||||||
|
|
||||||
|
// BloquearPorRepuestoAlmacen busca la fila de stock con FOR UPDATE para una
|
||||||
|
// combinacion repuesto/almacen de la empresa activa.
|
||||||
|
func (r *repositorioStock) BloquearPorRepuestoAlmacen(tx *gorm.DB, repuestoID uint64, almacenID uint) (*models.Stock, error) {
|
||||||
|
var stock models.Stock
|
||||||
|
query := tx.Clauses(clause.Locking{Strength: "UPDATE"}).
|
||||||
|
Where("repuesto_id = ? AND almacen_id = ?", repuestoID, almacenID)
|
||||||
|
if r.empresaID > 0 {
|
||||||
|
query = query.Where("empresa_id = ?", r.empresaID)
|
||||||
|
}
|
||||||
|
if err := query.First(&stock).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &stock, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ActualizarObservacion guarda el ultimo comentario visible del item.
|
||||||
|
func (r *repositorioStock) ActualizarObservacion(tx *gorm.DB, id uint64, texto string) error {
|
||||||
|
query := tx.Model(&models.Stock{}).Where("id = ?", id)
|
||||||
|
if r.empresaID > 0 {
|
||||||
|
query = query.Where("empresa_id = ?", r.empresaID)
|
||||||
|
}
|
||||||
|
return query.Update("observacion", texto).Error
|
||||||
|
}
|
||||||
|
|
||||||
|
func normalizarPagina(pagina, porPagina int) (int, int) {
|
||||||
|
if pagina < 1 {
|
||||||
|
pagina = 1
|
||||||
|
}
|
||||||
|
if porPagina < 1 {
|
||||||
|
porPagina = 50
|
||||||
|
}
|
||||||
|
if porPagina > 200 {
|
||||||
|
porPagina = 200
|
||||||
|
}
|
||||||
|
return pagina, porPagina
|
||||||
|
}
|
||||||
@@ -36,11 +36,13 @@ func main() {
|
|||||||
&models.Marca{},
|
&models.Marca{},
|
||||||
&models.Repuesto{},
|
&models.Repuesto{},
|
||||||
&models.Stock{},
|
&models.Stock{},
|
||||||
|
&models.MovimientoStock{},
|
||||||
&models.Factura{},
|
&models.Factura{},
|
||||||
&models.OrdenCompra{},
|
&models.OrdenCompra{},
|
||||||
&models.Devolucion{},
|
&models.Devolucion{},
|
||||||
&models.Reserva{},
|
&models.Reserva{},
|
||||||
&models.Remito{},
|
&models.Remito{},
|
||||||
|
&models.DiferenciaRemito{},
|
||||||
&models.NotaCredito{},
|
&models.NotaCredito{},
|
||||||
&models.NotaDebito{},
|
&models.NotaDebito{},
|
||||||
&models.Descuento{},
|
&models.Descuento{},
|
||||||
@@ -60,6 +62,11 @@ func main() {
|
|||||||
if err := config.MigrarMultitenant(); err != nil {
|
if err := config.MigrarMultitenant(); err != nil {
|
||||||
log.Fatalf("failed to migrate multitenant data: %v", err)
|
log.Fatalf("failed to migrate multitenant data: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if err := config.MigrarStock(); err != nil {
|
||||||
|
log.Fatalf("failed to migrate stock data: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
config.InitPermisos()
|
config.InitPermisos()
|
||||||
|
|
||||||
fmt.Println("Database connected and migrated successfully")
|
fmt.Println("Database connected and migrated successfully")
|
||||||
@@ -77,6 +84,10 @@ func main() {
|
|||||||
routes.RepuestoRoute(r)
|
routes.RepuestoRoute(r)
|
||||||
routes.LogsRoute(r)
|
routes.LogsRoute(r)
|
||||||
routes.MarcaRoute(r)
|
routes.MarcaRoute(r)
|
||||||
|
routes.AlmacenRoute(r)
|
||||||
|
routes.ProveedorRoute(r)
|
||||||
|
routes.ClienteRoute(r)
|
||||||
|
routes.FacturaRoute(r)
|
||||||
|
|
||||||
r.Run(":8080")
|
r.Run(":8080")
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
package routes
|
||||||
|
|
||||||
|
import (
|
||||||
|
almacen "repuestera_back/controllers/almacenes"
|
||||||
|
"repuestera_back/middleware"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
func AlmacenRoute(r *gin.Engine) {
|
||||||
|
grupo := r.Group("/almacenes")
|
||||||
|
grupo.Use(middleware.AuthMiddleware(10))
|
||||||
|
{
|
||||||
|
grupo.GET("/", almacen.ObtenerAlmacenes)
|
||||||
|
grupo.POST("/", almacen.CrearAlmacen)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
package routes
|
||||||
|
|
||||||
|
import (
|
||||||
|
cliente "repuestera_back/controllers/clientes"
|
||||||
|
"repuestera_back/middleware"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
func ClienteRoute(r *gin.Engine) {
|
||||||
|
grupo := r.Group("/clientes")
|
||||||
|
grupo.Use(middleware.AuthMiddleware(12))
|
||||||
|
{
|
||||||
|
grupo.GET("/", cliente.ObtenerClientes)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
package routes
|
||||||
|
|
||||||
|
import (
|
||||||
|
factura "repuestera_back/controllers/facturas"
|
||||||
|
"repuestera_back/middleware"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
func FacturaRoute(r *gin.Engine) {
|
||||||
|
grupo := r.Group("/facturas")
|
||||||
|
grupo.Use(middleware.AuthMiddleware(9))
|
||||||
|
{
|
||||||
|
grupo.GET("/", factura.ObtenerFacturas)
|
||||||
|
grupo.GET("/:id", factura.ObtenerFactura)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
package routes
|
||||||
|
|
||||||
|
import (
|
||||||
|
proveedor "repuestera_back/controllers/proveedores"
|
||||||
|
"repuestera_back/middleware"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
func ProveedorRoute(r *gin.Engine) {
|
||||||
|
grupo := r.Group("/proveedores")
|
||||||
|
grupo.Use(middleware.AuthMiddleware(11))
|
||||||
|
{
|
||||||
|
grupo.GET("/", proveedor.ObtenerProveedores)
|
||||||
|
grupo.POST("/", proveedor.CrearProveedor)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,996 @@
|
|||||||
|
// Package stock centraliza las reglas de negocio del módulo Stock.
|
||||||
|
// Todos los casos de uso (traslado, ajuste, ingreso, reservas, devoluciones y
|
||||||
|
// comentarios) pasan por este servicio para que las validaciones sean únicas.
|
||||||
|
package stock
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
applog "log"
|
||||||
|
"math"
|
||||||
|
"sort"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
"unicode/utf8"
|
||||||
|
|
||||||
|
dto_builders "repuestera_back/dto/Builders"
|
||||||
|
"repuestera_back/models"
|
||||||
|
"repuestera_back/models/contabilidad"
|
||||||
|
models_logs "repuestera_back/models/logs"
|
||||||
|
"repuestera_back/repositorios"
|
||||||
|
"repuestera_back/utils"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Errores de negocio del módulo. Los controllers los traducen a códigos HTTP.
|
||||||
|
var (
|
||||||
|
ErrCantidadInvalida = errors.New("la cantidad debe ser mayor a cero")
|
||||||
|
ErrStockInsuficiente = errors.New("stock insuficiente")
|
||||||
|
ErrMismoAlmacen = errors.New("el almacén de origen y destino deben ser distintos")
|
||||||
|
ErrStockNoEncontrado = errors.New("stock no encontrado")
|
||||||
|
ErrReservaInexistente = errors.New("reserva inexistente")
|
||||||
|
ErrReservaYaLiberada = errors.New("la reserva ya no está activa")
|
||||||
|
ErrComentarioLargo = errors.New("el comentario no puede superar los 60 caracteres")
|
||||||
|
ErrComentarioVacio = errors.New("el comentario no puede estar vacío")
|
||||||
|
ErrFacturaAnulada = errors.New("la factura está anulada")
|
||||||
|
ErrDevolucionExcedeVendido = errors.New("la devolución excede lo vendido")
|
||||||
|
ErrMotivoRequerido = errors.New("el motivo es obligatorio")
|
||||||
|
ErrItemDuplicado = errors.New("el repuesto está repetido en la operación")
|
||||||
|
ErrItemNoEncontrado = errors.New("el repuesto no pertenece a la factura")
|
||||||
|
ErrAlmacenInvalido = errors.New("el almacén no existe o no pertenece a la empresa")
|
||||||
|
ErrProveedorNoEncontrado = errors.New("el proveedor no existe o no pertenece a la empresa")
|
||||||
|
ErrRepuestoNoEncontrado = errors.New("el repuesto no existe o no pertenece a la empresa")
|
||||||
|
ErrRemitoDuplicado = errors.New("ya existe un remito con ese número para el proveedor")
|
||||||
|
ErrFechaVencimiento = errors.New("la fecha de vencimiento debe ser futura")
|
||||||
|
ErrAjusteBajoReserva = errors.New("el stock no puede quedar por debajo de lo reservado")
|
||||||
|
ErrSinAlmacen = errors.New("no hay almacenes cargados en la empresa")
|
||||||
|
)
|
||||||
|
|
||||||
|
// Estado clasifica un ítem según su cantidad física y su mínimo.
|
||||||
|
type Estado string
|
||||||
|
|
||||||
|
const (
|
||||||
|
EstadoAgotado Estado = "AGOTADO"
|
||||||
|
EstadoBajoMinimo Estado = "BAJO_MINIMO"
|
||||||
|
EstadoNormal Estado = "NORMAL"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Disponible es la cantidad que puede usarse sin afectar reservas.
|
||||||
|
func Disponible(stock *models.Stock) float64 {
|
||||||
|
if stock == nil {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
return redondearCantidad(stock.Cantidad - stock.CantidadReservada)
|
||||||
|
}
|
||||||
|
|
||||||
|
// EstadoStock devuelve AGOTADO, BAJO_MINIMO o NORMAL.
|
||||||
|
func EstadoStock(stock *models.Stock, repuesto *models.Repuesto) Estado {
|
||||||
|
if stock == nil {
|
||||||
|
return EstadoAgotado
|
||||||
|
}
|
||||||
|
if stock.Cantidad <= 0 {
|
||||||
|
return EstadoAgotado
|
||||||
|
}
|
||||||
|
if repuesto != nil && stock.Cantidad < float64(repuesto.StockMinimo) {
|
||||||
|
return EstadoBajoMinimo
|
||||||
|
}
|
||||||
|
return EstadoNormal
|
||||||
|
}
|
||||||
|
|
||||||
|
// ValidarCantidad acepta solo cantidades positivas y finitas.
|
||||||
|
func ValidarCantidad(cantidad float64) error {
|
||||||
|
if math.IsNaN(cantidad) || math.IsInf(cantidad, 0) || cantidad <= 0 {
|
||||||
|
return ErrCantidadInvalida
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ValidarObservacion limita el texto a 60 caracteres (runas, no bytes).
|
||||||
|
func ValidarObservacion(texto string) error {
|
||||||
|
if utf8.RuneCountInString(texto) > 60 {
|
||||||
|
return ErrComentarioLargo
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func redondearCantidad(valor float64) float64 {
|
||||||
|
return math.Round(valor*1000) / 1000
|
||||||
|
}
|
||||||
|
|
||||||
|
// Servicio expone las operaciones de escritura del módulo Stock.
|
||||||
|
type Servicio struct {
|
||||||
|
db *gorm.DB
|
||||||
|
repo *repositorios.Repositorios
|
||||||
|
empresaID uint
|
||||||
|
usuarioID uint
|
||||||
|
contabilidad bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// Nuevo arma el servicio a partir del contexto autenticado.
|
||||||
|
func Nuevo(c *gin.Context) *Servicio {
|
||||||
|
return &Servicio{
|
||||||
|
db: repositorios.BaseDeDatos(),
|
||||||
|
repo: repositorios.ObtenerRepositorios(c),
|
||||||
|
empresaID: utils.EmpresaID(c),
|
||||||
|
usuarioID: c.GetUint("userID"),
|
||||||
|
contabilidad: true,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// NuevoConDB permite inyectar la conexión y el usuario (tests / jobs).
|
||||||
|
func NuevoConDB(db *gorm.DB, empresaID, usuarioID uint) *Servicio {
|
||||||
|
return &Servicio{
|
||||||
|
db: db,
|
||||||
|
repo: repositorios.NuevoContenedor(db, empresaID),
|
||||||
|
empresaID: empresaID,
|
||||||
|
usuarioID: usuarioID,
|
||||||
|
contabilidad: true,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// SinContabilidad desactiva los asientos para pruebas o empresas que aún no
|
||||||
|
// tienen cuentas contables definidas.
|
||||||
|
func (s *Servicio) SinContabilidad() *Servicio {
|
||||||
|
s.contabilidad = false
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
|
// EntradaTraslado mueve mercadería entre dos almacenes de la empresa.
|
||||||
|
type EntradaTraslado struct {
|
||||||
|
RepuestoID uint64
|
||||||
|
AlmacenOrigenID uint
|
||||||
|
AlmacenDestinoID uint
|
||||||
|
Cantidad float64
|
||||||
|
Observacion string
|
||||||
|
}
|
||||||
|
|
||||||
|
type ResultadoTraslado struct {
|
||||||
|
Origen *models.Stock
|
||||||
|
Destino *models.Stock
|
||||||
|
}
|
||||||
|
|
||||||
|
// Trasladar descuenta el origen y suma el destino en una sola transacción.
|
||||||
|
func (s *Servicio) Trasladar(entrada EntradaTraslado) (*ResultadoTraslado, error) {
|
||||||
|
if err := ValidarCantidad(entrada.Cantidad); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if entrada.RepuestoID == 0 || entrada.AlmacenOrigenID == 0 || entrada.AlmacenDestinoID == 0 {
|
||||||
|
return nil, ErrStockNoEncontrado
|
||||||
|
}
|
||||||
|
if entrada.AlmacenOrigenID == entrada.AlmacenDestinoID {
|
||||||
|
return nil, ErrMismoAlmacen
|
||||||
|
}
|
||||||
|
if err := ValidarObservacion(entrada.Observacion); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
cantidad := redondearCantidad(entrada.Cantidad)
|
||||||
|
var resultado ResultadoTraslado
|
||||||
|
|
||||||
|
err := s.db.Transaction(func(tx *gorm.DB) error {
|
||||||
|
origen, err := s.buscarStockTx(tx, entrada.RepuestoID, entrada.AlmacenOrigenID)
|
||||||
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
return ErrStockNoEncontrado
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
destino, errDestino := s.buscarStockTx(tx, entrada.RepuestoID, entrada.AlmacenDestinoID)
|
||||||
|
existeDestino := errDestino == nil
|
||||||
|
if errDestino != nil && !errors.Is(errDestino, gorm.ErrRecordNotFound) {
|
||||||
|
return errDestino
|
||||||
|
}
|
||||||
|
|
||||||
|
// Bloquear siempre en orden ascendente de ID para evitar deadlocks
|
||||||
|
// cuando dos traslados cruzan el mismo par de filas.
|
||||||
|
if existeDestino && destino.ID < origen.ID {
|
||||||
|
destino, err = s.repo.Stock.BloquearPorID(tx, destino.ID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
origen, err = s.repo.Stock.BloquearPorID(tx, origen.ID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
origen, err = s.repo.Stock.BloquearPorID(tx, origen.ID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if existeDestino {
|
||||||
|
destino, err = s.repo.Stock.BloquearPorID(tx, destino.ID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
destino = &models.Stock{
|
||||||
|
RepuestoID: entrada.RepuestoID,
|
||||||
|
AlmacenID: entrada.AlmacenDestinoID,
|
||||||
|
}
|
||||||
|
if s.empresaID > 0 {
|
||||||
|
destino.EmpresaID = uint64(s.empresaID)
|
||||||
|
}
|
||||||
|
if err := tx.Create(destino).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if Disponible(origen) < cantidad {
|
||||||
|
return fmt.Errorf("%w: disponible %.3f, solicitado %.3f", ErrStockInsuficiente, Disponible(origen), cantidad)
|
||||||
|
}
|
||||||
|
|
||||||
|
saldoOrigen := origen.Cantidad
|
||||||
|
saldoDestino := destino.Cantidad
|
||||||
|
|
||||||
|
origen.Cantidad = redondearCantidad(origen.Cantidad - cantidad)
|
||||||
|
destino.Cantidad = redondearCantidad(destino.Cantidad + cantidad)
|
||||||
|
if err := s.repo.Stock.ActualizarCantidades(tx, origen); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := s.repo.Stock.ActualizarCantidades(tx, destino); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
referencia := fmt.Sprintf("Traslado %d → %d", entrada.AlmacenOrigenID, entrada.AlmacenDestinoID)
|
||||||
|
if err := s.registrarMovimiento(tx, origen, models.MovimientoTrasladoSalida, -cantidad, saldoOrigen, origen.Cantidad, "TRASLADO", entrada.RepuestoID, referencia); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := s.registrarMovimiento(tx, destino, models.MovimientoTrasladoEntrada, cantidad, saldoDestino, destino.Cantidad, "TRASLADO", entrada.RepuestoID, referencia); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
resultado = ResultadoTraslado{Origen: origen, Destino: destino}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
s.registrarLog("TRASLADO_STOCK", []models_logs.LogDetalle{
|
||||||
|
{Columna: "repuestoId", ValorNuevo: fmt.Sprintf("%d", entrada.RepuestoID)},
|
||||||
|
{Columna: "origenId", ValorNuevo: fmt.Sprintf("%d", entrada.AlmacenOrigenID)},
|
||||||
|
{Columna: "destinoId", ValorNuevo: fmt.Sprintf("%d", entrada.AlmacenDestinoID)},
|
||||||
|
{Columna: "cantidad", ValorNuevo: fmt.Sprintf("%.3f", cantidad)},
|
||||||
|
})
|
||||||
|
return &resultado, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// EntradaAjuste corrige la cantidad real de un ítem.
|
||||||
|
type EntradaAjuste struct {
|
||||||
|
StockID uint64
|
||||||
|
CantidadReal float64
|
||||||
|
Motivo string
|
||||||
|
Observacion string
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ajustar deja el stock en la cantidad real indicada y registra la diferencia.
|
||||||
|
func (s *Servicio) Ajustar(entrada EntradaAjuste) (*models.Stock, error) {
|
||||||
|
if entrada.CantidadReal < 0 || math.IsNaN(entrada.CantidadReal) || math.IsInf(entrada.CantidadReal, 0) {
|
||||||
|
return nil, ErrCantidadInvalida
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(entrada.Motivo) == "" {
|
||||||
|
return nil, ErrMotivoRequerido
|
||||||
|
}
|
||||||
|
if err := ValidarObservacion(entrada.Observacion); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
cantidadReal := redondearCantidad(entrada.CantidadReal)
|
||||||
|
var resultado *models.Stock
|
||||||
|
|
||||||
|
err := s.db.Transaction(func(tx *gorm.DB) error {
|
||||||
|
stock, err := s.repo.Stock.BloquearPorID(tx, entrada.StockID)
|
||||||
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
return ErrStockNoEncontrado
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if cantidadReal < stock.CantidadReservada {
|
||||||
|
return fmt.Errorf("%w: reservado %.3f", ErrAjusteBajoReserva, stock.CantidadReservada)
|
||||||
|
}
|
||||||
|
|
||||||
|
saldoAnterior := stock.Cantidad
|
||||||
|
diferencia := redondearCantidad(cantidadReal - saldoAnterior)
|
||||||
|
stock.Cantidad = cantidadReal
|
||||||
|
if err := s.repo.Stock.ActualizarCantidades(tx, stock); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
observacion := strings.TrimSpace(strings.Join([]string{entrada.Motivo, entrada.Observacion}, " - "))
|
||||||
|
if err := s.registrarMovimiento(tx, stock, models.MovimientoAjuste, diferencia, saldoAnterior, stock.Cantidad, "AJUSTE", stock.ID, observacion); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if diferencia != 0 {
|
||||||
|
if err := s.asientoAjuste(tx, stock, diferencia); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
resultado = stock
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
s.registrarLog("AJUSTE_STOCK", []models_logs.LogDetalle{
|
||||||
|
{Columna: "stockId", ValorNuevo: fmt.Sprintf("%d", entrada.StockID)},
|
||||||
|
{Columna: "cantidadReal", ValorNuevo: fmt.Sprintf("%.3f", cantidadReal)},
|
||||||
|
{Columna: "motivo", ValorNuevo: entrada.Motivo},
|
||||||
|
})
|
||||||
|
return resultado, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ItemIngreso es un renglón del remito de compra.
|
||||||
|
type ItemIngreso struct {
|
||||||
|
RepuestoID uint64
|
||||||
|
CantidadEsperada float64
|
||||||
|
CantidadRecibida float64
|
||||||
|
UnidadMedida string
|
||||||
|
Observacion string
|
||||||
|
}
|
||||||
|
|
||||||
|
// EntradaIngreso registra el ingreso de mercadería con remito.
|
||||||
|
type EntradaIngreso struct {
|
||||||
|
ProveedorID uint
|
||||||
|
Numero string
|
||||||
|
FechaEmision time.Time
|
||||||
|
AlmacenDestinoID uint
|
||||||
|
Observacion string
|
||||||
|
Items []ItemIngreso
|
||||||
|
}
|
||||||
|
|
||||||
|
type ResultadoIngreso struct {
|
||||||
|
Remito *models.Remito
|
||||||
|
Diferencias []models.DiferenciaRemito
|
||||||
|
Stocks []*models.Stock
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ingresar crea el remito, actualiza stock, registra diferencias y asiento.
|
||||||
|
func (s *Servicio) Ingresar(entrada EntradaIngreso) (*ResultadoIngreso, error) {
|
||||||
|
if entrada.ProveedorID == 0 {
|
||||||
|
return nil, ErrProveedorNoEncontrado
|
||||||
|
}
|
||||||
|
if entrada.AlmacenDestinoID == 0 {
|
||||||
|
return nil, ErrAlmacenInvalido
|
||||||
|
}
|
||||||
|
if entrada.FechaEmision.IsZero() {
|
||||||
|
return nil, fmt.Errorf("%w: fecha de emisión obligatoria", ErrMotivoRequerido)
|
||||||
|
}
|
||||||
|
if len(entrada.Items) == 0 {
|
||||||
|
return nil, fmt.Errorf("%w: el remito debe tener al menos un ítem", ErrCantidadInvalida)
|
||||||
|
}
|
||||||
|
if err := ValidarObservacion(entrada.Observacion); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err := s.repo.Proveedor.ObtenerPorID(entrada.ProveedorID); err != nil {
|
||||||
|
return nil, ErrProveedorNoEncontrado
|
||||||
|
}
|
||||||
|
if _, err := s.repo.Almacen.ObtenerPorID(entrada.AlmacenDestinoID); err != nil {
|
||||||
|
return nil, ErrAlmacenInvalido
|
||||||
|
}
|
||||||
|
|
||||||
|
items := append([]ItemIngreso(nil), entrada.Items...)
|
||||||
|
// Ordenar por repuesto para bloquear filas siempre en el mismo orden.
|
||||||
|
sort.Slice(items, func(i, j int) bool { return items[i].RepuestoID < items[j].RepuestoID })
|
||||||
|
|
||||||
|
repuestos := make(map[uint64]*models.Repuesto, len(items))
|
||||||
|
vistos := make(map[uint64]bool, len(items))
|
||||||
|
for _, item := range items {
|
||||||
|
if item.RepuestoID == 0 {
|
||||||
|
return nil, ErrRepuestoNoEncontrado
|
||||||
|
}
|
||||||
|
if vistos[item.RepuestoID] {
|
||||||
|
return nil, fmt.Errorf("%w: %d", ErrItemDuplicado, item.RepuestoID)
|
||||||
|
}
|
||||||
|
vistos[item.RepuestoID] = true
|
||||||
|
if math.IsNaN(item.CantidadEsperada) || item.CantidadEsperada < 0 || math.IsNaN(item.CantidadRecibida) || item.CantidadRecibida < 0 {
|
||||||
|
return nil, ErrCantidadInvalida
|
||||||
|
}
|
||||||
|
if item.CantidadEsperada == 0 && item.CantidadRecibida == 0 {
|
||||||
|
return nil, ErrCantidadInvalida
|
||||||
|
}
|
||||||
|
if err := ValidarObservacion(item.Observacion); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
repuestoPtr, err := s.repo.Repuesto.ObtenerPorID(uint(item.RepuestoID))
|
||||||
|
if err != nil || repuestoPtr == nil || *repuestoPtr == nil {
|
||||||
|
return nil, fmt.Errorf("%w: %d", ErrRepuestoNoEncontrado, item.RepuestoID)
|
||||||
|
}
|
||||||
|
repuestos[item.RepuestoID] = *repuestoPtr
|
||||||
|
}
|
||||||
|
|
||||||
|
var resultado ResultadoIngreso
|
||||||
|
err := s.db.Transaction(func(tx *gorm.DB) error {
|
||||||
|
var existentes int64
|
||||||
|
query := tx.Model(&models.Remito{}).
|
||||||
|
Where("numero = ? AND proveedor_id = ?", entrada.Numero, entrada.ProveedorID)
|
||||||
|
if s.empresaID > 0 {
|
||||||
|
query = query.Where("empresa_id = ?", s.empresaID)
|
||||||
|
}
|
||||||
|
if err := query.Count(&existentes).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if existentes > 0 {
|
||||||
|
return ErrRemitoDuplicado
|
||||||
|
}
|
||||||
|
|
||||||
|
remito := &models.Remito{
|
||||||
|
Numero: entrada.Numero,
|
||||||
|
FechaEmision: entrada.FechaEmision,
|
||||||
|
TipoOperacion: models.OperacionCompra,
|
||||||
|
EmisorID: entrada.ProveedorID,
|
||||||
|
ReceptorID: s.empresaID,
|
||||||
|
ProveedorID: &entrada.ProveedorID,
|
||||||
|
AlmacenDestinoID: &entrada.AlmacenDestinoID,
|
||||||
|
Observacion: entrada.Observacion,
|
||||||
|
}
|
||||||
|
remito.Estado = "confirmado"
|
||||||
|
remito.ResponsableID = s.usuarioID
|
||||||
|
|
||||||
|
var total float64
|
||||||
|
for _, item := range items {
|
||||||
|
repuesto := repuestos[item.RepuestoID]
|
||||||
|
recibida := redondearCantidad(item.CantidadRecibida)
|
||||||
|
total += redondearCantidad(recibida * repuesto.Precio)
|
||||||
|
remito.Detalles = append(remito.Detalles, models.RemitoDetalle{
|
||||||
|
ProductoID: uint(item.RepuestoID),
|
||||||
|
CantidadEsperada: redondearCantidad(item.CantidadEsperada),
|
||||||
|
CantidadRecibida: recibida,
|
||||||
|
UnidadMedida: item.UnidadMedida,
|
||||||
|
Observacion: item.Observacion,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
total = redondearCantidad(total)
|
||||||
|
remito.Total = total
|
||||||
|
|
||||||
|
if err := s.repo.Remito.CrearConDetalles(tx, remito); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, item := range items {
|
||||||
|
recibida := redondearCantidad(item.CantidadRecibida)
|
||||||
|
if recibida > 0 {
|
||||||
|
stock, err := s.bloquearOCrearStock(tx, item.RepuestoID, entrada.AlmacenDestinoID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
saldoAnterior := stock.Cantidad
|
||||||
|
stock.Cantidad = redondearCantidad(stock.Cantidad + recibida)
|
||||||
|
if err := s.repo.Stock.ActualizarCantidades(tx, stock); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := s.registrarMovimiento(tx, stock, models.MovimientoIngreso, recibida, saldoAnterior, stock.Cantidad, "REMITO", uint64(remito.ID), remito.Numero); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
resultado.Stocks = append(resultado.Stocks, stock)
|
||||||
|
}
|
||||||
|
|
||||||
|
esperada := redondearCantidad(item.CantidadEsperada)
|
||||||
|
if esperada != recibida {
|
||||||
|
diferencia := &models.DiferenciaRemito{
|
||||||
|
RemitoID: remito.ID,
|
||||||
|
RepuestoID: item.RepuestoID,
|
||||||
|
CantidadEsperada: esperada,
|
||||||
|
CantidadRecibida: recibida,
|
||||||
|
Diferencia: redondearCantidad(recibida - esperada),
|
||||||
|
UsuarioID: s.usuarioID,
|
||||||
|
Observacion: item.Observacion,
|
||||||
|
}
|
||||||
|
if err := s.repo.DiferenciaRemito.Registrar(tx, diferencia); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
resultado.Diferencias = append(resultado.Diferencias, *diferencia)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if total > 0 {
|
||||||
|
if err := s.registrarAsiento(tx, "REMITO", remito.ID, []lineaAsiento{
|
||||||
|
{cuenta: cuentaInventario, tipo: tipoActivo, debe: total, descripcion: "Ingreso de mercadería"},
|
||||||
|
{cuenta: cuentaProveedores, tipo: tipoPasivo, haber: total, descripcion: "Compra con remito"},
|
||||||
|
}); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
resultado.Remito = remito
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
s.registrarLog("INGRESO_STOCK", []models_logs.LogDetalle{
|
||||||
|
{Columna: "remitoId", ValorNuevo: fmt.Sprintf("%d", resultado.Remito.ID)},
|
||||||
|
{Columna: "numero", ValorNuevo: entrada.Numero},
|
||||||
|
{Columna: "items", ValorNuevo: fmt.Sprintf("%d", len(items))},
|
||||||
|
{Columna: "diferencias", ValorNuevo: fmt.Sprintf("%d", len(resultado.Diferencias))},
|
||||||
|
})
|
||||||
|
return &resultado, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// EntradaReserva descuenta disponible sin mover la cantidad física.
|
||||||
|
type EntradaReserva struct {
|
||||||
|
RepuestoID uint64
|
||||||
|
AlmacenID uint
|
||||||
|
Cantidad float64
|
||||||
|
ClienteID *uint
|
||||||
|
FechaVencimiento *time.Time
|
||||||
|
Observacion string
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reservar bloquea stock, incrementa lo reservado y crea la reserva activa.
|
||||||
|
func (s *Servicio) Reservar(entrada EntradaReserva) (*models.Reserva, error) {
|
||||||
|
if err := ValidarCantidad(entrada.Cantidad); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := ValidarObservacion(entrada.Observacion); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if entrada.FechaVencimiento != nil && !entrada.FechaVencimiento.After(time.Now()) {
|
||||||
|
return nil, ErrFechaVencimiento
|
||||||
|
}
|
||||||
|
if entrada.ClienteID != nil {
|
||||||
|
if _, err := s.repo.Cliente.ObtenerPorID(*entrada.ClienteID); err != nil {
|
||||||
|
return nil, fmt.Errorf("%w: cliente %d", ErrItemNoEncontrado, *entrada.ClienteID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
cantidad := redondearCantidad(entrada.Cantidad)
|
||||||
|
var reserva *models.Reserva
|
||||||
|
|
||||||
|
err := s.db.Transaction(func(tx *gorm.DB) error {
|
||||||
|
stock, err := s.repo.Stock.BloquearPorRepuestoAlmacen(tx, entrada.RepuestoID, entrada.AlmacenID)
|
||||||
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
return ErrStockNoEncontrado
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if Disponible(stock) < cantidad {
|
||||||
|
return fmt.Errorf("%w: disponible %.3f, solicitado %.3f", ErrStockInsuficiente, Disponible(stock), cantidad)
|
||||||
|
}
|
||||||
|
|
||||||
|
saldoReservado := stock.CantidadReservada
|
||||||
|
stock.CantidadReservada = redondearCantidad(stock.CantidadReservada + cantidad)
|
||||||
|
if err := s.repo.Stock.ActualizarCantidades(tx, stock); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
reserva = &models.Reserva{
|
||||||
|
RepuestoID: uint(entrada.RepuestoID),
|
||||||
|
AlmacenID: entrada.AlmacenID,
|
||||||
|
Cantidad: cantidad,
|
||||||
|
Estado: models.ReservaActiva,
|
||||||
|
ClienteID: entrada.ClienteID,
|
||||||
|
CreadoPorID: s.usuarioID,
|
||||||
|
Observacion: entrada.Observacion,
|
||||||
|
}
|
||||||
|
if entrada.FechaVencimiento != nil {
|
||||||
|
reserva.FechaVencimiento = *entrada.FechaVencimiento
|
||||||
|
}
|
||||||
|
if s.empresaID > 0 {
|
||||||
|
reserva.EmpresaID = s.empresaID
|
||||||
|
}
|
||||||
|
if reserva.Estado == "" {
|
||||||
|
reserva.Estado = models.ReservaActiva
|
||||||
|
}
|
||||||
|
if err := tx.Create(reserva).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return s.registrarMovimiento(tx, stock, models.MovimientoReserva, cantidad, saldoReservado, stock.CantidadReservada, "RESERVA", uint64(reserva.ID), entrada.Observacion)
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
s.registrarLog("RESERVAR_STOCK", []models_logs.LogDetalle{
|
||||||
|
{Columna: "reservaId", ValorNuevo: fmt.Sprintf("%d", reserva.ID)},
|
||||||
|
{Columna: "repuestoId", ValorNuevo: fmt.Sprintf("%d", entrada.RepuestoID)},
|
||||||
|
{Columna: "almacenId", ValorNuevo: fmt.Sprintf("%d", entrada.AlmacenID)},
|
||||||
|
{Columna: "cantidad", ValorNuevo: fmt.Sprintf("%.3f", cantidad)},
|
||||||
|
})
|
||||||
|
return reserva, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Liberar devuelve el disponible de una reserva activa.
|
||||||
|
func (s *Servicio) Liberar(reservaID uint) (*models.Reserva, error) {
|
||||||
|
var reserva *models.Reserva
|
||||||
|
|
||||||
|
err := s.db.Transaction(func(tx *gorm.DB) error {
|
||||||
|
actual, err := s.repo.Reserva.ObtenerPorID(reservaID)
|
||||||
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
return ErrReservaInexistente
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if actual.Estado != models.ReservaActiva {
|
||||||
|
return ErrReservaYaLiberada
|
||||||
|
}
|
||||||
|
|
||||||
|
stock, err := s.repo.Stock.BloquearPorRepuestoAlmacen(tx, uint64(actual.RepuestoID), actual.AlmacenID)
|
||||||
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
return ErrStockNoEncontrado
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
liberada, err := s.repo.Reserva.Liberar(tx, reservaID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if !liberada {
|
||||||
|
return ErrReservaYaLiberada
|
||||||
|
}
|
||||||
|
|
||||||
|
saldoAnterior := stock.CantidadReservada
|
||||||
|
stock.CantidadReservada = redondearCantidad(math.Max(0, stock.CantidadReservada-actual.Cantidad))
|
||||||
|
if err := s.repo.Stock.ActualizarCantidades(tx, stock); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := s.registrarMovimiento(tx, stock, models.MovimientoLiberacion, -actual.Cantidad, saldoAnterior, stock.CantidadReservada, "RESERVA", uint64(actual.ID), "Liberación de reserva"); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
reserva = actual
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
s.registrarLog("LIBERAR_RESERVA", []models_logs.LogDetalle{
|
||||||
|
{Columna: "reservaId", ValorNuevo: fmt.Sprintf("%d", reserva.ID)},
|
||||||
|
{Columna: "cantidad", ValorNuevo: fmt.Sprintf("%.3f", reserva.Cantidad)},
|
||||||
|
})
|
||||||
|
return reserva, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ItemDevolucion es un renglón devuelto de una factura.
|
||||||
|
type ItemDevolucion struct {
|
||||||
|
RepuestoID uint64
|
||||||
|
Cantidad float64
|
||||||
|
PrecioUnitario float64
|
||||||
|
}
|
||||||
|
|
||||||
|
// EntradaDevolucion registra una devolución sobre una factura.
|
||||||
|
type EntradaDevolucion struct {
|
||||||
|
FacturaID uint
|
||||||
|
AlmacenID uint
|
||||||
|
Motivo string
|
||||||
|
Items []ItemDevolucion
|
||||||
|
}
|
||||||
|
|
||||||
|
type ResultadoDevolucion struct {
|
||||||
|
Devolucion *models.Devolucion
|
||||||
|
Stocks []*models.Stock
|
||||||
|
}
|
||||||
|
|
||||||
|
// Devolver valida contra lo vendido, repone stock y registra el comprobante.
|
||||||
|
func (s *Servicio) Devolver(entrada EntradaDevolucion) (*ResultadoDevolucion, error) {
|
||||||
|
if strings.TrimSpace(entrada.Motivo) == "" {
|
||||||
|
return nil, ErrMotivoRequerido
|
||||||
|
}
|
||||||
|
if len(entrada.Items) == 0 {
|
||||||
|
return nil, fmt.Errorf("%w: la devolución debe tener al menos un ítem", ErrCantidadInvalida)
|
||||||
|
}
|
||||||
|
|
||||||
|
factura, err := s.repo.Factura.ObtenerPorID(entrada.FacturaID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%w: factura %d", ErrItemNoEncontrado, entrada.FacturaID)
|
||||||
|
}
|
||||||
|
if strings.EqualFold(strings.TrimSpace(factura.Estado), "anulada") {
|
||||||
|
return nil, ErrFacturaAnulada
|
||||||
|
}
|
||||||
|
|
||||||
|
almacenID := entrada.AlmacenID
|
||||||
|
if almacenID == 0 {
|
||||||
|
almacenes, err := s.repo.Almacen.Listar()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if len(almacenes) == 0 {
|
||||||
|
return nil, ErrSinAlmacen
|
||||||
|
}
|
||||||
|
almacenID = almacenes[0].ID
|
||||||
|
} else if _, err := s.repo.Almacen.ObtenerPorID(almacenID); err != nil {
|
||||||
|
return nil, ErrAlmacenInvalido
|
||||||
|
}
|
||||||
|
|
||||||
|
items := append([]ItemDevolucion(nil), entrada.Items...)
|
||||||
|
sort.Slice(items, func(i, j int) bool { return items[i].RepuestoID < items[j].RepuestoID })
|
||||||
|
|
||||||
|
vendidos := make(map[uint64]float64)
|
||||||
|
precios := make(map[uint64]float64)
|
||||||
|
for _, detalle := range factura.Detalles {
|
||||||
|
vendidos[detalle.RepuestoID] += float64(detalle.Cantidad)
|
||||||
|
precios[detalle.RepuestoID] = detalle.PrecioUnitario
|
||||||
|
}
|
||||||
|
|
||||||
|
anteriores, err := s.repo.Devolucion.ListarPorFactura(factura.ID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
var resultado ResultadoDevolucion
|
||||||
|
err = s.db.Transaction(func(tx *gorm.DB) error {
|
||||||
|
devueltos := make(map[uint64]float64)
|
||||||
|
for _, devolucion := range anteriores {
|
||||||
|
for _, detalle := range devolucion.Detalles {
|
||||||
|
devueltos[detalle.RepuestoID] += detalle.Cantidad
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
devolucion := &models.Devolucion{
|
||||||
|
Motivo: entrada.Motivo,
|
||||||
|
FacturaOrigenID: factura.ID,
|
||||||
|
}
|
||||||
|
devolucion.Estado = "confirmada"
|
||||||
|
devolucion.ResponsableID = s.usuarioID
|
||||||
|
|
||||||
|
detalles := make([]models.DevolucionDetalle, 0, len(items))
|
||||||
|
for _, item := range items {
|
||||||
|
if err := ValidarCantidad(item.Cantidad); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
vendido, ok := vendidos[item.RepuestoID]
|
||||||
|
if !ok {
|
||||||
|
return fmt.Errorf("%w: %d", ErrItemNoEncontrado, item.RepuestoID)
|
||||||
|
}
|
||||||
|
cantidad := redondearCantidad(item.Cantidad)
|
||||||
|
if cantidad > redondearCantidad(vendido-devueltos[item.RepuestoID]) {
|
||||||
|
return fmt.Errorf("%w: repuesto %d, vendido %.3f, ya devuelto %.3f", ErrDevolucionExcedeVendido, item.RepuestoID, vendido, devueltos[item.RepuestoID])
|
||||||
|
}
|
||||||
|
|
||||||
|
precio := item.PrecioUnitario
|
||||||
|
if precio <= 0 {
|
||||||
|
precio = precios[item.RepuestoID]
|
||||||
|
}
|
||||||
|
detalles = append(detalles, models.DevolucionDetalle{
|
||||||
|
RepuestoID: item.RepuestoID,
|
||||||
|
Cantidad: cantidad,
|
||||||
|
PrecioUnitario: precio,
|
||||||
|
Subtotal: redondearCantidad(cantidad * precio),
|
||||||
|
})
|
||||||
|
devolucion.Total = redondearCantidad(devolucion.Total + cantidad*precio)
|
||||||
|
}
|
||||||
|
devolucion.Detalles = detalles
|
||||||
|
|
||||||
|
if err := s.repo.Devolucion.CrearConDetalles(tx, devolucion); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, detalle := range detalles {
|
||||||
|
stock, err := s.bloquearOCrearStock(tx, detalle.RepuestoID, almacenID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
saldoAnterior := stock.Cantidad
|
||||||
|
stock.Cantidad = redondearCantidad(stock.Cantidad + detalle.Cantidad)
|
||||||
|
if err := s.repo.Stock.ActualizarCantidades(tx, stock); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := s.registrarMovimiento(tx, stock, models.MovimientoDevolucion, detalle.Cantidad, saldoAnterior, stock.Cantidad, "DEVOLUCION", uint64(devolucion.ID), entrada.Motivo); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
resultado.Stocks = append(resultado.Stocks, stock)
|
||||||
|
}
|
||||||
|
|
||||||
|
if devolucion.Total > 0 {
|
||||||
|
if err := s.registrarAsiento(tx, "DEVOLUCION", devolucion.ID, []lineaAsiento{
|
||||||
|
{cuenta: cuentaInventario, tipo: tipoActivo, debe: devolucion.Total, descripcion: "Devolución de mercadería"},
|
||||||
|
{cuenta: cuentaDevoluciones, tipo: tipoResultado, haber: devolucion.Total, descripcion: "Devoluciones sobre ventas"},
|
||||||
|
}); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
resultado.Devolucion = devolucion
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
s.registrarLog("DEVOLUCION_STOCK", []models_logs.LogDetalle{
|
||||||
|
{Columna: "devolucionId", ValorNuevo: fmt.Sprintf("%d", resultado.Devolucion.ID)},
|
||||||
|
{Columna: "facturaId", ValorNuevo: fmt.Sprintf("%d", factura.ID)},
|
||||||
|
{Columna: "total", ValorNuevo: fmt.Sprintf("%.2f", resultado.Devolucion.Total)},
|
||||||
|
})
|
||||||
|
return &resultado, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Comentar guarda el último comentario visible y su historial.
|
||||||
|
func (s *Servicio) Comentar(stockID uint64, texto string) (*models.Stock, error) {
|
||||||
|
texto = strings.TrimSpace(texto)
|
||||||
|
if texto == "" {
|
||||||
|
return nil, ErrComentarioVacio
|
||||||
|
}
|
||||||
|
if err := ValidarObservacion(texto); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
var stock *models.Stock
|
||||||
|
err := s.db.Transaction(func(tx *gorm.DB) error {
|
||||||
|
actual, err := s.repo.Stock.BloquearPorID(tx, stockID)
|
||||||
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
return ErrStockNoEncontrado
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := s.repo.Stock.ActualizarObservacion(tx, stockID, texto); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
actual.Observacion = texto
|
||||||
|
stock = actual
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
s.registrarLog("COMENTAR_STOCK", []models_logs.LogDetalle{
|
||||||
|
{Columna: "stockId", ValorNuevo: fmt.Sprintf("%d", stockID)},
|
||||||
|
{Columna: "observacion", ValorNuevo: texto},
|
||||||
|
})
|
||||||
|
return stock, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// buscarStockTx busca sin bloquear; el bloqueo se hace después en orden de ID.
|
||||||
|
func (s *Servicio) buscarStockTx(tx *gorm.DB, repuestoID uint64, almacenID uint) (*models.Stock, error) {
|
||||||
|
var stock models.Stock
|
||||||
|
query := tx.Where("repuesto_id = ? AND almacen_id = ?", repuestoID, almacenID)
|
||||||
|
if s.empresaID > 0 {
|
||||||
|
query = query.Where("empresa_id = ?", s.empresaID)
|
||||||
|
}
|
||||||
|
if err := query.First(&stock).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &stock, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// bloquearOCrearStock obtiene la fila con FOR UPDATE o la crea en cero.
|
||||||
|
func (s *Servicio) bloquearOCrearStock(tx *gorm.DB, repuestoID uint64, almacenID uint) (*models.Stock, error) {
|
||||||
|
stock, err := s.repo.Stock.BloquearPorRepuestoAlmacen(tx, repuestoID, almacenID)
|
||||||
|
if err == nil {
|
||||||
|
return stock, nil
|
||||||
|
}
|
||||||
|
if !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
nuevo := &models.Stock{RepuestoID: repuestoID, AlmacenID: almacenID}
|
||||||
|
if s.empresaID > 0 {
|
||||||
|
nuevo.EmpresaID = uint64(s.empresaID)
|
||||||
|
}
|
||||||
|
if err := tx.Create(nuevo).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return nuevo, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Servicio) registrarMovimiento(
|
||||||
|
tx *gorm.DB,
|
||||||
|
stock *models.Stock,
|
||||||
|
tipo models.TipoMovimientoStock,
|
||||||
|
cantidad float64,
|
||||||
|
saldoAnterior float64,
|
||||||
|
saldoPosterior float64,
|
||||||
|
referenciaTipo string,
|
||||||
|
referenciaID uint64,
|
||||||
|
observacion string,
|
||||||
|
) error {
|
||||||
|
movimiento := &models.MovimientoStock{
|
||||||
|
StockID: stock.ID,
|
||||||
|
RepuestoID: stock.RepuestoID,
|
||||||
|
AlmacenID: stock.AlmacenID,
|
||||||
|
Tipo: tipo,
|
||||||
|
Cantidad: redondearCantidad(cantidad),
|
||||||
|
SaldoAnterior: redondearCantidad(saldoAnterior),
|
||||||
|
SaldoPosterior: redondearCantidad(saldoPosterior),
|
||||||
|
ReferenciaTipo: referenciaTipo,
|
||||||
|
ReferenciaID: referenciaID,
|
||||||
|
UsuarioID: s.usuarioID,
|
||||||
|
Observacion: observacion,
|
||||||
|
Fecha: time.Now(),
|
||||||
|
}
|
||||||
|
return s.repo.MovimientoStock.Registrar(tx, movimiento)
|
||||||
|
}
|
||||||
|
|
||||||
|
const (
|
||||||
|
cuentaInventario = "Inventario"
|
||||||
|
cuentaProveedores = "Proveedores"
|
||||||
|
cuentaPerdida = "Pérdida por ajuste"
|
||||||
|
cuentaDevoluciones = "Devoluciones sobre ventas"
|
||||||
|
|
||||||
|
tipoActivo = "activo"
|
||||||
|
tipoPasivo = "pasivo"
|
||||||
|
tipoResultado = "resultado"
|
||||||
|
)
|
||||||
|
|
||||||
|
type lineaAsiento struct {
|
||||||
|
cuenta string
|
||||||
|
tipo string
|
||||||
|
debe float64
|
||||||
|
haber float64
|
||||||
|
descripcion string
|
||||||
|
}
|
||||||
|
|
||||||
|
// asientoAjuste registra la pérdida o recuperación de valor de un ajuste.
|
||||||
|
func (s *Servicio) asientoAjuste(tx *gorm.DB, stock *models.Stock, diferencia float64) error {
|
||||||
|
repuestoPtr, err := s.repo.Repuesto.ObtenerPorID(uint(stock.RepuestoID))
|
||||||
|
if err != nil || repuestoPtr == nil || *repuestoPtr == nil {
|
||||||
|
return fmt.Errorf("%w: %d", ErrRepuestoNoEncontrado, stock.RepuestoID)
|
||||||
|
}
|
||||||
|
monto := redondearCantidad(math.Abs(diferencia) * (*repuestoPtr).Precio)
|
||||||
|
if monto == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if diferencia < 0 {
|
||||||
|
return s.registrarAsiento(tx, "AJUSTE", uint(stock.ID), []lineaAsiento{
|
||||||
|
{cuenta: cuentaPerdida, tipo: tipoResultado, debe: monto, descripcion: "Faltante de inventario"},
|
||||||
|
{cuenta: cuentaInventario, tipo: tipoActivo, haber: monto, descripcion: "Ajuste negativo de stock"},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return s.registrarAsiento(tx, "AJUSTE", uint(stock.ID), []lineaAsiento{
|
||||||
|
{cuenta: cuentaInventario, tipo: tipoActivo, debe: monto, descripcion: "Ajuste positivo de stock"},
|
||||||
|
{cuenta: cuentaPerdida, tipo: tipoResultado, haber: monto, descripcion: "Sobrante de inventario"},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// registrarAsiento crea las cuentas si faltan y persiste el asiento completo.
|
||||||
|
func (s *Servicio) registrarAsiento(tx *gorm.DB, comprobanteTipo string, comprobanteID uint, lineas []lineaAsiento) error {
|
||||||
|
if !s.contabilidad || len(lineas) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
asiento := &contabilidad.AsientoContable{
|
||||||
|
ComprobanteTipo: comprobanteTipo,
|
||||||
|
ComprobanteID: comprobanteID,
|
||||||
|
}
|
||||||
|
for _, linea := range lineas {
|
||||||
|
if linea.debe == 0 && linea.haber == 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
cuenta := &contabilidad.CuentaContable{Nombre: linea.cuenta, Tipo: linea.tipo}
|
||||||
|
if err := s.repo.Contabilidad.GuardarCuenta(tx, cuenta); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
asiento.Movimientos = append(asiento.Movimientos, contabilidad.MovimientoContable{
|
||||||
|
CuentaID: cuenta.ID,
|
||||||
|
Debe: redondearCantidad(linea.debe),
|
||||||
|
Haber: redondearCantidad(linea.haber),
|
||||||
|
Descripcion: linea.descripcion,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
if len(asiento.Movimientos) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return s.repo.Contabilidad.CrearAsientoConMovimientos(tx, asiento)
|
||||||
|
}
|
||||||
|
|
||||||
|
// registrarLog guarda la auditoría fuera de la transacción: si falla, la
|
||||||
|
// operación de negocio ya confirmada no se revierte.
|
||||||
|
func (s *Servicio) registrarLog(accion string, detalles []models_logs.LogDetalle) {
|
||||||
|
log, err := dto_builders.NewLogDirector().Custom(s.usuarioID, accion, detalles)
|
||||||
|
if err != nil {
|
||||||
|
applog.Printf("stock: no se pudo construir el log de %s: %v", accion, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
log.EmpresaID = s.empresaID
|
||||||
|
if err := s.repo.Logs.Crear(log, s.usuarioID); err != nil {
|
||||||
|
applog.Printf("stock: no se pudo registrar el log de %s: %v", accion, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user