424 lines
21 KiB
PHP
424 lines
21 KiB
PHP
<?php
|
|
require_once __DIR__ . '/config.php';
|
|
|
|
try {
|
|
$pdo = db();
|
|
echo "Conexión a la base de datos exitosa.\n";
|
|
|
|
$sql_statements = [
|
|
"CREATE TABLE IF NOT EXISTS `usuarios` (
|
|
`id` INT AUTO_INCREMENT PRIMARY KEY,
|
|
`nombre` VARCHAR(255) NOT NULL,
|
|
`email` VARCHAR(255) NOT NULL UNIQUE,
|
|
`password` VARCHAR(255) NOT NULL,
|
|
`rol` ENUM('Administrador General', 'Encargado de Stock') NOT NULL,
|
|
`created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;",
|
|
|
|
"CREATE TABLE IF NOT EXISTS `productos` (
|
|
`id` INT AUTO_INCREMENT PRIMARY KEY,
|
|
`sku` VARCHAR(100) NOT NULL UNIQUE,
|
|
`nombre` VARCHAR(255) NOT NULL,
|
|
`categoria` VARCHAR(100),
|
|
`unidad` VARCHAR(50),
|
|
`precio_venta` DECIMAL(10, 2) NOT NULL DEFAULT 0.00,
|
|
`costo` DECIMAL(10, 2) NOT NULL DEFAULT 0.00,
|
|
`codigo_barras` VARCHAR(255),
|
|
`activo` BOOLEAN NOT NULL DEFAULT TRUE,
|
|
`descripcion` TEXT,
|
|
`created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;",
|
|
|
|
"CREATE TABLE IF NOT EXISTS `ciudades` (
|
|
`id` INT AUTO_INCREMENT PRIMARY KEY,
|
|
`nombre` VARCHAR(100) NOT NULL UNIQUE,
|
|
`codigo` VARCHAR(20)
|
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;",
|
|
|
|
"CREATE TABLE IF NOT EXISTS `stock_por_ciudad` (
|
|
`id` INT AUTO_INCREMENT PRIMARY KEY,
|
|
`producto_id` INT NOT NULL,
|
|
`ciudad_id` INT NOT NULL,
|
|
`stock_actual` INT NOT NULL DEFAULT 0,
|
|
`stock_minimo` INT NOT NULL DEFAULT 0,
|
|
`stock_reservado` INT NOT NULL DEFAULT 0,
|
|
FOREIGN KEY (`producto_id`) REFERENCES `productos`(`id`) ON DELETE CASCADE,
|
|
FOREIGN KEY (`ciudad_id`) REFERENCES `ciudades`(`id`) ON DELETE CASCADE,
|
|
UNIQUE KEY `producto_ciudad` (`producto_id`, `ciudad_id`)
|
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;",
|
|
|
|
"CREATE TABLE IF NOT EXISTS `movimientos` (
|
|
`id` INT AUTO_INCREMENT PRIMARY KEY,
|
|
`tipo` ENUM('Entrada', 'Salida', 'Transferencia', 'Reverso de Salida', 'Reverso de Entrada') NOT NULL,
|
|
`producto_id` INT NOT NULL,
|
|
`ciudad_origen_id` INT,
|
|
`ciudad_destino_id` INT,
|
|
`cantidad` INT NOT NULL,
|
|
`fecha` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
|
`usuario_id` INT NOT NULL,
|
|
`documento_referencia` VARCHAR(255),
|
|
`observacion` TEXT,
|
|
FOREIGN KEY (`producto_id`) REFERENCES `productos`(`id`),
|
|
FOREIGN KEY (`ciudad_origen_id`) REFERENCES `ciudades`(`id`),
|
|
FOREIGN KEY (`ciudad_destino_id`) REFERENCES `ciudades`(`id`),
|
|
FOREIGN KEY (`usuario_id`) REFERENCES `usuarios`(`id`)
|
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;",
|
|
|
|
"CREATE TABLE IF NOT EXISTS `ventas` (
|
|
`id` INT AUTO_INCREMENT PRIMARY KEY,
|
|
`nro_doc` VARCHAR(50) UNIQUE,
|
|
`fecha` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
|
`cliente` VARCHAR(255),
|
|
`ciudad_id` INT NOT NULL,
|
|
`vendedor_id` INT NOT NULL,
|
|
`estado` ENUM('Borrador', 'Confirmado', 'Anulado') NOT NULL DEFAULT 'Borrador',
|
|
`total` DECIMAL(10, 2) NOT NULL DEFAULT 0.00,
|
|
FOREIGN KEY (`ciudad_id`) REFERENCES `ciudades`(`id`),
|
|
FOREIGN KEY (`vendedor_id`) REFERENCES `usuarios`(`id`)
|
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;",
|
|
|
|
"CREATE TABLE IF NOT EXISTS `ventas_items` (
|
|
`id` INT AUTO_INCREMENT PRIMARY KEY,
|
|
`venta_id` INT NOT NULL,
|
|
`producto_id` INT NOT NULL,
|
|
`cantidad` INT NOT NULL,
|
|
`precio` DECIMAL(10, 2) NOT NULL,
|
|
FOREIGN KEY (`venta_id`) REFERENCES `ventas`(`id`) ON DELETE CASCADE,
|
|
FOREIGN KEY (`producto_id`) REFERENCES `productos`(`id`)
|
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;",
|
|
|
|
"CREATE TABLE IF NOT EXISTS `compras` (
|
|
`id` INT AUTO_INCREMENT PRIMARY KEY,
|
|
`nro_doc` VARCHAR(50) UNIQUE,
|
|
`fecha` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
|
`proveedor` VARCHAR(255),
|
|
`ciudad_id` INT NOT NULL,
|
|
`usuario_id` INT NOT NULL,
|
|
`estado` ENUM('Borrador', 'Confirmado', 'Anulado') NOT NULL DEFAULT 'Borrador',
|
|
`total` DECIMAL(10, 2) NOT NULL DEFAULT 0.00,
|
|
FOREIGN KEY (`ciudad_id`) REFERENCES `ciudades`(`id`),
|
|
FOREIGN KEY (`usuario_id`) REFERENCES `usuarios`(`id`)
|
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;",
|
|
|
|
"CREATE TABLE IF NOT EXISTS `compras_items` (
|
|
`id` INT AUTO_INCREMENT PRIMARY KEY,
|
|
`compra_id` INT NOT NULL,
|
|
`producto_id` INT NOT NULL,
|
|
`cantidad` INT NOT NULL,
|
|
`costo` DECIMAL(10, 2) NOT NULL,
|
|
FOREIGN KEY (`compra_id`) REFERENCES `compras`(`id`) ON DELETE CASCADE,
|
|
FOREIGN KEY (`producto_id`) REFERENCES `productos`(`id`)
|
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;",
|
|
|
|
"CREATE TABLE IF NOT EXISTS `bitacora` (
|
|
`id` INT AUTO_INCREMENT PRIMARY KEY,
|
|
`fecha_hora` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
|
`usuario_ejecutor` INT NOT NULL,
|
|
`tipo_operacion` VARCHAR(100) NOT NULL,
|
|
`entidad_origen` VARCHAR(100),
|
|
`id_referencia_origen` INT,
|
|
`ciudad_origen` INT,
|
|
`ciudad_destino` INT,
|
|
`before_after` JSON,
|
|
`observacion` TEXT,
|
|
FOREIGN KEY (`usuario_ejecutor`) REFERENCES `usuarios`(`id`)
|
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;",
|
|
|
|
"CREATE TABLE IF NOT EXISTS `stock_confirmaciones` (
|
|
`id` INT AUTO_INCREMENT PRIMARY KEY,
|
|
`usuario_id` INT NOT NULL,
|
|
`fecha_hora` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
|
FOREIGN KEY (`usuario_id`) REFERENCES `usuarios`(`id`) ON DELETE CASCADE
|
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;",
|
|
|
|
"CREATE TABLE IF NOT EXISTS `stock_confirmacion_ciudades` (
|
|
`confirmacion_id` INT NOT NULL,
|
|
`ciudad_id` INT NOT NULL,
|
|
PRIMARY KEY (`confirmacion_id`, `ciudad_id`),
|
|
FOREIGN KEY (`confirmacion_id`) REFERENCES `stock_confirmaciones`(`id`) ON DELETE CASCADE,
|
|
FOREIGN KEY (`ciudad_id`) REFERENCES `ciudades`(`id`) ON DELETE CASCADE
|
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;",
|
|
|
|
"CREATE TABLE IF NOT EXISTS `liquidaciones` (
|
|
`id` INT AUTO_INCREMENT PRIMARY KEY,
|
|
`fecha` DATE NOT NULL,
|
|
`monto` DECIMAL(10, 2) NOT NULL,
|
|
`ciudad_id` INT,
|
|
FOREIGN KEY (`ciudad_id`) REFERENCES `ciudades`(`id`)
|
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;",
|
|
|
|
"CREATE TABLE IF NOT EXISTS `inversiones_operativas` (
|
|
`id` INT AUTO_INCREMENT PRIMARY KEY,
|
|
`mercaderia` VARCHAR(255) NOT NULL,
|
|
`fecha` DATE NOT NULL,
|
|
`cantidad` INT NOT NULL,
|
|
`precio` DECIMAL(10, 2) NOT NULL,
|
|
`created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;",
|
|
|
|
"CREATE TABLE IF NOT EXISTS `liquidaciones_ciudades_estados` (
|
|
`id` INT AUTO_INCREMENT PRIMARY KEY,
|
|
`liquidacion_id` INT NOT NULL,
|
|
`ciudad_id` INT NOT NULL,
|
|
`fecha` DATE NOT NULL,
|
|
`estado` ENUM('Pendiente', 'Pagado') NOT NULL DEFAULT 'Pendiente',
|
|
FOREIGN KEY (`liquidacion_id`) REFERENCES `liquidaciones`(`id`) ON DELETE CASCADE,
|
|
FOREIGN KEY (`ciudad_id`) REFERENCES `ciudades`(`id`) ON DELETE CASCADE,
|
|
UNIQUE KEY `liquidacion_ciudad_fecha` (`liquidacion_id`, `ciudad_id`, `fecha`)
|
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;",
|
|
|
|
"CREATE TABLE IF NOT EXISTS `flujo_de_caja` (
|
|
`id` INT AUTO_INCREMENT PRIMARY KEY,
|
|
`fecha` DATE NOT NULL,
|
|
`bcp_yape` DECIMAL(10, 2) DEFAULT 0.00,
|
|
`banco_nacion` DECIMAL(10, 2) DEFAULT 0.00,
|
|
`interbank` DECIMAL(10, 2) DEFAULT 0.00,
|
|
`bbva` DECIMAL(10, 2) DEFAULT 0.00,
|
|
`otros_ingresos` DECIMAL(10, 2) DEFAULT 0.00,
|
|
`created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;",
|
|
|
|
"CREATE TABLE IF NOT EXISTS `kanban_columns` (
|
|
`id` INT AUTO_INCREMENT PRIMARY KEY,
|
|
`nombre` VARCHAR(255) NOT NULL,
|
|
`orden` INT NOT NULL DEFAULT 0
|
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;",
|
|
|
|
"CREATE TABLE IF NOT EXISTS `info_productos` (
|
|
`id` INT AUTO_INCREMENT PRIMARY KEY,
|
|
`producto_id` INT NOT NULL,
|
|
`imagen_url` VARCHAR(255) NOT NULL,
|
|
`texto_informativo` TEXT,
|
|
`created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
|
`column_id` INT,
|
|
`orden` INT NOT NULL DEFAULT 0,
|
|
FOREIGN KEY (`producto_id`) REFERENCES `productos`(`id`) ON DELETE CASCADE,
|
|
FOREIGN KEY (`column_id`) REFERENCES `kanban_columns`(`id`) ON DELETE SET NULL
|
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;"
|
|
];
|
|
|
|
foreach ($sql_statements as $sql) {
|
|
$pdo->exec($sql);
|
|
echo "Ejecutado: " . substr($sql, 0, 50) . "...\n";
|
|
}
|
|
echo "Todas las tablas fueron creadas exitosamente.\n";
|
|
|
|
// Add column_id to info_productos if it doesn't exist
|
|
$stmt = $pdo->prepare("SELECT COUNT(*) FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = 'info_productos' AND column_name = 'column_id'");
|
|
$stmt->execute();
|
|
if ($stmt->fetchColumn() == 0) {
|
|
$pdo->exec("ALTER TABLE `info_productos` ADD `column_id` INT NULL DEFAULT NULL AFTER `texto_informativo`;");
|
|
$pdo->exec("ALTER TABLE `info_productos` ADD FOREIGN KEY (`column_id`) REFERENCES `kanban_columns`(`id`) ON DELETE SET NULL;");
|
|
echo "Columna 'column_id' añadida a la tabla 'info_productos'.\n";
|
|
} else {
|
|
echo "La columna 'column_id' ya existe en la tabla 'info_productos'.\n";
|
|
}
|
|
|
|
// Add orden to info_productos if it doesn't exist
|
|
$stmt = $pdo->prepare("SELECT COUNT(*) FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = 'info_productos' AND column_name = 'orden'");
|
|
$stmt->execute();
|
|
if ($stmt->fetchColumn() == 0) {
|
|
$pdo->exec("ALTER TABLE `info_productos` ADD `orden` INT NOT NULL DEFAULT 0;");
|
|
echo "Columna 'orden' añadida a la tabla 'info_productos'.\n";
|
|
} else {
|
|
echo "La columna 'orden' ya existe en la tabla 'info_productos'.\n";
|
|
}
|
|
|
|
// Add fecha_actualizacion to stock_confirmaciones if it doesn't exist
|
|
$stmt = $pdo->prepare("SELECT COUNT(*) FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = 'stock_confirmaciones' AND column_name = 'fecha_actualizacion'");
|
|
$stmt->execute();
|
|
if ($stmt->fetchColumn() == 0) {
|
|
$pdo->exec("ALTER TABLE `stock_confirmaciones` ADD `fecha_actualizacion` DATE DEFAULT NULL AFTER `fecha_hora`");
|
|
echo "Columna 'fecha_actualizacion' añadida a la tabla 'stock_confirmaciones'.\n";
|
|
} else {
|
|
echo "La columna 'fecha_actualizacion' ya existe en la tabla 'stock_confirmaciones'.\n";
|
|
}
|
|
|
|
// Add precio_liquidacion column to movimientos table if it doesn't exist
|
|
$stmt = $pdo->prepare("SELECT COUNT(*) FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = 'movimientos' AND column_name = 'precio_liquidacion'");
|
|
$stmt->execute();
|
|
if ($stmt->fetchColumn() == 0) {
|
|
$pdo->exec("ALTER TABLE `movimientos` ADD `precio_liquidacion` DECIMAL(10, 2) DEFAULT NULL;");
|
|
echo "Columna 'precio_liquidacion' añadida a la tabla 'movimientos'.\n";
|
|
} else {
|
|
echo "La columna 'precio_liquidacion' ya existe en la tabla 'movimientos'.\n";
|
|
}
|
|
|
|
// Add cantidad_pedidos column to movimientos table if it doesn't exist
|
|
$stmt = $pdo->prepare("SELECT COUNT(*) FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = 'movimientos' AND column_name = 'cantidad_pedidos'");
|
|
$stmt->execute();
|
|
if ($stmt->fetchColumn() == 0) {
|
|
$pdo->exec("ALTER TABLE `movimientos` ADD `cantidad_pedidos` INT DEFAULT NULL;");
|
|
echo "Columna 'cantidad_pedidos' añadida a la tabla 'movimientos'.\n";
|
|
} else {
|
|
echo "La columna 'cantidad_pedidos' ya existe en la tabla 'movimientos'.\n";
|
|
}
|
|
|
|
// Insertar ciudades iniciales
|
|
$ciudades = [
|
|
'Lima', 'Arequipa', 'Piura', 'Cusco', 'Trujillo',
|
|
'Chiclayo', 'Iquitos', 'Tacna', 'Puno', 'Huancayo'
|
|
];
|
|
$stmt = $pdo->prepare("INSERT IGNORE INTO `ciudades` (`nombre`) VALUES (:nombre)");
|
|
echo "Insertando ciudades...\n";
|
|
foreach ($ciudades as $ciudad) {
|
|
$stmt->execute(['nombre' => $ciudad]);
|
|
}
|
|
echo "Ciudades insertadas.\n";
|
|
|
|
// Añadir columna de orden si no existe
|
|
$stmt = $pdo->prepare("SELECT COUNT(*) FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = 'ciudades' AND column_name = 'orden'");
|
|
$stmt->execute();
|
|
if ($stmt->fetchColumn() == 0) {
|
|
$pdo->exec("ALTER TABLE `ciudades` ADD `orden` INT NOT NULL DEFAULT 0;");
|
|
echo "Columna 'orden' añadida a la tabla 'ciudades'.\n";
|
|
|
|
// Asignar un orden inicial a las ciudades existentes
|
|
$pdo->exec("SET @i = 0; UPDATE `ciudades` SET `orden` = (@i:=@i+1) ORDER BY `nombre`;");
|
|
echo "Orden inicial asignado a las ciudades existentes.\n";
|
|
} else {
|
|
echo "La columna 'orden' ya existe en la tabla 'ciudades'.\n";
|
|
}
|
|
|
|
// Añadir columna de orden a productos si no existe
|
|
$stmt = $pdo->prepare("SELECT COUNT(*) FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = 'productos' AND column_name = 'orden'");
|
|
$stmt->execute();
|
|
if ($stmt->fetchColumn() == 0) {
|
|
$pdo->exec("ALTER TABLE `productos` ADD `orden` INT NOT NULL DEFAULT 0;");
|
|
echo "Columna 'orden' añadida a la tabla 'productos'.\n";
|
|
|
|
// Asignar un orden inicial a los productos existentes
|
|
$pdo->exec("SET @i = 0; UPDATE `productos` SET `orden` = (@i:=@i+1) ORDER BY `nombre`;");
|
|
echo "Orden inicial asignado a los productos existentes.\n";
|
|
} else {
|
|
echo "La columna 'orden' ya existe en la tabla 'productos'.\n";
|
|
}
|
|
|
|
// --- Migration for liquidaciones_ciudades_estados ---
|
|
echo "Verificando estructura de 'liquidaciones_ciudades_estados'...\n";
|
|
|
|
// Ensure 'fecha' column exists
|
|
$stmt_col = $pdo->prepare("SELECT COUNT(*) FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = 'liquidaciones_ciudades_estados' AND column_name = 'fecha'");
|
|
$stmt_col->execute();
|
|
if ($stmt_col->fetchColumn() == 0) {
|
|
// This block might run on a partially migrated DB
|
|
echo "Añadiendo columna 'fecha'...\n";
|
|
$pdo->exec("ALTER TABLE `liquidaciones_ciudades_estados` ADD `fecha` DATE NOT NULL AFTER `ciudad_id`;");
|
|
|
|
// Drop old key if it exists
|
|
$stmt_key = $pdo->prepare("SHOW KEYS FROM `liquidaciones_ciudades_estados` WHERE Key_name = 'liquidacion_ciudad'");
|
|
$stmt_key->execute();
|
|
if ($stmt_key->fetch()) {
|
|
$pdo->exec("ALTER TABLE `liquidaciones_ciudades_estados` DROP KEY `liquidacion_ciudad`;");
|
|
}
|
|
|
|
// Add new unique key
|
|
$pdo->exec("ALTER TABLE `liquidaciones_ciudades_estados` ADD UNIQUE KEY `liquidacion_ciudad_fecha` (`liquidacion_id`, `ciudad_id`, `fecha`);");
|
|
}
|
|
|
|
// Ensure foreign key to 'liquidaciones' exists
|
|
$stmt_fk = $pdo->prepare("SELECT COUNT(*) FROM information_schema.key_column_usage WHERE table_schema = DATABASE() AND table_name = 'liquidaciones_ciudades_estados' AND column_name = 'liquidacion_id' AND referenced_table_name = 'liquidaciones';");
|
|
$stmt_fk->execute();
|
|
if ($stmt_fk->fetchColumn() == 0) {
|
|
echo "Añadiendo clave foránea a 'liquidaciones'...\n";
|
|
// Truncate before adding FK to prevent integrity errors from old data
|
|
$pdo->exec("TRUNCATE TABLE `liquidaciones_ciudades_estados`;");
|
|
$pdo->exec("ALTER TABLE `liquidaciones_ciudades_estados` ADD FOREIGN KEY (`liquidacion_id`) REFERENCES `liquidaciones`(`id`) ON DELETE CASCADE;");
|
|
echo "Clave foránea añadida.\n";
|
|
}
|
|
|
|
echo "Verificación de 'liquidaciones_ciudades_estados' completada.\n";
|
|
|
|
// Find and drop the problematic foreign key if it exists
|
|
$stmt = $pdo->prepare("SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'liquidaciones_ciudades_estados' AND COLUMN_NAME = 'liquidacion_id' AND REFERENCED_TABLE_NAME = 'liquidaciones';");
|
|
$stmt->execute();
|
|
$constraint_name = $stmt->fetchColumn();
|
|
|
|
if ($constraint_name) {
|
|
$pdo->exec("ALTER TABLE `liquidaciones_ciudades_estados` DROP FOREIGN KEY `{$constraint_name}`;");
|
|
echo "Clave foránea '{$constraint_name}' eliminada de la tabla 'liquidaciones_ciudades_estados'.\n";
|
|
} else {
|
|
echo "La clave foránea de liquidacion_id en liquidaciones_ciudades_estados a liquidaciones no existe o ya fue eliminada.\n";
|
|
}
|
|
|
|
// Crear usuario administrador por defecto
|
|
$admin_email = 'admin@example.com';
|
|
$admin_pass = 'admin123';
|
|
$hashed_pass = password_hash($admin_pass, PASSWORD_DEFAULT);
|
|
|
|
$stmt = $pdo->prepare("SELECT id FROM `usuarios` WHERE `email` = :email");
|
|
$stmt->execute(['email' => $admin_email]);
|
|
if ($stmt->fetchColumn()) {
|
|
echo "El usuario administrador ya existe.\n";
|
|
} else {
|
|
$stmt = $pdo->prepare("INSERT INTO `usuarios` (`nombre`, `email`, `password`, `rol`) VALUES (:nombre, :email, :password, :rol)");
|
|
$stmt->execute([
|
|
'nombre' => 'Administrador',
|
|
'email' => $admin_email,
|
|
'password' => $hashed_pass,
|
|
'rol' => 'Administrador General'
|
|
]);
|
|
echo "Usuario administrador creado exitosamente.\n";
|
|
echo "Email: " . $admin_email . "\n";
|
|
echo "Contraseña: " . $admin_pass . "\n";
|
|
}
|
|
|
|
|
|
// Rename 'otros' to 'otros_ingresos' in 'flujo_de_caja' if necessary
|
|
$stmt_check_otros = $pdo->prepare("SELECT COUNT(*) FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = 'flujo_de_caja' AND column_name = 'otros'");
|
|
$stmt_check_otros->execute();
|
|
$otros_exists = $stmt_check_otros->fetchColumn() > 0;
|
|
|
|
$stmt_check_otros_ingresos = $pdo->prepare("SELECT COUNT(*) FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = 'flujo_de_caja' AND column_name = 'otros_ingresos'");
|
|
$stmt_check_otros_ingresos->execute();
|
|
$otros_ingresos_exists = $stmt_check_otros_ingresos->fetchColumn() > 0;
|
|
|
|
if ($otros_exists && !$otros_ingresos_exists) {
|
|
$pdo->exec("ALTER TABLE `flujo_de_caja` CHANGE `otros` `otros_ingresos` DECIMAL(10, 2) DEFAULT 0.00;");
|
|
echo "Columna 'otros' renombrada a 'otros_ingresos' en la tabla 'flujo_de_caja'.\n";
|
|
} else {
|
|
echo "La columna 'otros_ingresos' ya existe o la columna 'otros' no fue encontrada en 'flujo_de_caja'.\n";
|
|
}
|
|
|
|
|
|
// Add new columns to flujo_de_caja if they don't exist
|
|
$new_columns = [
|
|
'fl_1' => 'DECIMAL(10, 2) DEFAULT 0.00',
|
|
'tu1' => 'DECIMAL(10, 2) DEFAULT 0.00',
|
|
'tu2' => 'DECIMAL(10, 2) DEFAULT 0.00',
|
|
'tu3' => 'DECIMAL(10, 2) DEFAULT 0.00',
|
|
'fl_2' => 'DECIMAL(10, 2) DEFAULT 0.00',
|
|
'fl_3' => 'DECIMAL(10, 2) DEFAULT 0.00',
|
|
'rc_envio' => 'DECIMAL(10, 2) NOT NULL DEFAULT 0.00'
|
|
];
|
|
|
|
foreach ($new_columns as $column_name => $column_definition) {
|
|
$stmt = $pdo->prepare("SELECT COUNT(*) FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = 'flujo_de_caja' AND column_name = :column_name");
|
|
$stmt->execute(['column_name' => $column_name]);
|
|
if ($stmt->fetchColumn() == 0) {
|
|
$pdo->exec("ALTER TABLE `flujo_de_caja` ADD `{$column_name}` {$column_definition}");
|
|
echo "Columna '{$column_name}' añadida a la tabla 'flujo_de_caja'.\n";
|
|
} else {
|
|
echo "La columna '{$column_name}' ya existe en la tabla 'flujo_de_caja'.\n";
|
|
}
|
|
}
|
|
|
|
// --- Migration for inversiones_operativas ---
|
|
echo "Verificando estructura de 'inversiones_operativas'...";
|
|
$stmt_check_desc = $pdo->prepare("SELECT COUNT(*) FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = 'inversiones_operativas' AND column_name = 'descripcion'");
|
|
$stmt_check_desc->execute();
|
|
if ($stmt_check_desc->fetchColumn() > 0) {
|
|
echo "Migrando tabla 'inversiones_operativas'. Cambiando columnas...";
|
|
$pdo->exec("ALTER TABLE `inversiones_operativas` DROP COLUMN `descripcion`;");
|
|
$pdo->exec("ALTER TABLE `inversiones_operativas` DROP COLUMN `monto`;");
|
|
$pdo->exec("ALTER TABLE `inversiones_operativas` ADD `mercaderia` VARCHAR(255) NOT NULL AFTER `id`;");
|
|
$pdo->exec("ALTER TABLE `inversiones_operativas` ADD `cantidad` INT NOT NULL AFTER `fecha`;");
|
|
$pdo->exec("ALTER TABLE `inversiones_operativas` ADD `precio` DECIMAL(10, 2) NOT NULL AFTER `cantidad`;");
|
|
echo "Tabla 'inversiones_operativas' actualizada a la nueva estructura.";
|
|
} else {
|
|
echo "La tabla 'inversiones_operativas' ya tiene la nueva estructura.";
|
|
}
|
|
|
|
} catch (PDOException $e) {
|
|
die("Error en la base de datos: " . $e->getMessage());
|
|
} |