Private
Public Access
eliminado migraciones antiguas
Signed-off-by: fede <federico.nicolas.polidoro@gmail.com>
This commit is contained in:
1 parent
6ffc398b19
commit
1073c69d5c
5 files changed
-765
No files matched your search
@@ -1,145 +0,0 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"log"
|
||||
|
||||
models_seguridad "repuestera_back/models/seguridad"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// tablasTenant son las tablas de negocio que se filtran por empresa_id.
|
||||
var tablasTenant = []string{
|
||||
"groupos",
|
||||
"almacen",
|
||||
"marca",
|
||||
"repuesto",
|
||||
"stock",
|
||||
"movimiento_stock",
|
||||
"clientes",
|
||||
"descuentos",
|
||||
"forma_de_pago",
|
||||
"proveedors",
|
||||
"pago",
|
||||
"logs",
|
||||
"reservas",
|
||||
"factura",
|
||||
"recibo",
|
||||
"remitos",
|
||||
"diferencia_remito",
|
||||
"nota_credito",
|
||||
"nota_debito",
|
||||
"orden_compra",
|
||||
"devolucion",
|
||||
"asiento_contables",
|
||||
"movimiento_contables",
|
||||
"cuenta_contables",
|
||||
}
|
||||
|
||||
// MigrarMultitenant hace el backfill necesario para pasar de una instalación
|
||||
// de una sola empresa a una base compartida con empresa_id. Es idempotente.
|
||||
func MigrarMultitenant() error {
|
||||
empresaID, err := empresaDefault()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for _, tabla := range tablasTenant {
|
||||
if !DB.Migrator().HasTable(tabla) || !DB.Migrator().HasColumn(tabla, "empresa_id") {
|
||||
continue
|
||||
}
|
||||
if err := DB.Exec("UPDATE `"+tabla+"` SET empresa_id = ? WHERE empresa_id IS NULL OR empresa_id = 0", empresaID).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if err := migrarJoinAntiguo(); err != nil {
|
||||
log.Printf("multitenant: no se pudo migrar el join antiguo usuario_grupos: %v", err)
|
||||
}
|
||||
|
||||
if err := asegurarMembresias(empresaID); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func empresaDefault() (uint, error) {
|
||||
var empresa models_seguridad.Empresa
|
||||
err := DB.Order("id ASC").First(&empresa).Error
|
||||
if err == nil {
|
||||
return empresa.ID, nil
|
||||
}
|
||||
if err != gorm.ErrRecordNotFound {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
empresa = models_seguridad.Empresa{
|
||||
ID: 1,
|
||||
Nombre: "Repuestera",
|
||||
Slug: "repuestera",
|
||||
Activa: true,
|
||||
}
|
||||
if err := DB.Create(&empresa).Error; err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return empresa.ID, nil
|
||||
}
|
||||
|
||||
func migrarJoinAntiguo() error {
|
||||
if !DB.Migrator().HasTable("usuario_grupos") || !DB.Migrator().HasTable("usuarios_grupos") {
|
||||
return nil
|
||||
}
|
||||
return DB.Exec(
|
||||
"INSERT IGNORE INTO usuarios_grupos (usuario_id, grupo_id) SELECT usuario_id, grupo_id FROM usuario_grupos",
|
||||
).Error
|
||||
}
|
||||
|
||||
// asegurarMembresias garantiza que todos los usuarios existentes tengan
|
||||
// membresía en la empresa default. El primer usuario queda como OWNER.
|
||||
func asegurarMembresias(empresaID uint) error {
|
||||
var usuarios []models_seguridad.Usuario
|
||||
if err := DB.Order("id ASC").Find(&usuarios).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for i, usuario := range usuarios {
|
||||
var count int64
|
||||
if err := DB.Model(&models_seguridad.EmpresaUsuario{}).
|
||||
Where("empresa_id = ? AND usuario_id = ?", empresaID, usuario.ID).
|
||||
Count(&count).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if count > 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
rol := models_seguridad.RolMiembro
|
||||
if i == 0 {
|
||||
rol = models_seguridad.RolOwner
|
||||
}
|
||||
if err := DB.Create(&models_seguridad.EmpresaUsuario{
|
||||
EmpresaID: empresaID,
|
||||
UsuarioID: usuario.ID,
|
||||
Rol: rol,
|
||||
Activo: true,
|
||||
}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// Si no hay ningún owner, promover al usuario más antiguo de la empresa.
|
||||
var owners int64
|
||||
DB.Model(&models_seguridad.EmpresaUsuario{}).
|
||||
Where("empresa_id = ? AND rol = ? AND activo = ?", empresaID, models_seguridad.RolOwner, true).
|
||||
Count(&owners)
|
||||
if owners > 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
var primera models_seguridad.EmpresaUsuario
|
||||
if err := DB.Where("empresa_id = ?", empresaID).Order("usuario_id ASC").First(&primera).Error; err != nil {
|
||||
return nil
|
||||
}
|
||||
return DB.Model(&primera).Update("rol", models_seguridad.RolOwner).Error
|
||||
}
|
||||
@@ -1,142 +0,0 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
)
|
||||
|
||||
// MigrarAlmacen convierte la vieja tabla almacen (id varchar) al nuevo esquema
|
||||
// con id numérico y codigo. Se ejecuta antes de AutoMigrate para que GORM no
|
||||
// intente cambiar una PK referenciada por claves foráneas incompatibles.
|
||||
func MigrarAlmacen() error {
|
||||
if !DB.Migrator().HasTable("almacen") || !DB.Migrator().HasColumn("almacen", "id") {
|
||||
return nil
|
||||
}
|
||||
|
||||
var tipo string
|
||||
if err := DB.Raw(`
|
||||
SELECT DATA_TYPE FROM information_schema.COLUMNS
|
||||
WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'almacen' AND COLUMN_NAME = 'id'
|
||||
`).Scan(&tipo).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if tipo != "varchar" && tipo != "char" {
|
||||
return nil
|
||||
}
|
||||
|
||||
log.Println("migrando almacen a id numérico...")
|
||||
|
||||
if err := DB.Exec("SET FOREIGN_KEY_CHECKS = 0").Error; err != nil {
|
||||
return err
|
||||
}
|
||||
defer DB.Exec("SET FOREIGN_KEY_CHECKS = 1")
|
||||
|
||||
type fk struct {
|
||||
Tabla string
|
||||
Nombre string
|
||||
}
|
||||
var claves []fk
|
||||
if err := DB.Raw(`
|
||||
SELECT TABLE_NAME AS tabla, CONSTRAINT_NAME AS nombre
|
||||
FROM information_schema.KEY_COLUMN_USAGE
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND REFERENCED_TABLE_NAME = 'almacen'
|
||||
AND REFERENCED_COLUMN_NAME = 'id'
|
||||
`).Scan(&claves).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
for _, clave := range claves {
|
||||
if err := DB.Exec(fmt.Sprintf(
|
||||
"ALTER TABLE `%s` DROP FOREIGN KEY `%s`", clave.Tabla, clave.Nombre,
|
||||
)).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
tieneEmpresa := DB.Migrator().HasColumn("almacen", "empresa_id")
|
||||
empresaExpr := "1"
|
||||
if tieneEmpresa {
|
||||
empresaExpr = "COALESCE(empresa_id, 1)"
|
||||
}
|
||||
|
||||
if err := DB.Exec("DROP TABLE IF EXISTS almacen_nuevo").Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if err := DB.Exec(`
|
||||
CREATE TABLE almacen_nuevo (
|
||||
id bigint unsigned NOT NULL AUTO_INCREMENT,
|
||||
empresa_id bigint unsigned NOT NULL DEFAULT 1,
|
||||
codigo varchar(5) NOT NULL,
|
||||
ubicacion varchar(40) NULL,
|
||||
PRIMARY KEY (id),
|
||||
UNIQUE KEY uq_almacen_empresa_codigo (empresa_id, codigo)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
|
||||
`).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := DB.Exec(fmt.Sprintf(
|
||||
"INSERT INTO almacen_nuevo (empresa_id, codigo, ubicacion) SELECT %s, id, ubicacion FROM almacen",
|
||||
empresaExpr,
|
||||
)).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := DB.Exec("DROP TABLE IF EXISTS tmp_almacen_map").Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if err := DB.Exec(`
|
||||
CREATE TABLE tmp_almacen_map (
|
||||
old_id varchar(5) NOT NULL,
|
||||
new_id bigint unsigned NOT NULL
|
||||
) ENGINE=InnoDB
|
||||
`).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if err := DB.Exec(`
|
||||
INSERT INTO tmp_almacen_map (old_id, new_id)
|
||||
SELECT a.id, n.id
|
||||
FROM almacen a
|
||||
JOIN almacen_nuevo n ON n.codigo = a.id AND n.empresa_id = ` + empresaExpr + `
|
||||
`).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if DB.Migrator().HasTable("stock") && DB.Migrator().HasColumn("stock", "almacen_id") {
|
||||
if err := DB.Exec(`
|
||||
UPDATE stock s JOIN tmp_almacen_map m ON s.almacen_id = m.old_id
|
||||
SET s.almacen_id = m.new_id
|
||||
`).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if DB.Migrator().HasTable("reservas") && DB.Migrator().HasColumn("reservas", "almacen_id") {
|
||||
if err := DB.Exec(`
|
||||
UPDATE reservas r JOIN tmp_almacen_map m ON r.almacen_id = m.old_id
|
||||
SET r.almacen_id = m.new_id
|
||||
`).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if DB.Migrator().HasTable("remitos") && DB.Migrator().HasColumn("remitos", "almacen_origen_id") {
|
||||
if err := DB.Exec(`
|
||||
UPDATE remitos r JOIN tmp_almacen_map m ON r.almacen_origen_id = m.old_id
|
||||
SET r.almacen_origen_id = m.new_id
|
||||
`).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if err := DB.Exec("RENAME TABLE almacen TO almacen_viejo, almacen_nuevo TO almacen").Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if err := DB.Exec("DROP TABLE almacen_viejo").Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if err := DB.Exec("DROP TABLE tmp_almacen_map").Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
log.Println("almacen migrado")
|
||||
return nil
|
||||
}
|
||||
@@ -1,99 +0,0 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"strings"
|
||||
|
||||
"repuestera_back/models"
|
||||
models_seguridad "repuestera_back/models/seguridad"
|
||||
)
|
||||
|
||||
var formasPagoDemo = []string{
|
||||
"Transferencia",
|
||||
"Efectivo",
|
||||
"Tarjeta de Débito",
|
||||
"Tarjeta de Crédito",
|
||||
"Cheque",
|
||||
}
|
||||
|
||||
// MigrarPagos completa la preparacion posterior a AutoMigrate del modulo de
|
||||
// pagos:
|
||||
// - garantiza que pago.importe tenga la misma precision que factura.total;
|
||||
// - siembra formas de pago basicas para las empresas que todavia no tienen
|
||||
// ninguna cargada.
|
||||
//
|
||||
// Es idempotente.
|
||||
func MigrarPagos() error {
|
||||
if !DB.Migrator().HasTable("pago") {
|
||||
return nil
|
||||
}
|
||||
|
||||
if err := migrarImportePago(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return sembrarFormasPagoDemo()
|
||||
}
|
||||
|
||||
// migrarImportePago convierte pago.importe a decimal(15,2) si quedo con la
|
||||
// precision vieja. GORM no siempre detecta el cambio solo con AutoMigrate.
|
||||
func migrarImportePago() error {
|
||||
columnas, err := DB.Migrator().ColumnTypes(&models.Pago{})
|
||||
if err != nil {
|
||||
return fmt.Errorf("leer columnas de pago: %w", err)
|
||||
}
|
||||
|
||||
for _, columna := range columnas {
|
||||
if columna.Name() != "importe" {
|
||||
continue
|
||||
}
|
||||
if strings.EqualFold(columna.DatabaseTypeName(), "decimal") {
|
||||
precision, escala, ok := columna.DecimalSize()
|
||||
if ok && precision >= 15 && escala >= 2 {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
if err := DB.Migrator().AlterColumn(&models.Pago{}, "importe"); err != nil {
|
||||
return fmt.Errorf("convertir pago.importe a decimal(15,2): %w", err)
|
||||
}
|
||||
log.Printf("pagos: columna pago.importe convertida a decimal(15,2)")
|
||||
return nil
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// sembrarFormasPagoDemo crea un catalogo minimo solo cuando la empresa no
|
||||
// tiene ninguna forma de pago. No pisa catalogos existentes.
|
||||
func sembrarFormasPagoDemo() error {
|
||||
var empresas []models_seguridad.Empresa
|
||||
if err := DB.Find(&empresas).Error; err != nil {
|
||||
return fmt.Errorf("listar empresas para formas de pago: %w", err)
|
||||
}
|
||||
|
||||
for _, empresa := range empresas {
|
||||
var count int64
|
||||
if err := DB.Unscoped().Model(&models.FormaDePago{}).
|
||||
Where("empresa_id = ?", empresa.ID).
|
||||
Count(&count).Error; err != nil {
|
||||
return fmt.Errorf("contar formas de pago de empresa %d: %w", empresa.ID, err)
|
||||
}
|
||||
if count > 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
for _, descripcion := range formasPagoDemo {
|
||||
forma := models.FormaDePago{
|
||||
EmpresaID: empresa.ID,
|
||||
Descripcion: descripcion,
|
||||
}
|
||||
if err := DB.Create(&forma).Error; err != nil {
|
||||
return fmt.Errorf("crear forma de pago %s de empresa %d: %w", descripcion, empresa.ID, err)
|
||||
}
|
||||
}
|
||||
log.Printf("pagos: formas de pago iniciales creadas para empresa %d", empresa.ID)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -1,363 +0,0 @@
|
||||
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
|
||||
}
|
||||
@@ -20,10 +20,6 @@ func main() {
|
||||
log.Fatalf("failed to connect to database: %v", err)
|
||||
}
|
||||
|
||||
if err := config.MigrarAlmacen(); err != nil {
|
||||
log.Fatalf("failed to migrate almacen: %v", err)
|
||||
}
|
||||
|
||||
if err := config.DB.AutoMigrate(
|
||||
&models_seguridad.Empresa{},
|
||||
&models_seguridad.Usuario{},
|
||||
@@ -59,18 +55,6 @@ func main() {
|
||||
log.Fatalf("failed to migrate database: %v", err)
|
||||
}
|
||||
|
||||
if err := config.MigrarMultitenant(); err != nil {
|
||||
log.Fatalf("failed to migrate multitenant data: %v", err)
|
||||
}
|
||||
|
||||
if err := config.MigrarStock(); err != nil {
|
||||
log.Fatalf("failed to migrate stock data: %v", err)
|
||||
}
|
||||
|
||||
if err := config.MigrarPagos(); err != nil {
|
||||
log.Fatalf("failed to migrate payment data: %v", err)
|
||||
}
|
||||
|
||||
config.InitPermisos()
|
||||
|
||||
fmt.Println("Database connected and migrated successfully")
|
||||
|
||||
Reference in new issue
Block a user