Private
Public Access
364 lines
9.9 KiB
Go
364 lines
9.9 KiB
Go
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
|
|
}
|