mirror of
https://git.imnavajas.es/jjimenez/safekat.git
synced 2025-07-25 22:52:08 +00:00
Refactorizacion
This commit is contained in:
@ -0,0 +1,184 @@
|
||||
<?php
|
||||
|
||||
namespace App\Controllers\Presupuestos;
|
||||
|
||||
use App\Controllers\BaseController;
|
||||
use App\Services\PresupuestoUploaderService;
|
||||
use App\Libraries\SftpClientWrapper;
|
||||
use App\Models\Presupuestos\PresupuestoFicheroModel;
|
||||
use Config\PresupuestoSFTP;
|
||||
|
||||
class PresupuestoFicheroController extends BaseController
|
||||
{
|
||||
|
||||
|
||||
public function get_files()
|
||||
{
|
||||
// Aceptar solo POST (puedes cambiar a GET si lo necesitas)
|
||||
if ($this->request->getMethod(true) !== 'POST') {
|
||||
return $this->response->setStatusCode(405)->setJSON(['message' => 'Método no permitido']);
|
||||
}
|
||||
|
||||
$presupuesto_id = $this->request->getPost('presupuesto_id') ?? 0;
|
||||
|
||||
$model = model('App\Models\Presupuestos\PresupuestoFicheroModel');
|
||||
$files = $model->getFiles($presupuesto_id);
|
||||
|
||||
$result = [];
|
||||
|
||||
foreach ($files as $file) {
|
||||
$relativePath = $file->file_path;
|
||||
$fullPath = WRITEPATH . ltrim($relativePath, '/');
|
||||
|
||||
$relativePath = $file->file_path;
|
||||
$basename = basename($relativePath); // solo el nombre del archivo
|
||||
|
||||
$result[] = (object) [
|
||||
'name' => $file->nombre,
|
||||
'size' => file_exists(WRITEPATH . $relativePath) ? filesize(WRITEPATH . $relativePath) : 0,
|
||||
'hash' => $basename
|
||||
];
|
||||
}
|
||||
|
||||
return $this->response->setJSON($result);
|
||||
}
|
||||
|
||||
|
||||
public function upload_files()
|
||||
{
|
||||
$request = service('request');
|
||||
$model = model('App\Models\Presupuestos\PresupuestoFicheroModel');
|
||||
$files = $request->getFiles()['file'] ?? [];
|
||||
$presupuesto_id = $request->getPost('presupuesto_id');
|
||||
$old_files = json_decode($request->getPost('oldFiles') ?? '[]');
|
||||
|
||||
if (!is_array($files)) {
|
||||
$files = [$files];
|
||||
}
|
||||
|
||||
// Servicio de subida (con SFTP)
|
||||
$service = new \App\Services\PresupuestoUploaderService(
|
||||
new \App\Libraries\SftpClientWrapper(config('PresupuestoSFTP')),
|
||||
$model,
|
||||
config('PresupuestoSFTP')
|
||||
);
|
||||
|
||||
// Borrar ficheros eliminados por el usuario (BD y remoto)
|
||||
$service->removeFromRemote($presupuesto_id);
|
||||
$numDeleted = $model->deleteMissingFiles($presupuesto_id, $old_files);
|
||||
|
||||
$results = [];
|
||||
foreach ($files as $file) {
|
||||
if (!$file->isValid()) {
|
||||
$results[] = [
|
||||
'name' => $file->getName(),
|
||||
'status' => 'invalid',
|
||||
'message' => $file->getErrorString()
|
||||
];
|
||||
continue;
|
||||
}
|
||||
|
||||
$newName = $model->saveFileInBBDD(
|
||||
$presupuesto_id,
|
||||
$file->getClientName(),
|
||||
$file->getClientExtension(),
|
||||
auth()->id()
|
||||
);
|
||||
|
||||
// Crear directorio si no existe
|
||||
$uploadDir = dirname($model->getAbsolutePath($presupuesto_id, $newName));
|
||||
if (!is_dir($uploadDir)) {
|
||||
mkdir($uploadDir, 0755, true);
|
||||
}
|
||||
|
||||
$file->move($uploadDir, $newName);
|
||||
|
||||
$results[] = [
|
||||
'name' => $file->getClientName(),
|
||||
'status' => 'uploaded'
|
||||
];
|
||||
}
|
||||
|
||||
// Subida al SFTP
|
||||
$sftpResult = $service->uploadToRemote($presupuesto_id);
|
||||
|
||||
// ✅ Contar totales para mostrar en el frontend
|
||||
$numUploaded = count(array_filter($results, fn($f) => $f['status'] === 'uploaded'));
|
||||
$numErrores = count(array_filter($results, fn($f) => $f['status'] !== 'uploaded'));
|
||||
|
||||
if (!$sftpResult['success']) {
|
||||
return $this->response->setJSON([
|
||||
'message' => 'Error en la subida de algunos archivos.',
|
||||
'summary' => [
|
||||
'subidos_ok' => $numUploaded,
|
||||
'errores_locales' => $numErrores,
|
||||
'errores_remotos' => count(array_filter($sftpResult['files'], fn($f) => !$f['success'])),
|
||||
'borrados' => $numDeleted,
|
||||
],
|
||||
'details' => [
|
||||
'local' => $results,
|
||||
'sftp' => $sftpResult['files']
|
||||
]
|
||||
])->setStatusCode(500);
|
||||
}
|
||||
|
||||
return $this->response->setJSON([
|
||||
'message' => 'Archivos subidos correctamente.',
|
||||
'summary' => [
|
||||
'subidos_ok' => $numUploaded,
|
||||
'errores_locales' => $numErrores,
|
||||
'errores_remotos' => 0,
|
||||
'borrados' => $numDeleted
|
||||
],
|
||||
'details' => [
|
||||
'local' => $results,
|
||||
'sftp' => $sftpResult['files']
|
||||
]
|
||||
]);
|
||||
}
|
||||
|
||||
public function download_zip()
|
||||
{
|
||||
$presupuesto_id = $this->request->getPost('presupuesto_id');
|
||||
$ot_id = $this->request->getPost('ot_id');
|
||||
|
||||
if (!$presupuesto_id) {
|
||||
return $this->response->setStatusCode(400)->setBody('Presupuesto ID requerido');
|
||||
}
|
||||
|
||||
$prefijo = (!empty($ot_id) && is_numeric($ot_id)) ? "OT_{$ot_id}" : null;
|
||||
|
||||
$service = new \App\Services\PresupuestoUploaderService(
|
||||
new \App\Libraries\SftpClientWrapper(config('PresupuestoSFTP')),
|
||||
model('App\Models\Presupuestos\PresupuestoFicheroModel'),
|
||||
config('PresupuestoSFTP')
|
||||
);
|
||||
|
||||
$result = $service->downloadZip((int) $presupuesto_id, $prefijo);
|
||||
|
||||
if (!$result['success'] || empty($result['zipPath'])) {
|
||||
return $this->response
|
||||
->setStatusCode(500)
|
||||
->setJSON(['error' => $result['message']]);
|
||||
}
|
||||
|
||||
$zipPath = $result['zipPath'];
|
||||
|
||||
// Definir nombre final del ZIP para el cliente
|
||||
$nombreArchivo = $prefijo
|
||||
? "{$prefijo}_PRESUPUESTO_{$presupuesto_id}.zip"
|
||||
: "archivos_presupuesto_{$presupuesto_id}.zip";
|
||||
|
||||
// Eliminar archivo ZIP tras terminar la descarga (una vez enviada la respuesta)
|
||||
register_shutdown_function(function () use ($zipPath) {
|
||||
if (file_exists($zipPath)) {
|
||||
unlink($zipPath);
|
||||
}
|
||||
});
|
||||
|
||||
// Descargar el archivo al cliente
|
||||
return $this->response
|
||||
->download($zipPath, null)
|
||||
->setFileName($nombreArchivo);
|
||||
}
|
||||
}
|
||||
@ -1747,110 +1747,7 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
|
||||
}
|
||||
}
|
||||
|
||||
public function get_files()
|
||||
{
|
||||
// Aceptar solo POST (puedes cambiar a GET si lo necesitas)
|
||||
if ($this->request->getMethod(true) !== 'POST') {
|
||||
return $this->response->setStatusCode(405)->setJSON(['message' => 'Método no permitido']);
|
||||
}
|
||||
|
||||
$presupuesto_id = $this->request->getPost('presupuesto_id') ?? 0;
|
||||
|
||||
$model = model('App\Models\Presupuestos\PresupuestoFicheroModel');
|
||||
$files = $model->getFiles($presupuesto_id);
|
||||
|
||||
$result = [];
|
||||
|
||||
foreach ($files as $file) {
|
||||
$relativePath = $file->file_path;
|
||||
$fullPath = WRITEPATH . ltrim($relativePath, '/');
|
||||
|
||||
$relativePath = $file->file_path;
|
||||
$basename = basename($relativePath); // solo el nombre del archivo
|
||||
|
||||
$result[] = (object) [
|
||||
'name' => $file->nombre,
|
||||
'size' => file_exists(WRITEPATH . $relativePath) ? filesize(WRITEPATH . $relativePath) : 0,
|
||||
'hash' => $basename
|
||||
];
|
||||
}
|
||||
|
||||
return $this->response->setJSON($result);
|
||||
}
|
||||
|
||||
|
||||
|
||||
public function upload_files()
|
||||
{
|
||||
$request = service('request');
|
||||
$model = model('App\Models\Presupuestos\PresupuestoFicheroModel');
|
||||
$files = $request->getFiles()['file'] ?? [];
|
||||
$presupuesto_id = $request->getPost('presupuesto_id');
|
||||
$old_files = json_decode($request->getPost('oldFiles') ?? '[]');
|
||||
|
||||
if (!is_array($files)) {
|
||||
$files = [$files];
|
||||
}
|
||||
|
||||
// Instanciar servicio con dependencias inyectadas manualmente
|
||||
$service = new \App\Services\PresupuestoUploaderService(
|
||||
new \App\Libraries\SftpClientWrapper(config('PresupuestoSFTP')),
|
||||
$model,
|
||||
config('PresupuestoSFTP')
|
||||
);
|
||||
|
||||
// Borrar antiguos del SFTP y de la BD (pero no del disco local)
|
||||
$service->removeFromRemote($presupuesto_id);
|
||||
$model->deleteMissingFiles($presupuesto_id, $old_files);
|
||||
|
||||
$results = [];
|
||||
foreach ($files as $file) {
|
||||
if (!$file->isValid()) {
|
||||
$results[] = ['name' => $file->getName(), 'status' => 'invalid'];
|
||||
continue;
|
||||
}
|
||||
|
||||
$newName = $model->saveFileInBBDD(
|
||||
$presupuesto_id,
|
||||
$file->getClientName(),
|
||||
$file->getClientExtension(),
|
||||
auth()->id()
|
||||
);
|
||||
|
||||
$uploadPath = WRITEPATH . 'uploads/presupuestos/' . $newName;
|
||||
$file->move(dirname($uploadPath), basename($uploadPath));
|
||||
|
||||
$results[] = ['name' => $file->getClientName(), 'status' => 'uploaded'];
|
||||
}
|
||||
|
||||
// Subida al SFTP
|
||||
$sftpResult = $service->uploadToRemote($presupuesto_id);
|
||||
|
||||
// Preparar notificación
|
||||
if (!$sftpResult['success']) {
|
||||
return $this->response->setJSON([
|
||||
'message' => 'Error al subir uno o más archivos al SFTP.',
|
||||
'details' => [
|
||||
'local' => $results,
|
||||
'sftp' => $sftpResult['files']
|
||||
]
|
||||
])->setStatusCode(500);
|
||||
}
|
||||
|
||||
return $this->response->setJSON([
|
||||
'message' => 'Archivos subidos correctamente al sistema y al SFTP.',
|
||||
'details' => [
|
||||
'local' => $results,
|
||||
'sftp' => $sftpResult['files']
|
||||
]
|
||||
]);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
/***********************
|
||||
*
|
||||
@ -3657,37 +3554,5 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
|
||||
|
||||
return $servicios;
|
||||
}
|
||||
|
||||
public function download_zip()
|
||||
{
|
||||
$presupuesto_id = $this->request->getPost('presupuesto_id');
|
||||
$ot_id = $this->request->getPost('ot_id');
|
||||
|
||||
if (!$presupuesto_id) {
|
||||
return $this->response->setStatusCode(400)->setBody('Presupuesto ID requerido');
|
||||
}
|
||||
|
||||
// Definir prefijo si se recibió un ot_id válido
|
||||
$prefijo = (!empty($ot_id) && is_numeric($ot_id)) ? "OT_{$ot_id}" : null;
|
||||
|
||||
$ftpClient = new \App\Libraries\SafekatFtpClient();
|
||||
try {
|
||||
$zipPath = $ftpClient->downloadZipPresupuesto((int) $presupuesto_id, $prefijo);
|
||||
|
||||
if ($zipPath === null || !file_exists($zipPath)) {
|
||||
return $this->response->setStatusCode(404)->setBody('No se encontraron archivos');
|
||||
}
|
||||
|
||||
$nombreArchivo = $prefijo
|
||||
? "{$prefijo}_PRESUPUESTO_{$presupuesto_id}.zip"
|
||||
: "archivos_presupuesto_{$presupuesto_id}.zip";
|
||||
|
||||
return $this->response
|
||||
->download($zipPath, null)
|
||||
->setFileName($nombreArchivo);
|
||||
} catch (\Throwable $e) {
|
||||
log_message('error', $e->getMessage());
|
||||
return $this->response->setStatusCode(500)->setBody('Error interno');
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@ -3,6 +3,7 @@
|
||||
namespace App\Controllers\Sistema;
|
||||
|
||||
use CodeIgniter\Controller;
|
||||
use App\Models\Presupuestos\PresupuestoFicheroModel;
|
||||
|
||||
class Intranet extends Controller
|
||||
{
|
||||
@ -11,25 +12,24 @@ class Intranet extends Controller
|
||||
{
|
||||
helper('file');
|
||||
|
||||
$resource_path = WRITEPATH . 'uploads/presupuestos/' . $resource_name;
|
||||
$model = new PresupuestoFicheroModel();
|
||||
$file = $model->where('file_path LIKE', "%{$resource_name}")->first();
|
||||
|
||||
if (file_exists($resource_path)) {
|
||||
// Get the mime type of the file
|
||||
$mime_type = mime_content_type($resource_path);
|
||||
|
||||
// Get an instance of the Response class
|
||||
$response = service('response');
|
||||
|
||||
// Set the content type
|
||||
$response->setContentType($mime_type);
|
||||
|
||||
// Set the output
|
||||
$response->setBody(file_get_contents($resource_path));
|
||||
|
||||
// Send the response to the browser
|
||||
$response->send();
|
||||
if (!$file) {
|
||||
return service('response')->setStatusCode(404)->setBody("Archivo no encontrado");
|
||||
}
|
||||
|
||||
$resource_path = WRITEPATH . $file->file_path;
|
||||
|
||||
if (file_exists($resource_path)) {
|
||||
$mime_type = mime_content_type($resource_path);
|
||||
$response = service('response');
|
||||
$response->setContentType($mime_type);
|
||||
$response->setBody(file_get_contents($resource_path));
|
||||
$response->send();
|
||||
} else {
|
||||
return service('response')->setStatusCode(404)->setBody("Archivo no encontrado");
|
||||
}
|
||||
}
|
||||
|
||||
function tickets($resource_name)
|
||||
@ -54,7 +54,6 @@ class Intranet extends Controller
|
||||
// Send the response to the browser
|
||||
$response->send();
|
||||
}
|
||||
|
||||
}
|
||||
function orden_trabajo($ot_id, $resource_name)
|
||||
{
|
||||
@ -76,7 +75,6 @@ class Intranet extends Controller
|
||||
// Send the response to the browser
|
||||
$response->send();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
function catalogo($catalogo_id, $resource_name)
|
||||
@ -99,7 +97,5 @@ class Intranet extends Controller
|
||||
// Send the response to the browser
|
||||
$response->send();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user