mirror of
https://git.imnavajas.es/jjimenez/safekat.git
synced 2025-07-25 22:52:08 +00:00
275 lines
11 KiB
PHP
275 lines
11 KiB
PHP
<?php
|
|
|
|
namespace App\Commands;
|
|
|
|
use CodeIgniter\CLI\BaseCommand;
|
|
use CodeIgniter\CLI\CLI;
|
|
|
|
class ClienteImportar extends BaseCommand
|
|
{
|
|
protected $group = 'Safekat';
|
|
protected $name = 'cliente:importar';
|
|
protected $description = 'Importa registros desde customers a clientes solo si no existen por ID';
|
|
|
|
public function run(array $params)
|
|
{
|
|
$db = \Config\Database::connect();
|
|
$accion = $params[0] ?? 'todo';
|
|
|
|
// Mapeo de provincias
|
|
$provincias = $db->table('lg_provincias')
|
|
->select('id, nombre')
|
|
->get()
|
|
->getResultArray();
|
|
|
|
$provinciaMap = [];
|
|
foreach ($provincias as $provincia) {
|
|
$clave = trim(mb_strtolower($provincia['nombre']));
|
|
$provinciaMap[$clave] = $provincia['id'];
|
|
}
|
|
|
|
if (in_array($accion, ['clientes', 'todo'])) {
|
|
// ⬅️ aquí va tu bloque actual de importación de clientes
|
|
$insertados = 0;
|
|
$omitidos = 0;
|
|
|
|
CLI::write("Iniciando importación de clientes por ID...", 'yellow');
|
|
|
|
$clientes = $db->table('customers')
|
|
->where('deleted_at', null)
|
|
->get()
|
|
->getResultArray();
|
|
|
|
if (empty($clientes)) {
|
|
CLI::write('No se encontraron registros en "customers".', 'red');
|
|
return;
|
|
}
|
|
|
|
foreach ($clientes as $cliente) {
|
|
$id = (int) $cliente['id'];
|
|
|
|
// Verifica si ya existe en la tabla destino
|
|
$yaExiste = $db->table('clientes')->where('id', $id)->countAllResults();
|
|
|
|
if ($yaExiste) {
|
|
$omitidos++;
|
|
CLI::write("Cliente ID $id ya existe. Omitido.", 'blue');
|
|
continue;
|
|
}
|
|
|
|
$datos = [
|
|
'id' => $id,
|
|
'nombre' => $cliente['name'],
|
|
'alias' => $cliente['alias'],
|
|
'cif' => $cliente['cif'],
|
|
'direccion' => $cliente['direccion'],
|
|
'ciudad' => $cliente['ciudad'],
|
|
'comunidad_autonoma_id' => $cliente['comunidad_autonoma_id'],
|
|
'provincia_id' => $this->getProvinciaId($cliente['provincia'], $provinciaMap),
|
|
'cp' => $cliente['cp'],
|
|
'pais_id' => $cliente['pais_id'],
|
|
'telefono' => $cliente['telefono'],
|
|
'email' => $cliente['email'],
|
|
'comercial_id' => 122,
|
|
'soporte_id' => 122,
|
|
'forma_pago_id' => ($cliente['forma_pago_id'] > 6) ? 1 : $cliente['forma_pago_id'], // Si no se reconoce fijar a transferencias
|
|
'vencimiento' => $cliente['vencimiento'],
|
|
'fecha_vencimiento' => $cliente['fechaVencimiento'],
|
|
'margen' => $cliente['margen'],
|
|
'descuento' => $cliente['descuento'],
|
|
'limite_credito' => $cliente['limite_credito'],
|
|
'limite_credito_user_id' => $cliente['limite_credito_user_id'],
|
|
'limite_credito_change_at' => $cliente['limite_credito_change_at'],
|
|
'credito_asegurado' => $cliente['creditoAsegurado'],
|
|
'ccc' => $cliente['ccc'],
|
|
'ccc_cliente' => $cliente['ccc_customer'],
|
|
'num_cuenta' => $cliente['num_cuenta'],
|
|
'message_tracking' => $cliente['message_tracking'],
|
|
'message_production_start' => $cliente['message_production_start'],
|
|
'tirada_flexible' => $cliente['tirada_flexible'],
|
|
'descuento_tirada_flexible' => $cliente['descuento_tirada_flexible'],
|
|
'comentarios_tirada_flexible' => $cliente['comentarios_tirada_flexible'],
|
|
'margen_plantilla_id' => $cliente['margen_plantilla_id'],
|
|
'comentarios' => $cliente['comentarios'],
|
|
'deleted_at' => null,
|
|
'created_at' => date('Y-m-d H:i:s'),
|
|
'updated_at' => date('Y-m-d H:i:s'),
|
|
'user_created_id' => 10,
|
|
'user_update_id' => 10,
|
|
'no_envio_base' => 0,
|
|
'forzar_rotativa_pod' => 0,
|
|
];
|
|
|
|
try {
|
|
$db->table('clientes')->insert($datos);
|
|
$insertados++;
|
|
CLI::write("Cliente ID $id insertado correctamente.", 'green');
|
|
} catch (\Throwable $e) {
|
|
CLI::error("❌ Error al insertar cliente ID $id: " . $e->getMessage());
|
|
CLI::error("📦 Datos del cliente: " . json_encode($datos, JSON_PRETTY_PRINT));
|
|
$omitidos++;
|
|
continue;
|
|
}
|
|
}
|
|
|
|
CLI::write("Importación completada.", 'green');
|
|
CLI::write("Clientes insertados: $insertados", 'green');
|
|
CLI::write("Clientes ya existentes: $omitidos", 'blue');
|
|
|
|
}
|
|
|
|
if (in_array($accion, ['direcciones', 'todo'])) {
|
|
// ⬅️ aquí va tu bloque actual de importación de direcciones
|
|
CLI::write("Iniciando importación de direcciones...", 'yellow');
|
|
|
|
$direcciones = $db->table('customers_address')
|
|
->where('deleted_at', null)
|
|
->get()
|
|
->getResultArray();
|
|
|
|
$direccionesInsertadas = 0;
|
|
$direccionesOmitidas = 0;
|
|
|
|
foreach ($direcciones as $dir) {
|
|
$clienteId = (int) $dir['customer_id'];
|
|
|
|
$clienteExiste = $db->table('clientes')
|
|
->where('id', $clienteId)
|
|
->countAllResults();
|
|
|
|
if (!$clienteExiste) {
|
|
CLI::write("⚠️ Dirección ID {$dir['id']} omitida: cliente_id $clienteId no existe.", 'blue');
|
|
$direccionesOmitidas++;
|
|
continue;
|
|
}
|
|
|
|
$direccionExiste = $db->table('cliente_direcciones')
|
|
->where([
|
|
'cliente_id' => $clienteId,
|
|
'direccion' => $dir['direccion'] ?? '',
|
|
'cp' => $dir['cp'] ?? '0',
|
|
'municipio' => $dir['ciudad'] ?? '',
|
|
'provincia' => $dir['provincia'],
|
|
])
|
|
->countAllResults();
|
|
|
|
if ($direccionExiste) {
|
|
CLI::write("⚠️ Dirección ID {$dir['id']} ya existe para cliente $clienteId. Omitida.", 'blue');
|
|
$direccionesOmitidas++;
|
|
continue;
|
|
}
|
|
|
|
$nuevaDir = [
|
|
'cliente_id' => $clienteId,
|
|
'alias' => $dir['nombre'] ?? '',
|
|
'att' => $dir['persona_contacto'] ?? '',
|
|
'email' => $dir['email'],
|
|
'direccion' => $dir['direccion'] ?? '',
|
|
'pais_id' => is_numeric($dir['pais_id']) ? (int) $dir['pais_id'] : null,
|
|
'provincia' => $dir['provincia'],
|
|
'municipio' => $dir['ciudad'] ?? '',
|
|
'cp' => $dir['cp'] ?? '0',
|
|
'telefono' => $dir['telefono'],
|
|
];
|
|
|
|
try {
|
|
$db->table('cliente_direcciones')->insert($nuevaDir);
|
|
$direccionesInsertadas++;
|
|
CLI::write("✅ Dirección ID {$dir['id']} insertada para cliente $clienteId", 'green');
|
|
} catch (\Throwable $e) {
|
|
CLI::error("❌ Error al insertar dirección ID {$dir['id']} (cliente_id $clienteId): " . $e->getMessage());
|
|
$direccionesOmitidas++;
|
|
}
|
|
}
|
|
|
|
|
|
CLI::write("Importación de direcciones finalizada.", 'green');
|
|
CLI::write("Direcciones insertadas: $direccionesInsertadas", 'green');
|
|
CLI::write("Direcciones omitidas: $direccionesOmitidas", 'blue');
|
|
}
|
|
|
|
if (in_array($accion, ['contactos', 'todo'])) {
|
|
CLI::write("Iniciando importación de contactos...", 'yellow');
|
|
|
|
$contactos = $db->table('customers_contact')
|
|
->where('deleted_at', null)
|
|
->get()
|
|
->getResultArray();
|
|
|
|
$contactosInsertados = 0;
|
|
$contactosOmitidos = 0;
|
|
|
|
foreach ($contactos as $contacto) {
|
|
$clienteId = (int) $contacto['customer_id'];
|
|
|
|
// Verificar si cliente existe
|
|
$clienteExiste = $db->table('clientes')
|
|
->where('id', $clienteId)
|
|
->countAllResults();
|
|
|
|
if (!$clienteExiste) {
|
|
CLI::write("⚠️ Contacto ID {$contacto['id']} omitido: cliente_id $clienteId no existe.", 'blue');
|
|
$contactosOmitidos++;
|
|
continue;
|
|
}
|
|
|
|
// Validación para evitar duplicados básicos
|
|
$yaExiste = $db->table('cliente_contactos')
|
|
->where([
|
|
'cliente_id' => $clienteId,
|
|
'email' => $contacto['email'],
|
|
'nombre' => $contacto['nombre']
|
|
])
|
|
->countAllResults();
|
|
|
|
if ($yaExiste) {
|
|
CLI::write("⚠️ Contacto ID {$contacto['id']} ya existe para cliente $clienteId. Omitido.", 'blue');
|
|
$contactosOmitidos++;
|
|
continue;
|
|
}
|
|
|
|
$nuevoContacto = [
|
|
'cliente_id' => $clienteId,
|
|
'cargo' => $contacto['cargo'],
|
|
'nombre' => $contacto['nombre'],
|
|
'apellidos' => $contacto['apellidos'],
|
|
'telefono' => $contacto['telefono'],
|
|
'email' => $contacto['email'],
|
|
'deleted_at' => null,
|
|
'created_at' => date('Y-m-d H:i:s'),
|
|
'updated_at' => date('Y-m-d H:i:s'),
|
|
];
|
|
|
|
try {
|
|
$db->table('cliente_contactos')->insert($nuevoContacto);
|
|
$contactosInsertados++;
|
|
CLI::write("✅ Contacto ID {$contacto['id']} insertado para cliente $clienteId", 'green');
|
|
} catch (\Throwable $e) {
|
|
CLI::error("❌ Error al insertar contacto ID {$contacto['id']}: " . $e->getMessage());
|
|
$contactosOmitidos++;
|
|
}
|
|
}
|
|
|
|
CLI::write("Importación de contactos finalizada.", 'green');
|
|
CLI::write("Contactos insertados: $contactosInsertados", 'green');
|
|
CLI::write("Contactos omitidos: $contactosOmitidos", 'blue');
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
private function getProvinciaId(?string $nombre, array $map): ?int
|
|
{
|
|
if ($nombre === null) {
|
|
return null;
|
|
}
|
|
|
|
$clave = trim(mb_strtolower($nombre));
|
|
return $map[$clave] ?? null;
|
|
}
|
|
|
|
|
|
}
|