mirror of
https://git.imnavajas.es/jjimenez/safekat.git
synced 2025-07-25 22:52:08 +00:00
Compare commits
563 Commits
feat/ot-pd
...
41ac08fcd8
| Author | SHA1 | Date | |
|---|---|---|---|
| 41ac08fcd8 | |||
| 709a802db4 | |||
| 5e8a36a345 | |||
| 54816180df | |||
| 0a8ecdb939 | |||
| e3c4cf48ed | |||
| 1d7f2e044f | |||
| 702e6bf77c | |||
| 599fce7f2f | |||
| e01b824045 | |||
| cc757b5db3 | |||
| df21b5ba05 | |||
| 2639fe705e | |||
| 3f65c9e92a | |||
| e804aa3768 | |||
| f73472c729 | |||
| 4ffd280302 | |||
| d1cbb8eb24 | |||
| 3f6037de76 | |||
| 619fd9beba | |||
| e69503c273 | |||
| 6a3a825b26 | |||
| 1ef6d476fe | |||
| 2f6e27d4ca | |||
| 38f6656842 | |||
| d31830cf1a | |||
| f40e88ed6e | |||
| 7e7b39fc38 | |||
| 6c94858d8c | |||
| c79ae6245c | |||
| 107e66a2be | |||
| be3e9a47c2 | |||
| 45ec831f8f | |||
| 9aa7d2e0cb | |||
| 40391405eb | |||
| 7bfe9c002a | |||
| d5c51f2063 | |||
| 61d8dca583 | |||
| e257a3516e | |||
| 26249c893c | |||
| b9360ef7e5 | |||
| 911124287f | |||
| 18b96f020b | |||
| 055274d6df | |||
| f900ace902 | |||
| 401c2c8f5a | |||
| 594da68b3a | |||
| 8a32e13eb4 | |||
| 34701e5960 | |||
| 364b9f8ccd | |||
| 813e5b1980 | |||
| b3336273d0 | |||
| bbd2a389af | |||
| 8007e33760 | |||
| 266e872f8f | |||
| b11b1807d8 | |||
| f5a58dc32d | |||
| ee9e3eb143 | |||
| 5c34316bc2 | |||
| 91f22fd3fb | |||
| 102ba8267b | |||
| 508758331d | |||
| 416b4db915 | |||
| bdb1d1aaec | |||
| bdc0252c72 | |||
| 47eafa75ec | |||
| 4e2003b8b8 | |||
| 5590076d7d | |||
| ddf3255a8a | |||
| 4694d62cd4 | |||
| 0c85af66da | |||
| f6ffa20d5f | |||
| 53ec5945e8 | |||
| 9fcda514f0 | |||
| 410d21dc5f | |||
| 4a60bcdd61 | |||
| 33a196667e | |||
| 03b43de185 | |||
| 2d267386a6 | |||
| 7e82142b38 | |||
| b240107565 | |||
| 647c0bd72d | |||
| 847b476341 | |||
| 6081a34c05 | |||
| c3bce03921 | |||
| 0b598e14d7 | |||
| 83753d1784 | |||
| c35e683089 | |||
| c9b822c9c2 | |||
| ff9ce9eda2 | |||
| 41fde19f43 | |||
| 3b0da8d560 | |||
| fc68676c29 | |||
| 365a487791 | |||
| 9c505584b1 | |||
| 94b72073e4 | |||
| 0b3574ca63 | |||
| cf8ddb3156 | |||
| fd81a188d4 | |||
| 4bfc679c3e | |||
| 819f297e90 | |||
| da0ca27c8c | |||
| 75ac2e0218 | |||
| d89d140dac | |||
| 4da6ee19c6 | |||
| 4fde46a222 | |||
| 55b10a7266 | |||
| 219bdfeaa3 | |||
| 1f5a625513 | |||
| beefc2f416 | |||
| 73fe7e5097 | |||
| 7d1eef9b28 | |||
| 018119a3c3 | |||
| b2652fc277 | |||
| 6c020375be | |||
| 45bd973507 | |||
| 75020a075c | |||
| 900e0b373e | |||
| 00073b3f7e | |||
| 154dfd14f6 | |||
| 8288219872 | |||
| db91776747 | |||
| 70087a24b6 | |||
| 505cc6fb31 | |||
| b0bceb20bc | |||
| b31d9b94eb | |||
| ae60955b3f | |||
| ee4de11cca | |||
| 7aa577f316 | |||
| 882cc913de | |||
| 4fe8930217 | |||
| 0bcd9899ef | |||
| 6967a61d93 | |||
| e53626bbfe | |||
| 808bcd3847 | |||
| e0974068a0 | |||
| d3bcd295cb | |||
| 6a3a10c7e8 | |||
| e2ff0f6667 | |||
| 3a0f355ffe | |||
| 87661d855d | |||
| 95ffb22c84 | |||
| 0e802f791b | |||
| 5a9326ae82 | |||
| 06ba0c0500 | |||
| 760144b5fc | |||
| 49140cea40 | |||
| 6a9331747e | |||
| fb292520a2 | |||
| 909228512c | |||
| 602fb591f9 | |||
| 764d5c8f29 | |||
| b1cd63f665 | |||
| 5058ae488b | |||
| 10889a9e7f | |||
| 8d363b8abd | |||
| 63866b6f2f | |||
| 4e65361df8 | |||
| 391927aaf6 | |||
| 96e12c0192 | |||
| 7f88ea7296 | |||
| 884f9f1a67 | |||
| c5dc026c33 | |||
| 5fbb6cc854 | |||
| 40439b532f | |||
| 84693d5c6c | |||
| 2c711c526b | |||
| a12f034daa | |||
| e732b36ece | |||
| 5fcc1bdd9d | |||
| da57cb23ee | |||
| e1aa62f198 | |||
| 50e8c35ef3 | |||
| f10d584453 | |||
| 67c4b4bc93 | |||
| 23a577b55e | |||
| 6ca84232fa | |||
| 95e153adbb | |||
| 4e8265d8a5 | |||
| e9986dd3bb | |||
| 96bc9cde73 | |||
| b9c18bf78c | |||
| 784789841d | |||
| 744680198b | |||
| f42063dd4c | |||
| 53ce60f6de | |||
| b5128bdcaf | |||
| 1350c04060 | |||
| 8ab2c28686 | |||
| b7563598e0 | |||
| 192525ebae | |||
| 78c4082596 | |||
| e0da3b56c7 | |||
| be16690f73 | |||
| aaf2ee6fd3 | |||
| 81393317b7 | |||
| 2f1b34f668 | |||
| 52c53e6920 | |||
| 3b43551064 | |||
| e5389db7be | |||
| 3db124ea24 | |||
| cd0a1c3c2a | |||
| 97568151a6 | |||
| a6fc99e726 | |||
| a86bdcac53 | |||
| 303fde9861 | |||
| 0cd68f369e | |||
| 6dc91bfa4c | |||
| 43e0ced1bd | |||
| 981eb30c02 | |||
| e070e5101e | |||
| 55ac2b4bcb | |||
| 4da8981cd8 | |||
| e625dd1e76 | |||
| e3c202ae64 | |||
| b084d1bd7c | |||
| 611df53de1 | |||
| aba97202cc | |||
| b775f65b3a | |||
| 690eaf4195 | |||
| 1e47b58400 | |||
| dd530b8b89 | |||
| e33e5e0840 | |||
| 2faa88297e | |||
| 306ae02a10 | |||
| 242029714d | |||
| edbca8fc6e | |||
| cb17d661a8 | |||
| 5f76e0e437 | |||
| 976c7980d4 | |||
| 42edf2bbc0 | |||
| 64337257ee | |||
| 2ef98a9496 | |||
| b500229b37 | |||
| 438000ebad | |||
| decdcf3703 | |||
| f5a015bc6d | |||
| 359e13260f | |||
| cfdc8d64e1 | |||
| 22bdb9b960 | |||
| 1991691533 | |||
| 760b9bdd94 | |||
| ce124cb38a | |||
| 778ef712e9 | |||
| bc7929f44b | |||
| 438e696e88 | |||
| 199e5f2018 | |||
| cb15fbe94a | |||
| fa77952ea6 | |||
| 88d6b69857 | |||
| 7ffaec042c | |||
| 6ba2694733 | |||
| 15ce7ed670 | |||
| 565ef7f170 | |||
| f3c92fa205 | |||
| 6ee4b1e89d | |||
| d253183ab6 | |||
| 3e6ba658cd | |||
| de536b894d | |||
| 836ace0e42 | |||
| bbea2229d7 | |||
| 90a47aa6bb | |||
| 59609df471 | |||
| 43ae427137 | |||
| 36a2740eb7 | |||
| 0a9d1ef68d | |||
| a9d9dbab5c | |||
| 79dc8ca713 | |||
| f7d08b9c79 | |||
| f4ef874568 | |||
| 6537e16a0a | |||
| 5d228cc10c | |||
| ed9f67badd | |||
| ff7ed8f594 | |||
| ec4d00e0ab | |||
| 85318aa10e | |||
| a4782358c6 | |||
| 528f117c7c | |||
| 6775646ec3 | |||
| efef0c0199 | |||
| 5057586987 | |||
| 15227998aa | |||
| 456dc7ff18 | |||
| 89bcd0bda1 | |||
| 1a1f5947a0 | |||
| 999553f767 | |||
| 89e6d0787a | |||
| cbe8ee0f5c | |||
| 51d0a1bcfe | |||
| eeba76b124 | |||
| 33a3ccb832 | |||
| d3dd18a156 | |||
| cab7bc3daf | |||
| 804d8ba28b | |||
| 7101c8934e | |||
| 20594bd44c | |||
| c2011e1c25 | |||
| 8b340b76d3 | |||
| 5ae2827623 | |||
| f6b8d2ba85 | |||
| ddd7c471a1 | |||
| 30c5b06d3d | |||
| aac8ab24be | |||
| 99ffe1f462 | |||
| caac71a48d | |||
| 478077721b | |||
| 10b5ae911a | |||
| 43fef3a1a0 | |||
| c6fb4b3213 | |||
| 247fa7e6f9 | |||
| 21e907ad50 | |||
| bf146d4024 | |||
| 68a39bd749 | |||
| 514905ff47 | |||
| 75f06c44a1 | |||
| 4120ded07b | |||
| 24fc4ff1c1 | |||
| 899365f2c2 | |||
| 302d12da1e | |||
| 659d1d17ea | |||
| ff5d853032 | |||
| ba6f92b3e6 | |||
| 1ebc22c74b | |||
| 785b9ea693 | |||
| d2c6d131b3 | |||
| df1f003cbd | |||
| 3936e3175a | |||
| 571338c4b3 | |||
| 5e5cff9eae | |||
| 1d75f825a4 | |||
| 95e10820a3 | |||
| b41dc836c7 | |||
| 4afcf05049 | |||
| 0ecd18f5ff | |||
| ff648fec87 | |||
| b5c1053f8c | |||
| 4701329d25 | |||
| 7a119eb197 | |||
| 3f8b7981c7 | |||
| fa6e9208a1 | |||
| 1f1bd32fa4 | |||
| 8100350e3b | |||
| 2af2dcdbb8 | |||
| 1c581db4cf | |||
| b4dfdfa101 | |||
| 8cbe5a7051 | |||
| 46176adc70 | |||
| 67bac8f666 | |||
| ba3f4ab43c | |||
| 058857e51b | |||
| 5ce6859a2f | |||
| 2bfdd89085 | |||
| 305eea00e6 | |||
| 8ea6128109 | |||
| 7b645539e3 | |||
| fb7f2a28d9 | |||
| 39639d9ff8 | |||
| 3f90665c39 | |||
| 71e70bf551 | |||
| db70c57fb3 | |||
| 91b044bbae | |||
| a88ffda50d | |||
| d7a85ca04f | |||
| 746955c3b1 | |||
| 8ca0a40b2b | |||
| 20c009f445 | |||
| 5138681718 | |||
| 9283059f9d | |||
| b75278f449 | |||
| 3fb944ff97 | |||
| c7250cb8fd | |||
| 7a9b2af8a6 | |||
| cf5a42de8d | |||
| a259d76e5e | |||
| f696153d74 | |||
| 9181905233 | |||
| 0ec7dff479 | |||
| b0fb0f18fb | |||
| cf4c4df80a | |||
| 36c9227586 | |||
| 4e9dfb51c7 | |||
| 5aab9a33ac | |||
| ea762a09c0 | |||
| 21014d029f | |||
| 9c31f2bbc5 | |||
| b288ca498c | |||
| 96a6845c0c | |||
| eed5c0994e | |||
| e2ab42cd84 | |||
| 7da76af866 | |||
| bf1e66d746 | |||
| adccc414be | |||
| 95fa192cb9 | |||
| 9310d2dabd | |||
| 3abf45ca6e | |||
| 6ea22066c2 | |||
| bf21a336b1 | |||
| d1e5731d1d | |||
| 029757bb40 | |||
| bb4c9690b9 | |||
| 6d45a950df | |||
| 6f8890a8b1 | |||
| c093c01c00 | |||
| a4532a7ff6 | |||
| 31a12ff343 | |||
| 1d6f5fe53e | |||
| 0b767c63e9 | |||
| e464652fe2 | |||
| dd20f2a20e | |||
| 97554bffc9 | |||
| 73e9e941ed | |||
| 05720cf1ce | |||
| 04e9e3ee6f | |||
| 9804a6a927 | |||
| 3402e67fb2 | |||
| b1932e6f85 | |||
| 13ae70236e | |||
| 4d8332e625 | |||
| c75d08b3c3 | |||
| a0b5f3b4df | |||
| 0e444295e3 | |||
| ae7707057a | |||
| ff115f4f20 | |||
| 45e41c77e4 | |||
| ae456c8890 | |||
| e8958dc893 | |||
| b0ac132e59 | |||
| b50e564641 | |||
| 894770d6ce | |||
| 367c7c2ea8 | |||
| 9375b9b624 | |||
| 9a6a4f89a2 | |||
| 7f31e65960 | |||
| 5aa2a2e6c9 | |||
| dfbcb13ba5 | |||
| 033184cfa2 | |||
| 25b6d14423 | |||
| 96bd24ae8b | |||
| b5b86b4164 | |||
| ef173ab0fc | |||
| f473caf06c | |||
| 5e8a7f8bd4 | |||
| 905112334f | |||
| d0f37cb714 | |||
| 151e4a2d7a | |||
| 05ebfa06df | |||
| dafdf68c41 | |||
| 4379a9d23b | |||
| cc2c9eee1c | |||
| b942064608 | |||
| 52b3b1ae4d | |||
| 86dafb1133 | |||
| 5c68334e9a | |||
| f16654f4ad | |||
| a1fd7075d6 | |||
| 4fd242d4d2 | |||
| 3838bcb536 | |||
| e2011529b4 | |||
| 616c12002e | |||
| ab36e86bdb | |||
| 1ce4ac36a6 | |||
| 7bfb49f412 | |||
| f7b9c23f69 | |||
| f7d1c59c6a | |||
| e918b5f400 | |||
| 8b949a3173 | |||
| e0916b567c | |||
| 3779b3b8a0 | |||
| 6175da1d61 | |||
| 9473c10f97 | |||
| 800d32afde | |||
| 00401aaf7f | |||
| 919c80fa9b | |||
| b5b4d6b026 | |||
| 5ac1e3d4c1 | |||
| 7dee2c26e8 | |||
| 649a244a10 | |||
| 288a3f02eb | |||
| 952500e10e | |||
| 2cfe03b2ec | |||
| b28c0d9f71 | |||
| 01c7da8ca6 | |||
| 13128ebdae | |||
| 6016b6145c | |||
| 6450231b53 | |||
| b86acc3949 | |||
| 92a6a3c16c | |||
| 62a95a0ca8 | |||
| ed5f73db25 | |||
| ddf02f73b8 | |||
| b555e988be | |||
| 2050f0ae1e | |||
| fc1b69f2fe | |||
| 946527cc1a | |||
| 33d3e74e80 | |||
| 67a7cda036 | |||
| ed28263994 | |||
| 0d24e50d01 | |||
| a27536e406 | |||
| 4af34d7ba4 | |||
| 753aafe05d | |||
| 63254f0bf3 | |||
| 0afd31aae0 | |||
| dd723f9889 | |||
| 703781e115 | |||
| 9ae3d8707c | |||
| c344274f9d | |||
| e18a39938b | |||
| 5ebf2c670f | |||
| 12e06937c4 | |||
| fe164c4ab3 | |||
| 9cb7762905 | |||
| 548a444b7d | |||
| 969966ac78 | |||
| b318721b90 | |||
| a137ede1a7 | |||
| 5eaa5fea0b | |||
| 19fd76e910 | |||
| 14b5f4bf95 | |||
| 61abcb3dbd | |||
| f2ea93ddb6 | |||
| 31524dcf61 | |||
| c3d38e29a4 | |||
| f93ecda648 | |||
| 49f9fe4009 | |||
| 65c9b34f56 | |||
| 46c29f3c13 | |||
| 0b04e6dabd | |||
| 15f6d0d675 | |||
| 3949607a3c | |||
| 9e90ec798c | |||
| 76baae9e92 | |||
| 52a4e7d37b | |||
| 972d0c4ec8 | |||
| 36f5d42d03 | |||
| c28753e1f1 | |||
| 8e97e7b58c | |||
| f19d2b7ffe | |||
| 2a8c4b9da6 | |||
| d50b511e83 | |||
| 3ada529b6e | |||
| 02a64fa40a | |||
| c42f223b9a | |||
| 173afe403e | |||
| c76f4428a6 | |||
| 6a4e753a06 | |||
| 6d5b8ab621 | |||
| a74021f97d | |||
| 725ea61078 | |||
| 6a4e9b611e | |||
| fedc608463 | |||
| 4667e77144 | |||
| 7cf1bf006d | |||
| 67e588dd67 | |||
| 16dc39ee15 | |||
| c157b1215c | |||
| c226f031d9 | |||
| f9909bd8cd | |||
| c75a2f9ef4 | |||
| f0a4f19089 | |||
| e2da90926d | |||
| 5e8da603f9 | |||
| 9981f878d1 |
7
.vscode/sftp.json
vendored
7
.vscode/sftp.json
vendored
@ -24,10 +24,15 @@
|
||||
"username": "sk-dev",
|
||||
"password": "KXvYsubai9v*g61~"
|
||||
},
|
||||
"prod":{
|
||||
"sk-prod":{
|
||||
"host": "erp.safekat.es",
|
||||
"username": "erp-demo",
|
||||
"password": "lNkEyukTc1~*3yy9"
|
||||
},
|
||||
"sk-dev":{
|
||||
"host": "erp-dev.safekat.es",
|
||||
"username": "erp-dev",
|
||||
"password": "snqyxNZIhg8m3!9~"
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
55
ci4/app/Commands/CatalogoLibroAsignarIskn.php
Normal file
55
ci4/app/Commands/CatalogoLibroAsignarIskn.php
Normal file
@ -0,0 +1,55 @@
|
||||
<?php
|
||||
|
||||
namespace App\Commands;
|
||||
|
||||
use CodeIgniter\CLI\BaseCommand;
|
||||
use CodeIgniter\CLI\CLI;
|
||||
use Config\Database;
|
||||
use App\Models\Catalogo\IdentificadorIsknModel;
|
||||
|
||||
class CatalogoLibroAsignarIskn extends BaseCommand
|
||||
{
|
||||
protected $group = 'Safekat';
|
||||
protected $name = 'catalogo:libro-asignar-iskn';
|
||||
protected $description = 'Asigna ISKN directamente en la base de datos a los libros que no lo tienen.';
|
||||
|
||||
public function run(array $params)
|
||||
{
|
||||
$db = Database::connect();
|
||||
$modelISKN = new IdentificadorIsknModel();
|
||||
|
||||
// Obtener todos los libros sin ISKN
|
||||
$libros = $db->table('catalogo_libros')
|
||||
->select('id')
|
||||
->where('iskn IS NULL')
|
||||
->where('deleted_at IS NULL')
|
||||
->get()
|
||||
->getResultArray();
|
||||
|
||||
if (empty($libros)) {
|
||||
CLI::write('No hay libros sin ISKN por asignar.', 'green');
|
||||
return;
|
||||
}
|
||||
|
||||
CLI::write('Asignando ISKN a ' . count($libros) . ' libros...', 'yellow');
|
||||
|
||||
$i = 1;
|
||||
foreach ($libros as $libro) {
|
||||
$iskn = $modelISKN->newIskn();
|
||||
|
||||
if ($iskn !== null) {
|
||||
$db->table('catalogo_libros')
|
||||
->where('id', $libro['id'])
|
||||
->update(['iskn' => $iskn]);
|
||||
|
||||
CLI::write("[{$i}] ISKN '{$iskn}' asignado a libro ID {$libro['id']}", 'cyan');
|
||||
} else {
|
||||
CLI::error("[{$i}] No se pudo generar ISKN para libro ID {$libro['id']}");
|
||||
}
|
||||
|
||||
$i++;
|
||||
}
|
||||
|
||||
CLI::write('Proceso finalizado.', 'green');
|
||||
}
|
||||
}
|
||||
204
ci4/app/Commands/CatalogoLibroImportar.php
Normal file
204
ci4/app/Commands/CatalogoLibroImportar.php
Normal file
@ -0,0 +1,204 @@
|
||||
<?php
|
||||
|
||||
namespace App\Commands;
|
||||
|
||||
use CodeIgniter\CLI\BaseCommand;
|
||||
use CodeIgniter\CLI\CLI;
|
||||
|
||||
class CatalogoLibroImportar extends BaseCommand
|
||||
{
|
||||
protected $group = 'Safekat';
|
||||
protected $name = 'catalogo:libro-importar';
|
||||
protected $description = 'Importa los registros de catalogo_libro a catalogo_libros para un customer_id dado';
|
||||
|
||||
public function run(array $params)
|
||||
{
|
||||
$db = \Config\Database::connect();
|
||||
$totalImportados = 0;
|
||||
|
||||
// Al inicio del método run()
|
||||
$papeles = $db->table('lg_papel_generico')
|
||||
->select('id, code')
|
||||
->where('is_deleted', 0)
|
||||
->get()
|
||||
->getResultArray();
|
||||
|
||||
// Mapa code => id
|
||||
$papelMap = [];
|
||||
foreach ($papeles as $p) {
|
||||
if (!empty($p['code'])) {
|
||||
$papelMap[trim($p['code'])] = $p['id'];
|
||||
}
|
||||
}
|
||||
|
||||
// Mapa de acabados => id
|
||||
$acabadosMap = [
|
||||
'plastificado_brillo' => 1,
|
||||
'plastificado_mate' => 5,
|
||||
];
|
||||
|
||||
// Mapa de encuadernaciones => id
|
||||
$encuadernacionMap = [
|
||||
'RCHV' => 4, // cosido tapa blanda
|
||||
'RCHVS' => 20, // cosido tapa blanda solapas
|
||||
'RDF' => 1, // fresado tapa dura
|
||||
'RF' => 2, // fresado tapa blanda
|
||||
'RFS' => 2, // fresado tapa blanda solapas
|
||||
'TDC' => 3, // cosido tapa dura
|
||||
];
|
||||
|
||||
|
||||
if (empty($params[0]) || !is_numeric($params[0])) {
|
||||
CLI::error('Debes proporcionar un customer_id válido como parámetro.');
|
||||
return;
|
||||
}
|
||||
|
||||
$customerId = (int) $params[0];
|
||||
CLI::write("Iniciando importación para customer_id = $customerId ...", 'yellow');
|
||||
|
||||
$libros = $db->table('catalogo_libro_antiguo_erp')
|
||||
->where('customer_id', $customerId)
|
||||
->where('deleted_at', null)
|
||||
->get()
|
||||
->getResultArray();
|
||||
|
||||
if (empty($libros)) {
|
||||
CLI::write('No se encontraron registros para importar.', 'red');
|
||||
return;
|
||||
}
|
||||
|
||||
foreach ($libros as $libro) {
|
||||
$nuevoLibro = [
|
||||
'id' => $libro['id'],
|
||||
'cliente_id' => $libro['customer_id'],
|
||||
'proveedor_id' => null,
|
||||
'user_created_id' => 1,
|
||||
'user_update_id' => 1,
|
||||
'cubierta_archivo' => $libro['cover_file'],
|
||||
'cubierta_url' => $libro['cover_url'],
|
||||
'ancho' => $libro['ancho'],
|
||||
'alto' => $libro['alto'],
|
||||
'peso' => $libro['peso'],
|
||||
'titulo' => $libro['titulo'],
|
||||
'autor' => $libro['autor'] ?? null,
|
||||
'autor_entidad' => $libro['autor_entidad'],
|
||||
'traductor' => $libro['traductor'],
|
||||
'ilustrador' => $libro['ilustrador'],
|
||||
'idioma' => $libro['idioma'],
|
||||
'num_edic' => $libro['num_edic'],
|
||||
'fecha_disponibilidad' => $libro['fecha_disponibilidad'],
|
||||
'fecha_public' => $libro['fecha_public'],
|
||||
'num_fotos' => $libro['num_fotos'],
|
||||
'num_ilustr' => $libro['num_ilustr'],
|
||||
'num_ilustr_color' => $libro['num_ilustr_color'],
|
||||
'num_ilustr_bn' => $libro['num_ilustr_bn'],
|
||||
'coleccion' => $libro['coleccion'] ?? null,
|
||||
'isbn' => $libro['isbn'],
|
||||
'ean' => $this->generarEAN($libro['isbn']),
|
||||
'editorial' => $libro['editorial'],
|
||||
'resumen' => $libro['resumen'],
|
||||
'resumen_breve' => $libro['resumen_breve'],
|
||||
'sello' => $libro['sello'],
|
||||
'paginas' => $libro['paginas'],
|
||||
'tipo_impresion' => $this->mapTipoImpresion($libro['tipo_impresion']),
|
||||
'comentarios' => $libro['comentarios'],
|
||||
|
||||
'negro_paginas' => $libro['negro_paginas'],
|
||||
'negro_papel_id' => $this->getPapelId($libro['negro_papel'], $papelMap),
|
||||
'negro_gramaje' => $libro['negro_gramaje'],
|
||||
'negro_pod_papel_id' => $this->getPapelId($libro['negro_papel'], $papelMap),
|
||||
'negro_pod_gramaje' => $libro['negro_gramaje'],
|
||||
|
||||
'color_paginas' => $libro['color_paginas'],
|
||||
'color_papel_id' => $this->getPapelId($libro['color_papel'], $papelMap),
|
||||
'color_gramaje' => $libro['color_gramaje'],
|
||||
'color_pod_papel_id' => $this->getPapelId($libro['color_papel'], $papelMap),
|
||||
'color_pod_gramaje' => $libro['color_gramaje'],
|
||||
|
||||
'cubierta_paginas' => $libro['portada_paginas'],
|
||||
'cubierta_papel_id' => $this->getPapelId($libro['portada_papel'], $papelMap),
|
||||
'cubierta_gramaje' => $libro['portada_gramaje'],
|
||||
'cubierta_pod_papel_id' => $this->getPapelId($libro['portada_papel'], $papelMap),
|
||||
'cubierta_pod_gramaje' => $libro['portada_gramaje'],
|
||||
'cubierta_acabado_id' => $this->getAcabadoId($libro['portada_acabado'], $acabadosMap),
|
||||
'cubierta_ancho_solapas' => $libro['solapas_ancho'],
|
||||
|
||||
'sobrecubierta_paginas' => $libro['cubierta_paginas'],
|
||||
'sobrecubierta_papel_id' => $this->getPapelId($libro['cubierta_papel'], $papelMap),
|
||||
'sobrecubierta_gramaje' => $libro['cubierta_gramaje'],
|
||||
'sobrecubierta_pod_papel_id' => $this->getPapelId($libro['cubierta_papel'], $papelMap),
|
||||
'sobrecubierta_pod_gramaje' => $libro['cubierta_gramaje'],
|
||||
'sobrecubierta_acabado_id' => $this->getAcabadoId($libro['cubierta_acabado'], $acabadosMap),
|
||||
'sobrecubierta_ancho_solapas' => 0,
|
||||
|
||||
'encuadernacion_id' => $this->getEncuadernacionId($libro['encuardenacion'], $encuadernacionMap),
|
||||
|
||||
'ubicacion' => $libro['ubicacion'],
|
||||
'created_at' => date('Y-m-d H:i:s'),
|
||||
'updated_at' => date('Y-m-d H:i:s'),
|
||||
'deleted_at' => $libro['deleted_at'],
|
||||
'iskn' => null,
|
||||
];
|
||||
|
||||
$exists = $db->table('catalogo_libros')
|
||||
->where('id', $libro['id'])
|
||||
->countAllResults();
|
||||
|
||||
if ($exists == 0) {
|
||||
$db->table('catalogo_libros')->insert($nuevoLibro);
|
||||
$totalImportados++;
|
||||
}else{
|
||||
CLI::write("El libro con ISBN " . $libro['isbn'] . " ya existe para el cliente con id " . $customerId . ".", 'yellow');
|
||||
}
|
||||
}
|
||||
|
||||
CLI::write("Importación finalizada. Se insertaron " . $totalImportados . " registros.", 'green');
|
||||
}
|
||||
|
||||
private function mapTipoImpresion($tipo)
|
||||
{
|
||||
switch ($tipo) {
|
||||
case 'bn':
|
||||
return 'negro';
|
||||
case 'color':
|
||||
return 'color';
|
||||
case 'colorfoto':
|
||||
return 'colorhq';
|
||||
case 'bicolor':
|
||||
return 'color';
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private function getPapelId(?string $code, array $map): ?int
|
||||
{
|
||||
if ($code === null)
|
||||
return null;
|
||||
$code = trim($code);
|
||||
return $map[$code] ?? null;
|
||||
}
|
||||
|
||||
private function getAcabadoId(?string $nombre, array $map): ?int
|
||||
{
|
||||
if ($nombre === null)
|
||||
return null;
|
||||
$nombre = trim($nombre);
|
||||
return $map[$nombre] ?? null;
|
||||
}
|
||||
private function getEncuadernacionId(?string $codigo, array $map): ?int
|
||||
{
|
||||
if ($codigo === null)
|
||||
return null;
|
||||
$codigo = trim($codigo);
|
||||
return $map[$codigo] ?? null;
|
||||
}
|
||||
|
||||
private function generarEAN(?string $isbn): ?string
|
||||
{
|
||||
if ($isbn === null)
|
||||
return null;
|
||||
return str_replace('-', '', $isbn);
|
||||
}
|
||||
|
||||
}
|
||||
274
ci4/app/Commands/ClienteImportar.php
Normal file
274
ci4/app/Commands/ClienteImportar.php
Normal file
@ -0,0 +1,274 @@
|
||||
<?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;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
93
ci4/app/Commands/RestoreBackup.php
Normal file
93
ci4/app/Commands/RestoreBackup.php
Normal file
@ -0,0 +1,93 @@
|
||||
<?php
|
||||
|
||||
namespace App\Commands;
|
||||
|
||||
use CodeIgniter\CLI\BaseCommand;
|
||||
use CodeIgniter\CLI\CLI;
|
||||
use ZipArchive;
|
||||
|
||||
class RestoreBackup extends BaseCommand
|
||||
{
|
||||
protected $group = 'Safekat';
|
||||
protected $name = 'restore:backup';
|
||||
protected $description = 'Restaura un backup desde un archivo .zip en writable/backups/.';
|
||||
protected $usage = 'restore:backup [--dry-run]';
|
||||
protected $options = [
|
||||
'--dry-run' => 'Simula el proceso de restauración sin ejecutarlo realmente.',
|
||||
];
|
||||
|
||||
public function run(array $params)
|
||||
{
|
||||
$isDryRun = CLI::getOption('dry-run');
|
||||
|
||||
$backupDir = WRITEPATH . 'backups/';
|
||||
$backups = glob($backupDir . '*.zip');
|
||||
|
||||
if (empty($backups)) {
|
||||
CLI::error("No se encontraron backups .zip en: $backupDir");
|
||||
return;
|
||||
}
|
||||
|
||||
CLI::write("Backups disponibles:", 'blue');
|
||||
foreach ($backups as $i => $file) {
|
||||
CLI::write("[" . ($i + 1) . "] " . basename($file));
|
||||
}
|
||||
|
||||
$index = CLI::prompt("Selecciona el número del backup a restaurar", null, 'required');
|
||||
|
||||
if (!is_numeric($index) || $index < 1 || $index > count($backups)) {
|
||||
CLI::error("Selección no válida.");
|
||||
return;
|
||||
}
|
||||
|
||||
$selectedFile = $backups[$index - 1];
|
||||
CLI::write("🎯 Seleccionado: " . basename($selectedFile), 'cyan');
|
||||
|
||||
if ($isDryRun) {
|
||||
CLI::write("🔍 Modo simulación activado (--dry-run)", 'yellow');
|
||||
}
|
||||
|
||||
$zip = new ZipArchive();
|
||||
if ($zip->open($selectedFile) !== TRUE) {
|
||||
CLI::error("No se pudo abrir el archivo ZIP.");
|
||||
return;
|
||||
}
|
||||
|
||||
$extractPath = WRITEPATH . 'backups/tmp_restore/';
|
||||
if (!is_dir($extractPath)) {
|
||||
mkdir($extractPath, 0775, true);
|
||||
}
|
||||
|
||||
$zip->extractTo($extractPath);
|
||||
$zip->close();
|
||||
|
||||
$sqlFiles = glob($extractPath . '*.sql');
|
||||
if (count($sqlFiles) === 0) {
|
||||
CLI::error("No se encontró ningún .sql dentro del backup.");
|
||||
return;
|
||||
}
|
||||
|
||||
$sqlFile = escapeshellarg($sqlFiles[0]);
|
||||
$db = config('Database')->default;
|
||||
|
||||
$cmd = "mysql -h {$db['hostname']} -u {$db['username']} -p'{$db['password']}' {$db['database']} < {$sqlFile}";
|
||||
|
||||
if ($isDryRun) {
|
||||
CLI::write("📋 Comando que se ejecutaría:", 'yellow');
|
||||
CLI::write($cmd, 'light_gray');
|
||||
CLI::write("✅ Simulación completa. No se hizo ninguna modificación.", 'green');
|
||||
} else {
|
||||
CLI::write("⏳ Restaurando...", 'yellow');
|
||||
system($cmd, $retval);
|
||||
|
||||
if ($retval !== 0) {
|
||||
CLI::error("❌ Error al restaurar la base de datos (código $retval).");
|
||||
} else {
|
||||
CLI::write("✅ Backup restaurado correctamente.", 'green');
|
||||
}
|
||||
}
|
||||
|
||||
array_map('unlink', glob($extractPath . '*'));
|
||||
rmdir($extractPath);
|
||||
}
|
||||
}
|
||||
2
ci4/app/Config/Auth.php
Normal file → Executable file
2
ci4/app/Config/Auth.php
Normal file → Executable file
@ -154,7 +154,7 @@ class Auth extends ShieldAuth
|
||||
* --------------------------------------------------------------------
|
||||
* Determines whether users can register for the site.
|
||||
*/
|
||||
public bool $allowRegistration = true;
|
||||
public bool $allowRegistration = false;
|
||||
|
||||
/**
|
||||
* --------------------------------------------------------------------
|
||||
|
||||
0
ci4/app/Config/AuthGroups.php
Normal file → Executable file
0
ci4/app/Config/AuthGroups.php
Normal file → Executable file
0
ci4/app/Config/AuthJWT.php
Normal file → Executable file
0
ci4/app/Config/AuthJWT.php
Normal file → Executable file
0
ci4/app/Config/AuthToken.php
Normal file → Executable file
0
ci4/app/Config/AuthToken.php
Normal file → Executable file
0
ci4/app/Config/CURLRequest.php
Normal file → Executable file
0
ci4/app/Config/CURLRequest.php
Normal file → Executable file
@ -6,14 +6,14 @@ use CodeIgniter\Config\BaseConfig;
|
||||
|
||||
class Email extends BaseConfig
|
||||
{
|
||||
public string $fromEmail = 'soporte_erp@safekat.es';
|
||||
public string $fromName = 'Safekat ERP';
|
||||
public string $fromEmail = 'no-reply@safekat.es';
|
||||
public string $fromName = 'ERP Safekat 2.0';
|
||||
public string $recipients = '';
|
||||
|
||||
/**
|
||||
* The "user agent"
|
||||
*/
|
||||
public string $userAgent = 'Safekat SL';
|
||||
public string $userAgent = 'ERP Safekat 2.0';
|
||||
|
||||
/**
|
||||
* The mail sending protocol: mail, sendmail, smtp
|
||||
@ -28,22 +28,22 @@ class Email extends BaseConfig
|
||||
/**
|
||||
* SMTP Server Hostname
|
||||
*/
|
||||
public string $SMTPHost = 'localhost';
|
||||
public string $SMTPHost = 'smtp.ionos.es';
|
||||
|
||||
/**
|
||||
* SMTP Username
|
||||
*/
|
||||
public string $SMTPUser = 'soporte_erp@safekat.es';
|
||||
public string $SMTPUser = 'no-reply@safekat.es';
|
||||
|
||||
/**
|
||||
* SMTP Password
|
||||
*/
|
||||
public string $SMTPPass = '';
|
||||
public string $SMTPPass = '5LKHH^CR#ecR#l55x7ke';
|
||||
|
||||
/**
|
||||
* SMTP Port
|
||||
*/
|
||||
public int $SMTPPort = 465;
|
||||
public int $SMTPPort = 587;
|
||||
|
||||
/**
|
||||
* SMTP Timeout (in seconds)
|
||||
|
||||
0
ci4/app/Config/Feature.php
Normal file → Executable file
0
ci4/app/Config/Feature.php
Normal file → Executable file
2
ci4/app/Config/Kint.php
Normal file → Executable file
2
ci4/app/Config/Kint.php
Normal file → Executable file
@ -42,7 +42,7 @@ class Kint extends BaseConfig
|
||||
*/
|
||||
public string $richTheme = 'aante-light.css';
|
||||
public bool $richFolder = false;
|
||||
public int $richSort = AbstractRenderer::SORT_FULL;
|
||||
public int $richSort = 0; //AbstractRenderer::SORT_FULL;
|
||||
|
||||
/**
|
||||
* @var array<string, class-string<ValuePluginInterface>>|null
|
||||
|
||||
0
ci4/app/Config/LogoImpresion.php
Normal file → Executable file
0
ci4/app/Config/LogoImpresion.php
Normal file → Executable file
24
ci4/app/Config/OrdenTrabajo.php
Normal file → Executable file
24
ci4/app/Config/OrdenTrabajo.php
Normal file → Executable file
@ -12,8 +12,14 @@ class OrdenTrabajo extends BaseConfig
|
||||
"interior_bn_at" => "interior_bn_user_id",
|
||||
"interior_color_at" => "interior_color_user_id",
|
||||
"cubierta_at" => "cubierta_user_id",
|
||||
"sobrecubierta_at" => "sobrecubierta_user_id",
|
||||
"guarda_at" => "guarda_user_id",
|
||||
//ACABADO
|
||||
"plastificado_at" => "plastificado_user_id",
|
||||
"plakene_at" => "plakene_user_id",
|
||||
"retractilado_at" => "retractilado_user_id",
|
||||
"estampado_at" => "estampado_user_id",
|
||||
"uvi_at" => "uvi_user_id",
|
||||
"encuadernacion_at" => "encuadernacion_user_id",
|
||||
"corte_at" => "corte_user_id",
|
||||
"preparacion_interiores_at" => "preparacion_interior_user_id",
|
||||
@ -21,10 +27,10 @@ class OrdenTrabajo extends BaseConfig
|
||||
"cosido_at" => "cosido_user_id",
|
||||
"grapado_at" => "grapado_user_id",
|
||||
"solapa_at" => "solapa_user_id",
|
||||
"retractilado_at" => "retractilado_user_id",
|
||||
"retractilado5_at" => "retractilado5_user_id",
|
||||
"prototipo_at" => "prototipo_user_id",
|
||||
"marcapaginas_at" => "marcapaginas_user_id",
|
||||
"espiral_at" => "espiral_user_id",
|
||||
//FERRO
|
||||
"pendiente_ferro_at" => "pendiente_ferro_user_id",
|
||||
"ferro_en_cliente_at" => "ferro_en_cliente_user_id",
|
||||
@ -64,7 +70,7 @@ class OrdenTrabajo extends BaseConfig
|
||||
["bg" => "yellow", "color" => "black"],
|
||||
["bg" => "purple", "color" => "white"],
|
||||
["bg" => "orange", "color" => "white"],
|
||||
["bg" => "blue", "color" => "black"],
|
||||
["bg" => "blue", "color" => "white"],
|
||||
["bg" => "pink", "color" => "black"],
|
||||
["bg" => "#FFFFFF", "color" => "black"],
|
||||
];
|
||||
@ -99,9 +105,9 @@ class OrdenTrabajo extends BaseConfig
|
||||
];
|
||||
public array $OT_PLASTIFICADO_COLOR =
|
||||
[
|
||||
"BRIL" => ["bg" => "#00B0F0", "color" => "white"],
|
||||
"BRILLO" => ["bg" => "#00B0F0", "color" => "white"],
|
||||
"MATE" => ["bg" => "#FF0000", "color" => "white"],
|
||||
"SOFT_TOUCH" => ["bg" => "#00B050", "color" => "white"],
|
||||
"SOFT" => ["bg" => "#00B050", "color" => "white"],
|
||||
"SANDY" => ["bg" => "#782170", "color" => "white"],
|
||||
"ANTIRAYADO" => ["bg" => "#E97132", "color" => "white"],
|
||||
"GOFRADO" => ["bg" => "#FFFF00", "color" => "black"],
|
||||
@ -115,6 +121,16 @@ class OrdenTrabajo extends BaseConfig
|
||||
"default" => ["bg" => "white", "color" => "black"],
|
||||
];
|
||||
|
||||
public array $OT_TAREA_STATUS_COLOR = [
|
||||
"P" => '#FFB22C',
|
||||
"F" => '#67AE6E',
|
||||
"S" => '#EB5B00',
|
||||
"I" => '#3A59D1',
|
||||
"E" => '#FF0B55',
|
||||
"D" => '#FFA725',
|
||||
];
|
||||
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
|
||||
0
ci4/app/Config/PedidoXML.php
Normal file → Executable file
0
ci4/app/Config/PedidoXML.php
Normal file → Executable file
0
ci4/app/Config/Publisher.php
Normal file → Executable file
0
ci4/app/Config/Publisher.php
Normal file → Executable file
0
ci4/app/Config/RBAC/.gitkeep
Normal file → Executable file
0
ci4/app/Config/RBAC/.gitkeep
Normal file → Executable file
167
ci4/app/Config/Routes.php
Normal file → Executable file
167
ci4/app/Config/Routes.php
Normal file → Executable file
@ -20,19 +20,13 @@ $routes->get('viewmode/(:alpha)', 'Viewmode::index/$1');
|
||||
$routes->get('test', 'Test::index');
|
||||
|
||||
|
||||
$routes->group('activity', ['namespace' => 'App\Controllers\Sistema'], function ($routes) {
|
||||
$routes->get('', 'Actividad::index', ['as' => 'activityList']);
|
||||
$routes->post('datatable', 'Actividad::datatable', ['as' => 'activityDT']);
|
||||
});
|
||||
|
||||
|
||||
/*
|
||||
* --------------------------------------------------------------------
|
||||
* Route Definitions
|
||||
* --------------------------------------------------------------------
|
||||
*/
|
||||
|
||||
// Carga archivos de rutas por dominio
|
||||
// Carga archivos de rutas por dominio
|
||||
foreach (glob(APPPATH . 'Config/Routes/*Routes.php') as $routeFile) {
|
||||
require $routeFile;
|
||||
}
|
||||
@ -40,6 +34,8 @@ foreach (glob(APPPATH . 'Config/Routes/*Routes.php') as $routeFile) {
|
||||
|
||||
$routes->group('users', ['namespace' => 'App\Controllers\Configuracion'], function ($routes) {
|
||||
$routes->get('', 'Users::index', ['as' => 'userList']);
|
||||
$routes->get('maquinista/change/user', 'Users::index_maquinista_change_user', ['as' => 'maquinistaUserChangeList']);
|
||||
$routes->get('maquinista/change/session/(:num)', 'Users::change_user_session/$1', ['as' => 'maquinistaChangeUserSession']);
|
||||
$routes->get('list', 'Users::index', ['as' => 'userList2']);
|
||||
$routes->get('add', 'Users::add', ['as' => 'newUser']);
|
||||
$routes->post('add', 'Users::add', ['as' => 'createUser']);
|
||||
@ -146,17 +142,24 @@ $routes->group('tipologiaslibros', ['namespace' => 'App\Controllers\Configuracio
|
||||
$routes->group('imposiciones', ['namespace' => 'App\Controllers\Configuracion'], function ($routes) {
|
||||
$routes->get('', 'Imposiciones::index', ['as' => 'imposicionList']);
|
||||
$routes->get('add', 'Imposiciones::add', ['as' => 'newImposicion']);
|
||||
$routes->post('add', 'Imposiciones::add', ['as' => 'createImposicion']);
|
||||
$routes->get('add/esquema', 'Imposiciones::add_esquema', ['as' => 'newImposicionEsquema']);
|
||||
$routes->get('find/(:num)', 'Imposiciones::find_imposicion/$1', ['as' => 'findImposicion']);
|
||||
$routes->get('esquema/find/(:num)', 'Imposiciones::find_imposicion_esquema/$1', ['as' => 'findImposicionEsquema']);
|
||||
$routes->post('create', 'Imposiciones::create', ['as' => 'ajaxCreateImposicion']);
|
||||
$routes->put('(:num)/update', 'Imposiciones::update/$1', ['as' => 'ajaxUpdateImposicion']);
|
||||
$routes->post('(:num)/edit', 'Imposiciones::edit/$1', ['as' => 'updateImposicion']);
|
||||
$routes->post('datatable', 'Imposiciones::datatable', ['as' => 'dataTableOfImposiciones']);
|
||||
$routes->post('esquema/create', 'Imposiciones::create_imposicion_esquema', ['as' => 'ajaxCreateImposicionEsquema']);
|
||||
$routes->post('(:num)', 'Imposiciones::update/$1', ['as' => 'ajaxUpdateImposicion']);
|
||||
$routes->post('esquema/(:num)', 'Imposiciones::update_imposicion_esquema/$1', ['as' => 'ajaxUpdateImposicionEsquema']);
|
||||
$routes->delete('(:num)', 'Imposiciones::delete/$1', ['as' => 'deleteImposicion']);
|
||||
$routes->delete('esquema/(:num)', 'Imposiciones::delete_imposicion_esquema/$1', ['as' => 'deleteImposicionEsquema']);
|
||||
$routes->get('edit/(:num)', 'Imposiciones::edit/$1', ['as' => 'updateImposicionForm']);
|
||||
$routes->get('esquema/edit/(:num)', 'Imposiciones::edit_imposicion_esquema/$1', ['as' => 'updateImposicionEsquemaForm']);
|
||||
$routes->get('datatable', 'Imposiciones::datatable', ['as' => 'dataTableOfImposiciones']);
|
||||
$routes->get('esquema/datatable', 'Imposiciones::datatable_imposicion_esquema', ['as' => 'dataTableOfEsquemaImposiciones']);
|
||||
$routes->post('allmenuitems', 'Imposiciones::allItemsSelect', ['as' => 'select2ItemsOfImposiciones']);
|
||||
$routes->post('menuitems', 'Imposiciones::menuItems', ['as' => 'menuItemsOfImposiciones']);
|
||||
$routes->get('select', 'Imposiciones::selectImposicion', ['as' => 'selectImposicion']);
|
||||
|
||||
$routes->get('esquema/select', 'Imposiciones::selectImposicionEsquema', ['as' => 'selectImposicionEsquema']);
|
||||
});
|
||||
$routes->resource('imposiciones', ['namespace' => 'App\Controllers\Configuracion', 'controller' => 'Imposiciones', 'except' => 'show,new,create,update']);
|
||||
|
||||
$routes->group('papelimpresiontipologias', ['namespace' => 'App\Controllers\Configuracion'], function ($routes) {
|
||||
$routes->get('add', 'Papelimpresiontipologias::add', ['as' => 'newPapelImpresionTipologia']);
|
||||
@ -316,6 +319,7 @@ $routes->group('clienteusuarios', ['namespace' => 'App\Controllers\Clientes'], f
|
||||
$routes->group('misdirecciones', ['namespace' => 'App\Controllers\Clientes'], function ($routes) {
|
||||
$routes->get('', 'Clientedirecciones::index', ['as' => 'clientedireccionesIndex']);
|
||||
$routes->get('get/(:num)', 'Clientedirecciones::get/$1', ['as' => 'get']);
|
||||
$routes->get('getId', 'Clientedirecciones::getDireccionIdFromData');
|
||||
$routes->get('getDireccionPresupuesto/(:num)', 'Clientedirecciones::getDireccionPresupuesto/$1', ['as' => 'getDireccionPresupuesto']);
|
||||
$routes->post('add', 'Clientedirecciones::add', ['as' => 'newClientedirecciones']);
|
||||
$routes->get('getSelect2', 'Clientedirecciones::getSelect2', ['as' => 'listaClientedirecciones']);
|
||||
@ -505,15 +509,19 @@ $routes->group('pedidos', ['namespace' => 'App\Controllers\Pedidos'], function (
|
||||
$routes->resource('pedidos', ['namespace' => 'App\Controllers\Pedidos', 'controller' => 'Pedido', 'except' => 'show,new,create,update']);
|
||||
|
||||
|
||||
$routes->group('albaranes', ['namespace' => 'App\Controllers\Pedidos'], function ($routes) {
|
||||
$routes->post('add', 'Albaran::add', ['as' => 'crearAlbaranesPedido']);
|
||||
$routes->post('update/(:any)', 'Albaran::update/$1', ['as' => 'actualizarAlbaran']);
|
||||
$routes->post('updateLinea/(:any)', 'Albaran::updateLinea/$1', ['as' => 'actualizarLineaAlbaran']);
|
||||
$routes->post('deletelinea', 'Albaran::borrarlinea', ['as' => 'borrarAlbaranLinea']);
|
||||
$routes->get('delete/(:any)', 'Albaran::delete/$1', ['as' => 'borrarAlbaran']);
|
||||
$routes->get('getalbaranes/(:any)', 'Albaran::getAlbaranes/$1', ['as' => 'getAlbaranes']);
|
||||
$routes->get('nuevalinea/(:any)', 'Albaran::addLinea/$1', ['as' => 'addAlbaranLinea']);
|
||||
$routes->post('nuevalinea/(:any)', 'Albaran::addLinea/$1', ['as' => 'addIVA']);
|
||||
$routes->group('albaranes', ['namespace' => 'App\Controllers\Albaranes'], function ($routes) {
|
||||
$routes->post('generarAlbaran', 'Albaran::generateAlbaran', ['as' => 'generarAlbaran']);
|
||||
$routes->get('albaranesEnvio', 'Albaran::getAlbaranes');
|
||||
$routes->get('datatablesAlbaranLinea', 'Albaran::datatablesLineasAlbaran');
|
||||
$routes->post('updateAlbaran', 'Albaran::updateAlbaran');
|
||||
$routes->post('borrarAlbaranLinea', 'Albaran::borrarLinea');
|
||||
$routes->post('borrarAlbaran', 'Albaran::borrarAlbaran');
|
||||
$routes->post('updateAlbaranLinea', 'Albaran::updateAlbaranLinea');
|
||||
$routes->post('addIvaAlbaran', 'Albaran::addLineasIva');
|
||||
$routes->post('nuevaLineaAlbaran', 'Albaran::addBlankLineaAlbaran');
|
||||
$routes->get('datatable', 'Albaran::datatable', ['as' => 'dataTableOfAlbaranes']);
|
||||
$routes->get('getAlbaran', 'Albaran::getAlbaran');
|
||||
$routes->get('edit/(:num)', 'Albaran::editAlbaran/$1', ['as' => 'editarAlbaran']);
|
||||
});
|
||||
$routes->resource('albaranes', ['namespace' => 'App\Controllers\Pedidos', 'controller' => 'Albaran', 'except' => 'show,new,create,update']);
|
||||
|
||||
@ -539,7 +547,9 @@ $routes->group('facturas', ['namespace' => 'App\Controllers\Facturacion'], funct
|
||||
$routes->post('updateTotales/(:any)', 'Facturas::updateTotales/$1', ['as' => 'updateFacturaTotales']);
|
||||
$routes->post('updateCabecera/(:any)', 'Facturas::updateCabecera/$1', ['as' => 'updateCabecera']);
|
||||
$routes->post('datatablePagos/(:any)', 'FacturasPagos::datatable/$1', ['as' => 'dataTableOfPagosFacturas']);
|
||||
$routes->post('conformarFactura', 'FacturasPagos::addPagoRectificativa');
|
||||
$routes->post('editorPagos', 'FacturasPagos::datatable_editor', ['as' => 'editorOfPagosFacturas']);
|
||||
$routes->post('deleteFacturaLineaPago', 'Facturas::deleteLineaPago', ['as' => 'deleteLineaPago']);
|
||||
$routes->post('datatablePedidos', 'Facturas::datatablePedidos', ['as' => 'dataTableOfFacturasPedido']);
|
||||
$routes->get('getdatoscliente/(:any)', 'Facturas::getDatosFacturacionClienteForm/$1');
|
||||
});
|
||||
@ -560,6 +570,7 @@ $routes->group(
|
||||
function ($routes) {
|
||||
$routes->get('index/(:num)', 'PrintAlbaranes::index/$1', ['as' => 'viewAlbaranPDF']);
|
||||
$routes->get('generar/(:num)', 'PrintAlbaranes::generar/$1', ['as' => 'albaranToPdf']);
|
||||
$routes->get('generar-anonimo/(:num)', 'PrintAlbaranes::generarAnonimo/$1', ['as' => 'albaranAnonimoToPdf']);
|
||||
}
|
||||
);
|
||||
|
||||
@ -630,6 +641,9 @@ $routes->group('messages', ['namespace' => 'App\Controllers\Chat'], function ($r
|
||||
$routes->get('datatable/presupuesto', 'ChatController::datatable_presupuesto_messages', ['as' => 'getDatatablePresupuestoMessages']);
|
||||
$routes->get('datatable/pedido', 'ChatController::datatable_pedido_messages', ['as' => 'getDatatablePedidoMessages']);
|
||||
$routes->get('datatable/factura', 'ChatController::datatable_factura_messages', ['as' => 'getDatatableFacturaMessages']);
|
||||
$routes->get('datatable/ots', 'ChatController::datatable_ot_messages', ['as' => 'getDatatableOtMessages']);
|
||||
$routes->get('datatable/direct', 'ChatController::datatable_direct_messages', ['as' => 'getDatatableDirectMessages']);
|
||||
|
||||
|
||||
$routes->post('direct', 'ChatController::store_new_direct_message', ['as' => 'storeNewDirectMessage']);
|
||||
$routes->post('direct/client', 'ChatController::store_new_direct_message_client', ['as' => 'storeNewDirectMessageClient']);
|
||||
@ -640,6 +654,8 @@ $routes->group('chat', ['namespace' => 'App\Controllers\Chat'], function ($route
|
||||
$routes->get('presupuesto/(:num)', 'ChatController::get_chat_presupuesto_view/$1', ['as' => 'getChatPresupuestoView']);
|
||||
$routes->get('pedido/(:num)', 'ChatController::get_chat_pedido_view/$1', ['as' => 'getChatPedidoView']);
|
||||
$routes->get('factura/(:num)', 'ChatController::get_chat_factura_view/$1', ['as' => 'getChatFacturaView']);
|
||||
$routes->get('ot/(:num)', 'ChatController::get_chat_ot_view/$1', ['as' => 'getChatOtView']);
|
||||
|
||||
|
||||
$routes->get('direct/conversation/(:num)', 'ChatController::get_chat_direct/$1', ['as' => 'getChatDirect']);
|
||||
$routes->get('direct/users/select/(:num)', 'ChatController::get_chat_direct_select_users/$1', ['as' => 'getChatDirectSelectUsers']);
|
||||
@ -725,39 +741,74 @@ $routes->group('soporte', ['namespace' => 'App\Controllers\Soporte'], function (
|
||||
|
||||
$routes->group('produccion', ['namespace' => 'App\Controllers\Produccion'], function ($routes) {
|
||||
$routes->group('ordentrabajo', ['namespace' => 'App\Controllers\Produccion'], function ($routes) {
|
||||
/** VIEWS */
|
||||
$routes->get('', 'Ordentrabajo::index', ['as' => 'viewOrdenTrabajoIndex']);
|
||||
$routes->get('edit/(:num)', 'Ordentrabajo::edit/$1', ['as' => 'viewOrdenTrabajoEdit']);
|
||||
$routes->delete('reset/tareas/(:num)', 'Ordentrabajo::reset_tareas/$1');
|
||||
$routes->delete('tareas/(:num)', 'Ordentrabajo::delete_tarea/$1');
|
||||
|
||||
/** GET */
|
||||
$routes->get('summary/(:num)', 'Ordentrabajo::get_orden_trabajo_summary/$1', ['as' => 'getOrdenTrabajoSumary']);
|
||||
$routes->get("tarea/progress/(:num)", "Ordentrabajo::get_orden_trabajo_progress_date/$1");
|
||||
$routes->get('tarea/(:num)', 'Ordentrabajo::find_tarea/$1');
|
||||
$routes->get('tarea/dates/(:num)', 'Ordentrabajo::get_orden_trabajo_tareas_dates/$1');
|
||||
$routes->get('tareas/maquina/(:num)/(:num)','Ordentrabajo::get_tareas_ot_maquina/$1/$2');
|
||||
/** DATATABLES */
|
||||
$routes->get('datatable', 'Ordentrabajo::datatable');
|
||||
$routes->get('datatable_pendientes', 'Ordentrabajo::datatable_pendientes');
|
||||
$routes->get('datatable_ferro_pendiente', 'Ordentrabajo::datatable_ferro_pendiente');
|
||||
$routes->get('datatable_ferro_ok', 'Ordentrabajo::datatable_ferro_ok');
|
||||
$routes->get('datatable_news', 'Ordentrabajo::datatable_news');
|
||||
$routes->get('datatable_prod', 'Ordentrabajo::datatable_prod');
|
||||
$routes->get('datatable_waiting', 'Ordentrabajo::datatable_waiting');
|
||||
$routes->get('datatable_revision_com', 'Ordentrabajo::datatable_revision_com');
|
||||
$routes->get('tareas/datatable/(:num)', 'Ordentrabajo::tareas_datatable/$1', ['as' => 'datatableTareasOrdenTrabajo']);
|
||||
$routes->get('maquinas/ots/datatable/(:num)','Ordentrabajo::datatable_maquina_ordenes_trabajo/$1');
|
||||
$routes->get('maquinas/ots/(:num)','Ordentrabajo::get_maquina_ots/$1');
|
||||
|
||||
/**======================
|
||||
* UPDATES
|
||||
*========================**/
|
||||
$routes->post("update/tarea", 'Ordentrabajo::update_orden_trabajo_tarea');
|
||||
$routes->post("update/date", 'Ordentrabajo::update_orden_trabajo_date');
|
||||
$routes->post("reset/date", 'Ordentrabajo::reset_orden_trabajo_date');
|
||||
$routes->post("update/pedido/date", 'Ordentrabajo::update_orden_trabajo_pedido_date');
|
||||
$routes->post("reset/pedido/date", 'Ordentrabajo::reset_orden_trabajo_pedido_date');
|
||||
$routes->post("update/pod/pedido/date/(:num)", 'Ordentrabajo::update_pod_pedido_dates/$1');
|
||||
$routes->post("update/pedido", 'Ordentrabajo::update_orden_trabajo_pedido');
|
||||
$routes->post("update/user", 'Ordentrabajo::update_orden_trabajo_user');
|
||||
$routes->post("update", 'Ordentrabajo::update_orden_trabajo');
|
||||
$routes->post("upload/portada", 'Ordentrabajo::upload_orden_trabajo_portada');
|
||||
$routes->delete("portada/(:num)", 'Ordentrabajo::delete_orden_trabajo_portada/$1');
|
||||
$routes->get("color/(:num)", 'Ordentrabajo::get_orden_trabajo_color_status/$1');
|
||||
$routes->post("update/tarea/progress", "Ordentrabajo::store_orden_trabajo_progress_date");
|
||||
$routes->post("update/tarea/pliegos", "Ordentrabajo::update_orden_trabajo_pliegos");
|
||||
$routes->post("update/tarea/proveedor", "Ordentrabajo::update_presupuesto_tarea_proveedor");
|
||||
$routes->post("fa/tareas/update", 'Ordentrabajo::update_orden_trabajo_fa_tareas');
|
||||
$routes->post("fa/tareas/reset",'Ordentrabajo::delete_orden_trabajo_fa_tareas');
|
||||
$routes->post('maquinas/ots','Ordentrabajo::store_maquina_ordenes_trabajo');
|
||||
$routes->post('maquinas/ots/estado','Ordentrabajo::update_maquina_ordenes_trabajo_estado');
|
||||
|
||||
|
||||
/**DELETES */
|
||||
$routes->delete("portada/(:num)", 'Ordentrabajo::delete_orden_trabajo_portada/$1');
|
||||
$routes->delete("tarea/progress/(:num)", "Ordentrabajo::delete_orden_trabajo_progress_date/$1");
|
||||
$routes->delete('reset/tareas/(:num)', 'Ordentrabajo::reset_tareas/$1');
|
||||
$routes->delete('tareas/(:num)', 'Ordentrabajo::delete_tarea/$1');
|
||||
$routes->delete('maquinas/ots/(:num)', 'Ordentrabajo::delete_maquina_orden_trabajo_tarea/$1');
|
||||
$routes->delete('maquinas/ots/all/(:num)', 'Ordentrabajo::delete_maquina_orden_trabajo_all/$1');
|
||||
/**======================
|
||||
* FILES
|
||||
*========================**/
|
||||
$routes->post('get_files', 'Ordentrabajo::get_files');
|
||||
$routes->post('upload_files', 'Ordentrabajo::upload_files');
|
||||
$routes->get('barcode/(:num)', 'Ordentrabajo::imprimir_codigo_safekat/$1', ['as' => "getOrdenTrabajoBarCode"]);
|
||||
/**======================
|
||||
* PDF
|
||||
*========================**/
|
||||
$routes->get('pdf/(:num)', 'Ordentrabajo::get_pdf/$1');
|
||||
$routes->get('pdf/content/(:num)', 'Ordentrabajo::get_ot_pdf_content/$1');
|
||||
$routes->get('pdf/ferro/(:num)', 'Ordentrabajo::get_ferro_pdf/$1');
|
||||
$routes->get('pdf/prototipo/(:num)', 'Ordentrabajo::get_prototipo_pdf/$1');
|
||||
$routes->get('portada/(:num)', 'Ordentrabajo::get_portada_img/$1');
|
||||
/** PLANNING */
|
||||
$routes->group('planning', ['namespace' => 'App\Controllers\Produccion'], function ($routes) {
|
||||
$routes->get('select/maquina/rotativa', 'Ordentrabajo::select_maquina_planning_rot');
|
||||
$routes->get('select/papel/rotativa', 'Ordentrabajo::select_papel_planning_rot');
|
||||
@ -767,18 +818,82 @@ $routes->group('produccion', ['namespace' => 'App\Controllers\Produccion'], func
|
||||
$routes->get('rotativa', 'Ordentrabajo::index_planning_rotativa');
|
||||
$routes->get('papel/datatable', 'Ordentrabajo::papel_gramaje_datatable');
|
||||
$routes->get('papel/plana/datatable', 'Ordentrabajo::papel_pliego_datatable');
|
||||
$routes->get('maquina/plana/datatable', 'Ordentrabajo::maquina_plana_datatable');
|
||||
$routes->get('rotativa/datatable', 'Ordentrabajo::planning_rotativa_datatable');
|
||||
$routes->get('plana/datatable', 'Ordentrabajo::planning_plana_datatable');
|
||||
$routes->post('tarea/toggle/corte/(:num)', 'Ordentrabajo::tarea_toggle_corte/$1');
|
||||
});
|
||||
|
||||
$routes->group('maquinista', ['namespace' => 'App\Controllers\Produccion'], function ($routes) {
|
||||
/**
|
||||
* VIEWS
|
||||
*/
|
||||
$routes->get('maquinas/view', 'Ordentrabajo::maquinista_maquinas_view', ['as' => 'viewProduccionMaquinistaMaquinas']);
|
||||
$routes->get('maquinas/view/(:num)', 'Ordentrabajo::maquinista_maquina_tareas_list/$1', ['as' => 'viewProduccionMaquinaTareasList']);
|
||||
$routes->get('maquinas/view/auto/(:num)', 'Ordentrabajo::maquinista_maquina_tareas_fichaje_automatico/$1', ['as' => 'viewMaquinistaFichajeAutomatico']);
|
||||
$routes->get('maquinas/view/scan/(:num)', 'Ordentrabajo::maquinista_maquina_tareas_scan/$1', ['as' => 'viewMaquinistaTareaScan']);
|
||||
$routes->get('maquinas/view/tarea/(:num)', 'Ordentrabajo::maquinista_maquina_tarea_view/$1', ['as' => 'viewProduccionMaquinistaTareaView']);
|
||||
$routes->get('maquinas/view/maquina/ot/tareas/(:num)', 'Ordentrabajo::maquinista_maquina_ot_tareas_view/$1', ['as' => 'viewProduccionMaquinistaOtTareasView']);
|
||||
|
||||
$routes->get('colas/view', 'Ordentrabajo::maquinista_colas_view', ['as' => 'viewProduccionMaquinistaColas']);
|
||||
|
||||
/** DATATABLE */
|
||||
$routes->get('maquinas/tareas/datatable/(:alpha)/(:num)', 'Ordentrabajo::maquinista_maquina_tareas_datatable/$1/$2', ['as' => 'viewMaquinistaMaquinaTareaDatatable']);
|
||||
$routes->get('maquinas/tareas/aplazadas/datatable/(:num)', 'Ordentrabajo::maquinista_maquina_tareas_aplazada_datatable/$1', ['as' => 'viewMaquinistaMaquinaTareaAplazadaDatatable']);
|
||||
|
||||
/** POST */
|
||||
$routes->post('maquinas/tareas/printLabels', 'Ordentrabajo::printPackagingLabels');
|
||||
});
|
||||
});
|
||||
});
|
||||
$routes->group('logistica', ['namespace' => 'App\Controllers\Logistica'], function ($routes) {
|
||||
|
||||
$routes->get('print/label/test', 'LogisticaController::print_test_label');
|
||||
$routes->get('panel', 'LogisticaController::panel', ['as' => 'LogisticaPanel']);
|
||||
$routes->get('envios', 'LogisticaController::gestionEnvios', ['as' => 'gestionEnvios']);
|
||||
$routes->get('enviosFerros', 'LogisticaController::gestionEnviosFerros', ['as' => 'gestionEnviosFerros']);
|
||||
$routes->get('etiquetasLogistica', 'LogisticaController::etiquetasLogistica', ['as' => 'etiquetasLogistica']);
|
||||
$routes->get('datatableEnvios', 'LogisticaController::datatable_envios');
|
||||
$routes->get('datatableLineasEnvios/(:num)', 'LogisticaController::datatable_enviosEdit/$1');
|
||||
$routes->get('envio/(:num)', 'LogisticaController::editEnvio/$1');
|
||||
$routes->get('selectAddLinea', 'LogisticaController::selectAddEnvioLinea');
|
||||
$routes->get('addLineaEnvio', 'LogisticaController::addEnvioLinea');
|
||||
$routes->post('updateCajaLinea', 'LogisticaController::setCajaLinea');
|
||||
$routes->post('deleteLineasEnvio', 'LogisticaController::deleteLineas');
|
||||
$routes->post('updateLineaEnvio', 'LogisticaController::updateLineaEnvio');
|
||||
$routes->post('updateComentariosEnvio', 'LogisticaController::saveComments');
|
||||
$routes->post('updateCajasEnvio', 'LogisticaController::updateCajasEnvio');
|
||||
$routes->post('updateCodigoSeguimiento', 'LogisticaController::updateCodigoSeguimiento');
|
||||
$routes->post('updateProveedorEnvio', 'LogisticaController::updateProveedorEnvio');
|
||||
$routes->post('finalizarEnvio', 'LogisticaController::finalizarEnvio');
|
||||
$routes->post('generateEnvio', 'LogisticaController::generarEnvio');
|
||||
$routes->post('generateEnvioFerro', 'LogisticaController::generarEnvioFerro');
|
||||
$routes->get('selectForNewEnvio', 'LogisticaController::findForNewEnvio');
|
||||
$routes->get('selectDireccionForEnvio', 'LogisticaController::selectDireccionForEnvio');
|
||||
$routes->post('imprimirEtiquetas', 'LogisticaController::imprimirEtiquetas');
|
||||
$routes->post('ficharEmbalaje', 'LogisticaController::ficharEmbalaje');
|
||||
$routes->get('datatableProximosEnvios/(:num)', 'LogisticaController::datatable_proximosEnvios/$1');
|
||||
|
||||
$routes->get('listAlbaranes', 'LogisticaController::listAlbaranes', ['as' => 'albaranesList']);
|
||||
});
|
||||
|
||||
$routes->group('etiquetasTitulos', ['namespace' => 'App\Controllers\Logistica'], function ($routes) {
|
||||
|
||||
$routes->get('otList', 'EtiquetasTitulosController::findOTs');
|
||||
$routes->get('addList', 'EtiquetasTitulosController::findAddresses');
|
||||
$routes->post('newEtiquetaTitulos', 'EtiquetasTitulosController::addEtiqueta');
|
||||
$routes->get('datatable', 'EtiquetasTitulosController::datatable');
|
||||
$routes->post('delete', 'EtiquetasTitulosController::deleteEtiqueta');
|
||||
$routes->get('edit/(:num)', 'EtiquetasTitulosController::edit/$1');
|
||||
$routes->get('datatableLineas/(:num)', 'EtiquetasTitulosController::datatableLineasEtiquetas/$1');
|
||||
$routes->get('findOts', 'EtiquetasTitulosController::findOtsWithAddress');
|
||||
$routes->post('addLineas', 'EtiquetasTitulosController::addLineasEtiqueta');
|
||||
$routes->post('deleteLineas', 'EtiquetasTitulosController::deleteLineasEtiqueta');
|
||||
$routes->post('updateLineas', 'EtiquetasTitulosController::updateLineasEtiqueta');
|
||||
$routes->post('updateComentarios', 'EtiquetasTitulosController::updateComentarios');
|
||||
$routes->post('updateOrdenCajas', 'EtiquetasTitulosController::updateOrdenCajas');
|
||||
$routes->post('renumber', 'EtiquetasTitulosController::renumberCajas');
|
||||
$routes->post('imprimirEtiquetas', 'EtiquetasTitulosController::imprimirEtiquetas');
|
||||
});
|
||||
|
||||
/*
|
||||
@ -788,6 +903,8 @@ $routes->group('logistica', ['namespace' => 'App\Controllers\Logistica'], functi
|
||||
*/
|
||||
$routes->group('translate', ['namespace' => 'App\Controllers'], function ($routes) {
|
||||
$routes->post('getTranslation', 'Language::getTranslation', ['as' => 'getKeys']);
|
||||
$routes->get('lang/(:segment)', 'Language::file/$1');
|
||||
|
||||
});
|
||||
$routes->resource('translate', ['namespace' => 'App\Controllers', 'controller' => 'Language', 'except' => '']);
|
||||
|
||||
|
||||
0
ci4/app/Config/Routes/ApiRoutes.php
Normal file → Executable file
0
ci4/app/Config/Routes/ApiRoutes.php
Normal file → Executable file
30
ci4/app/Config/Routes/CatalogoRoutes.php
Normal file
30
ci4/app/Config/Routes/CatalogoRoutes.php
Normal file
@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
use CodeIgniter\Router\RouteCollection;
|
||||
|
||||
/** @var RouteCollection $routes */
|
||||
|
||||
/* Rutas para tarifas */
|
||||
$routes->group('catalogo', ['namespace' => 'App\Controllers\Catalogo'], function ($routes) {
|
||||
/* Libros */
|
||||
$routes->group('libros', ['namespace' => 'App\Controllers\Catalogo'], function ($routes) {
|
||||
/**======================
|
||||
* CRUD
|
||||
*========================**/
|
||||
$routes->get('', 'CatalogoLibros::index', ['as' => 'catalogoLibrosList']);
|
||||
$routes->get('gettarifas', 'CatalogoLibros::getSelect2');
|
||||
$routes->match(['get', 'post'], 'add', 'CatalogoLibros::add', ['as' => 'catalogoLibrosAdd']);
|
||||
$routes->match(['get', 'post'], 'edit/(:num)', 'CatalogoLibros::edit/$1', ['as' => 'catalogoLibrosEdit']);
|
||||
$routes->get('delete/(:num)', 'CatalogoLibros::delete/$1', ['as' => 'catalogoLibrosDelete']);
|
||||
$routes->get('datatable', 'CatalogoLibros::datatable', ['as' => 'catalogoLibrosDT']);
|
||||
|
||||
|
||||
/**======================
|
||||
* AJAX
|
||||
*========================**/
|
||||
$routes->get('clientlist', 'CatalogoLibros::getClientList', ['as' => 'catalogoLibrosClientList']);
|
||||
$routes->get('pedidosAntiguos', 'CatalogoLibros::datatablePedidosAntiguos', ['as' => 'catalogoLibrosPedidosAntiguosDT']);
|
||||
|
||||
|
||||
});
|
||||
});
|
||||
1
ci4/app/Config/Routes/ComprasRoutes.php
Normal file → Executable file
1
ci4/app/Config/Routes/ComprasRoutes.php
Normal file → Executable file
@ -19,6 +19,7 @@ $routes->group('compras', ['namespace' => 'App\Controllers\Compras'], function (
|
||||
$routes->get('delete/(:num)', 'Proveedores::delete/$1', ['as' => 'deleteProveedores']);
|
||||
$routes->post('allmenuitems', 'Proveedores::allItemsSelect', ['as' => 'select2ItemsOfProveedores']);
|
||||
$routes->post('menuitems', 'Proveedores::menuItems', ['as' => 'menuItemsOfProveedores']);
|
||||
$routes->get('getProveedores', 'Proveedores::getForSelect');
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
13
ci4/app/Config/Routes/ConfiguracionRoutes.php
Normal file → Executable file
13
ci4/app/Config/Routes/ConfiguracionRoutes.php
Normal file → Executable file
@ -53,7 +53,6 @@ $routes->group('configuracion', ['namespace' => 'App\Controllers\Configuracion']
|
||||
$routes->post('duplicate/(:num)', 'Papelesimpresion::duplicate/$1', ['as' => 'duplicatePapelImpresion']);
|
||||
$routes->get('select', 'Papelesimpresion::papel_impresion_select', ['as' => 'papelImpresionSelect']);
|
||||
$routes->get('show/(:num)', 'Papelesimpresion::papel_impresion_find/$1', ['as' => 'showPapelImpresion']);
|
||||
|
||||
});
|
||||
|
||||
/* Maquinas */
|
||||
@ -149,5 +148,15 @@ $routes->group('configuracion', ['namespace' => 'App\Controllers\Configuracion']
|
||||
$routes->group("messages", ["namespace" => 'App\Controllers\Chat'], function ($routes) {
|
||||
$routes->get('', 'ChatController::config_view', ['as' => 'configMessagesIndex']);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
/* Festivos */
|
||||
$routes->group("festivos", ["namespace" => 'App\Controllers\Configuracion'], function ($routes) {
|
||||
$routes->get('', 'FestivoController::index', ['as' => 'festivosList']);
|
||||
$routes->post('', 'FestivoController::store_festivo_date', ['as' => 'storeFestivoDate']);
|
||||
$routes->delete('(:num)', 'FestivoController::delete_festivo_date/$1', ['as' => 'deleteFestivoDate']);
|
||||
$routes->get('all', 'FestivoController::find_all', ['as' => 'getFindAllFestivos']);
|
||||
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
39
ci4/app/Config/Routes/ImportadoresRoutes.php
Normal file
39
ci4/app/Config/Routes/ImportadoresRoutes.php
Normal file
@ -0,0 +1,39 @@
|
||||
<?php
|
||||
|
||||
use CodeIgniter\Router\RouteCollection;
|
||||
|
||||
/** @var RouteCollection $routes */
|
||||
|
||||
/* Rutas para tarifas */
|
||||
$routes->group('importador', ['namespace' => 'App\Controllers\Importadores'], function ($routes) {
|
||||
|
||||
/* Desde Catalogo */
|
||||
$routes->group('catalogo', ['namespace' => 'App\Controllers\Importadores'], function ($routes) {
|
||||
/**======================
|
||||
* Tool
|
||||
*========================**/
|
||||
$routes->get('', 'ImportadorCatalogo::index', ['as' => 'importadorCatalogoTool']);
|
||||
|
||||
/**======================
|
||||
* AJAX
|
||||
*========================**/
|
||||
$routes->post('validar-fila', 'ImportadorCatalogo::validarFila');
|
||||
$routes->post('importar-fila', 'ImportadorCatalogo::importarFila');
|
||||
|
||||
});
|
||||
|
||||
/* Desde Cliente Bubok */
|
||||
$routes->group('bubok', ['namespace' => 'App\Controllers\Importadores'], function ($routes) {
|
||||
/**======================
|
||||
* Tool
|
||||
*========================**/
|
||||
$routes->get('', 'ImportadorBubok::index', ['as' => 'importadorBubokTool']);
|
||||
|
||||
/**======================
|
||||
* AJAX
|
||||
*========================**/
|
||||
$routes->post('validar-fila', 'ImportadorBubok::validarFila');
|
||||
$routes->post('importar-fila', 'ImportadorBubok::importarFila');
|
||||
|
||||
});
|
||||
});
|
||||
8
ci4/app/Config/Routes/PresupuestosRoutes.php
Normal file → Executable file
8
ci4/app/Config/Routes/PresupuestosRoutes.php
Normal file → Executable file
@ -17,6 +17,8 @@ $routes->group('presupuestoadmin', ['namespace' => 'App\Controllers\Presupuestos
|
||||
$routes->post('allmenuitems', 'Presupuestoadmin::allItemsSelect', ['as' => 'select2ItemsOfPresupuestoAdmin']);
|
||||
$routes->post('menuitems', 'Presupuestoadmin::menuItems', ['as' => 'menuItemsOfPresupuestoAdmin']);
|
||||
|
||||
$routes->get('checklomointerior', 'Presupuestoadmin::checkLomo');
|
||||
|
||||
$routes->get('cargar/(:any)', 'Presupuestoadmin::cargar/$1');
|
||||
$routes->post('comparadorinterior', 'Presupuestoadmin::obtenerComparadorInterior');
|
||||
$routes->post('comparadorexteriores', 'Presupuestoadmin::obtenerComparadorExteriores');
|
||||
@ -30,6 +32,11 @@ $routes->group('presupuestoadmin', ['namespace' => 'App\Controllers\Presupuestos
|
||||
|
||||
$routes->get('presupuestosCliente', 'Presupuestoadmin::tablaClienteForm');
|
||||
$routes->get('getSumCliente/(:num)', 'Presupuestoadmin::obtenerTotalPresupuestosCliente/$1');
|
||||
|
||||
$routes->get('hasFiles', 'Presupuestoadmin::hasFiles');
|
||||
$routes->post('reprint', 'Presupuestoadmin::reprintPresupuesto');
|
||||
|
||||
$routes->post('download_zip', 'Presupuestocliente::download_zip', ['as' => 'descargarAdminArchivos']);
|
||||
});
|
||||
|
||||
//$routes->resource('presupuestoadmin', ['namespace' => 'App\Controllers\Presupuestos', 'controller' => 'Presupuestoadmin', 'except' => 'show,new,create,update']);
|
||||
@ -51,6 +58,7 @@ $routes->group('presupuestocliente', ['namespace' => 'App\Controllers\Presupuest
|
||||
$routes->post('calcular', 'Presupuestocliente::calcular', ['as' => 'calcularPresupuesto']);
|
||||
$routes->post('calcularsolapas', 'Presupuestocliente::calcularMaxSolapas', ['as' => 'calcularSolapas']);
|
||||
$routes->post('checklomo', 'Presupuestocliente::check_lomo_interior');
|
||||
$routes->post('download_zip', 'Presupuestocliente::download_zip', ['as' => 'descargarClienteArchivos']);
|
||||
});
|
||||
//$routes->resource('presupuestocliente', ['namespace' => 'App\Controllers\Presupuestos', 'controller' => 'Presupuestocliente', 'except' => 'show,new,create,update']);
|
||||
|
||||
|
||||
13
ci4/app/Config/Routes/ScriptsRoutes.php
Normal file
13
ci4/app/Config/Routes/ScriptsRoutes.php
Normal file
@ -0,0 +1,13 @@
|
||||
<?php
|
||||
|
||||
use CodeIgniter\Router\RouteCollection;
|
||||
|
||||
/** @var RouteCollection $routes */
|
||||
|
||||
/* Rutas para tarifas */
|
||||
$routes->group('scripts', ['namespace' => 'App\Controllers\Scripts'], function ($routes) {
|
||||
|
||||
//$routes->get('completar-identidades', 'UsersIntegrity::completarIdentidades');
|
||||
|
||||
|
||||
});
|
||||
35
ci4/app/Config/Routes/SistemaRoutes.php
Normal file
35
ci4/app/Config/Routes/SistemaRoutes.php
Normal file
@ -0,0 +1,35 @@
|
||||
<?php
|
||||
|
||||
use CodeIgniter\Router\RouteCollection;
|
||||
|
||||
/** @var RouteCollection $routes */
|
||||
|
||||
/* Rutas para tarifas */
|
||||
$routes->group('sistema', ['namespace' => 'App\Controllers\Sistema'], function ($routes) {
|
||||
/* Actividad */
|
||||
$routes->group('actividad', ['namespace' => 'App\Controllers\Sistema'], function ($routes) {
|
||||
/**======================
|
||||
* CRUD
|
||||
*========================**/
|
||||
$routes->get('', 'Actividad::index', ['as' => 'activityList']);
|
||||
$routes->post('datatable', 'Actividad::datatable', ['as' => 'activityDT']);
|
||||
|
||||
});
|
||||
|
||||
/* Backups */
|
||||
$routes->group('backups', function ($routes) {
|
||||
/**======================
|
||||
* Tool
|
||||
*========================**/
|
||||
$routes->get('', 'Backups::index', ['as' => 'backupsList']);
|
||||
$routes->get('create', 'Backups::create', ['as' => 'backupsCreate']);
|
||||
$routes->get('create-dev', 'Backups::createDevelopment', ['as' => 'backupsCreateDev']);
|
||||
$routes->get('backups/download/(:segment)', 'Backups::download/$1', ['as' => 'backupsDownload']);
|
||||
$routes->get('delete-local/(:num)', 'Backups::deleteLocal/$1', ['as' => 'backupsDeleteLocal']);
|
||||
$routes->get('delete-local-dev/(:segment)', 'Backups::deleteLocalDevelopment/$1', ['as' => 'backupsDeleteLocalDev']);
|
||||
$routes->get('restore/(:segment)/local', 'Backups::restoreLocal/$1', ['as' => 'backupsRestoreLocal']);
|
||||
$routes->get('restore/(:segment)/remote', 'Backups::restoreRemote/$1', ['as' => 'backupsRestoreRemote']);
|
||||
|
||||
});
|
||||
|
||||
});
|
||||
0
ci4/app/Config/Routes/TarifasRoutes.php
Normal file → Executable file
0
ci4/app/Config/Routes/TarifasRoutes.php
Normal file → Executable file
0
ci4/app/Config/Routing.php
Normal file → Executable file
0
ci4/app/Config/Routing.php
Normal file → Executable file
0
ci4/app/Config/Safekat.php
Normal file → Executable file
0
ci4/app/Config/Safekat.php
Normal file → Executable file
@ -11,6 +11,7 @@ use App\Services\PapelImpresionService;
|
||||
use CodeIgniter\Config\BaseService;
|
||||
use App\Services\ProductionService;
|
||||
use App\Services\TarifaMaquinaService;
|
||||
use App\Services\PapelService;
|
||||
use CodeIgniter\Email\Email;
|
||||
|
||||
/**
|
||||
@ -39,6 +40,9 @@ class Services extends BaseService
|
||||
* }
|
||||
*/
|
||||
|
||||
public static function papel(){
|
||||
return new PapelService();
|
||||
}
|
||||
public static function production(){
|
||||
return new ProductionService();
|
||||
}
|
||||
|
||||
0
ci4/app/Config/Session.php
Normal file → Executable file
0
ci4/app/Config/Session.php
Normal file → Executable file
0
ci4/app/Config/Toolbar.php
Normal file → Executable file
0
ci4/app/Config/Toolbar.php
Normal file → Executable file
@ -155,12 +155,61 @@ class Validation extends BaseConfig
|
||||
],
|
||||
|
||||
];
|
||||
public array $orden_trabajo_tarea_progress_date = [
|
||||
|
||||
"ot_tarea_id" => [
|
||||
"rules" => "required|integer",
|
||||
"label" => "tarea"
|
||||
],
|
||||
"estado" => [
|
||||
"rules" => "required|in_list[P,I,S,D,F,E]",
|
||||
"label" => "estado"
|
||||
]
|
||||
];
|
||||
public array $orden_trabajo = [
|
||||
"orden_trabajo_id" => [
|
||||
"rules" => "required|integer",
|
||||
"label" => "Orden trabajo"
|
||||
],
|
||||
|
||||
];
|
||||
public array $orden_trabajo_fichaje_auto = [
|
||||
"orden_trabajo_id" => [
|
||||
"rules" => "required|integer",
|
||||
"label" => "Orden trabajo"
|
||||
],
|
||||
"maquina_id" => [
|
||||
"rules" => "required|integer",
|
||||
"label" => "Máquina"
|
||||
],
|
||||
"estado" => [
|
||||
"rules" => "required|in_list[P,I,S,D,F,E]",
|
||||
"label" => "estado"
|
||||
],
|
||||
"tareas" => [
|
||||
"rules" => "required",
|
||||
"label" => "Tareas"
|
||||
],
|
||||
"click_init" => [
|
||||
"rules" => "required|integer",
|
||||
"label" => "Click init"
|
||||
],
|
||||
"click_end" => [
|
||||
"rules" => "required|integer",
|
||||
"label" => "Click end"
|
||||
],
|
||||
|
||||
];
|
||||
public array $maquina_ordenes_trabajo = [
|
||||
"ordenes_trabajo" => [
|
||||
"rules" => "required",
|
||||
"label" => "Orden trabajo"
|
||||
],
|
||||
"maquina_id" => [
|
||||
"rules" => "required|integer",
|
||||
"label" => "Máquina"
|
||||
],
|
||||
|
||||
];
|
||||
public array $chat_department =
|
||||
[
|
||||
@ -173,4 +222,15 @@ class Validation extends BaseConfig
|
||||
"label" => "maquina",
|
||||
],
|
||||
];
|
||||
public array $proveedor_tarea =
|
||||
[
|
||||
"proveedor_id" => [
|
||||
"rules" => "required|integer",
|
||||
"label" => "Proveedor",
|
||||
],
|
||||
"orden_trabajo_tarea_id" => [
|
||||
"rules" => "required|integer",
|
||||
"label" => "Tarea",
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
0
ci4/app/Config/Wiki/WikiRoutes.php
Normal file → Executable file
0
ci4/app/Config/Wiki/WikiRoutes.php
Normal file → Executable file
11
ci4/app/Controllers/API/ImprimelibrosApi.php
Normal file → Executable file
11
ci4/app/Controllers/API/ImprimelibrosApi.php
Normal file → Executable file
@ -5,22 +5,13 @@ namespace App\Controllers\API;
|
||||
use App\Controllers\Presupuestos\Presupuestocliente;
|
||||
use CodeIgniter\RESTful\ResourceController;
|
||||
use CodeIgniter\API\ResponseTrait;
|
||||
use App\Models\API\ItemModel;
|
||||
|
||||
class ImprimelibrosApi extends ResourceController
|
||||
{
|
||||
|
||||
use ResponseTrait;
|
||||
|
||||
public function index()
|
||||
{
|
||||
$model = new ItemModel();
|
||||
$data = $model->findAll();
|
||||
return $this->respond($data);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
public function calcular()
|
||||
{
|
||||
helper(['form']);
|
||||
|
||||
642
ci4/app/Controllers/Albaranes/Albaran.php
Executable file
642
ci4/app/Controllers/Albaranes/Albaran.php
Executable file
@ -0,0 +1,642 @@
|
||||
<?php
|
||||
|
||||
namespace App\Controllers\Albaranes;
|
||||
use App\Entities\Albaranes\AlbaranEntity;
|
||||
use App\Models\Albaranes\AlbaranModel;
|
||||
use Hermawan\DataTables\DataTable;
|
||||
|
||||
class Albaran extends \App\Controllers\BaseResourceController
|
||||
{
|
||||
protected $modelName = AlbaranModel::class;
|
||||
protected $format = 'json';
|
||||
|
||||
protected static $singularObjectNameCc = 'albaran';
|
||||
protected static $singularObjectName = 'Albaran';
|
||||
protected static $pluralObjectName = 'Albaranes';
|
||||
protected static $controllerSlug = 'albaran';
|
||||
|
||||
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
|
||||
{
|
||||
parent::initController($request, $response, $logger);
|
||||
}
|
||||
|
||||
public function index()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
public function delete($id = null)
|
||||
{
|
||||
if ($this->request->isAJAX()) {
|
||||
|
||||
$newTokenHash = csrf_hash();
|
||||
$csrfTokenName = csrf_token();
|
||||
|
||||
$model_linea = model('App\Models\Albaranes\AlbaranLineaModel');
|
||||
$model_linea->where('albaran_id', $id)->delete();
|
||||
|
||||
$this->model->where('id', $id)->delete();
|
||||
|
||||
$data = [
|
||||
'error' => 0,
|
||||
$csrfTokenName => $newTokenHash
|
||||
];
|
||||
return $this->respond($data);
|
||||
} else {
|
||||
return $this->failUnauthorized('Invalid request', 403);
|
||||
}
|
||||
}
|
||||
|
||||
public function editAlbaran($albaran_id){
|
||||
|
||||
$albaran = $this->model->find($albaran_id);
|
||||
if ($albaran == false) {
|
||||
return redirect()->to(base_url('albaranesList'));
|
||||
}
|
||||
$this->viewData['boxTitle'] = lang('Albaran.editAlbaran') . ' ' . $albaran->numero_albaran;
|
||||
$this->viewData['albaranId'] = $albaran_id;
|
||||
|
||||
return view('themes/vuexy/form/logistica/albaranes/viewAlbaranesEdit', $this->viewData);
|
||||
}
|
||||
|
||||
public function addLinea($albaran_id)
|
||||
{
|
||||
|
||||
if ($this->request->isAJAX()) {
|
||||
|
||||
$model_linea = model('App\Models\Albaranes\AlbaranLineaModel');
|
||||
$newTokenHash = csrf_hash();
|
||||
$csrfTokenName = csrf_token();
|
||||
|
||||
// si es un post, es el iva
|
||||
if ($this->request->getPost()) {
|
||||
$reqData = $this->request->getPost();
|
||||
$albaran_id = $reqData['albaran_id'] ?? 0;
|
||||
|
||||
$albaran = $this->model->find($albaran_id);
|
||||
if ($albaran == false) {
|
||||
$data = [
|
||||
'error' => 'Albaran no encontrado',
|
||||
$csrfTokenName => $newTokenHash
|
||||
];
|
||||
return $this->respond($data);
|
||||
}
|
||||
$presupuesto_model = model('App\Models\Presupuestos\PresupuestoModel');
|
||||
$presupuesto = $presupuesto_model->find($albaran->presupuesto_id);
|
||||
if ($presupuesto == false) {
|
||||
$data = [
|
||||
'error' => 'Presupuesto no encontrado',
|
||||
$csrfTokenName => $newTokenHash
|
||||
];
|
||||
return $this->respond($data);
|
||||
}
|
||||
$iva_reducido = $presupuesto->iva_reducido;
|
||||
$lineas = $model_linea->where('albaran_id', $albaran_id)->findAll();
|
||||
$total = 0;
|
||||
foreach ($lineas as $linea) {
|
||||
$total += $linea->total;
|
||||
}
|
||||
$iva = $iva_reducido ? $total * 4.0 / 100 : $total * 21.0 / 100;
|
||||
$data_linea = [
|
||||
'albaran_id' => $albaran_id,
|
||||
'titulo' => $iva_reducido ? lang('Pedidos.iva4') : lang('Pedidos.iva21'),
|
||||
'cantidad' => 1,
|
||||
'precio_unidad' => round($iva, 2),
|
||||
'total' => round($iva, 2),
|
||||
'user_created_id' => auth()->user()->id,
|
||||
'user_updated_id' => auth()->user()->id
|
||||
];
|
||||
$id_linea = $model_linea->insert($data_linea);
|
||||
$linea = $model_linea->find($id_linea);
|
||||
$data = [
|
||||
'error' => 0,
|
||||
'data' => $linea,
|
||||
$csrfTokenName => $newTokenHash
|
||||
];
|
||||
return $this->respond($data);
|
||||
} else {
|
||||
$linea = [
|
||||
'albaran_id' => $albaran_id,
|
||||
'user_created_id' => auth()->user()->id,
|
||||
'user_updated_id' => auth()->user()->id
|
||||
];
|
||||
$id_linea = $model_linea->insert($linea);
|
||||
$data = $model_linea->find($id_linea);
|
||||
|
||||
$data = [
|
||||
'error' => 0,
|
||||
'data' => $data,
|
||||
$csrfTokenName => $newTokenHash
|
||||
];
|
||||
return $this->respond($data);
|
||||
}
|
||||
} else {
|
||||
return $this->failUnauthorized('Invalid request', 403);
|
||||
}
|
||||
}
|
||||
|
||||
public function add()
|
||||
{
|
||||
if ($this->request->isAJAX()) {
|
||||
|
||||
$user = auth()->user()->id;
|
||||
|
||||
$newTokenHash = csrf_hash();
|
||||
$csrfTokenName = csrf_token();
|
||||
|
||||
$reqData = $this->request->getPost();
|
||||
$pedido_id = $reqData['pedido_id'] ?? 0;
|
||||
$presupuestos_id = $reqData['presupuestos_id'] ?? 0;
|
||||
|
||||
$return_data = $this->model->generarAlbaranes($pedido_id, $presupuestos_id, $user);
|
||||
$data = [
|
||||
'data' => $return_data,
|
||||
$csrfTokenName => $newTokenHash
|
||||
];
|
||||
|
||||
return $this->respond($data);
|
||||
|
||||
} else {
|
||||
return $this->failUnauthorized('Invalid request', 403);
|
||||
}
|
||||
}
|
||||
|
||||
public function updateAlbaran()
|
||||
{
|
||||
|
||||
if ($this->request->isAJAX()) {
|
||||
|
||||
$fieldName = $this->request->getPost('fieldName');
|
||||
$fieldValue = $this->request->getPost('fieldValue');
|
||||
$id = $this->request->getPost('albaranId');
|
||||
|
||||
if ($id == null) {
|
||||
$data = [
|
||||
'success' => false,
|
||||
'message' => lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('Pedidos.albaran')), $id]),
|
||||
];
|
||||
return $this->respond($data);
|
||||
}
|
||||
$albaranEntity = $this->model->find($id);
|
||||
|
||||
if ($albaranEntity == false) {
|
||||
$data = [
|
||||
'success' => false,
|
||||
'message' => lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('Pedidos.albaran')), $id]),
|
||||
];
|
||||
return $this->respond($data);
|
||||
}
|
||||
|
||||
if($fieldName == 'fecha_albaran'){
|
||||
if($fieldValue == null || $fieldValue == '')
|
||||
$fieldValue = null;
|
||||
else
|
||||
$fieldValue = date('Y-m-d H:i:s', strtotime($fieldValue));
|
||||
}
|
||||
|
||||
$albaranEntity->fill([
|
||||
$fieldName => $fieldValue,
|
||||
'user_updated_id' => auth()->user()->id,
|
||||
]);
|
||||
$successfulResult = $this->model->skipValidation(true)->update($id, $albaranEntity);
|
||||
if ($successfulResult) {
|
||||
$data = [
|
||||
'success' => true,
|
||||
'message' => lang('Basic.global.updateSuccess', [lang('Basic.global.record')]) . '.',
|
||||
];
|
||||
} else {
|
||||
$data = [
|
||||
'success' => false,
|
||||
'message' => lang('Basic.global.updateError', [lang('Basic.global.record')]) . '.',
|
||||
];
|
||||
}
|
||||
|
||||
return $this->respond($data);
|
||||
} else {
|
||||
return $this->failUnauthorized('Invalid request', 403);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public function updateLinea($id = null)
|
||||
{
|
||||
|
||||
if ($this->request->isAJAX()) {
|
||||
|
||||
$model_linea = model('App\Models\Albaranes\AlbaranLineaModel');
|
||||
$newTokenHash = csrf_hash();
|
||||
$csrfTokenName = csrf_token();
|
||||
|
||||
if ($id == null):
|
||||
$data = [
|
||||
'error' => 2,
|
||||
$csrfTokenName => $newTokenHash
|
||||
];
|
||||
return $this->respond($data);
|
||||
endif;
|
||||
$id = filter_var($id, FILTER_SANITIZE_URL);
|
||||
$albaranEntity = $model_linea->find($id);
|
||||
|
||||
if ($albaranEntity == false):
|
||||
$message = lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('Pedidos.albaran')), $id]);
|
||||
$data = [
|
||||
'error' => $message,
|
||||
$csrfTokenName => $newTokenHash
|
||||
];
|
||||
return $this->respond($data);
|
||||
endif;
|
||||
|
||||
if ($this->request->getPost()):
|
||||
|
||||
$nullIfEmpty = true; // !(phpversion() >= '8.1');
|
||||
|
||||
$postData = $this->request->getPost();
|
||||
|
||||
$sanitizedData = $this->sanitized($postData, $nullIfEmpty);
|
||||
|
||||
// JJO
|
||||
$sanitizedData['user_updated_id'] = auth()->user()->id;
|
||||
|
||||
$noException = true;
|
||||
if ($successfulResult = $this->canValidate()): // if ($successfulResult = $this->validate($this->formValidationRules) ) :
|
||||
|
||||
if ($this->canValidate()):
|
||||
try {
|
||||
$successfulResult = $model_linea->skipValidation(true)->update($id, $sanitizedData);
|
||||
} catch (\Exception $e) {
|
||||
$noException = false;
|
||||
$this->dealWithException($e);
|
||||
}
|
||||
else:
|
||||
$this->viewData['warningMessage'] = lang('Basic.global.formErr1', [mb_strtolower(lang('Pedidos.albaran'))]);
|
||||
$this->session->setFlashdata('formErrors', $model_linea->errors());
|
||||
|
||||
endif;
|
||||
|
||||
$albaranEntity->fill($sanitizedData);
|
||||
|
||||
endif;
|
||||
if ($noException && $successfulResult):
|
||||
$id = $albaranEntity->id ?? $id;
|
||||
$message = lang('Basic.global.updateSuccess', [lang('Basic.global.record')]) . '.';
|
||||
|
||||
$data = [
|
||||
'error' => 0,
|
||||
$csrfTokenName => $newTokenHash
|
||||
];
|
||||
return $this->respond($data);
|
||||
|
||||
endif; // $noException && $successfulResult
|
||||
endif; // ($requestMethod === 'post')
|
||||
|
||||
$data = [
|
||||
'error' => 1,
|
||||
$csrfTokenName => $newTokenHash
|
||||
];
|
||||
return $this->respond($data);
|
||||
} else {
|
||||
return $this->failUnauthorized('Invalid request', 403);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public function getAlbaranes()
|
||||
{
|
||||
|
||||
if ($this->request->isAJAX()) {
|
||||
|
||||
$envio_id = $this->request->getGet('envio_id');
|
||||
$albaranes = $this->model->getAlbaranesEnvio($envio_id);
|
||||
$data = [
|
||||
'status' => true,
|
||||
'data' => $albaranes,
|
||||
];
|
||||
return $this->respond($data);
|
||||
} else {
|
||||
return $this->failUnauthorized('Invalid request', 403);
|
||||
}
|
||||
}
|
||||
|
||||
public function getAlbaran()
|
||||
{
|
||||
|
||||
if ($this->request->isAJAX()) {
|
||||
|
||||
$id = $this->request->getGet('id');
|
||||
$albaran = $this->model->getAlbaranData($id);
|
||||
$data = [
|
||||
'success' => true,
|
||||
'data' => $albaran,
|
||||
];
|
||||
return $this->respond($data);
|
||||
} else {
|
||||
return $this->failUnauthorized('Invalid request', 403);
|
||||
}
|
||||
}
|
||||
|
||||
public function generateAlbaran()
|
||||
{
|
||||
|
||||
if ($this->request->isAJAX()) {
|
||||
|
||||
$reqData = $this->request->getPost();
|
||||
$envio_id = $reqData['envio_id'] ?? 0;
|
||||
$envio_lineas = $reqData['envio_lineas'] ?? [];
|
||||
$cajas = $reqData['cajas'] ?? 0;
|
||||
|
||||
$response = $this->model->generarAlbaranes($envio_id, $envio_lineas, $cajas);
|
||||
|
||||
return $this->respond($response);
|
||||
|
||||
} else {
|
||||
return $this->failUnauthorized('Invalid request', 403);
|
||||
}
|
||||
}
|
||||
|
||||
public function datatable(){
|
||||
|
||||
$pedidosFilter = $this->request->getGet('pedidosFilter');
|
||||
$q = $this->model->getDatatableQuery();
|
||||
|
||||
if($pedidosFilter != null && !empty($pedidosFilter)) {
|
||||
$q->groupStart();
|
||||
$q->like('t4.id', $pedidosFilter);
|
||||
$q->groupEnd();
|
||||
}
|
||||
$result = DataTable::of($q)
|
||||
->add(
|
||||
"action",
|
||||
callback: function ($q) {
|
||||
return '
|
||||
<div class="btn-group btn-group-sm">
|
||||
<a href="javascript:void(0);"><i class="ti ti-pencil ti-sm btn-edit mx-2" data-id="' . $q->id . '"></i></a>
|
||||
<a href="javascript:void(0);"><i class="ti ti-trash ti-sm btn-delete mx-2" data-id="' . $q->id . '"></i></a>
|
||||
</div>
|
||||
';
|
||||
}
|
||||
);
|
||||
|
||||
return $result->toJson(returnAsObject: true);
|
||||
}
|
||||
|
||||
public function datatablesLineasAlbaran()
|
||||
{
|
||||
|
||||
$albaranId = $this->request->getGet('albaranId');
|
||||
$model = model('App\Models\Albaranes\AlbaranLineaModel');
|
||||
$q = $model->getDatatableQuery($albaranId);
|
||||
|
||||
$result = DataTable::of($q)
|
||||
->add(
|
||||
"action",
|
||||
callback: function ($q) {
|
||||
return '
|
||||
<div class="btn-group btn-group-sm">
|
||||
<a href="javascript:void(0);"><i class="ti ti-trash ti-sm btn-delete-albaran-lineas mx-2" data-id="' . $q->id . '"></i></a>
|
||||
</div>
|
||||
';
|
||||
}
|
||||
)
|
||||
->edit('pedido', function ($q) {
|
||||
return '<a href="' . base_url('pedidos/edit/' . $q->pedido) . '" target="_blank">' . $q->pedido . '</a>';
|
||||
})
|
||||
->edit('unidades', function ($q) {
|
||||
if(str_contains($q->titulo, 'IVA'))
|
||||
return null;
|
||||
else
|
||||
return '<input type="number" class="form-control form-control-sm input-albaran-linea text-center"
|
||||
value="' . $q->unidades . '" data-id="' . $q->id . '" data-field="cantidad" />';
|
||||
})
|
||||
->edit('titulo', function ($q) {
|
||||
return '<input type="text" class="form-control form-control-sm input-albaran-linea" value="' . $q->titulo .
|
||||
'" data-id="' . $q->id . '" data-field="titulo" />';
|
||||
})
|
||||
->edit('cajas', function ($q) {
|
||||
return '<input class="form-control input-albaran-linea
|
||||
form-control-sm text-center" value="' . $q->cajas . '" data-id="' . $q->id . '" data-field="cajas" />';
|
||||
})
|
||||
->edit('unidades_cajas', function ($q) {
|
||||
return '<input class="form-control input-albaran-linea
|
||||
form-control-sm text-center" value="' . $q->unidades_cajas . '" data-id="' . $q->id . '" data-field="unidades_cajas" />';
|
||||
})
|
||||
->edit('total', function ($q) {
|
||||
return '<input class="form-control autonumeric-2 input-albaran-linea
|
||||
form-control-sm text-center" value="' . $q->total . '" data-id="' . $q->id . '" data-field="total" />';
|
||||
})
|
||||
->edit('precio_unidad', function ($q) {
|
||||
if(str_contains($q->titulo, 'IVA'))
|
||||
return null;
|
||||
else
|
||||
return '<input class="form-control autonumeric-4 form-control-sm text-center input-albaran-linea" value="' .
|
||||
number_format((float) $q->precio_unidad, 4, ',', '') .
|
||||
'" data-id="' . $q->id . '" data-field="precio_unidad" />';
|
||||
});
|
||||
|
||||
|
||||
return $result->toJson(returnAsObject: true);
|
||||
}
|
||||
|
||||
public function updateAlbaranLinea(){
|
||||
|
||||
if ($this->request->isAJAX()) {
|
||||
|
||||
$model_linea = model('App\Models\Albaranes\AlbaranLineaModel');
|
||||
|
||||
|
||||
$fieldName = $this->request->getPost('fieldName');
|
||||
$fieldValue = $this->request->getPost('fieldValue');
|
||||
$id = $this->request->getPost('lineaId');
|
||||
|
||||
$linea = $model_linea->find($id);
|
||||
if ($linea == false) {
|
||||
$data = [
|
||||
'success' => false,
|
||||
'message' => lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('Pedidos.albaran')), $id]),
|
||||
];
|
||||
return $this->respond($data);
|
||||
}
|
||||
if($fieldName == 'cantidad') {
|
||||
$linea->total = round($linea->precio_unidad * intval($fieldValue), 4);
|
||||
$linea->cantidad = intval($fieldValue);
|
||||
}
|
||||
else if($fieldName == 'precio_unidad') {
|
||||
$fieldValue2 = str_replace(',', '.', $fieldValue);
|
||||
$linea->total = round(round(floatval($fieldValue2), 4) * intval($linea->cantidad), 2);
|
||||
$linea->precio_unidad = round(floatval($fieldValue2), 4);
|
||||
}
|
||||
else if($fieldName == 'total') {
|
||||
$linea->total = round(floatval($fieldValue), 2);
|
||||
$linea->precio_unidad = round(floatval($fieldValue) / intval($linea->cantidad), 4);
|
||||
}
|
||||
else{
|
||||
$linea->$fieldName = $fieldValue;
|
||||
}
|
||||
$linea->user_updated_id = auth()->user()->id;
|
||||
$linea->updated_at = date('Y-m-d H:i:s');
|
||||
|
||||
$model_linea->update($id, $linea->toArray());
|
||||
|
||||
if($fieldName == 'cajas'){
|
||||
$cajas = $model_linea->where('albaran_id', $linea->albaran_id)
|
||||
->where('cajas > 0')
|
||||
->select('SUM(cajas) as total_cajas')
|
||||
->get();
|
||||
|
||||
$albaranModel = model('App\Models\Albaranes\AlbaranModel');
|
||||
$albaran = $albaranModel->find($linea->albaran_id);
|
||||
if($albaran != false) {
|
||||
$albaran->cajas = $cajas->getRow()->total_cajas;
|
||||
$albaran->user_updated_id = auth()->user()->id;
|
||||
$albaran->updated_at = date('Y-m-d H:i:s');
|
||||
$albaranModel->update($linea->albaran_id, $albaran->toArray());
|
||||
}
|
||||
}
|
||||
|
||||
$data = [
|
||||
'success' => true,
|
||||
'message' => lang('Basic.global.updateSuccess', [lang('Basic.global.record')]) . '.',
|
||||
];
|
||||
if($fieldName == 'cajas') {
|
||||
$data['cajas'] = $cajas->getRow()->total_cajas;
|
||||
};
|
||||
return $this->respond($data);
|
||||
|
||||
} else {
|
||||
return $this->failUnauthorized('Invalid request', 403);
|
||||
}
|
||||
}
|
||||
|
||||
public function addLineasIva(){
|
||||
|
||||
if ($this->request->isAJAX()) {
|
||||
|
||||
$albaran_id = $this->request->getPost('albaranId');
|
||||
$model_linea = model('App\Models\Albaranes\AlbaranLineaModel');
|
||||
|
||||
$lineas_albaran = $model_linea->where('albaran_id', $albaran_id)->findAll();
|
||||
$iva_reducido = 0;
|
||||
$iva_no_reducido = 0;
|
||||
foreach ($lineas_albaran as $linea) {
|
||||
if($linea->iva_reducido == 1) {
|
||||
$iva_reducido += round(floatval($linea->total)*0.04, 2);
|
||||
} else {
|
||||
$iva_no_reducido += round(floatval($linea->total)*0.21, 2);
|
||||
}
|
||||
}
|
||||
$iva_reducido = round($iva_reducido, 2);
|
||||
$iva_no_reducido = round($iva_no_reducido, 2);
|
||||
if($iva_reducido > 0) {
|
||||
$linea = [
|
||||
'albaran_id' => $albaran_id,
|
||||
'titulo' => lang('Albaran.iva4'),
|
||||
'total' => round($iva_reducido, 2),
|
||||
'user_created_id' => auth()->user()->id,
|
||||
'user_updated_id' => auth()->user()->id
|
||||
];
|
||||
$model_linea->insert($linea);
|
||||
}
|
||||
if($iva_no_reducido > 0) {
|
||||
$linea = [
|
||||
'albaran_id' => $albaran_id,
|
||||
'titulo' => lang('Albaran.iva21'),
|
||||
'total' => round($iva_no_reducido, 2),
|
||||
'user_created_id' => auth()->user()->id,
|
||||
'user_updated_id' => auth()->user()->id
|
||||
];
|
||||
$model_linea->insert($linea);
|
||||
}
|
||||
$data = [
|
||||
'success' => true,
|
||||
'message' => lang('Basic.global.updateSuccess', [lang('Basic.global.record')]) . '.',
|
||||
];
|
||||
return $this->respond($data);
|
||||
|
||||
} else {
|
||||
return $this->failUnauthorized('Invalid request', 403);
|
||||
}
|
||||
}
|
||||
|
||||
public function addBlankLineaAlbaran(){
|
||||
|
||||
if ($this->request->isAJAX()) {
|
||||
|
||||
$albaran_id = $this->request->getPost('albaranId');
|
||||
$model_linea = model('App\Models\Albaranes\AlbaranLineaModel');
|
||||
|
||||
$linea = [
|
||||
'albaran_id' => $albaran_id,
|
||||
'user_created_id' => auth()->user()->id,
|
||||
'user_updated_id' => auth()->user()->id
|
||||
];
|
||||
$id_linea = $model_linea->insert($linea);
|
||||
$data = $model_linea->find($id_linea);
|
||||
|
||||
$data = [
|
||||
'success' => true,
|
||||
];
|
||||
return $this->respond($data);
|
||||
} else {
|
||||
return $this->failUnauthorized('Invalid request', 403);
|
||||
}
|
||||
}
|
||||
|
||||
public function borrarLinea()
|
||||
{
|
||||
|
||||
if ($this->request->isAJAX()) {
|
||||
|
||||
$model_linea = model('App\Models\Albaranes\AlbaranLineaModel');
|
||||
|
||||
$reqData = $this->request->getPost();
|
||||
$id = $reqData['linea'] ?? 0;
|
||||
$id = filter_var($id, FILTER_SANITIZE_URL);
|
||||
$albaranLineaEntity = $model_linea->find($id);
|
||||
|
||||
if ($albaranLineaEntity == false):
|
||||
$message = lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('Pedidos.albaran')), $id]);
|
||||
$data = [
|
||||
'success' => false,
|
||||
'error' => $message,
|
||||
];
|
||||
return $this->respond($data);
|
||||
endif;
|
||||
|
||||
$successfulResult = $model_linea->skipValidation(true)->update($id, ['deleted_at' => date('Y-m-d H:i:s')]);
|
||||
|
||||
if ($successfulResult):
|
||||
$data = [
|
||||
'success' => true,
|
||||
];
|
||||
else:
|
||||
$data = [
|
||||
'success' => false,
|
||||
'error' => lang('Basic.global.deleteError', [lang('Basic.global.record')]) . '.',
|
||||
];
|
||||
endif;
|
||||
return $this->respond($data);
|
||||
} else {
|
||||
return $this->failUnauthorized('Invalid request', 403);
|
||||
}
|
||||
}
|
||||
|
||||
public function borrarAlbaran()
|
||||
{
|
||||
|
||||
if ($this->request->isAJAX()) {
|
||||
|
||||
$id = $this->request->getPost('albaranId');
|
||||
$model_linea = model('App\Models\Albaranes\AlbaranLineaModel');
|
||||
$model_linea->where('albaran_id', $id)->delete();
|
||||
|
||||
$this->model->where('id', $id)->delete();
|
||||
|
||||
$data = [
|
||||
'success' => true
|
||||
];
|
||||
return $this->respond($data);
|
||||
} else {
|
||||
return $this->failUnauthorized('Invalid request', 403);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@ -35,7 +35,7 @@ class BaseController extends Controller
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $helpers = ['general', 'go_common', 'rbac'];
|
||||
protected $helpers = ['general', 'go_common', 'rbac', 'assets'];
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
|
||||
30
ci4/app/Controllers/BaseResourceController.php
Normal file → Executable file
30
ci4/app/Controllers/BaseResourceController.php
Normal file → Executable file
@ -77,6 +77,14 @@ abstract class BaseResourceController extends \CodeIgniter\RESTful\ResourceContr
|
||||
*/
|
||||
public $alertStyle = 'alerts';
|
||||
|
||||
/**
|
||||
* Permiso requerido para borrar. Si es false/null, no se valida.
|
||||
* Si es un string (nombre del permiso), se valida.
|
||||
*
|
||||
* @var string|false|null
|
||||
*/
|
||||
protected $deletePermission = false;
|
||||
|
||||
|
||||
/**
|
||||
* An array of helpers to be loaded automatically upon
|
||||
@ -85,7 +93,7 @@ abstract class BaseResourceController extends \CodeIgniter\RESTful\ResourceContr
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $helpers = ['session', 'go_common', 'form', 'text', 'general', 'rbac']; //JJO
|
||||
protected $helpers = ['session', 'go_common', 'form', 'text', 'general', 'rbac', 'assets']; //JJO
|
||||
|
||||
/**
|
||||
* Initializer method.
|
||||
@ -222,6 +230,13 @@ abstract class BaseResourceController extends \CodeIgniter\RESTful\ResourceContr
|
||||
*/
|
||||
public function delete($id = null)
|
||||
{
|
||||
|
||||
// 🔒 Verificar permiso solo si está definido como string
|
||||
if (is_string($this->deletePermission) && !auth()->user()->can($this->deletePermission)) {
|
||||
$message = lang('Basic.global.permissionDenied'); // O el mensaje que uses
|
||||
return $this->failWithNewToken($message, 403); // Estilo coherente con tu clase
|
||||
}
|
||||
|
||||
if (!empty(static::$pluralObjectNameCc) && !empty(static::$singularObjectNameCc)) {
|
||||
$objName = mb_strtolower(lang(ucfirst(static::$pluralObjectNameCc) . '.' . static::$singularObjectNameCc));
|
||||
} else {
|
||||
@ -236,8 +251,10 @@ abstract class BaseResourceController extends \CodeIgniter\RESTful\ResourceContr
|
||||
} else {
|
||||
$datetime = (new \CodeIgniter\I18n\Time("now"));
|
||||
$rawResult = $this->model->where('id', $id)
|
||||
->set(['deleted_at' => $datetime->format('Y-m-d H:i:s'),
|
||||
'is_deleted' => $this->delete_flag])
|
||||
->set([
|
||||
'deleted_at' => $datetime->format('Y-m-d H:i:s'),
|
||||
'is_deleted' => $this->delete_flag
|
||||
])
|
||||
->update();
|
||||
if (!$rawResult) {
|
||||
return $this->failNotFound(lang('Basic.global.deleteError', [$objName]));
|
||||
@ -270,7 +287,8 @@ abstract class BaseResourceController extends \CodeIgniter\RESTful\ResourceContr
|
||||
}
|
||||
|
||||
if ($customValidationMessages == null) {
|
||||
$validationErrorMessages = $this->model->validationMessages ?? $this->formValidationErrorMessagess ?? null;;
|
||||
$validationErrorMessages = $this->model->validationMessages ?? $this->formValidationErrorMessagess ?? null;
|
||||
;
|
||||
} else {
|
||||
$validationErrorMessages = $customValidationMessages;
|
||||
}
|
||||
@ -366,12 +384,12 @@ abstract class BaseResourceController extends \CodeIgniter\RESTful\ResourceContr
|
||||
$queryStr = !is_null($query) ? $query->getQuery() : '';
|
||||
$dbError = $this->model->db->error();
|
||||
$userFriendlyErrMsg = lang('Basic.global.persistErr1', [static::$singularObjectNameCc]);
|
||||
if (isset($dbError['code']) && $dbError['code'] == 1062) :
|
||||
if (isset($dbError['code']) && $dbError['code'] == 1062):
|
||||
$userFriendlyErrMsg .= PHP_EOL . lang('Basic.global.persistDuplErr', [static::$singularObjectNameCc]);
|
||||
endif;
|
||||
// $userFriendlyErrMsg = str_replace("'", "\'", $userFriendlyErrMsg); // Uncomment if experiencing unescaped single quote errors
|
||||
log_message('error', $userFriendlyErrMsg . PHP_EOL . $e->getMessage() . PHP_EOL . $queryStr);
|
||||
if (isset($dbError['message']) && !empty($dbError['message'])) :
|
||||
if (isset($dbError['message']) && !empty($dbError['message'])):
|
||||
log_message('error', $dbError['code'] . ' : ' . $dbError['message']);
|
||||
endif;
|
||||
$this->viewData['errorMessage'] = $userFriendlyErrMsg;
|
||||
|
||||
274
ci4/app/Controllers/Catalogo/CatalogoLibros.php
Normal file
274
ci4/app/Controllers/Catalogo/CatalogoLibros.php
Normal file
@ -0,0 +1,274 @@
|
||||
<?php
|
||||
namespace App\Controllers\Catalogo;
|
||||
|
||||
use App\Controllers\BaseResourceController;
|
||||
use App\Entities\Catalogo\CatalogoLibroEntity;
|
||||
use App\Models\Catalogo\CatalogoLibroModel;
|
||||
use App\Models\Clientes\ClienteModel;
|
||||
use App\Models\Presupuestos\ImportadorModel;
|
||||
use Hermawan\DataTables\DataTable;
|
||||
|
||||
class CatalogoLibros extends BaseResourceController
|
||||
{
|
||||
|
||||
protected $modelName = CatalogoLibroModel::class;
|
||||
protected $format = 'json';
|
||||
|
||||
protected static $singularObjectName = 'Catalogo';
|
||||
protected static $singularObjectNameCc = 'CatalogoLibros';
|
||||
protected static $pluralObjectName = 'Catalogos';
|
||||
protected static $pluralObjectNameCc = 'catalogos';
|
||||
|
||||
protected static $controllerSlug = 'catalogo';
|
||||
|
||||
protected static $viewPath = 'themes/vuexy/form/catalogo/';
|
||||
|
||||
protected $indexRoute = 'CatalogoLibrosList';
|
||||
|
||||
|
||||
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
|
||||
{
|
||||
$this->viewData['pageTitle'] = lang('Catalogo.listingPage');
|
||||
$this->viewData['usingSweetAlert'] = true;
|
||||
|
||||
// Breadcrumbs (IMN)
|
||||
$this->viewData['breadcrumb'] = [
|
||||
['title' => lang("App.menu_catalogo"), 'route' => "javascript:void(0);", 'active' => false],
|
||||
['title' => lang("App.menu_catalogo_libros"), 'route' => route_to('catalogoLibrosList'), 'active' => true]
|
||||
];
|
||||
|
||||
parent::initController($request, $response, $logger);
|
||||
}
|
||||
|
||||
|
||||
public function index()
|
||||
{
|
||||
|
||||
$viewData = [
|
||||
'currentModule' => static::$controllerSlug,
|
||||
'pageSubTitle' => lang('Basic.global.ManageAllRecords', [lang('Catalogo.catalogo')]),
|
||||
'catalogoLibrosEntity' => new CatalogoLibroEntity(),
|
||||
'usingServerSideDataTable' => true,
|
||||
];
|
||||
|
||||
$viewData = array_merge($this->viewData, $viewData); // merge any possible values from the parent controller class
|
||||
|
||||
return view(static::$viewPath . 'viewCatalogoLibrosList', $viewData);
|
||||
}
|
||||
|
||||
|
||||
public function add()
|
||||
{
|
||||
|
||||
if ($this->request->getPost()):
|
||||
|
||||
$postData = $this->request->getPost();
|
||||
|
||||
$sanitizedData = $this->sanitized($postData, true);
|
||||
|
||||
$sanitizedData['user_created_id'] = auth()->user()->id;
|
||||
unset($sanitizedData['iskn']);
|
||||
|
||||
$noException = true;
|
||||
if ($successfulResult = $this->canValidate()):
|
||||
|
||||
if ($this->canValidate()):
|
||||
try {
|
||||
$successfulResult = $this->model->skipValidation(true)->save($sanitizedData);
|
||||
} catch (\Exception $e) {
|
||||
$noException = false;
|
||||
$this->dealWithException($e);
|
||||
}
|
||||
else:
|
||||
$this->viewData['errorMessage'] = lang('Basic.global.formErr1', [lang('Basic.global.record')]);
|
||||
$this->session->setFlashdata('formErrors', $this->model->errors());
|
||||
endif;
|
||||
|
||||
$thenRedirect = true; // Change this to false if you want your user to stay on the form after submission
|
||||
endif;
|
||||
|
||||
if ($noException && $successfulResult):
|
||||
|
||||
$id = $this->model->db->insertID();
|
||||
|
||||
$message = lang('Basic.global.saveSuccess', [lang('Basic.global.record')]) . '.';
|
||||
|
||||
if ($thenRedirect):
|
||||
if (!empty($this->indexRoute)):
|
||||
return redirect()->to(route_to($this->indexRoute))->with('sweet-success', $message);
|
||||
else:
|
||||
return $this->redirect2listView('sweet-success', $message);
|
||||
endif;
|
||||
else:
|
||||
$this->session->setFlashData('sweet-success', $message);
|
||||
endif;
|
||||
|
||||
endif; // $noException && $successfulResult
|
||||
|
||||
endif; // ($requestMethod === 'post')
|
||||
|
||||
$this->viewData['catalogoLibrosEntity'] = isset($sanitizedData) ? new CatalogoLibroEntity($sanitizedData) : new CatalogoLibroEntity();
|
||||
$this->viewData['formAction'] = route_to('catalogoLibrosAdd');
|
||||
$this->viewData['boxTitle'] = lang('Basic.global.addNew') . ' ' . lang('Catalogo.moduleTitle') . ' ' . lang('Basic.global.addNewSuffix');
|
||||
|
||||
return $this->displayForm(__METHOD__);
|
||||
} // end function add()
|
||||
|
||||
public function edit($requestedId = null)
|
||||
{
|
||||
|
||||
if ($requestedId == null):
|
||||
return $this->redirect2listView();
|
||||
endif;
|
||||
$id = filter_var($requestedId, FILTER_SANITIZE_URL);
|
||||
$catalogoLibrosEntity = $this->model->find($id);
|
||||
|
||||
if ($catalogoLibrosEntity == false):
|
||||
$message = lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('Catalogo.pais')), $id]);
|
||||
return $this->redirect2listView('sweet-error', $message);
|
||||
endif;
|
||||
|
||||
if ($this->request->getPost()):
|
||||
|
||||
$postData = $this->request->getPost();
|
||||
$sanitizedData = $this->sanitized($postData, true);
|
||||
unset($sanitizedData['iskn']);
|
||||
$sanitizedData['user_update_id'] = auth()->user()->id;
|
||||
|
||||
$noException = true;
|
||||
|
||||
if ($successfulResult = $this->canValidate()): // if ($successfulResult = $this->validate($this->formValidationRules) ) :
|
||||
|
||||
|
||||
if ($this->canValidate()):
|
||||
try {
|
||||
$successfulResult = $this->model->skipValidation(true)->update($id, $sanitizedData);
|
||||
} catch (\Exception $e) {
|
||||
$noException = false;
|
||||
$this->dealWithException($e);
|
||||
}
|
||||
else:
|
||||
$this->viewData['warningMessage'] = lang('Basic.global.formErr1', [mb_strtolower(lang('Catalogo.catalogo'))]);
|
||||
$this->session->setFlashdata('formErrors', $this->model->errors());
|
||||
|
||||
endif;
|
||||
|
||||
$catalogoLibrosEntity->fill($sanitizedData);
|
||||
$thenRedirect = false;
|
||||
endif;
|
||||
|
||||
if ($noException && $successfulResult):
|
||||
$id = $catalogoLibrosEntity->id ?? $id;
|
||||
$message = lang('Basic.global.updateSuccess', [lang('Basic.global.record')]) . '.';
|
||||
|
||||
if ($thenRedirect):
|
||||
if (!empty($this->indexRoute)):
|
||||
return redirect()->to(route_to($this->indexRoute))->with('sweet-success', $message);
|
||||
else:
|
||||
return $this->redirect2listView('sweet-success', $message);
|
||||
endif;
|
||||
else:
|
||||
$this->session->setFlashData('sweet-success', $message);
|
||||
endif;
|
||||
|
||||
endif; // $noException && $successfulResult
|
||||
endif; // ($requestMethod === 'post')
|
||||
|
||||
|
||||
$this->viewData['catalogoLibrosEntity'] = $catalogoLibrosEntity;
|
||||
$this->viewData['formAction'] = route_to('catalogoLibrosEdit', $id);
|
||||
$this->viewData['boxTitle'] = lang('Basic.global.edit2') . ' ' . lang('Catalogo.moduleTitle') . ' ' . lang('Basic.global.edit3');
|
||||
|
||||
|
||||
return $this->displayForm(__METHOD__, $id);
|
||||
} // end function edit(...)
|
||||
|
||||
|
||||
public function datatable()
|
||||
{
|
||||
$reqData = $this->request->getGet();
|
||||
$start = $reqData['start'] ?? 0;
|
||||
$length = $reqData['length'] ?? 5;
|
||||
|
||||
$q = $this->model->getDatatableQuery()->limit($length, $start);
|
||||
|
||||
$result = DataTable::of($q)
|
||||
->edit(
|
||||
"portada",
|
||||
function ($row, $meta) {
|
||||
if (is_null($row->cubierta_archivo)) {
|
||||
return '<img class="img-thumbnail" src="' . $row->portada . '" alt="Portada" style="max-height: 80px;">';
|
||||
|
||||
} else {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
)
|
||||
->add("actionBtns", callback: function ($q) {
|
||||
$actions = '';
|
||||
if (auth()->user()->can('catalogo.edit')) {
|
||||
$actions .= '
|
||||
<div class="btn-group btn-group-sm">
|
||||
<a href="javascript:void(0);"><i class="ti ti-pencil ti-sm btn-edit mx-2" data-id="' . $q->id . '"></i></a>
|
||||
</div>';
|
||||
}
|
||||
if (auth()->user()->can('catalogo.delete')) {
|
||||
$actions .= '
|
||||
<div class="btn-group btn-group-sm">
|
||||
<a href="javascript:void(0);"><i class="ti ti-trash ti-sm btn-delete mx-2" data-id="' . $q->id . '"></i></a>
|
||||
</div>';
|
||||
}
|
||||
return $actions;
|
||||
});
|
||||
|
||||
return $result->toJson(returnAsObject: true);
|
||||
|
||||
}
|
||||
|
||||
/* IMN */
|
||||
public function getClientList()
|
||||
{
|
||||
$search = $this->request->getGet("q") ?? "";
|
||||
$data = (new ClienteModel())->getIdName($search);
|
||||
return $this->response->setJSON($data);
|
||||
|
||||
}
|
||||
|
||||
/* Historico de pedidos ERP antiguo */
|
||||
public function datatablePedidosAntiguos()
|
||||
{
|
||||
$reqData = $this->request->getGet();
|
||||
$start = $reqData['start'] ?? 0;
|
||||
$length = $reqData['length'] ?? 10;
|
||||
$catalogoId = $reqData['catalogo_id'] ?? null;
|
||||
|
||||
// Instanciar el modelo directamente
|
||||
$importadorModel = new ImportadorModel();
|
||||
|
||||
$q = $importadorModel->getHistoricoPedidosCatalogo($catalogoId);
|
||||
|
||||
return DataTable::of($q)
|
||||
->setSearchableColumns([
|
||||
't1.id',
|
||||
't1.created_at',
|
||||
't1.tirada',
|
||||
'(CASE WHEN t1.tirada > 0 THEN t1.total / t1.tirada ELSE 0 END)',
|
||||
't1.total',
|
||||
't1.estado'
|
||||
])
|
||||
->edit('total', fn($row) => number_format((float) $row->total, 2, ',', '.') . ' €')
|
||||
->edit('precio_ud', fn($row) => number_format((float) $row->precio_ud, 2, ',', '.') . ' €')
|
||||
->edit('created_at', fn($row) => date('d/m/Y', strtotime($row->created_at)))
|
||||
->add('actionBtns', function ($row) {
|
||||
return '<div class="btn-group btn-group-sm">
|
||||
<a href="https://gestion.safekat.es/pedido/detail/' . $row->id . '" class="btn btn-sm btn-info" target="_blank">
|
||||
<i class="ti ti-eye"></i> Ver
|
||||
</a>
|
||||
</div>';
|
||||
}, 'last')
|
||||
->toJson(returnAsObject: true);
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
192
ci4/app/Controllers/Chat/ChatController.php
Normal file → Executable file
192
ci4/app/Controllers/Chat/ChatController.php
Normal file → Executable file
@ -61,11 +61,13 @@ class ChatController extends BaseController
|
||||
$this->chatService = service("chat");
|
||||
|
||||
}
|
||||
public function index() {}
|
||||
public function get_chat_departments(string $model,int $modelId)
|
||||
public function index()
|
||||
{
|
||||
}
|
||||
public function get_chat_departments(string $model, int $modelId)
|
||||
{
|
||||
|
||||
$data = $this->chatService->getChatDepartments($model,$modelId);
|
||||
$data = $this->chatService->getChatDepartments($model, $modelId);
|
||||
|
||||
return $this->response->setJSON($data);
|
||||
}
|
||||
@ -222,6 +224,25 @@ class ChatController extends BaseController
|
||||
return view(static::$viewPath . 'messageChatInternal', $this->viewData);
|
||||
}
|
||||
}
|
||||
public function get_chat_ot_view($chat_id)
|
||||
{
|
||||
$chat = $this->chatModel->find($chat_id);
|
||||
$this->viewData['breadcrumb'] = [
|
||||
['title' => lang("Chat.chat"), 'route' => route_to("mensajeriaView"), 'active' => false],
|
||||
['title' => $chat->title, 'route' => 'javascript:void(0);', 'active' => true]
|
||||
];
|
||||
$this->viewData["modelId"] = $chat->orden_trabajo_id;
|
||||
$this->viewData["type"] = "ot";
|
||||
$auth_user = auth()->user();
|
||||
$this->chatModel->setAsViewedChatUserNotifications($chat_id, $auth_user->id);
|
||||
$this->chatModel->setAsUnviewedChatUserMessages($chat_id, $auth_user->id);
|
||||
|
||||
if ($chat->chat_department_id) {
|
||||
return view(static::$viewPath . 'messageChatFactura', $this->viewData);
|
||||
} else {
|
||||
return view(static::$viewPath . 'messageChatInternal', $this->viewData);
|
||||
}
|
||||
}
|
||||
public function get_chat(int $chat_id)
|
||||
{
|
||||
|
||||
@ -231,7 +252,7 @@ class ChatController extends BaseController
|
||||
public function store_message($model)
|
||||
{
|
||||
$data = $this->request->getPost();
|
||||
$chatMessageEntity = $this->chatService->storeChatMessage($data["chat_department_id"],$model,$data["model_id"],$data);
|
||||
$chatMessageEntity = $this->chatService->storeChatMessage($data["chat_department_id"], $model, $data["model_id"], $data);
|
||||
return $this->response->setJSON($chatMessageEntity);
|
||||
|
||||
}
|
||||
@ -322,36 +343,39 @@ class ChatController extends BaseController
|
||||
}
|
||||
public function get_chat_users_internal()
|
||||
{
|
||||
$query = $this->userModel->builder()->select(
|
||||
[
|
||||
"id",
|
||||
"CONCAT(first_name,' ',last_name,'(',username,')') as name"
|
||||
]
|
||||
)->where("cliente_id", null)
|
||||
->where("deleted_at", null)
|
||||
->whereNotIn("id", [auth()->user()->id]);
|
||||
if ($this->request->getGet("q")) {
|
||||
$query->groupStart()
|
||||
->orLike("users.username", $this->request->getGet("q"))
|
||||
->orLike("CONCAT(first_name,' ',last_name)", $this->request->getGet("q"))
|
||||
$builder = $this->userModel->builder();
|
||||
|
||||
$builder->select([
|
||||
'users.id',
|
||||
"CONCAT(first_name, ' ', last_name, ' (', auth_identities.secret, ')') AS name"
|
||||
])
|
||||
->join('auth_identities', 'auth_identities.user_id = users.id AND auth_identities.type = "email_password"')
|
||||
->where('cliente_id', null)
|
||||
->where('deleted_at', null)
|
||||
->whereNotIn('users.id', [auth()->user()->id]);
|
||||
|
||||
if ($this->request->getGet('q')) {
|
||||
$q = $this->request->getGet('q');
|
||||
$builder->groupStart()
|
||||
->orLike('auth_identities.secret', $q)
|
||||
->orLike("CONCAT(first_name, ' ', last_name)", $q)
|
||||
->groupEnd();
|
||||
}
|
||||
|
||||
return $this->response->setJSON($query->get()->getResultObject());
|
||||
return $this->response->setJSON($builder->get()->getResultObject());
|
||||
}
|
||||
public function get_chat_users_all()
|
||||
{
|
||||
$query = $this->userModel->builder()->select(
|
||||
[
|
||||
"id",
|
||||
"CONCAT(first_name,' ',last_name,'(',username,')') as name"
|
||||
"CONCAT(first_name,' ',last_name) as name"
|
||||
]
|
||||
)
|
||||
->where("deleted_at", null)
|
||||
->whereNotIn("id", [auth()->user()->id]);
|
||||
if ($this->request->getGet("q")) {
|
||||
$query->groupStart()
|
||||
->orLike("users.username", $this->request->getGet("q"))
|
||||
->orLike("CONCAT(first_name,' ',last_name)", $this->request->getGet("q"))
|
||||
->groupEnd();
|
||||
}
|
||||
@ -363,7 +387,7 @@ class ChatController extends BaseController
|
||||
$pm = model(PresupuestoModel::class);
|
||||
$p = $pm->find($presupuesto_id);
|
||||
$cm = model(ClienteModel::class);
|
||||
$clienteContactos = $cm->querySelectClienteContacto($p->cliente_id,$this->request->getGet('q'));
|
||||
$clienteContactos = $cm->querySelectClienteContacto($p->cliente_id, $this->request->getGet('q'));
|
||||
return $this->response->setJSON($clienteContactos);
|
||||
}
|
||||
public function get_pedido_client_users(int $pedido_id)
|
||||
@ -371,7 +395,7 @@ class ChatController extends BaseController
|
||||
$pm = model(PedidoModel::class);
|
||||
$p = $pm->find($pedido_id);
|
||||
$cm = model(ClienteModel::class);
|
||||
$clienteContactos = $cm->querySelectClienteContacto($p->cliente()->id,$this->request->getGet('q'));
|
||||
$clienteContactos = $cm->querySelectClienteContacto($p->cliente()->id, $this->request->getGet('q'));
|
||||
return $this->response->setJSON($clienteContactos);
|
||||
}
|
||||
public function get_factura_client_users(int $factura_id)
|
||||
@ -379,7 +403,7 @@ class ChatController extends BaseController
|
||||
$fm = model(FacturaModel::class);
|
||||
$f = $fm->find($factura_id);
|
||||
$cm = model(ClienteModel::class);
|
||||
$clienteContactos = $cm->querySelectClienteContacto($f->cliente_id,$this->request->getGet('q'));
|
||||
$clienteContactos = $cm->querySelectClienteContacto($f->cliente_id, $this->request->getGet('q'));
|
||||
return $this->response->setJSON($clienteContactos);
|
||||
}
|
||||
public function get_orden_trabajo_client_users(int $orden_trabajo_id)
|
||||
@ -388,21 +412,21 @@ class ChatController extends BaseController
|
||||
$ot = $otm->find($orden_trabajo_id);
|
||||
$cm = model(ClienteModel::class);
|
||||
$cliente = $ot->pedido()->cliente();
|
||||
$clienteContactos = $cm->querySelectClienteContacto($cliente->id,$this->request->getGet('q'));
|
||||
$clienteContactos = $cm->querySelectClienteContacto($cliente->id, $this->request->getGet('q'));
|
||||
return $this->response->setJSON($clienteContactos);
|
||||
}
|
||||
public function store_hebra(string $model)
|
||||
{
|
||||
$auth_user = auth()->user();
|
||||
$bodyData = $this->request->getPost();
|
||||
$status = $this->chatService->storeHebra($model,$bodyData['modelId'],$bodyData);
|
||||
$status = $this->chatService->storeHebra($model, $bodyData['modelId'], $bodyData);
|
||||
return $this->response->setJSON(["message" => "Hebra creada correctamente", "status" => $status]);
|
||||
}
|
||||
|
||||
public function update_hebra($chat_id)
|
||||
{
|
||||
$bodyData = $this->request->getPost();
|
||||
$chatMessageId = $this->chatMessageModel->insert([
|
||||
$chatMessageId = $this->chatMessageModel->insert([
|
||||
"chat_id" => $chat_id,
|
||||
"message" => $bodyData["message"],
|
||||
"sender_id" => auth()->user()->id
|
||||
@ -423,9 +447,9 @@ class ChatController extends BaseController
|
||||
}
|
||||
return $this->response->setJSON(["message" => "Hebra actualizada correctamente", "status" => true]);
|
||||
}
|
||||
public function get_hebra(string $model,int $modelId)
|
||||
public function get_hebra(string $model, int $modelId)
|
||||
{
|
||||
$data = $this->chatService->getHebras($model,$modelId);
|
||||
$data = $this->chatService->getHebras($model, $modelId);
|
||||
return $this->response->setJSON($data);
|
||||
}
|
||||
|
||||
@ -438,8 +462,8 @@ class ChatController extends BaseController
|
||||
return DataTable::of($query)
|
||||
->edit('created_at', fn($q) => Time::createFromFormat('Y-m-d H:i:s', $q->created_at)->format("d/m/Y H:i"))
|
||||
->edit('updated_at', fn($q) => Time::createFromFormat('Y-m-d H:i:s', $q->updated_at)->format("d/m/Y H:i"))
|
||||
->edit("creator",fn($q) => $q->userId == $auth_user_id ? '<span class="badge text-bg-success w-100">'.lang("App.me").'</span>' : $q->creator)
|
||||
->add("viewed", fn($q) => $this->chatModel->isMessageChatViewed($q->id, $auth_user_id))
|
||||
->edit("creator", fn($q) => $q->userId == $auth_user_id ? '<span class="badge text-bg-success w-100">' . lang("App.me") . '</span>' : $q->creator)
|
||||
->add("viewed", fn($q) => $this->chatModel->isMessageChatViewed($q->id, $auth_user_id))
|
||||
->add("action", fn($q) => [
|
||||
"type" => "direct",
|
||||
"modelId" => $q->id,
|
||||
@ -460,12 +484,18 @@ class ChatController extends BaseController
|
||||
return DataTable::of($query)
|
||||
->edit('created_at', fn($q) => $q->created_at ? Time::createFromFormat('Y-m-d H:i:s', $q->created_at)->format("d/m/Y H:i") : "")
|
||||
->edit('updated_at', fn($q) => $q->updated_at ? Time::createFromFormat('Y-m-d H:i:s', $q->updated_at)->format("d/m/Y H:i") : "")
|
||||
->add("viewed", fn($q) => $this->chatModel->isMessageChatViewed($q->chatMessageId))
|
||||
->edit("creator",fn($q) => $q->userId == $auth_user_id ? '<span class="badge text-bg-success w-100">'.lang("App.me").'</span>' : $q->creator)
|
||||
->add("action", fn($q) => ["type" => "presupuesto", "modelId" => $q->id, "isAdmin" => $isAdmin,"chatMessageId" => $q->chatMessageId, "lang" => [
|
||||
"view_chat" => lang('Chat.view_chat'),
|
||||
"view_by_alt_message" => lang('Chat.view_by_alt_message')
|
||||
]])
|
||||
->add("viewed", fn($q) => $this->chatModel->isMessageChatViewed($q->chatMessageId))
|
||||
->edit("creator", fn($q) => $q->userId == $auth_user_id ? '<span class="badge text-bg-success w-100">' . lang("App.me") . '</span>' : $q->creator)
|
||||
->add("action", fn($q) => [
|
||||
"type" => "presupuesto",
|
||||
"modelId" => $q->id,
|
||||
"isAdmin" => $isAdmin,
|
||||
"chatMessageId" => $q->chatMessageId,
|
||||
"lang" => [
|
||||
"view_chat" => lang('Chat.view_chat'),
|
||||
"view_by_alt_message" => lang('Chat.view_by_alt_message')
|
||||
]
|
||||
])
|
||||
->toJson(true);
|
||||
}
|
||||
public function datatable_pedido_messages()
|
||||
@ -476,12 +506,18 @@ class ChatController extends BaseController
|
||||
return DataTable::of($query)
|
||||
->edit('created_at', fn($q) => $q->created_at ? Time::createFromFormat('Y-m-d H:i:s', $q->created_at)->format("d/m/Y H:i") : "")
|
||||
->edit('updated_at', fn($q) => $q->updated_at ? Time::createFromFormat('Y-m-d H:i:s', $q->updated_at)->format("d/m/Y H:i") : "")
|
||||
->edit("creator",fn($q) => $q->userId == $auth_user_id ? '<span class="badge text-bg-success w-100">'.lang("App.me").'</span>' : $q->creator)
|
||||
->add("viewed", fn($q) => $this->chatModel->isMessageChatViewed($q->chatMessageId))
|
||||
->add("action", fn($q) => ["type" => "pedido", "modelId" => $q->id, "isAdmin" => $isAdmin,"chatMessageId" => $q->chatMessageId, "lang" => [
|
||||
"view_chat" => lang('Chat.view_chat'),
|
||||
"view_by_alt_message" => lang('Chat.view_by_alt_message')
|
||||
]])
|
||||
->edit("creator", fn($q) => $q->userId == $auth_user_id ? '<span class="badge text-bg-success w-100">' . lang("App.me") . '</span>' : $q->creator)
|
||||
->add("viewed", fn($q) => $this->chatModel->isMessageChatViewed($q->chatMessageId))
|
||||
->add("action", fn($q) => [
|
||||
"type" => "pedido",
|
||||
"modelId" => $q->id,
|
||||
"isAdmin" => $isAdmin,
|
||||
"chatMessageId" => $q->chatMessageId,
|
||||
"lang" => [
|
||||
"view_chat" => lang('Chat.view_chat'),
|
||||
"view_by_alt_message" => lang('Chat.view_by_alt_message')
|
||||
]
|
||||
])
|
||||
|
||||
->toJson(true);
|
||||
}
|
||||
@ -493,12 +529,64 @@ class ChatController extends BaseController
|
||||
return DataTable::of($query)
|
||||
->edit('created_at', fn($q) => $q->created_at ? Time::createFromFormat('Y-m-d H:i:s', $q->created_at)->format("d/m/Y H:i") : "")
|
||||
->edit('updated_at', fn($q) => $q->updated_at ? Time::createFromFormat('Y-m-d H:i:s', $q->updated_at)->format("d/m/Y H:i") : "")
|
||||
->edit("creator",fn($q) => $q->userId == $auth_user_id ? '<span class="badge text-bg-success w-100">'.lang("App.me").'</span>' : $q->creator)
|
||||
->add("viewed", fn($q) => $this->chatModel->isMessageChatViewed($q->chatMessageId))
|
||||
->add("action", fn($q) => ["type" => "factura", "modelId" => $q->id, "isAdmin" => $isAdmin,"chatMessageId" => $q->chatMessageId, "lang" => [
|
||||
"view_chat" => lang('Chat.view_chat'),
|
||||
"view_by_alt_message" => lang('Chat.view_by_alt_message')
|
||||
]])
|
||||
->edit("creator", fn($q) => $q->userId == $auth_user_id ? '<span class="badge text-bg-success w-100">' . lang("App.me") . '</span>' : $q->creator)
|
||||
->add("viewed", fn($q) => $this->chatModel->isMessageChatViewed($q->chatMessageId))
|
||||
->add("action", fn($q) => [
|
||||
"type" => "factura",
|
||||
"modelId" => $q->id,
|
||||
"isAdmin" => $isAdmin,
|
||||
"chatMessageId" => $q->chatMessageId,
|
||||
"lang" => [
|
||||
"view_chat" => lang('Chat.view_chat'),
|
||||
"view_by_alt_message" => lang('Chat.view_by_alt_message')
|
||||
]
|
||||
])
|
||||
|
||||
->toJson(true);
|
||||
}
|
||||
public function datatable_ot_messages()
|
||||
{
|
||||
$auth_user_id = auth()->user()->id;
|
||||
$isAdmin = auth()->user()->inGroup('admin');
|
||||
$query = $this->chatModel->getQueryDatatableMessageOrdenTrabajo($auth_user_id);
|
||||
return DataTable::of($query)
|
||||
->edit('created_at', fn($q) => $q->created_at ? Time::createFromFormat('Y-m-d H:i:s', $q->created_at)->format("d/m/Y H:i") : "")
|
||||
->edit('updated_at', fn($q) => $q->updated_at ? Time::createFromFormat('Y-m-d H:i:s', $q->updated_at)->format("d/m/Y H:i") : "")
|
||||
->edit("creator", fn($q) => $q->userId == $auth_user_id ? '<span class="badge text-bg-success w-100">' . lang("App.me") . '</span>' : $q->creator)
|
||||
->add("viewed", fn($q) => $this->chatModel->isMessageChatViewed($q->chatMessageId))
|
||||
->add("action", fn($q) => [
|
||||
"type" => "ot",
|
||||
"modelId" => $q->id,
|
||||
"isAdmin" => $isAdmin,
|
||||
"chatMessageId" => $q->chatMessageId,
|
||||
"lang" => [
|
||||
"view_chat" => lang('Chat.view_chat'),
|
||||
"view_by_alt_message" => lang('Chat.view_by_alt_message')
|
||||
]
|
||||
])
|
||||
|
||||
->toJson(true);
|
||||
}
|
||||
public function datatable_direct_messages()
|
||||
{
|
||||
$auth_user_id = auth()->user()->id;
|
||||
$isAdmin = auth()->user()->inGroup('admin');
|
||||
$query = $this->chatModel->getQueryDatatableDirectMessages($auth_user_id);
|
||||
return DataTable::of($query)
|
||||
->edit('created_at', fn($q) => $q->created_at ? Time::createFromFormat('Y-m-d H:i:s', $q->created_at)->format("d/m/Y H:i") : "")
|
||||
->edit('updated_at', fn($q) => $q->updated_at ? Time::createFromFormat('Y-m-d H:i:s', $q->updated_at)->format("d/m/Y H:i") : "")
|
||||
->edit("creator", fn($q) => $q->userId == $auth_user_id ? '<span class="badge text-bg-success w-100">' . lang("App.me") . '</span>' : $q->creator)
|
||||
->add("viewed", fn($q) => $this->chatModel->isMessageChatViewed($q->chatMessageId))
|
||||
->add("action", fn($q) => [
|
||||
"type" => "direct",
|
||||
"modelId" => $q->id,
|
||||
"isAdmin" => $isAdmin,
|
||||
"chatMessageId" => $q->chatMessageId,
|
||||
"lang" => [
|
||||
"view_chat" => lang('Chat.view_chat'),
|
||||
"view_by_alt_message" => lang('Chat.view_by_alt_message')
|
||||
]
|
||||
])
|
||||
|
||||
->toJson(true);
|
||||
}
|
||||
@ -569,14 +657,13 @@ class ChatController extends BaseController
|
||||
$query = $this->userModel->builder()->select(
|
||||
[
|
||||
"id",
|
||||
"CONCAT(first_name,' ',last_name,'(',username,')') as name"
|
||||
"CONCAT(first_name,' ',last_name) as name"
|
||||
]
|
||||
)
|
||||
->where("deleted_at", null)
|
||||
->whereNotIn("id", $chat_users_id);
|
||||
if ($this->request->getGet("q")) {
|
||||
$query->groupStart()
|
||||
->orLike("users.username", $this->request->getGet("q"))
|
||||
->orLike("CONCAT(first_name,' ',last_name)", $this->request->getGet("q"))
|
||||
->groupEnd();
|
||||
}
|
||||
@ -600,14 +687,15 @@ class ChatController extends BaseController
|
||||
{
|
||||
$bodyData = $this->request->getPost();
|
||||
$auth_user = auth()->user();
|
||||
$bodyData["sender_id"] = $auth_user->id;
|
||||
$bodyData["sender_id"] = $auth_user->id;
|
||||
$chat_message_id = $this->chatMessageModel->insert($bodyData);
|
||||
$users_id = $this->chatUserModel->getChatUserArrayId($chat_id);
|
||||
foreach ($users_id as $user_id) {
|
||||
if ($user_id != $auth_user->id) {
|
||||
$this->chatNotificationModel->insert(["chat_message_id" => $chat_message_id, "user_id" => $user_id]);
|
||||
}
|
||||
};
|
||||
}
|
||||
;
|
||||
$message = $this->chatMessageModel->get_chat_message($chat_message_id);
|
||||
return $this->response->setJSON($message);
|
||||
}
|
||||
@ -696,7 +784,7 @@ class ChatController extends BaseController
|
||||
}
|
||||
public function chat_department_edit($chat_department_id)
|
||||
{
|
||||
$chatDepartment = $this->chatDeparmentModel->find($chat_department_id);
|
||||
$chatDepartment = $this->chatDeparmentModel->find($chat_department_id);
|
||||
$this->viewData['breadcrumb'] = [
|
||||
['title' => lang("App.menu_configuration"), 'route' => 'javascript:void(0);', 'active' => false],
|
||||
['title' => lang("App.menu_config_messages"), 'route' => route_to("configMessagesIndex"), 'active' => false],
|
||||
|
||||
@ -215,13 +215,13 @@ class Clientedirecciones extends \App\Controllers\BaseResourceController
|
||||
{
|
||||
try {
|
||||
$resourceData = $this->model->getDireccion($id);
|
||||
$response = (object)[
|
||||
$response = (object) [
|
||||
'error' => false,
|
||||
'data' => $resourceData
|
||||
];
|
||||
return $this->respond($response);
|
||||
} catch (\Exception $e) {
|
||||
$response = (object)[
|
||||
$response = (object) [
|
||||
'error' => true,
|
||||
'message' => $e->getMessage()
|
||||
];
|
||||
@ -229,22 +229,61 @@ class Clientedirecciones extends \App\Controllers\BaseResourceController
|
||||
}
|
||||
}
|
||||
|
||||
public function getDireccionIdFromData()
|
||||
{
|
||||
$data = $this->request->getGet('data') ?? [];
|
||||
$cliente_id = $this->request->getGet('cliente_id') ?? -1;
|
||||
$att = $data['att'] ?? "";
|
||||
$direccion = $data['direccion'] ?? "";
|
||||
$cp = $data['cp'] ?? "";
|
||||
$municipio = $data['municipio'] ?? "";
|
||||
$provincia = $data['provincia'] ?? "";
|
||||
$pais_id = $data['pais_id'] ?? -1;
|
||||
$email = $data['email'] ?? "";
|
||||
$telefono = $data['telefono'] ?? "";
|
||||
try {
|
||||
$model = model('App\Models\Clientes\ClienteDireccionesModel');
|
||||
$id = $model->select('id')
|
||||
->where('att', $att)
|
||||
->where('direccion', $direccion)
|
||||
->where('cp', $cp)
|
||||
->where('municipio', $municipio)
|
||||
->where('provincia', $provincia)
|
||||
->where('pais_id', $pais_id)
|
||||
->where('email', $email)
|
||||
->where('telefono', $telefono)
|
||||
->where('cliente_id', $cliente_id)
|
||||
->get()
|
||||
->getResultObject();
|
||||
|
||||
if (count($id) > 0) {
|
||||
$id = $id[0]->id;
|
||||
} else {
|
||||
$id = null;
|
||||
}
|
||||
return $id;
|
||||
|
||||
} catch (\Exception $e) {
|
||||
throw new \RuntimeException($e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public function getDireccionPresupuesto($id)
|
||||
{
|
||||
try {
|
||||
$model = model('App\Models\Presupuestos\PresupuestoDireccionesModel');
|
||||
$resourceData = $model->getDireccion($id);
|
||||
if(count($resourceData) > 0){
|
||||
if (count($resourceData) > 0) {
|
||||
$resourceData[0]->direccionId = $id;
|
||||
}
|
||||
|
||||
$response = (object)[
|
||||
|
||||
$response = (object) [
|
||||
'error' => false,
|
||||
'data' => $resourceData
|
||||
];
|
||||
return $this->respond($response);
|
||||
} catch (\Exception $e) {
|
||||
$response = (object)[
|
||||
$response = (object) [
|
||||
'error' => true,
|
||||
'message' => $e->getMessage()
|
||||
];
|
||||
@ -400,11 +439,11 @@ class Clientedirecciones extends \App\Controllers\BaseResourceController
|
||||
protected function getComunidadAutonomaListItems($selId = null)
|
||||
{
|
||||
$data = ['' => lang('Basic.global.pleaseSelectA', [mb_strtolower(lang('ComunidadesAutonomas.comunidadAutonoma'))])];
|
||||
if (!is_null($selId)) :
|
||||
if (!is_null($selId)):
|
||||
$comunidadAutonomaModel = model('App\Models\Configuracion\ComunidadAutonomaModel');
|
||||
|
||||
$selOption = $comunidadAutonomaModel->where('id', $selId)->findColumn('nombre');
|
||||
if (!empty($selOption)) :
|
||||
if (!empty($selOption)):
|
||||
$data[$selId] = $selOption[0];
|
||||
endif;
|
||||
endif;
|
||||
@ -414,11 +453,11 @@ class Clientedirecciones extends \App\Controllers\BaseResourceController
|
||||
protected function getProvinciaListItems($selId = null)
|
||||
{
|
||||
$data = ['' => lang('Basic.global.pleaseSelectA', [mb_strtolower(lang('Provincias.provincia'))])];
|
||||
if (!empty($selId)) :
|
||||
if (!empty($selId)):
|
||||
$provinciaModel = model('App\Models\Configuracion\ProvinciaModel');
|
||||
|
||||
$selOption = $provinciaModel->where('id', $selId)->findColumn('nombre');
|
||||
if (!empty($selOption)) :
|
||||
if (!empty($selOption)):
|
||||
$data[$selId] = $selOption[0];
|
||||
endif;
|
||||
endif;
|
||||
|
||||
@ -154,7 +154,6 @@ class Clienteplantillaprecioslineas extends \App\Controllers\BaseResourceControl
|
||||
Field::inst( 'tipo_maquina' ),
|
||||
Field::inst( 'tipo_impresion' ),
|
||||
Field::inst( 'user_updated_id' ),
|
||||
Field::inst( 'deleted_at' ),
|
||||
Field::inst( 'updated_at' ),
|
||||
Field::inst( 'tiempo_min' )
|
||||
->getFormatter( 'Format::toDecimalChar')->setFormatter( 'Format::fromDecimalChar')
|
||||
|
||||
0
ci4/app/Controllers/Clientes/Clienteusuarios.php
Normal file → Executable file
0
ci4/app/Controllers/Clientes/Clienteusuarios.php
Normal file → Executable file
@ -25,6 +25,7 @@ class Proveedores extends \App\Controllers\BaseResourceController {
|
||||
|
||||
protected $indexRoute = 'proveedorList';
|
||||
|
||||
protected $deletePermission = 'proveedores.delete';
|
||||
|
||||
|
||||
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger) {
|
||||
@ -383,4 +384,26 @@ class Proveedores extends \App\Controllers\BaseResourceController {
|
||||
}
|
||||
}
|
||||
|
||||
public function getForSelect(){
|
||||
|
||||
if ($this->request->isAJAX()) {
|
||||
$tipo_id = $this->request->getGet("tipo_id");
|
||||
$query = $this->model->builder()->select(
|
||||
[
|
||||
"id",
|
||||
"nombre as name"
|
||||
]
|
||||
)->where('tipo_id', $tipo_id)->where('deleted_at', null)->orderBy("nombre", "asc");
|
||||
if ($this->request->getGet("q")) {
|
||||
$query->groupStart()
|
||||
->orLike("lg_proveedores.nombre", $this->request->getGet("q"))
|
||||
->groupEnd();
|
||||
}
|
||||
|
||||
return $this->response->setJSON($query->get()->getResultObject());
|
||||
} else {
|
||||
return $this->failUnauthorized('Invalid request', 403);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
0
ci4/app/Controllers/Configuracion/ConfigErrores.php
Normal file → Executable file
0
ci4/app/Controllers/Configuracion/ConfigErrores.php
Normal file → Executable file
0
ci4/app/Controllers/Configuracion/ConfigVariables.php
Normal file → Executable file
0
ci4/app/Controllers/Configuracion/ConfigVariables.php
Normal file → Executable file
103
ci4/app/Controllers/Configuracion/FestivoController.php
Normal file
103
ci4/app/Controllers/Configuracion/FestivoController.php
Normal file
@ -0,0 +1,103 @@
|
||||
<?php
|
||||
|
||||
namespace App\Controllers\Configuracion;
|
||||
|
||||
use App\Controllers\BaseController;
|
||||
use App\Controllers\BaseResourceController;
|
||||
use App\Entities\Configuracion\FestivoEntity;
|
||||
use App\Models\Collection;
|
||||
|
||||
use App\Entities\Configuracion\Imposicion;
|
||||
use App\Models\Configuracion\FestivoModel;
|
||||
use App\Models\Configuracion\ImposicionEsquemaModel;
|
||||
use App\Models\Configuracion\ImposicionModel;
|
||||
use CodeIgniter\HTTP\RequestInterface;
|
||||
use CodeIgniter\HTTP\ResponseInterface;
|
||||
use CodeIgniter\Validation\Validation;
|
||||
use Hermawan\DataTables\DataTable;
|
||||
use Psr\Log\LoggerInterface;
|
||||
|
||||
class FestivoController extends BaseController
|
||||
{
|
||||
|
||||
protected $modelName = FestivoModel::class;
|
||||
protected FestivoModel $model;
|
||||
protected static $controllerSlug = 'festivos';
|
||||
protected $format = 'json';
|
||||
|
||||
protected string $viewPath = 'themes/vuexy/form/configuracion/festivos/';
|
||||
|
||||
protected $indexRoute = 'festivoList';
|
||||
protected array $viewData = [];
|
||||
protected Validation $validation;
|
||||
|
||||
public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
|
||||
{
|
||||
$this->viewData['pageTitle'] = lang('Festivos.moduleTitle');
|
||||
$this->viewData['usingSweetAlert'] = true;
|
||||
$this->model = model($this->modelName);
|
||||
$this->validation = service("validation");
|
||||
parent::initController($request, $response, $logger);
|
||||
}
|
||||
|
||||
public function index()
|
||||
{
|
||||
return view($this->viewPath . $this->indexRoute);
|
||||
}
|
||||
|
||||
public function store_festivo_date()
|
||||
{
|
||||
$bodyData = $this->request->getPost();
|
||||
$date = $bodyData['date'];
|
||||
$count = $this->model->where('date',$date)->countAllResults();
|
||||
if ($count) {
|
||||
$status = $this->model->where('date', $date)->delete(purge: true);
|
||||
return $this->response->setJSON([
|
||||
"message" => lang("App.user_alert_delete"),
|
||||
"status" => $status,
|
||||
]);
|
||||
} else {
|
||||
|
||||
$status = $this->model->insert($bodyData);
|
||||
if ($status) {
|
||||
$festivoEntity = $this->model->find($status);
|
||||
return $this->response->setJSON([
|
||||
"message" => lang("App.global_alert_save_success"),
|
||||
"status" => $status,
|
||||
"data" => $festivoEntity
|
||||
]);
|
||||
} else {
|
||||
return $this->response->setJSON([
|
||||
"message" => lang("App.global_alert_save_error"),
|
||||
"errors" => $this->model->errors(),
|
||||
"status" => true
|
||||
])->setStatusCode(400);
|
||||
}
|
||||
}
|
||||
}
|
||||
public function delete_festivo_date($id)
|
||||
{
|
||||
$status = $this->model->delete($id, true);
|
||||
if ($status) {
|
||||
return $this->response->setJSON([
|
||||
"message" => lang("App.user_alert_delete"),
|
||||
"status" => $status,
|
||||
]);
|
||||
} else {
|
||||
return $this->response->setJSON([
|
||||
"message" => lang("App.global_alert_save_error"),
|
||||
"errors" => $this->model->errors(),
|
||||
"status" => true
|
||||
])->setStatusCode(400);
|
||||
}
|
||||
}
|
||||
public function find_all()
|
||||
{
|
||||
$festivos = $this->model->findAll();
|
||||
return $this->response->setJSON([
|
||||
"message" => lang("App.global_alert_fetch_success"),
|
||||
"status" => true,
|
||||
"data" => $festivos
|
||||
]);
|
||||
}
|
||||
}
|
||||
5
ci4/app/Controllers/Configuracion/FormasPago.php
Normal file → Executable file
5
ci4/app/Controllers/Configuracion/FormasPago.php
Normal file → Executable file
@ -26,6 +26,8 @@ class FormasPago extends \App\Controllers\BaseResourceController
|
||||
|
||||
protected $indexRoute = 'formaDePagoList';
|
||||
|
||||
protected $deletePermission = 'formas-pago.delete';
|
||||
|
||||
|
||||
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
|
||||
{
|
||||
@ -44,6 +46,7 @@ class FormasPago extends \App\Controllers\BaseResourceController
|
||||
|
||||
public function index()
|
||||
{
|
||||
checkPermission('formas-pago.menu');
|
||||
|
||||
$viewData = [
|
||||
'currentModule' => static::$controllerSlug,
|
||||
@ -61,6 +64,7 @@ class FormasPago extends \App\Controllers\BaseResourceController
|
||||
|
||||
public function add()
|
||||
{
|
||||
checkPermission('formas-pago.create');
|
||||
|
||||
if ($this->request->getPost()) :
|
||||
|
||||
@ -115,6 +119,7 @@ class FormasPago extends \App\Controllers\BaseResourceController
|
||||
|
||||
public function edit($requestedId = null)
|
||||
{
|
||||
checkPermission('formas-pago.edit');
|
||||
|
||||
if ($requestedId == null) :
|
||||
return $this->redirect2listView();
|
||||
|
||||
@ -21,6 +21,8 @@ class Group extends \App\Controllers\GoBaseController
|
||||
|
||||
protected $indexRoute = 'userGroupList';
|
||||
|
||||
protected $deletePermission = 'roles-permisos.delete';
|
||||
|
||||
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
|
||||
{
|
||||
self::$viewPath = getenv('theme.path') . 'form/group/';
|
||||
@ -37,6 +39,8 @@ class Group extends \App\Controllers\GoBaseController
|
||||
|
||||
public function index()
|
||||
{
|
||||
checkPermission('roles-permisos.menu');
|
||||
|
||||
$this->viewData['usingClientSideDataTable'] = true;
|
||||
$this->viewData['pageSubTitle'] = lang('Basic.global.ManageAllRecords', [lang('Groups.group')]);
|
||||
// IMN
|
||||
@ -48,11 +52,12 @@ class Group extends \App\Controllers\GoBaseController
|
||||
public function add()
|
||||
{
|
||||
|
||||
checkPermission('roles-permisos.create');
|
||||
|
||||
if ($this->request->getPost()) :
|
||||
|
||||
$postData = $this->request->getPost();
|
||||
|
||||
$temp_data['id'] = $groupEntity->id;
|
||||
$temp_data['title'] = $postData['title'];
|
||||
$temp_data['description'] = $postData['description'];
|
||||
|
||||
@ -124,6 +129,7 @@ class Group extends \App\Controllers\GoBaseController
|
||||
|
||||
public function edit($requestedId = null)
|
||||
{
|
||||
checkPermission('roles-permisos.edit');
|
||||
|
||||
helper('general');
|
||||
|
||||
@ -243,30 +249,4 @@ class Group extends \App\Controllers\GoBaseController
|
||||
}
|
||||
}
|
||||
|
||||
public function menuItems()
|
||||
{
|
||||
if ($this->request->isAJAX()) {
|
||||
$searchStr = goSanitize($this->request->getPost('searchTerm'))[0];
|
||||
$reqId = goSanitize($this->request->getPost('id'))[0];
|
||||
$reqText = goSanitize($this->request->getPost('text'))[0];
|
||||
$onlyActiveOnes = false;
|
||||
$columns2select = [$reqId ?? 'id', $reqText ?? 'nombre'];
|
||||
$onlyActiveOnes = false;
|
||||
$menu = $this->model->getSelect2MenuItems($columns2select, $columns2select[1], $onlyActiveOnes, $searchStr);
|
||||
$nonItem = new \stdClass;
|
||||
$nonItem->id = '';
|
||||
$nonItem->text = '- ' . lang('Basic.global.None') . ' -';
|
||||
array_unshift($menu, $nonItem);
|
||||
|
||||
$newTokenHash = csrf_hash();
|
||||
$csrfTokenName = csrf_token();
|
||||
$data = [
|
||||
'menu' => $menu,
|
||||
$csrfTokenName => $newTokenHash
|
||||
];
|
||||
return $this->respond($data);
|
||||
} else {
|
||||
return $this->failUnauthorized('Invalid request', 403);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -2,37 +2,41 @@
|
||||
|
||||
namespace App\Controllers\Configuracion;
|
||||
|
||||
|
||||
use App\Controllers\BaseController;
|
||||
use App\Controllers\BaseResourceController;
|
||||
|
||||
use App\Models\Collection;
|
||||
|
||||
use App\Entities\Configuracion\Imposicion;
|
||||
|
||||
use App\Models\Configuracion\ImposicionEsquemaModel;
|
||||
use App\Models\Configuracion\ImposicionModel;
|
||||
use CodeIgniter\HTTP\RequestInterface;
|
||||
use CodeIgniter\HTTP\ResponseInterface;
|
||||
use CodeIgniter\Validation\Validation;
|
||||
use Hermawan\DataTables\DataTable;
|
||||
use Psr\Log\LoggerInterface;
|
||||
|
||||
class Imposiciones extends \App\Controllers\BaseResourceController
|
||||
class Imposiciones extends BaseController
|
||||
{
|
||||
|
||||
protected $modelName = ImposicionModel::class;
|
||||
protected $format = 'json';
|
||||
|
||||
protected static $singularObjectName = 'Imposicion';
|
||||
protected static $singularObjectNameCc = 'imposicion';
|
||||
protected static $pluralObjectName = 'Imposiciones';
|
||||
protected static $pluralObjectNameCc = 'imposiciones';
|
||||
|
||||
protected ImposicionModel $model;
|
||||
protected ImposicionEsquemaModel $imposicionEsquemaModel;
|
||||
protected static $controllerSlug = 'imposiciones';
|
||||
protected $format = 'json';
|
||||
|
||||
protected static $viewPath = 'themes/vuexy/form/configuracion/imposiciones/';
|
||||
|
||||
protected $indexRoute = 'imposicionList';
|
||||
protected array $viewData = [];
|
||||
protected Validation $validation;
|
||||
|
||||
|
||||
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
|
||||
public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
|
||||
{
|
||||
$this->viewData['pageTitle'] = lang('Imposiciones.moduleTitle');
|
||||
$this->viewData['usingSweetAlert'] = true;
|
||||
$this->model = model($this->modelName);
|
||||
$this->validation = service("validation");
|
||||
$this->imposicionEsquemaModel = model(ImposicionEsquemaModel::class);
|
||||
parent::initController($request, $response, $logger);
|
||||
}
|
||||
|
||||
@ -47,7 +51,10 @@ class Imposiciones extends \App\Controllers\BaseResourceController
|
||||
'usingServerSideDataTable' => true,
|
||||
|
||||
];
|
||||
$this->viewData['breadcrumb'] = [
|
||||
['title' => lang("App.menu_imposiciones"), 'route' => route_to("imposicionList"), 'active' => true],
|
||||
|
||||
];
|
||||
$viewData = array_merge($this->viewData, $viewData); // merge any possible values from the parent controller class
|
||||
|
||||
return view(static::$viewPath . 'viewImposicionList', $viewData);
|
||||
@ -56,234 +63,155 @@ class Imposiciones extends \App\Controllers\BaseResourceController
|
||||
|
||||
public function add()
|
||||
{
|
||||
$this->viewData['breadcrumb'] = [
|
||||
['title' => lang("App.menu_imposiciones"), 'route' => route_to("imposicionList"), 'active' => true],
|
||||
|
||||
|
||||
|
||||
|
||||
if ($this->request->getPost()) :
|
||||
|
||||
$nullIfEmpty = true; // !(phpversion() >= '8.1');
|
||||
|
||||
$postData = $this->request->getPost();
|
||||
|
||||
$sanitizedData = $this->sanitized($postData, $nullIfEmpty);
|
||||
|
||||
|
||||
$noException = true;
|
||||
if ($successfulResult = $this->canValidate()) : // if ($successfulResult = $this->validate($this->formValidationRules) ) :
|
||||
|
||||
|
||||
if ($this->canValidate()) :
|
||||
try {
|
||||
$successfulResult = $this->model->skipValidation(true)->save($sanitizedData);
|
||||
} catch (\Exception $e) {
|
||||
$noException = false;
|
||||
$this->dealWithException($e);
|
||||
}
|
||||
else:
|
||||
$this->viewData['errorMessage'] = lang('Basic.global.formErr1', [lang('Basic.global.record')]);
|
||||
$this->session->setFlashdata('formErrors', $this->model->errors());
|
||||
endif;
|
||||
|
||||
$thenRedirect = true; // Change this to false if you want your user to stay on the form after submission
|
||||
endif;
|
||||
if ($noException && $successfulResult) :
|
||||
|
||||
$id = $this->model->db->insertID();
|
||||
|
||||
$message = lang('Basic.global.saveSuccess', [lang('Basic.global.record')]) . '.';
|
||||
|
||||
if ($thenRedirect) :
|
||||
if (!empty($this->indexRoute)) :
|
||||
return redirect()->to(route_to($this->indexRoute))->with('sweet-success', $message);
|
||||
else:
|
||||
return $this->redirect2listView('sweet-success', $message);
|
||||
endif;
|
||||
else:
|
||||
$this->session->setFlashData('sweet-success', $message);
|
||||
endif;
|
||||
|
||||
endif; // $noException && $successfulResult
|
||||
|
||||
endif; // ($requestMethod === 'post')
|
||||
|
||||
$this->viewData['imposicion'] = isset($sanitizedData) ? new Imposicion($sanitizedData) : new Imposicion();
|
||||
$this->viewData['orientacionList'] = $this->getOrientacionOptions();
|
||||
|
||||
$this->viewData['formAction'] = route_to('createImposicion');
|
||||
|
||||
$this->viewData['boxTitle'] = lang('Basic.global.addNew') . ' ' . lang('Imposiciones.moduleTitle') . ' ' . lang('Basic.global.addNewSuffix');
|
||||
|
||||
|
||||
return $this->displayForm(__METHOD__);
|
||||
} // end function add()
|
||||
|
||||
public function edit($requestedId = null)
|
||||
];
|
||||
$this->viewData["method"] = "add";
|
||||
return view(static::$viewPath . 'viewImposicionNewForm', $this->viewData);
|
||||
}
|
||||
public function add_esquema()
|
||||
{
|
||||
$this->viewData['breadcrumb'] = [
|
||||
['title' => lang("App.menu_imposiciones"), 'route' => route_to("imposicionList"), 'active' => true],
|
||||
];
|
||||
$this->viewData["imposicion_esquema"] = null;
|
||||
|
||||
if ($requestedId == null) :
|
||||
return $this->redirect2listView();
|
||||
endif;
|
||||
$id = filter_var($requestedId, FILTER_SANITIZE_URL);
|
||||
$imposicion = $this->model->find($id);
|
||||
return view(static::$viewPath . 'viewImposicionEsquemaForm', $this->viewData);
|
||||
}
|
||||
public function edit($imposicion_id = null)
|
||||
{
|
||||
if ($imposicion_id) {
|
||||
$this->viewData["imposicion"] = $this->model->find($imposicion_id);
|
||||
$this->viewData['breadcrumb'] = [
|
||||
['title' => lang("App.menu_imposiciones"), 'route' => route_to("imposicionList"), 'active' => false],
|
||||
['title' => $this->viewData["imposicion"]->full_name, 'route' => route_to("updateImposicionForm", $imposicion_id), 'active' => true],
|
||||
|
||||
if ($imposicion == false) :
|
||||
$message = lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('Imposiciones.imposicion')), $id]);
|
||||
return $this->redirect2listView('sweet-error', $message);
|
||||
endif;
|
||||
];
|
||||
}
|
||||
$this->viewData["method"] = "edit";
|
||||
return view(static::$viewPath . 'viewImposicionForm', $this->viewData);
|
||||
}
|
||||
public function edit_imposicion_esquema($imposicion_esquema_id = null)
|
||||
{
|
||||
if ($imposicion_esquema_id) {
|
||||
$this->viewData["imposicion_esquema"] = $this->imposicionEsquemaModel->find($imposicion_esquema_id);
|
||||
$this->viewData['breadcrumb'] = [
|
||||
['title' => lang("App.menu_imposiciones"), 'route' => route_to("imposicionList"), 'active' => false],
|
||||
['title' => $this->viewData["imposicion_esquema"]->name, 'route' => route_to("updateImposicionEsquemaForm", $imposicion_esquema_id), 'active' => true],
|
||||
|
||||
|
||||
|
||||
if ($this->request->getPost()) :
|
||||
|
||||
$nullIfEmpty = true; // !(phpversion() >= '8.1');
|
||||
|
||||
$postData = $this->request->getPost();
|
||||
|
||||
$sanitizedData = $this->sanitized($postData, $nullIfEmpty);
|
||||
|
||||
|
||||
$noException = true;
|
||||
if ($successfulResult = $this->canValidate()) : // if ($successfulResult = $this->validate($this->formValidationRules) ) :
|
||||
|
||||
|
||||
if ($this->canValidate()) :
|
||||
try {
|
||||
$successfulResult = $this->model->skipValidation(true)->update($id, $sanitizedData);
|
||||
} catch (\Exception $e) {
|
||||
$noException = false;
|
||||
$this->dealWithException($e);
|
||||
}
|
||||
else:
|
||||
$this->viewData['warningMessage'] = lang('Basic.global.formErr1', [mb_strtolower(lang('Imposiciones.imposicion'))]);
|
||||
$this->session->setFlashdata('formErrors', $this->model->errors());
|
||||
|
||||
endif;
|
||||
|
||||
$imposicion->fill($sanitizedData);
|
||||
|
||||
$thenRedirect = false;
|
||||
endif;
|
||||
if ($noException && $successfulResult) :
|
||||
$id = $imposicion->id ?? $id;
|
||||
$message = lang('Basic.global.updateSuccess', [lang('Basic.global.record')]) . '.';
|
||||
|
||||
if ($thenRedirect) :
|
||||
if (!empty($this->indexRoute)) :
|
||||
return redirect()->to(route_to($this->indexRoute))->with('sweet-success', $message);
|
||||
else:
|
||||
return $this->redirect2listView('sweet-success', $message);
|
||||
endif;
|
||||
else:
|
||||
$this->session->setFlashData('sweet-success', $message);
|
||||
endif;
|
||||
|
||||
endif; // $noException && $successfulResult
|
||||
endif; // ($requestMethod === 'post')
|
||||
|
||||
$this->viewData['imposicion'] = $imposicion;
|
||||
$this->viewData['orientacionList'] = $this->getOrientacionOptions();
|
||||
|
||||
$this->viewData['formAction'] = route_to('updateImposicion', $id);
|
||||
|
||||
$this->viewData['boxTitle'] = lang('Basic.global.edit2') . ' ' . lang('Imposiciones.moduleTitle') . ' ' . lang('Basic.global.edit3');
|
||||
|
||||
|
||||
return $this->displayForm(__METHOD__, $id);
|
||||
} // end function edit(...)
|
||||
];
|
||||
}
|
||||
return view(static::$viewPath . 'viewImposicionEsquemaForm', $this->viewData);
|
||||
}
|
||||
public function update($imposicion_id = null)
|
||||
{
|
||||
if ($imposicion_id) {
|
||||
$bodyData = $this->request->getPost();
|
||||
if(isset($bodyData["imposicion_esquema_id"])){
|
||||
if($bodyData["imposicion_esquema_id"] == ""){
|
||||
$bodyData["imposicion_esquema_id"] = null;
|
||||
}
|
||||
}
|
||||
$status = $this->model->update($imposicion_id, $bodyData);
|
||||
if ($status) {
|
||||
$imposicionEntity = $this->model->find($imposicion_id);
|
||||
} else {
|
||||
return $this->response->setJSON(["message" => lang("App.global_alert_save_error"), "errors" => $this->model->errors(), "status" => true])->setStatusCode(400);
|
||||
}
|
||||
return $this->response->setJSON(["message" => lang("App.global_alert_save_success"), "status" => $status, "data" => $imposicionEntity]);
|
||||
} else {
|
||||
return $this->response->setJSON(["message" => lang("App.global_alert_save_error"), "message" => "", "status" => false])->setStatusCode(400);
|
||||
}
|
||||
}
|
||||
public function update_imposicion_esquema($imposicion_esquema_id = null)
|
||||
{
|
||||
if ($imposicion_esquema_id) {
|
||||
$bodyData = $this->request->getPost();
|
||||
$status = $this->imposicionEsquemaModel->update($imposicion_esquema_id, $bodyData);
|
||||
if ($status) {
|
||||
$imposicionEsquemaEntity = $this->imposicionEsquemaModel->find($imposicion_esquema_id);
|
||||
} else {
|
||||
return $this->response->setJSON(["message" => lang("App.global_alert_save_error"), "errors" => $this->imposicionEsquemaModel->errors(), "status" => true])->setStatusCode(400);
|
||||
}
|
||||
return $this->response->setJSON(["message" => lang("App.global_alert_save_success"), "status" => $status, "data" => $imposicionEsquemaEntity]);
|
||||
} else {
|
||||
return $this->response->setJSON(["message" => lang("App.global_alert_save_error"), "message" => "", "status" => false])->setStatusCode(400);
|
||||
}
|
||||
}
|
||||
public function delete($imposicion_id = null)
|
||||
{
|
||||
$status = $this->model->delete($imposicion_id);
|
||||
return $this->response->setJSON(["message" => lang("App.user_alert_delete"), "status" => true]);
|
||||
}
|
||||
public function delete_imposicion_esquema($imposicion_esquema_id = null)
|
||||
{
|
||||
$status = $this->imposicionEsquemaModel->delete($imposicion_esquema_id);
|
||||
return $this->response->setJSON(["message" => lang("App.user_alert_delete"), "status" => $status]);
|
||||
}
|
||||
|
||||
|
||||
public function datatable()
|
||||
{
|
||||
if ($this->request->isAJAX()) {
|
||||
$reqData = $this->request->getPost();
|
||||
if (!isset($reqData['draw']) || !isset($reqData['columns'])) {
|
||||
$errstr = 'No data available in response to this specific request.';
|
||||
$response = $this->respond(Collection::datatable([], 0, 0, $errstr), 400, $errstr);
|
||||
return $response;
|
||||
}
|
||||
$start = $reqData['start'] ?? 0;
|
||||
$length = $reqData['length'] ?? 5;
|
||||
$search = $reqData['search']['value'];
|
||||
$requestedOrder = $reqData['order']['0']['column'] ?? 1;
|
||||
$order = ImposicionModel::SORTABLE[$requestedOrder > 0 ? $requestedOrder : 1];
|
||||
$dir = $reqData['order']['0']['dir'] ?? 'asc';
|
||||
|
||||
$resourceData = $this->model->getResource($search)->orderBy($order, $dir)->limit($length, $start)->get()->getResultObject();
|
||||
|
||||
return $this->respond(Collection::datatable(
|
||||
$resourceData,
|
||||
$this->model->getResource()->countAllResults(),
|
||||
$this->model->getResource($search)->countAllResults()
|
||||
));
|
||||
} else {
|
||||
return $this->failUnauthorized('Invalid request', 403);
|
||||
}
|
||||
$q = $this->model->queryDatatable();
|
||||
return DataTable::of($q)
|
||||
->add('esquema', fn($q) => ["imposicionId" => $q->id,"esquemaId" => $q->esquemaId, "esquemaName" => $q->esquemaName])
|
||||
->add(
|
||||
'action',
|
||||
fn($q) => "<div class='btn-group btn-group-md gap-2 w-100 d-flex justify-space-between'>" . ImposicionModel::datatable_buttons($q->id) . "</div>"
|
||||
)
|
||||
->toJson(true);
|
||||
}
|
||||
|
||||
public function allItemsSelect()
|
||||
public function datatable_imposicion_esquema()
|
||||
{
|
||||
if ($this->request->isAJAX()) {
|
||||
$onlyActiveOnes = true;
|
||||
$reqVal = $this->request->getPost('val') ?? 'id';
|
||||
$menu = $this->model->getAllForMenu($reqVal . ', ancho', 'ancho', $onlyActiveOnes, false);
|
||||
$nonItem = new \stdClass;
|
||||
$nonItem->id = '';
|
||||
$nonItem->ancho = '- ' . lang('Basic.global.None') . ' -';
|
||||
array_unshift($menu, $nonItem);
|
||||
|
||||
$newTokenHash = csrf_hash();
|
||||
$csrfTokenName = csrf_token();
|
||||
$data = [
|
||||
'menu' => $menu,
|
||||
$csrfTokenName => $newTokenHash
|
||||
];
|
||||
return $this->respond($data);
|
||||
} else {
|
||||
return $this->failUnauthorized('Invalid request', 403);
|
||||
}
|
||||
}
|
||||
|
||||
public function menuItems()
|
||||
{
|
||||
if ($this->request->isAJAX()) {
|
||||
$searchStr = goSanitize($this->request->getPost('searchTerm'))[0];
|
||||
$reqId = goSanitize($this->request->getPost('id'))[0];
|
||||
$reqText = goSanitize($this->request->getPost('text'))[0];
|
||||
$onlyActiveOnes = false;
|
||||
$columns2select = [$reqId ?? 'id', $reqText ?? 'ancho'];
|
||||
$onlyActiveOnes = false;
|
||||
$menu = $this->model->getSelect2MenuItems($columns2select, $columns2select[1], $onlyActiveOnes, $searchStr);
|
||||
$nonItem = new \stdClass;
|
||||
$nonItem->id = '';
|
||||
$nonItem->text = '- ' . lang('Basic.global.None') . ' -';
|
||||
array_unshift($menu, $nonItem);
|
||||
|
||||
$newTokenHash = csrf_hash();
|
||||
$csrfTokenName = csrf_token();
|
||||
$data = [
|
||||
'menu' => $menu,
|
||||
$csrfTokenName => $newTokenHash
|
||||
];
|
||||
return $this->respond($data);
|
||||
} else {
|
||||
return $this->failUnauthorized('Invalid request', 403);
|
||||
}
|
||||
$q = $this->imposicionEsquemaModel->queryDatatable();
|
||||
return DataTable::of($q)
|
||||
->add(
|
||||
'action',
|
||||
fn($q) => "<div class='btn-group btn-group-md gap-2'>" . ImposicionEsquemaModel::datatable_buttons($q->id) . "</div>"
|
||||
)
|
||||
->toJson(true);
|
||||
}
|
||||
|
||||
|
||||
protected function getOrientacionOptions()
|
||||
{
|
||||
$orientacionOptions = [
|
||||
'' => lang('Basic.global.pleaseSelect'),
|
||||
'H' => 'H',
|
||||
'V' => 'V',
|
||||
];
|
||||
return $orientacionOptions;
|
||||
}
|
||||
public function selectImposicion()
|
||||
{
|
||||
$data = $this->model->querySelect($this->request->getGet('q'));
|
||||
return $this->response->setJSON($data);
|
||||
}
|
||||
public function selectImposicionEsquema()
|
||||
{
|
||||
$data = $this->imposicionEsquemaModel->querySelect($this->request->getGet('q'));
|
||||
return $this->response->setJSON($data);
|
||||
}
|
||||
public function find_imposicion(int $imposicion_id)
|
||||
{
|
||||
$imposicionEntity = $this->model->find($imposicion_id)->withImposicionEsquema();
|
||||
return $this->response->setJSON($imposicionEntity);
|
||||
}
|
||||
public function find_imposicion_esquema(int $imposicion_esquema_id)
|
||||
{
|
||||
$imposicionEsquemaEntity = $this->imposicionEsquemaModel->find($imposicion_esquema_id);
|
||||
return $this->response->setJSON($imposicionEsquemaEntity);
|
||||
}
|
||||
public function create()
|
||||
{
|
||||
$bodyData = $this->request->getPost();
|
||||
$createdId = $this->model->insert($bodyData);
|
||||
if ($createdId) {
|
||||
return $this->response->setJSON(["message" => lang("App.global_alert_save_success"), "status" => true]);
|
||||
} else {
|
||||
return $this->response->setJSON(["message" => lang("App.global_alert_save_error"), "errors" => $this->model->errors(), "status" => true])->setStatusCode(400);
|
||||
}
|
||||
}
|
||||
public function create_imposicion_esquema()
|
||||
{
|
||||
$bodyData = $this->request->getPost();
|
||||
$createdId = $this->imposicionEsquemaModel->insert($bodyData);
|
||||
if ($createdId) {
|
||||
return $this->response->setJSON(["message" => lang("App.global_alert_save_success"), "status" => true]);
|
||||
} else {
|
||||
return $this->response->setJSON(["message" => lang("App.global_alert_save_error"), "errors" => $this->imposicionEsquemaModel->errors(), "status" => true])->setStatusCode(400);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
0
ci4/app/Controllers/Configuracion/MaquinaTarea.php
Normal file → Executable file
0
ci4/app/Controllers/Configuracion/MaquinaTarea.php
Normal file → Executable file
@ -28,6 +28,7 @@ class Maquinas extends \App\Controllers\BaseResourceController
|
||||
protected static $viewPath = 'themes/vuexy/form/configuracion/maquinas/';
|
||||
|
||||
protected $indexRoute = 'maquinaList';
|
||||
|
||||
protected MaquinaService $maquinaService;
|
||||
protected Validation $validation;
|
||||
|
||||
@ -55,6 +56,7 @@ class Maquinas extends \App\Controllers\BaseResourceController
|
||||
|
||||
public function index()
|
||||
{
|
||||
checkPermission('maquinas.menu');
|
||||
|
||||
$viewData = [
|
||||
'currentModule' => static::$controllerSlug,
|
||||
@ -112,6 +114,8 @@ class Maquinas extends \App\Controllers\BaseResourceController
|
||||
|
||||
public function add()
|
||||
{
|
||||
checkPermission('maquinas.create');
|
||||
|
||||
if ($this->request->getPost()):
|
||||
|
||||
$nullIfEmpty = true; // !(phpversion() >= '8.1');
|
||||
@ -176,7 +180,7 @@ class Maquinas extends \App\Controllers\BaseResourceController
|
||||
|
||||
public function edit($requestedId = null)
|
||||
{
|
||||
|
||||
checkPermission('maquinas.edit');
|
||||
|
||||
if ($requestedId == null):
|
||||
return $this->redirect2listView();
|
||||
@ -207,6 +211,9 @@ class Maquinas extends \App\Controllers\BaseResourceController
|
||||
if ($this->request->getPost('is_inkjet') == null) {
|
||||
$sanitizedData['is_inkjet'] = false;
|
||||
}
|
||||
if ($this->request->getPost('etiqueta_envio') == null) {
|
||||
$sanitizedData['etiqueta_envio'] = false;
|
||||
}
|
||||
|
||||
// JJO
|
||||
$sanitizedData['user_updated_id'] = auth()->user()->id;
|
||||
|
||||
@ -28,6 +28,8 @@ class Maquinasdefecto extends \App\Controllers\BaseResourceController
|
||||
|
||||
protected $indexRoute = 'maquinaPorDefectoList';
|
||||
|
||||
protected $deletePermission = 'maquinas-defecto.delete';
|
||||
|
||||
|
||||
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
|
||||
{
|
||||
@ -45,6 +47,7 @@ class Maquinasdefecto extends \App\Controllers\BaseResourceController
|
||||
|
||||
public function index()
|
||||
{
|
||||
checkPermission('maquinas-defecto.menu');
|
||||
|
||||
$viewData = [
|
||||
'currentModule' => static::$controllerSlug,
|
||||
@ -63,7 +66,7 @@ class Maquinasdefecto extends \App\Controllers\BaseResourceController
|
||||
public function add()
|
||||
{
|
||||
|
||||
|
||||
checkPermission('maquinas-defecto.create');
|
||||
|
||||
|
||||
if ($this->request->getPost()) :
|
||||
@ -138,6 +141,7 @@ class Maquinasdefecto extends \App\Controllers\BaseResourceController
|
||||
public function edit($requestedId = null)
|
||||
{
|
||||
|
||||
checkPermission('maquinas-defecto.edit');
|
||||
|
||||
if ($requestedId == null) :
|
||||
return $this->redirect2listView();
|
||||
|
||||
@ -100,6 +100,7 @@ class Maquinaspapelesimpresion extends \App\Controllers\BaseResourceController {
|
||||
$resourceData = $this->model->getResource($search, $isRotativa, $tarifas, $maquina_id)
|
||||
->orderBy($order, $dir)->orderBy($order2, $dir2)->orderBy($order3, $dir3)->orderBy($order4, $dir4)->limit($length, $start)->get()->getResultObject();
|
||||
|
||||
$query =$this->model->getLastQuery();
|
||||
return $this->respond(Collection::datatable(
|
||||
$resourceData,
|
||||
$this->model->getResource("", $isRotativa, $tarifas, $maquina_id)->countAllResults(),
|
||||
|
||||
@ -29,6 +29,7 @@ class Paises extends \App\Controllers\BaseResourceController
|
||||
|
||||
protected $indexRoute = 'paisList';
|
||||
|
||||
protected $deletePermission = 'paises.delete';
|
||||
|
||||
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
|
||||
{
|
||||
@ -47,6 +48,7 @@ class Paises extends \App\Controllers\BaseResourceController
|
||||
|
||||
public function index()
|
||||
{
|
||||
checkPermission('paises.menu');
|
||||
|
||||
$viewData = [
|
||||
'currentModule' => static::$controllerSlug,
|
||||
@ -65,6 +67,8 @@ class Paises extends \App\Controllers\BaseResourceController
|
||||
public function add()
|
||||
{
|
||||
|
||||
checkPermission('paises.create');
|
||||
|
||||
if ($this->request->getPost()):
|
||||
|
||||
$postData = $this->request->getPost();
|
||||
@ -119,6 +123,7 @@ class Paises extends \App\Controllers\BaseResourceController
|
||||
|
||||
public function edit($requestedId = null)
|
||||
{
|
||||
checkPermission('paises.edit');
|
||||
|
||||
if ($requestedId == null):
|
||||
return $this->redirect2listView();
|
||||
|
||||
@ -28,6 +28,7 @@ class Papelesgenericos extends \App\Controllers\BaseResourceController
|
||||
|
||||
protected $indexRoute = 'papelGenericoList';
|
||||
|
||||
protected $deletePermission = 'papel-generico.delete';
|
||||
|
||||
|
||||
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
|
||||
@ -40,6 +41,8 @@ class Papelesgenericos extends \App\Controllers\BaseResourceController
|
||||
// Se indica el flag para los ficheros borrados
|
||||
$this->delete_flag = 1;
|
||||
|
||||
$this->papelService = service('papel');
|
||||
|
||||
// Breadcrumbs (IMN)
|
||||
$this->viewData['breadcrumb'] = [
|
||||
['title' => lang("App.menu_configuration"), 'route' => "javascript:void(0);", 'active' => false],
|
||||
@ -52,6 +55,7 @@ class Papelesgenericos extends \App\Controllers\BaseResourceController
|
||||
|
||||
public function index()
|
||||
{
|
||||
checkPermission('papel-generico.menu');
|
||||
|
||||
$viewData = [
|
||||
'currentModule' => static::$controllerSlug,
|
||||
@ -69,10 +73,7 @@ class Papelesgenericos extends \App\Controllers\BaseResourceController
|
||||
|
||||
public function add()
|
||||
{
|
||||
|
||||
|
||||
|
||||
|
||||
checkPermission('papel-generico.create');
|
||||
|
||||
if ($this->request->getPost()):
|
||||
|
||||
@ -120,9 +121,11 @@ class Papelesgenericos extends \App\Controllers\BaseResourceController
|
||||
endif; // $noException && $successfulResult
|
||||
|
||||
endif; // ($requestMethod === 'post')
|
||||
|
||||
|
||||
$this->viewData['papelGenerico'] = isset($sanitizedData) ? new PapelGenerico($sanitizedData) : new PapelGenerico();
|
||||
|
||||
$this->viewData['tipoPapelGenericoList'] = $this->papelService->getTipoPapelGenerico();
|
||||
|
||||
$this->viewData['formAction'] = route_to('createPapelGenerico');
|
||||
|
||||
$this->viewData['boxTitle'] = lang('Basic.global.addNew') . ' ' . lang('PapelGenerico.moduleTitle') . ' ' . lang('Basic.global.addNewSuffix');
|
||||
@ -132,6 +135,7 @@ class Papelesgenericos extends \App\Controllers\BaseResourceController
|
||||
|
||||
public function edit($requestedId = null)
|
||||
{
|
||||
checkPermission('papel-generico.edit');
|
||||
|
||||
if ($requestedId == null):
|
||||
return $this->redirect2listView();
|
||||
@ -145,7 +149,6 @@ class Papelesgenericos extends \App\Controllers\BaseResourceController
|
||||
endif;
|
||||
|
||||
|
||||
|
||||
if ($this->request->getPost()):
|
||||
|
||||
$nullIfEmpty = true; // !(phpversion() >= '8.1');
|
||||
@ -211,6 +214,8 @@ class Papelesgenericos extends \App\Controllers\BaseResourceController
|
||||
|
||||
$this->viewData['papelGenerico'] = $papelGenerico;
|
||||
|
||||
$this->viewData['tipoPapelGenericoList'] = $this->papelService->getTipoPapelGenerico();
|
||||
|
||||
$this->viewData['formAction'] = route_to('updatePapelGenerico', $id);
|
||||
|
||||
$this->viewData['boxTitle'] = lang('Basic.global.edit2') . ' ' . lang('PapelGenerico.moduleTitle') . ' ' . lang('Basic.global.edit3');
|
||||
|
||||
@ -52,6 +52,9 @@ class Papelesimpresion extends \App\Controllers\BaseResourceController
|
||||
protected static $viewPath = 'themes/vuexy/form/configuracion/papel/';
|
||||
|
||||
protected $indexRoute = 'papelImpresionList';
|
||||
|
||||
protected $deletePermission = 'papel-impresion.delete';
|
||||
|
||||
protected Validation $validation;
|
||||
|
||||
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
|
||||
@ -81,6 +84,7 @@ class Papelesimpresion extends \App\Controllers\BaseResourceController
|
||||
|
||||
public function index()
|
||||
{
|
||||
checkPermission('papel-impresion.menu');
|
||||
|
||||
$viewData = [
|
||||
'currentModule' => static::$controllerSlug,
|
||||
@ -98,7 +102,7 @@ class Papelesimpresion extends \App\Controllers\BaseResourceController
|
||||
|
||||
public function add()
|
||||
{
|
||||
|
||||
checkPermission('papel-impresion.create');
|
||||
|
||||
if ($this->request->getPost()) :
|
||||
|
||||
@ -161,6 +165,7 @@ class Papelesimpresion extends \App\Controllers\BaseResourceController
|
||||
|
||||
public function edit($requestedId = null)
|
||||
{
|
||||
checkPermission('papel-impresion.edit');
|
||||
|
||||
if ($requestedId == null) :
|
||||
return $this->redirect2listView();
|
||||
|
||||
7
ci4/app/Controllers/Configuracion/SeriesFacturas.php
Normal file → Executable file
7
ci4/app/Controllers/Configuracion/SeriesFacturas.php
Normal file → Executable file
@ -22,6 +22,8 @@ class SeriesFacturas extends BaseResourceController
|
||||
|
||||
protected $indexRoute = 'seriesFacturasList';
|
||||
|
||||
protected $deletePermission = 'series-facturas.delete';
|
||||
|
||||
|
||||
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
|
||||
{
|
||||
@ -40,6 +42,7 @@ class SeriesFacturas extends BaseResourceController
|
||||
|
||||
public function index()
|
||||
{
|
||||
checkPermission('series-facturas.menu');
|
||||
|
||||
$viewData = [
|
||||
'currentModule' => static::$controllerSlug,
|
||||
@ -57,6 +60,8 @@ class SeriesFacturas extends BaseResourceController
|
||||
|
||||
public function add()
|
||||
{
|
||||
checkPermission('series-facturas.create');
|
||||
|
||||
if ($this->request->getPost()) :
|
||||
|
||||
$postData = $this->request->getPost();
|
||||
@ -110,6 +115,8 @@ class SeriesFacturas extends BaseResourceController
|
||||
public function edit($requestedId = null)
|
||||
{
|
||||
|
||||
checkPermission('series-facturas.edit');
|
||||
|
||||
if ($requestedId == null) :
|
||||
return $this->redirect2listView();
|
||||
endif;
|
||||
|
||||
6
ci4/app/Controllers/Configuracion/Ubicaciones.php
Normal file → Executable file
6
ci4/app/Controllers/Configuracion/Ubicaciones.php
Normal file → Executable file
@ -22,6 +22,8 @@ class Ubicaciones extends BaseResourceController
|
||||
|
||||
protected $indexRoute = 'ubicacionesList';
|
||||
|
||||
protected $deletePermission = 'ubicaciones.delete';
|
||||
|
||||
|
||||
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
|
||||
{
|
||||
@ -40,6 +42,7 @@ class Ubicaciones extends BaseResourceController
|
||||
|
||||
public function index()
|
||||
{
|
||||
checkPermission('ubicaciones.menu');
|
||||
|
||||
$viewData = [
|
||||
'currentModule' => static::$controllerSlug,
|
||||
@ -57,6 +60,8 @@ class Ubicaciones extends BaseResourceController
|
||||
|
||||
public function add()
|
||||
{
|
||||
checkPermission('ubicaciones.create');
|
||||
|
||||
if ($this->request->getPost()) :
|
||||
|
||||
$postData = $this->request->getPost();
|
||||
@ -111,6 +116,7 @@ class Ubicaciones extends BaseResourceController
|
||||
|
||||
public function edit($requestedId = null)
|
||||
{
|
||||
checkPermission('ubicaciones.edit');
|
||||
|
||||
if ($requestedId == null) :
|
||||
return $this->redirect2listView();
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
<?php namespace App\Controllers\Configuracion;
|
||||
<?php
|
||||
|
||||
namespace App\Controllers\Configuracion;
|
||||
|
||||
use App\Entities\Usuarios\UserEntity;
|
||||
use App\Models\Chat\ChatDeparmentModel;
|
||||
@ -54,7 +56,6 @@ class Users extends \App\Controllers\GoBaseController
|
||||
];
|
||||
|
||||
parent::initController($request, $response, $logger);
|
||||
|
||||
}
|
||||
|
||||
public function index()
|
||||
@ -68,7 +69,7 @@ class Users extends \App\Controllers\GoBaseController
|
||||
public function add()
|
||||
{
|
||||
|
||||
if ($this->request->getPost()) :
|
||||
if ($this->request->getPost()):
|
||||
|
||||
$postData = $this->request->getPost();
|
||||
|
||||
@ -87,14 +88,14 @@ class Users extends \App\Controllers\GoBaseController
|
||||
|
||||
// Marcar el username como NULL
|
||||
$sanitizedData = $this->sanitized($postData, true);
|
||||
|
||||
|
||||
$noException = true;
|
||||
|
||||
// Obtener proveedor de usuarios
|
||||
$users = auth()->getProvider();
|
||||
|
||||
if ($successfulResult = $this->canValidate()) :
|
||||
if ($this->canValidate()) :
|
||||
if ($successfulResult = $this->canValidate()):
|
||||
if ($this->canValidate()):
|
||||
try {
|
||||
|
||||
// The Email is unique
|
||||
@ -118,11 +119,10 @@ class Users extends \App\Controllers\GoBaseController
|
||||
|
||||
} // Email is not unique!
|
||||
else {
|
||||
$this->viewData['errorMessage'] = "El correo '". $sanitizedData['email'] ."' ya está registrado en el sistema";
|
||||
$this->viewData['errorMessage'] = "El correo '" . $sanitizedData['email'] . "' ya está registrado en el sistema";
|
||||
$this->session->setFlashdata('formErrors', $this->model->errors());
|
||||
$successfulResult = false; // Hacked
|
||||
}
|
||||
|
||||
} catch (\Exception $e) {
|
||||
$noException = false;
|
||||
$this->viewData['errorMessage'] = $e->getMessage();
|
||||
@ -134,17 +134,12 @@ class Users extends \App\Controllers\GoBaseController
|
||||
$thenRedirect = true; // Change this to false if you want your user to stay on the form after submission
|
||||
endif;
|
||||
|
||||
if ($noException && $successfulResult) :
|
||||
if ($noException && $successfulResult):
|
||||
|
||||
$id = $users->getInsertID();
|
||||
$this->group_user_model->where('user_id', $id)->delete();
|
||||
foreach ($currentGroups as $group) {
|
||||
$group_user_data = [
|
||||
'user_id' => $id,
|
||||
'group' => $group
|
||||
];
|
||||
$this->group_user_model->insert($group_user_data);
|
||||
}
|
||||
// Asignar los grupos de usuarios a los que pertenece el usuario editado
|
||||
$this->saveUserGroupsSafely($id, $currentGroups);
|
||||
|
||||
$this->chat_department_user_model->where("user_id", $id)->delete();
|
||||
foreach ($chatDepartments as $chatDepartment) {
|
||||
$this->chat_department_user_model->insert([
|
||||
@ -156,8 +151,8 @@ class Users extends \App\Controllers\GoBaseController
|
||||
$message = lang('Basic.global.saveSuccess', [mb_strtolower(lang('Users.user'))]) . '.';
|
||||
$message = ucfirst(str_replace("'", "\'", $message));
|
||||
|
||||
if ($thenRedirect) :
|
||||
if (!empty($this->indexRoute)) :
|
||||
if ($thenRedirect):
|
||||
if (!empty($this->indexRoute)):
|
||||
return redirect()->to(route_to($this->indexRoute))->with('successMessage', $message);
|
||||
else:
|
||||
return $this->redirect2listView('successMessage', $message);
|
||||
@ -173,7 +168,7 @@ class Users extends \App\Controllers\GoBaseController
|
||||
$this->viewData['user'] = isset($sanitizedData) ? new UserEntity($sanitizedData) : new UserEntity();
|
||||
$this->viewData['clienteList'] = $this->getClienteListItems();
|
||||
$this->viewData['formAction'] = route_to('createUser');
|
||||
$this->viewData['groups'] = $this->group_model->select('keyword, title')->findAll();
|
||||
$this->viewData['groups'] = $this->group_model->select('keyword, title')->where('id >', 0)->findAll();
|
||||
$this->viewData['chatDepartments'] = $this->chat_department_model->findAll();
|
||||
$this->viewData['boxTitle'] = lang('Basic.global.addNew') . ' ' . lang('Users.user') . ' ' . lang('Basic.global.addNewSuffix');
|
||||
|
||||
@ -191,12 +186,12 @@ class Users extends \App\Controllers\GoBaseController
|
||||
$users = auth()->getProvider();
|
||||
$user = $users->findById($id);
|
||||
|
||||
if ($user == false) :
|
||||
if ($user == false):
|
||||
$message = lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('Users.user')), $id]);
|
||||
return $this->redirect2listView('errorMessage', $message);
|
||||
endif;
|
||||
|
||||
if ($this->request->getPost()) :
|
||||
if ($this->request->getPost()):
|
||||
|
||||
$postData = $this->request->getPost();
|
||||
|
||||
@ -218,9 +213,9 @@ class Users extends \App\Controllers\GoBaseController
|
||||
}
|
||||
|
||||
$noException = true;
|
||||
if ($successfulResult = $this->canValidate()) :
|
||||
if ($successfulResult = $this->canValidate()):
|
||||
|
||||
if ($this->canValidate()) :
|
||||
if ($this->canValidate()):
|
||||
try {
|
||||
|
||||
if (in_array('cliente-editor', $currentGroups) || in_array('cliente-administrador', $currentGroups)) {
|
||||
@ -234,7 +229,6 @@ class Users extends \App\Controllers\GoBaseController
|
||||
} else {
|
||||
$successfulResult = $this->model->skipValidation(true)->update($id, $sanitizedData);
|
||||
}
|
||||
|
||||
} catch (\Exception $e) {
|
||||
$noException = false;
|
||||
$this->dealWithException($e);
|
||||
@ -250,16 +244,11 @@ class Users extends \App\Controllers\GoBaseController
|
||||
$thenRedirect = false;
|
||||
|
||||
endif;
|
||||
if ($noException && $successfulResult) :
|
||||
if ($noException && $successfulResult):
|
||||
|
||||
// Asignar los grupos de usuarios a los que pertenece el usuario editado
|
||||
$this->saveUserGroupsSafely($user->id, $currentGroups);
|
||||
|
||||
$this->group_user_model->where('user_id', $user->id)->delete();
|
||||
foreach ($currentGroups as $group) {
|
||||
$group_user_data = [
|
||||
'user_id' => $user->id,
|
||||
'group' => $group
|
||||
];
|
||||
$this->group_user_model->insert($group_user_data);
|
||||
}
|
||||
$this->chat_department_user_model->where("user_id", $id)->delete();
|
||||
foreach ($chatDepartments as $chatDepartment) {
|
||||
$this->chat_department_user_model->insert([
|
||||
@ -271,8 +260,8 @@ class Users extends \App\Controllers\GoBaseController
|
||||
$message = lang('Basic.global.updateSuccess', [mb_strtolower(lang('Users.user'))]) . '.';
|
||||
$message = ucfirst(str_replace("'", "\'", $message));
|
||||
|
||||
if ($thenRedirect) :
|
||||
if (!empty($this->indexRoute)) :
|
||||
if ($thenRedirect):
|
||||
if (!empty($this->indexRoute)):
|
||||
return redirect()->to(route_to($this->indexRoute))->with('successMessage', $message);
|
||||
else:
|
||||
return $this->redirect2listView('successMessage', $message);
|
||||
@ -288,7 +277,7 @@ class Users extends \App\Controllers\GoBaseController
|
||||
$this->viewData['clienteList'] = $this->getClienteListItems($user->cliente_id);
|
||||
$this->viewData['formAction'] = route_to('updateUser', $id);
|
||||
$this->viewData['selectedGroups'] = $this->group_model->getUsersRoles($requestedId);
|
||||
$this->viewData['groups'] = $this->group_model->select('keyword, title')->findAll();
|
||||
$this->viewData['groups'] = $this->group_model->select('keyword, title')->where('id >', 0)->findAll();
|
||||
$this->viewData['chatDepartments'] = $this->chat_department_model->select(["display", "name", "id as chatDepartmentId"])->findAll();
|
||||
$this->viewData['chatDepartmentUser'] = $this->chat_department_user_model->getChatDepartmentUser($user->id);
|
||||
$this->viewData['boxTitle'] = lang('Basic.global.edit2') . ' ' . lang('Users.user') . ' ' . lang('Basic.global.edit3');
|
||||
@ -300,18 +289,22 @@ class Users extends \App\Controllers\GoBaseController
|
||||
public function delete($requestedId = null, bool $deletePermanently = true)
|
||||
{
|
||||
|
||||
if ($requestedId == null) :
|
||||
if ($requestedId == null):
|
||||
return $this->redirect2listView();
|
||||
endif;
|
||||
|
||||
$id = filter_var($requestedId, FILTER_SANITIZE_URL);
|
||||
$user = $this->model->find($id);
|
||||
|
||||
if ($user == false) :
|
||||
if ($user == false):
|
||||
$message = lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('Users.user')), $id]);
|
||||
return $this->redirect2listView('errorMessage', $message);
|
||||
endif;
|
||||
|
||||
// Elimina todos los grupos actuales
|
||||
$this->group_user_model->where('user_id', $id)->delete();
|
||||
|
||||
// Elimina todos los grupos de chat actuales
|
||||
$this->chat_department_user_model->where("user_id", $id)->delete();
|
||||
|
||||
$users = auth()->getProvider();
|
||||
@ -319,8 +312,6 @@ class Users extends \App\Controllers\GoBaseController
|
||||
|
||||
$message = "Usuario eliminado correctamente";
|
||||
return $this->redirect2listView('successMessage', $message);
|
||||
|
||||
|
||||
} // end function delete(...)
|
||||
|
||||
|
||||
@ -374,9 +365,10 @@ class Users extends \App\Controllers\GoBaseController
|
||||
}
|
||||
}
|
||||
|
||||
public function datatable(){
|
||||
public function datatable()
|
||||
{
|
||||
|
||||
if($this->request->isAJAX()){
|
||||
if ($this->request->isAJAX()) {
|
||||
|
||||
$reqData = $this->request->getPost();
|
||||
if (!isset($reqData['draw']) || !isset($reqData['columns'])) {
|
||||
@ -405,7 +397,6 @@ class Users extends \App\Controllers\GoBaseController
|
||||
$this->model->getResource([])->countAllResults(),
|
||||
$this->model->getResource($searchValues)->countAllResults()
|
||||
));
|
||||
|
||||
} else {
|
||||
return $this->failUnauthorized('Invalid request', 403);
|
||||
}
|
||||
@ -436,15 +427,84 @@ class Users extends \App\Controllers\GoBaseController
|
||||
protected function getClienteListItems($selId = null)
|
||||
{
|
||||
$data = ['' => ""];
|
||||
if (!empty($selId)) :
|
||||
if (!empty($selId)):
|
||||
$clienteModel = model('App\Models\Clientes\ClienteModel');
|
||||
|
||||
$selOption = $clienteModel->where('id', $selId)->findColumn('nombre');
|
||||
if (!empty($selOption)) :
|
||||
if (!empty($selOption)):
|
||||
$data[$selId] = $selOption[0];
|
||||
endif;
|
||||
endif;
|
||||
return $data;
|
||||
}
|
||||
|
||||
public function index_maquinista_change_user()
|
||||
{
|
||||
$this->viewData['breadcrumb'] = [
|
||||
['title' => lang("App.menu_change_session"), 'route' => route_to('maquinistaUserChangeList'), 'active' => true]
|
||||
];
|
||||
$maquinistas = [];
|
||||
$users = auth()->getProvider()->whereNotIn('id', [auth()->user()->id])->findAll();
|
||||
foreach ($users as $key => $user) {
|
||||
if ($user->inGroup('maquina') && !$user->inGroup('admin', 'comercial', 'cliente-editor', 'cliente-admin')) {
|
||||
$maquinistas[] = $user;
|
||||
}
|
||||
}
|
||||
$this->viewData['maquinistas'] = $maquinistas;
|
||||
return view('/themes/vuexy/form/produccion/maquinista/viewMaquinistaCambioUserList.php', $this->viewData);
|
||||
}
|
||||
public function change_user_session(int $user_id)
|
||||
{
|
||||
// Check the credentials
|
||||
$user = auth()->getProvider()->findById($user_id);
|
||||
auth()->logout();
|
||||
auth()->login($user);
|
||||
return redirect("home");
|
||||
}
|
||||
|
||||
/**
|
||||
* Asigna grupos a un usuario, asegurando que no se pueda inyectar el grupo 'root',
|
||||
* pero manteniéndolo si ya lo tenía previamente.
|
||||
*
|
||||
* @param int $userId ID del usuario al que se le asignarán los grupos
|
||||
* @param array $requestedGroups Grupos solicitados desde el formulario
|
||||
* @return void
|
||||
*/
|
||||
private function saveUserGroupsSafely(int $userId, array $requestedGroups): void
|
||||
{
|
||||
// Verifica si el usuario ya tenía el grupo 'root'
|
||||
$existingGroups = $this->group_user_model
|
||||
->where('user_id', $userId)
|
||||
->findColumn('group') ?? [];
|
||||
|
||||
$hasRoot = in_array('root', $existingGroups);
|
||||
|
||||
// Elimina todos los grupos actuales
|
||||
$this->group_user_model->where('user_id', $userId)->delete();
|
||||
|
||||
// Inserta solo los grupos válidos (sin 'root')
|
||||
foreach ($requestedGroups as $group) {
|
||||
if (!empty($group) && $group !== 'root') {
|
||||
$this->group_user_model->insert([
|
||||
'user_id' => $userId,
|
||||
'group' => $group,
|
||||
'created_at' => date('Y-m-d H:i:s'),
|
||||
]);
|
||||
} elseif ($group === 'root') {
|
||||
log_message('alert', "Intento de asignar grupo 'root' al usuario ID $userId");
|
||||
}
|
||||
}
|
||||
|
||||
// Reasigna 'root' solo si el usuario ya lo tenía
|
||||
if ($hasRoot) {
|
||||
$this->group_user_model->insert([
|
||||
'user_id' => $userId,
|
||||
'group' => 'root',
|
||||
'created_at' => date('Y-m-d H:i:s'),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
0
ci4/app/Controllers/Excel/PrintGiros.php
Normal file → Executable file
0
ci4/app/Controllers/Excel/PrintGiros.php
Normal file → Executable file
0
ci4/app/Controllers/Excel/PrintLineas.php
Normal file → Executable file
0
ci4/app/Controllers/Excel/PrintLineas.php
Normal file → Executable file
@ -234,6 +234,13 @@ class Facturas extends \App\Controllers\BaseResourceController
|
||||
$factura->showDeleteButton = model('App\Models\Facturas\FacturaPagoModel')
|
||||
->where('factura_id', $factura->id)->countAllResults() == 0;
|
||||
|
||||
if($factura->numero != null && $factura->numero != '' && strpos($factura->numero, "REC ") === 0) {
|
||||
$modelPagos = model('App\Models\Facturas\FacturaPagoModel');
|
||||
if($modelPagos->where('factura_id', $factura->id)->countAllResults() > 0) {
|
||||
$factura->facturaRectificativaPagada = 1;
|
||||
}
|
||||
}
|
||||
|
||||
$this->viewData['facturaEntity'] = $factura;
|
||||
|
||||
$this->viewData['boxTitle'] = lang('Basic.global.edit2') . ' ' . lang('Facturas.factura') . ' ' . lang('Basic.global.edit3');
|
||||
@ -787,6 +794,32 @@ class Facturas extends \App\Controllers\BaseResourceController
|
||||
}
|
||||
}
|
||||
|
||||
public function deleteLineaPago()
|
||||
{
|
||||
|
||||
if ($this->request->isAJAX()) {
|
||||
|
||||
$postData = $this->request->getPost();
|
||||
$factura_id = $postData['factura_id'] ?? 0;
|
||||
$pago_id = $postData['pago_id'] ?? 0;
|
||||
|
||||
$model_factura_pago = model('\App\Models\Facturas\FacturaPagoModel');
|
||||
$model_factura_pago->update($pago_id, [
|
||||
'deleted_at' => date('Y-m-d H:i:s'),
|
||||
'user_updated_id' => auth()->user()->id,
|
||||
]);
|
||||
|
||||
$newTokenHash = csrf_hash();
|
||||
$csrfTokenName = csrf_token();
|
||||
$data = [
|
||||
$csrfTokenName => $newTokenHash
|
||||
];
|
||||
return $this->respond($data);
|
||||
} else {
|
||||
return $this->failUnauthorized('Invalid request', 403);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public function validar($factura_id)
|
||||
{
|
||||
@ -805,11 +838,15 @@ class Facturas extends \App\Controllers\BaseResourceController
|
||||
'user_updated_id' => auth()->user()->id,
|
||||
];
|
||||
|
||||
if ((strpos($numero, "REC ") === 0)) {
|
||||
$data['estado_pago'] = 'pagada';
|
||||
}
|
||||
|
||||
$this->model->update($factura_id, $data);
|
||||
|
||||
if ((strpos($numero, "REC ") === 0)) {
|
||||
|
||||
$this->model->where('numero', $factura->factura_rectificada_id)->set([
|
||||
'factura_rectificativa_id' => $numero,
|
||||
'user_updated_id' => auth()->user()->id,
|
||||
])->update();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
164
ci4/app/Controllers/Facturacion/FacturasLineas.php
Normal file → Executable file
164
ci4/app/Controllers/Facturacion/FacturasLineas.php
Normal file → Executable file
@ -16,14 +16,15 @@ class FacturasLineas extends \App\Controllers\BaseResourceController
|
||||
protected static $controllerSlug = 'factura-lineas';
|
||||
|
||||
|
||||
public function datatable($factura_id = null){
|
||||
public function datatable($factura_id = null)
|
||||
{
|
||||
|
||||
if ($this->request->isAJAX() && $factura_id != null) {
|
||||
|
||||
$reqData = $this->request->getPost();
|
||||
if (!isset($reqData['draw']) || !isset($reqData['columns']) ) {
|
||||
if (!isset($reqData['draw']) || !isset($reqData['columns'])) {
|
||||
$errstr = 'No data available in response to this specific request.';
|
||||
$response = $this->respond(Collection::datatable( [], 0, 0, $errstr ), 400, $errstr);
|
||||
$response = $this->respond(Collection::datatable([], 0, 0, $errstr), 400, $errstr);
|
||||
return $response;
|
||||
}
|
||||
$start = $reqData['start'] ?? 0;
|
||||
@ -46,31 +47,32 @@ class FacturasLineas extends \App\Controllers\BaseResourceController
|
||||
}
|
||||
|
||||
|
||||
public function deleteLinea($factura_linea_id = 0){
|
||||
|
||||
public function deleteLinea($factura_linea_id = 0)
|
||||
{
|
||||
|
||||
if (!empty(static::$pluralObjectNameCc) && !empty(static::$singularObjectNameCc)) {
|
||||
$objName = mb_strtolower(lang(ucfirst(static::$pluralObjectNameCc).'.'.static::$singularObjectNameCc));
|
||||
$objName = mb_strtolower(lang(ucfirst(static::$pluralObjectNameCc) . '.' . static::$singularObjectNameCc));
|
||||
} else {
|
||||
$objName = lang('Basic.global.record');
|
||||
}
|
||||
|
||||
if($factura_linea_id == 0){
|
||||
if ($factura_linea_id == 0) {
|
||||
return $this->failNotFound(lang('Basic.global.deleteError', [$objName]));
|
||||
}
|
||||
|
||||
$facturaLinea = $this->model->find($factura_linea_id);
|
||||
if($facturaLinea == null){
|
||||
if ($facturaLinea == null) {
|
||||
return $this->failNotFound(lang('Basic.global.deleteError', [$objName]));
|
||||
}
|
||||
|
||||
if($facturaLinea->pedido_linea_impresion_id != null){
|
||||
$this->model->deleteFacturasLineasPedido($facturaLinea->factura_id, $facturaLinea->pedido_linea_impresion_id, $facturaLinea->cantidad);
|
||||
if ($facturaLinea->pedido_linea_impresion_id != null) {
|
||||
$this->model->deleteFacturasLineasPedido($facturaLinea->factura_id, $facturaLinea->pedido_linea_impresion_id, $facturaLinea->cantidad);
|
||||
}
|
||||
|
||||
if($facturaLinea->pedido_maquetacion_id != null){
|
||||
if ($facturaLinea->pedido_maquetacion_id != null) {
|
||||
//$this->model->deleteFacturasLineasPedido($facturaLinea->factura_id, $facturaLinea->pedido_maquetacion_id, $facturaLinea->cantidad);
|
||||
}
|
||||
|
||||
|
||||
$facturaLinea = $this->model->delete($factura_linea_id);
|
||||
$message = lang('Basic.global.deleteSuccess', [lang('Basic.global.record')]);
|
||||
$response = $this->respondDeleted(['id' => $factura_linea_id, 'msg' => $message]);
|
||||
@ -78,51 +80,73 @@ class FacturasLineas extends \App\Controllers\BaseResourceController
|
||||
}
|
||||
|
||||
|
||||
public function datatable_editor() {
|
||||
public function datatable_editor()
|
||||
{
|
||||
if ($this->request->isAJAX()) {
|
||||
|
||||
include(APPPATH . "ThirdParty/DatatablesEditor/DataTables.php");
|
||||
|
||||
// Build our Editor instance and process the data coming from _POST
|
||||
$response = Editor::inst( $db, 'facturas_lineas' )
|
||||
$response = Editor::inst($db, 'facturas_lineas')
|
||||
->fields(
|
||||
Field::inst( 'id' ),
|
||||
Field::inst( 'base' ),
|
||||
Field::inst( 'total_iva' ),
|
||||
Field::inst( 'total' ),
|
||||
Field::inst( 'cantidad' )
|
||||
->validator('Validate::numeric', array(
|
||||
'message' => lang('Facturas.validation.numerico'))
|
||||
Field::inst('id'),
|
||||
Field::inst('base'),
|
||||
Field::inst('total_iva'),
|
||||
Field::inst('total')->set(Field::SET_BOTH),
|
||||
Field::inst('cantidad')
|
||||
->validator(
|
||||
'Validate::numeric',
|
||||
array(
|
||||
'message' => lang('Facturas.validation.numerico')
|
||||
)
|
||||
)
|
||||
->validator('Validate::notEmpty', array(
|
||||
'message' => lang('Facturas.validation.requerido'))
|
||||
->validator(
|
||||
'Validate::notEmpty',
|
||||
array(
|
||||
'message' => lang('Facturas.validation.requerido')
|
||||
)
|
||||
),
|
||||
Field::inst( 'descripcion' )
|
||||
->validator('Validate::notEmpty', array(
|
||||
'message' => lang('Facturas.validation.requerido'))
|
||||
Field::inst('descripcion')
|
||||
->validator(
|
||||
'Validate::notEmpty',
|
||||
array(
|
||||
'message' => lang('Facturas.validation.requerido')
|
||||
)
|
||||
),
|
||||
Field::inst( 'iva' )
|
||||
->validator('Validate::numeric', array(
|
||||
'message' => lang('Facturas.validation.numerico'))
|
||||
Field::inst('iva')
|
||||
->validator(
|
||||
'Validate::numeric',
|
||||
array(
|
||||
'message' => lang('Facturas.validation.numerico')
|
||||
)
|
||||
)
|
||||
->validator('Validate::notEmpty', array(
|
||||
'message' => lang('Facturas.validation.requerido'))
|
||||
->validator(
|
||||
'Validate::notEmpty',
|
||||
array(
|
||||
'message' => lang('Facturas.validation.requerido')
|
||||
)
|
||||
),
|
||||
Field::inst( 'pedido_linea_impresion_id' )
|
||||
->setFormatter(function($val, $data, $opts) {
|
||||
Field::inst('pedido_linea_impresion_id')
|
||||
->setFormatter(function ($val, $data, $opts) {
|
||||
return $val === '' ? null : $val;
|
||||
}),
|
||||
Field::inst( 'factura_id' ),
|
||||
Field::inst( 'user_updated_id' ),
|
||||
Field::inst('pedido_maquetacion_id')
|
||||
->setFormatter(function ($val, $data, $opts) {
|
||||
return $val === '' ? null : $val;
|
||||
}),
|
||||
Field::inst('factura_id'),
|
||||
Field::inst('user_updated_id'),
|
||||
)
|
||||
->on('preCreate', function ($editor, &$values) {
|
||||
$totales = $this->generate_totales(
|
||||
$values['factura_id'],
|
||||
$values['pedido_linea_impresion_id'],
|
||||
$values['total'],
|
||||
$values['iva'],
|
||||
$values['factura_id'],
|
||||
$values['pedido_linea_impresion_id'],
|
||||
$values['total'],
|
||||
$values['iva'],
|
||||
$values['cantidad'],
|
||||
$values['old_cantidad']);
|
||||
$values['old_cantidad'],
|
||||
$values['base']
|
||||
);
|
||||
$editor
|
||||
->field('user_updated_id')
|
||||
->setValue(auth()->user()->id);
|
||||
@ -141,12 +165,14 @@ class FacturasLineas extends \App\Controllers\BaseResourceController
|
||||
})
|
||||
->on('preEdit', function ($editor, $id, &$values) {
|
||||
$totales = $this->generate_totales(
|
||||
$values['factura_id'],
|
||||
$values['pedido_linea_impresion_id'],
|
||||
$values['total'],
|
||||
$values['iva'],
|
||||
$values['factura_id'],
|
||||
$values['pedido_linea_impresion_id'],
|
||||
$values['total'],
|
||||
$values['iva'],
|
||||
$values['cantidad'],
|
||||
$values['old_cantidad']);
|
||||
$values['old_cantidad'],
|
||||
$values['base']
|
||||
);
|
||||
$editor
|
||||
->field('factura_id')
|
||||
->setValue($values['factura_id']);
|
||||
@ -185,8 +211,9 @@ class FacturasLineas extends \App\Controllers\BaseResourceController
|
||||
}
|
||||
}
|
||||
|
||||
public function updateTotalesFactura($factura_id = 0){
|
||||
if($factura_id == 0){
|
||||
public function updateTotalesFactura($factura_id = 0)
|
||||
{
|
||||
if ($factura_id == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
@ -194,26 +221,41 @@ class FacturasLineas extends \App\Controllers\BaseResourceController
|
||||
$model->updateTotales($factura_id);
|
||||
}
|
||||
|
||||
private function generate_totales($factura_id, $pedido_linea_id, $total, $iva, $cantidad, $old_cantidad)
|
||||
private function generate_totales($factura_id, $pedido_linea_id, $total, $iva, $cantidad, $old_cantidad, $base_input)
|
||||
{
|
||||
|
||||
|
||||
// si es una linea que se refiere a pedido
|
||||
if ($pedido_linea_id != null && $factura_id != null) {
|
||||
// se actualiza la cantidad de la linea de pedido en la tabla pivote facturas_pedidos_lineas
|
||||
$this->model->updateFacturaPedidoLinea($factura_id, $pedido_linea_id, $old_cantidad, $cantidad);
|
||||
}
|
||||
|
||||
// se calcula y se actualiza el subtotal, total_iva y total
|
||||
// redondeando a 4 decimales el precio_unidad y a dos el resto
|
||||
$precio_unidad = round($total / $old_cantidad, 4);
|
||||
$base = round($precio_unidad * $cantidad, 2);
|
||||
$total_iva = round($base * $iva / 100, 2);
|
||||
$total = round($base + $total_iva, 2);
|
||||
$values = [];
|
||||
$values['base'] = $base;
|
||||
$values['total_iva'] = $total_iva;
|
||||
$values['total'] = $total;
|
||||
|
||||
|
||||
// Si es una linea añadida a mano, el total y el iva tienen que venir metidos a mano
|
||||
if ($pedido_linea_id != null) {
|
||||
|
||||
// se calcula y se actualiza el subtotal, total_iva y total
|
||||
// redondeando a 4 decimales el precio_unidad y a dos el resto
|
||||
$precio_unidad = round($total / $old_cantidad, 4);
|
||||
$base = round($precio_unidad * $cantidad, 2);
|
||||
$total_iva = round($base * $iva / 100, 2);
|
||||
$total = round($base + $total_iva, 2);
|
||||
$values = [];
|
||||
$values['base'] = $base;
|
||||
$values['total_iva'] = $total_iva;
|
||||
$values['total'] = $total;
|
||||
} else {
|
||||
// se pasa la base y el iva
|
||||
$total_iva = round($base_input * $iva / 100, 2);
|
||||
$total = round($base_input + $total_iva, 2);
|
||||
|
||||
$values = [];
|
||||
$values['base'] = (float) $base_input;
|
||||
$values['total_iva'] = $total_iva;
|
||||
$values['total'] = $total;
|
||||
|
||||
}
|
||||
|
||||
|
||||
return $values;
|
||||
}
|
||||
}
|
||||
|
||||
32
ci4/app/Controllers/Facturacion/FacturasPagos.php
Normal file → Executable file
32
ci4/app/Controllers/Facturacion/FacturasPagos.php
Normal file → Executable file
@ -136,4 +136,36 @@ class FacturasPagos extends \App\Controllers\BaseResourceController
|
||||
}
|
||||
}
|
||||
|
||||
public function addPagoRectificativa()
|
||||
{
|
||||
if ($this->request->isAJAX()) {
|
||||
$data['factura_id'] = $this->request->getPost('factura_id');
|
||||
$data['fecha_vencimiento_at'] = $this->request->getPost('fecha');
|
||||
$data['total'] = $this->request->getPost('total');
|
||||
$data['user_updated_id'] = auth()->user()->id;
|
||||
$data['forma_pago_id'] = 6; // compensada
|
||||
|
||||
if($data['fecha_vencimiento_at'] != null && $data['fecha_vencimiento_at'] != '') {
|
||||
$data['fecha_vencimiento_at'] = date('Y-m-d H:i:s', strtotime($data['fecha_vencimiento_at']));
|
||||
}
|
||||
|
||||
$model = new FacturaPagoModel();
|
||||
$model->insert($data);
|
||||
|
||||
$modelFactura = model('App\Models\Facturas\FacturaModel');
|
||||
$modelFactura->update($data['factura_id'], [
|
||||
'estado_pago' => 'pagada',
|
||||
'updated_at' => date('Y-m-d H:i:s'),
|
||||
'user_updated_id' => auth()->user()->id,
|
||||
]);
|
||||
|
||||
return $this->response->setJSON([
|
||||
'status' => true,
|
||||
'message' => lang('Facturas.facturaConformada'),
|
||||
]);
|
||||
} else {
|
||||
return $this->failUnauthorized('Invalid request', 403);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@ -139,7 +139,7 @@ abstract class GoBaseController extends Controller
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $helpers = ['session', 'go_common', 'text', 'general', 'jwt', 'rbac']; //JJO
|
||||
protected $helpers = ['session', 'go_common', 'text', 'general', 'jwt', 'rbac', 'assets']; //JJO
|
||||
|
||||
public static $queries = [];
|
||||
|
||||
|
||||
551
ci4/app/Controllers/Importadores/ImportadorBubok.php
Normal file
551
ci4/app/Controllers/Importadores/ImportadorBubok.php
Normal file
@ -0,0 +1,551 @@
|
||||
<?php
|
||||
namespace App\Controllers\Importadores;
|
||||
|
||||
use App\Controllers\BaseResourceController;
|
||||
use App\Controllers\Presupuestos\Presupuestocliente;
|
||||
use App\Models\Presupuestos\PresupuestoModel;
|
||||
use App\Services\PresupuestoService;
|
||||
|
||||
class ImportadorBubok extends BaseResourceController
|
||||
{
|
||||
|
||||
protected $format = 'json';
|
||||
|
||||
protected static $singularObjectName = 'Importador';
|
||||
protected static $singularObjectNameCc = 'ImportadorBubok';
|
||||
protected static $pluralObjectName = 'Importadores';
|
||||
protected static $pluralObjectNameCc = 'importadores';
|
||||
|
||||
protected static $controllerSlug = 'importador';
|
||||
|
||||
protected static $viewPath = 'themes/vuexy/form/importador/bubok/';
|
||||
|
||||
protected $indexRoute = 'ImportadorBubokTool';
|
||||
|
||||
|
||||
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
|
||||
{
|
||||
$this->viewData['pageTitle'] = lang('Importador.listingPage');
|
||||
$this->viewData['usingSweetAlert'] = true;
|
||||
|
||||
// Breadcrumbs (IMN)
|
||||
$this->viewData['breadcrumb'] = [
|
||||
['title' => lang("App.menu_importadores"), 'route' => "javascript:void(0);", 'active' => false],
|
||||
['title' => lang("App.menu_importadores_bubok"), 'route' => route_to('importadorBubokTool'), 'active' => true]
|
||||
];
|
||||
|
||||
parent::initController($request, $response, $logger);
|
||||
}
|
||||
|
||||
|
||||
public function index()
|
||||
{
|
||||
checkPermission('importadores.bubok');
|
||||
|
||||
$viewData = [
|
||||
'pageSubTitle' => lang('Basic.global.ManageAllRecords', [lang('Importador.importadorCatalogoTitle')]),
|
||||
|
||||
];
|
||||
|
||||
$viewData = array_merge($this->viewData, $viewData); // merge any possible values from the parent controller class
|
||||
|
||||
return view(static::$viewPath . 'viewImportadorBubokTool', $viewData);
|
||||
}
|
||||
|
||||
public function validarFila()
|
||||
{
|
||||
checkPermission('importadores.bubok');
|
||||
|
||||
$json = $this->request->getJSON();
|
||||
|
||||
if (!$json || empty($json->producto) || empty($json->pedido)) {
|
||||
return $this->response->setJSON([
|
||||
'apto' => false,
|
||||
'reason' => 'Datos incompletos'
|
||||
]);
|
||||
}
|
||||
|
||||
$producto = $json->producto;
|
||||
$pedido = $json->pedido;
|
||||
|
||||
// Validar existencia de ID de producto
|
||||
if (empty($producto->id)) {
|
||||
return $this->response->setJSON([
|
||||
'apto' => false,
|
||||
'reason' => 'ID de producto no proporcionado'
|
||||
]);
|
||||
}
|
||||
|
||||
$refCliente = $pedido->orderNumber . '-' . $producto->id;
|
||||
|
||||
// Validar formato Ref. Cliente
|
||||
if (strpos($refCliente, '-') === false || strlen($refCliente) < 5) {
|
||||
return $this->response->setJSON([
|
||||
'apto' => false,
|
||||
'reason' => 'Ref. cliente inválido'
|
||||
]);
|
||||
}
|
||||
|
||||
// 1. Verificar si ya fue importado
|
||||
$presupuestoModel = new PresupuestoModel();
|
||||
$yaExiste = $presupuestoModel->where('referencia_cliente', $refCliente)->first();
|
||||
|
||||
if ($yaExiste) {
|
||||
return $this->response->setJSON([
|
||||
'apto' => false,
|
||||
'reason' => 'Referencia ya importada'
|
||||
]);
|
||||
}
|
||||
|
||||
// 2. Validación básica del producto (puedes expandir con más reglas si lo necesitas)
|
||||
$errores = [];
|
||||
|
||||
if (empty($producto->title))
|
||||
$errores[] = 'Falta título';
|
||||
if (empty($producto->body->pages))
|
||||
$errores[] = 'Faltan páginas';
|
||||
if (empty($producto->amount))
|
||||
$errores[] = 'Falta tirada';
|
||||
|
||||
if (!empty($errores)) {
|
||||
return $this->response->setJSON([
|
||||
'apto' => false,
|
||||
'reason' => implode(', ', $errores)
|
||||
]);
|
||||
}
|
||||
|
||||
// 3. Producto considerado apto
|
||||
return $this->response->setJSON([
|
||||
'apto' => true
|
||||
]);
|
||||
}
|
||||
|
||||
|
||||
|
||||
public function importarFila()
|
||||
{
|
||||
|
||||
checkPermission('importadores.bubok');
|
||||
|
||||
$json = $this->request->getJSON();
|
||||
|
||||
// Validación mínima de datos comunes
|
||||
$pedido = $json->pedido ?? null;
|
||||
if (!$pedido || !isset($pedido->orderNumber)) {
|
||||
return $this->respond([
|
||||
'status' => 400,
|
||||
'message' => 'Datos comunes del pedido ausentes o inválidos.'
|
||||
]);
|
||||
}
|
||||
|
||||
// Validación mínima de existencia del producto en la linea
|
||||
if (!$json || !isset($json->producto)) {
|
||||
return $this->respond([
|
||||
'status' => 400,
|
||||
'message' => 'Producto no proporcionado o inválido.'
|
||||
]);
|
||||
}
|
||||
$producto = $json->producto;
|
||||
|
||||
// 1. Datos básicos:
|
||||
// Referencia del cliente
|
||||
$orderNumber = $pedido->orderNumber ?? null;
|
||||
$productId = $producto->id ?? null;
|
||||
if (is_null($orderNumber) || is_null($productId)) {
|
||||
return $this->respond([
|
||||
'status' => 400,
|
||||
'message' => 'Número de orden o ID del producto no reconocidos.'
|
||||
]);
|
||||
}
|
||||
$refCliente = "$orderNumber-$productId";
|
||||
|
||||
// Titulo
|
||||
$titulo = $producto->title ?? null;
|
||||
if (is_null($titulo)) {
|
||||
return $this->respond([
|
||||
'status' => 400,
|
||||
'message' => 'Título del libro no reconocido.'
|
||||
]);
|
||||
}
|
||||
|
||||
// Validación de páginas y tirada
|
||||
$paginas = isset($producto->body->pages) ? (int) $producto->body->pages : 0;
|
||||
$tirada = isset($producto->amount) ? (int) $producto->amount : 0;
|
||||
if ($paginas <= 0 || $tirada <= 0) {
|
||||
$errores = [];
|
||||
if ($paginas <= 0) {
|
||||
$errores[] = 'Número de páginas inválido.';
|
||||
}
|
||||
if ($tirada <= 0) {
|
||||
$errores[] = 'Tirada inválida.';
|
||||
}
|
||||
|
||||
return $this->respond([
|
||||
'status' => 400,
|
||||
'message' => implode(' ', $errores)
|
||||
]);
|
||||
}
|
||||
|
||||
// Ancho y alto
|
||||
$ancho = null;
|
||||
$alto = null;
|
||||
foreach ($producto->size as $key => $val) {
|
||||
if ($val == 1) {
|
||||
// ejemplo: size170x235
|
||||
$size = str_replace('size', '', $key);
|
||||
[$ancho, $alto] = explode('x', $size);
|
||||
$ancho = (int) $ancho;
|
||||
$alto = (int) $alto;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!$ancho || !$alto) {
|
||||
return $this->respond([
|
||||
'status' => 400,
|
||||
'message' => 'Tamaño del libro no reconocido.'
|
||||
]);
|
||||
}
|
||||
|
||||
/*$numGuardaPages = 4;
|
||||
$hasGuarda = !empty($producto->cover->guarda);
|
||||
if ($hasGuarda)
|
||||
$paginas += $numGuardaPages;*/
|
||||
|
||||
// 2. Interior: color o negro
|
||||
// Determinar tipo de impresión interior
|
||||
$interiorTipo = null;
|
||||
if (isset($producto->body->color->CMYK) && $producto->body->color->CMYK == '1') {
|
||||
$interiorTipo = 'color';
|
||||
} elseif (isset($producto->body->color->Monochrome) && $producto->body->color->Monochrome == '1') {
|
||||
$interiorTipo = 'negro';
|
||||
} elseif (isset($producto->body->color->Semicolor) && $producto->body->color->Semicolor == '1') {
|
||||
return $this->respond([
|
||||
'status' => 400,
|
||||
'message' => 'Tipo de impresión "Semicolor" no soportado.'
|
||||
]);
|
||||
}
|
||||
|
||||
if (is_null($interiorTipo)) {
|
||||
return $this->respond([
|
||||
'status' => 400,
|
||||
'message' => 'No se pudo determinar si el interior es en color o blanco y negro.'
|
||||
]);
|
||||
}
|
||||
|
||||
// Determinar tipo de papel interior
|
||||
$papelInteriorId = null;
|
||||
if (isset($producto->body->paperColor->white) && $producto->body->paperColor->white == '1') {
|
||||
$papelInteriorId = 3; // Offset blanco 'OFF1'
|
||||
} elseif (isset($producto->body->paperColor->cream) && $producto->body->paperColor->cream == '1') {
|
||||
$papelInteriorId = 4; // Offset ahuesado 'OFF2'
|
||||
} else {
|
||||
return $this->respond([
|
||||
'status' => 400,
|
||||
'message' => 'Tipo de papel interior no definido.'
|
||||
]);
|
||||
}
|
||||
|
||||
// Determinar el gramaje del papel
|
||||
$gramajePapelInterior = null;
|
||||
foreach ($producto->body->paperWeight as $key => $val) {
|
||||
if ($val == 1) {
|
||||
$gramajePapelInterior = (int) str_replace(['weight', 'gr'], '', $key);
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!$gramajePapelInterior) {
|
||||
return $this->respond([
|
||||
'status' => 400,
|
||||
'message' => 'Gramaje del papel no válido.'
|
||||
]);
|
||||
}
|
||||
|
||||
// 3. Encuadernación
|
||||
// Tapa dura
|
||||
$tapaDura = isset($producto->cover->type->tapadura) && $producto->cover->type->tapadura == '1';
|
||||
|
||||
// Solapas
|
||||
$solapas = isset($producto->cover->type->consolapas) && $producto->cover->type->consolapas == '1';
|
||||
|
||||
// Doble cara (a veces se activa con tapa dura) una cara => 2; dos caras => 4
|
||||
$doscara = false;
|
||||
|
||||
// Tipo de encuadernado
|
||||
$encuadernadoId = null;
|
||||
|
||||
if (isset($producto->cover->coverType->SoftCover) && $producto->cover->coverType->SoftCover == '1') {
|
||||
if ($tapaDura) {
|
||||
$encuadernadoId = 1; // Libro fresado tapa dura
|
||||
$doscara = true;
|
||||
} else {
|
||||
$encuadernadoId = 2; // Libro fresado tapa blanda
|
||||
}
|
||||
} elseif (isset($producto->cover->coverType->SaddleStitch) && $producto->cover->coverType->SaddleStitch == '1') {
|
||||
if ($tapaDura) {
|
||||
$encuadernadoId = 3; // Libro cosido tapa dura
|
||||
$doscara = true;
|
||||
} else {
|
||||
$encuadernadoId = $solapas ? 20 : 4; // Libro cosido tapa blanda (solapas) : (sin solapas)
|
||||
}
|
||||
} elseif (isset($producto->cover->coverType->CoilBinding) && $producto->cover->coverType->CoilBinding == '1') {
|
||||
if ($tapaDura) {
|
||||
$encuadernadoId = 5; // Libro espiral tapa dura
|
||||
$doscara = true;
|
||||
} else {
|
||||
$encuadernadoId = 6; // Libro espiral tapa blanda
|
||||
}
|
||||
}
|
||||
if (!$encuadernadoId) {
|
||||
return $this->respond([
|
||||
'status' => 400,
|
||||
'message' => 'Tipo de encuadernación no identificado.'
|
||||
]);
|
||||
}
|
||||
|
||||
// Determinar el acabado de la cubierta
|
||||
$acabadoId = null;
|
||||
if (isset($producto->cover->acabado->brillo) && $producto->cover->acabado->brillo == '1') {
|
||||
$acabadoId = 1; // Plastificado brillo 1/c
|
||||
} elseif (isset($producto->cover->acabado->mate) && $producto->cover->acabado->mate == '1') {
|
||||
$acabadoId = 2; // Plastificado mate 1/c
|
||||
} else {
|
||||
return $this->respond([
|
||||
'status' => 400,
|
||||
'message' => 'Tipo de acabado de cubierta no definido.'
|
||||
]);
|
||||
}
|
||||
|
||||
// 4. ENVÍO: recuperamos la primera dirección del cliente BUBOK (ID 40)
|
||||
$clienteDireccionModel = model('App\Models\Clientes\ClienteDireccionesModel');
|
||||
$direccionCliente = $clienteDireccionModel
|
||||
->where('cliente_id', 40)
|
||||
->orderBy('id', 'asc')
|
||||
->first();
|
||||
|
||||
if (!$direccionCliente) {
|
||||
return $this->respond([
|
||||
'status' => 400,
|
||||
'message' => 'El cliente Bubok no tiene direcciones asociadas.'
|
||||
]);
|
||||
}
|
||||
|
||||
$direcciones = [
|
||||
[
|
||||
'direccion' => [
|
||||
'id' => (int) $direccionCliente->id,
|
||||
'cliente_id' => (int) $direccionCliente->cliente_id,
|
||||
'cliente_nombre' => $direccionCliente->clienteNombre,
|
||||
'att' => $direccionCliente->persona_contacto ?? '',
|
||||
'alias' => $direccionCliente->alias ?? '',
|
||||
'email' => $direccionCliente->email ?? '',
|
||||
'direccion' => $direccionCliente->direccion,
|
||||
'pais_id' => (int) $direccionCliente->pais_id,
|
||||
'pais' => $direccionCliente->paisNombre,
|
||||
'municipio' => $direccionCliente->municipio,
|
||||
'provincia' => $direccionCliente->provincia,
|
||||
'cp' => $direccionCliente->cp,
|
||||
'telefono' => $direccionCliente->telefono,
|
||||
],
|
||||
'unidades' => $tirada,
|
||||
'entregaPalets' => false
|
||||
]
|
||||
];
|
||||
|
||||
// Recalcular calidad (isColor y isHq) en funcion del cliente
|
||||
[$isColor, $isHq] = PresupuestoService::getCalidad(
|
||||
'importador-bubok',
|
||||
null,
|
||||
((trim(strtolower($interiorTipo)) === 'color') ? 1 : 0),
|
||||
0,
|
||||
intval($tirada ?? 0)
|
||||
);
|
||||
|
||||
// Generamos el objeto a importar
|
||||
$dataToImport = [
|
||||
'selectedTirada' => $tirada,
|
||||
'datosCabecera' => [
|
||||
'titulo' => $titulo,
|
||||
'autor' => null,
|
||||
'isbn' => null,
|
||||
'coleccion' => null,
|
||||
'referenciaCliente' => $refCliente
|
||||
],
|
||||
'tirada' => [$tirada],
|
||||
'tamanio' => [
|
||||
'ancho' => $ancho,
|
||||
'alto' => $alto
|
||||
],
|
||||
'tipo' => '',
|
||||
'tipo_presupuesto_id' => $encuadernadoId,
|
||||
'clienteId' => 40, // BUBOK ID
|
||||
'isColor' => $isColor,
|
||||
'isHq' => $isHq,
|
||||
'paginas' => $paginas,
|
||||
'paginasColor' => ($interiorTipo === 'color') ? $paginas : 0,
|
||||
'paginasCuadernillo' => 32,
|
||||
'interior' => [
|
||||
'papelInterior' => $papelInteriorId,
|
||||
'gramajeInterior' => $gramajePapelInterior
|
||||
],
|
||||
'cubierta' => [
|
||||
'papelCubierta' => 2, // 'EST2'
|
||||
'carasCubierta' => $doscara ? 2 : 4,
|
||||
'gramajeCubierta' => in_array($encuadernadoId, [1, 3]) ? 150 : 300, // 150 gramos para "fresado tapa dura" y "cosido tapa dura"
|
||||
'solapas' => !empty($producto->cover->type->consolapas) ? 80 : 0,
|
||||
'acabado' => $acabadoId,
|
||||
'cabezada' => 'WHI',
|
||||
'lomoRedondo' => 0
|
||||
],
|
||||
'guardas' => [],
|
||||
'sobrecubierta' => [],
|
||||
'faja' => null,
|
||||
|
||||
'direcciones' => $direcciones,
|
||||
|
||||
'ivaReducido' => 1,
|
||||
];
|
||||
|
||||
/*return $this->respond([
|
||||
'status' => 400,
|
||||
'message' => $dataToImport,
|
||||
'interiorTipo' => $interiorTipo,
|
||||
'isColor' => $isColor
|
||||
]);*/
|
||||
|
||||
// 5. Guardar
|
||||
try {
|
||||
$presupuestocliente = new Presupuestocliente();
|
||||
$response = $presupuestocliente->guardar($dataToImport);
|
||||
|
||||
// Guardar la URL de la portada y el cuerpo en los comentarios del presupuesto
|
||||
$presupuestoModel = model('App\Models\Presupuestos\PresupuestoModel');
|
||||
$presupuestoModel->update($response['sk_id'], [
|
||||
'comentarios_safekat' => 'URL COVER: ' . $producto->cover->file . "\nURL BODY: " . $producto->body->file,
|
||||
]);
|
||||
|
||||
|
||||
// Ajuste del precio
|
||||
$precio_compra = $json->producto->prices->unitPrice ?? null;
|
||||
if ($precio_compra != null && $precio_compra > 0) {
|
||||
|
||||
$respuesta_ajuste = PresupuestoService::ajustarPresupuesto(
|
||||
$response['sk_id'],
|
||||
$precio_compra,
|
||||
$tirada,
|
||||
null,
|
||||
true
|
||||
);
|
||||
if ($respuesta_ajuste['warning'] == true) {
|
||||
$response['price_warning'] = [
|
||||
'new_precio_unidad' => $respuesta_ajuste['new_precio_unidad'],
|
||||
'new_total' => $respuesta_ajuste['new_total'],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
// confirmar y crear pedido y ot
|
||||
$presupuestoModel->confirmarPresupuesto($response['sk_id']);
|
||||
PresupuestoService::crearPedido($response['sk_id'], isImported: true);
|
||||
|
||||
|
||||
if (!isset($response['sk_id'])) {
|
||||
return $this->respond([
|
||||
'status' => 400,
|
||||
'error' => 'Missing sk_id',
|
||||
'message' => 'No se pudo crear el presupuesto.'
|
||||
], 400);
|
||||
}
|
||||
|
||||
|
||||
// Descarga y subida de archivos al SFTP
|
||||
$presupuestoFicheroModel = model('App\Models\Presupuestos\PresupuestoFicheroModel');
|
||||
$ftp = new \App\Libraries\SafekatFtpClient();
|
||||
|
||||
$archivoUrls = [
|
||||
'cover' => $producto->cover->file ?? null,
|
||||
'body' => $producto->body->file ?? null,
|
||||
];
|
||||
|
||||
foreach ($archivoUrls as $tipo => $url) {
|
||||
if (!$url)
|
||||
continue;
|
||||
|
||||
try {
|
||||
$contenido = @file_get_contents($url); // silenciar errores de PHP
|
||||
|
||||
if ($contenido === false || strlen($contenido) === 0) {
|
||||
// No se pudo descargar el archivo: generar archivo de error para FTP
|
||||
$errorMessage = "ERROR: No se pudo descargar el archivo remoto para $tipo desde la URL: $url";
|
||||
|
||||
$remoteDir = $ftp->getPresupuestoRemotePath($response['sk_id']); // crea esta función si no existe
|
||||
$remoteErrorFile = $remoteDir . '/ERROR_' . strtoupper($tipo) . '.txt';
|
||||
|
||||
// Crear archivo temporal con el mensaje de error
|
||||
$tempErrorFile = WRITEPATH . 'uploads/presupuestos/ERROR_' . $tipo . '.txt';
|
||||
file_put_contents($tempErrorFile, $errorMessage);
|
||||
|
||||
if (!$ftp->is_dir($remoteDir)) {
|
||||
$ftp->mkdir($remoteDir, recursive: true);
|
||||
}
|
||||
|
||||
$ftp->put($remoteErrorFile, $tempErrorFile, $ftp::SOURCE_LOCAL_FILE);
|
||||
|
||||
continue; // no procesar este archivo
|
||||
}
|
||||
|
||||
// ✅ Procesar normalmente si la descarga tuvo éxito
|
||||
$nombreOriginal = basename(parse_url($url, PHP_URL_PATH));
|
||||
$extension = pathinfo($nombreOriginal, PATHINFO_EXTENSION);
|
||||
|
||||
$nombreLimpio = $presupuestoFicheroModel->saveFileInBBDD(
|
||||
$response['sk_id'],
|
||||
$nombreOriginal,
|
||||
$extension,
|
||||
auth()->id()
|
||||
);
|
||||
|
||||
if (is_null($nombreLimpio))
|
||||
continue;
|
||||
|
||||
$rutaLocal = WRITEPATH . 'uploads/presupuestos/';
|
||||
if (!is_dir($rutaLocal)) {
|
||||
mkdir($rutaLocal, 0777, true);
|
||||
}
|
||||
|
||||
file_put_contents($rutaLocal . $nombreLimpio, $contenido);
|
||||
} catch (\Throwable $e) {
|
||||
//log_message('error', 'Error inesperado en descarga de archivo remoto: ' . $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Subir al FTP después de guardar localmente
|
||||
try {
|
||||
$ftp->uploadFilePresupuesto($response['sk_id']);
|
||||
} catch (\Throwable $e) {
|
||||
log_message('error', 'Error subiendo archivos al FTP: ' . $e->getMessage());
|
||||
}
|
||||
|
||||
return $this->respond([
|
||||
'status' => 200,
|
||||
'data' => [
|
||||
'sk_id' => $response['sk_id'],
|
||||
'sk_url' => $response['sk_url'] ?? null
|
||||
]
|
||||
]);
|
||||
|
||||
|
||||
} catch (\Throwable $e) {
|
||||
return $this->respond([
|
||||
'status' => 500,
|
||||
'error' => 'Server error',
|
||||
'message' => 'Error inesperado',
|
||||
'debug' => $e->getMessage()
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
462
ci4/app/Controllers/Importadores/ImportadorCatalogo.php
Normal file
462
ci4/app/Controllers/Importadores/ImportadorCatalogo.php
Normal file
@ -0,0 +1,462 @@
|
||||
<?php
|
||||
namespace App\Controllers\Importadores;
|
||||
|
||||
use App\Controllers\BaseResourceController;
|
||||
use App\Entities\Catalogo\CatalogoLibroEntity;
|
||||
use App\Models\Presupuestos\PresupuestoModel;
|
||||
use App\Models\Catalogo\CatalogoLibroModel;
|
||||
use App\Controllers\Presupuestos\Presupuestocliente;
|
||||
use App\Services\PresupuestoService;
|
||||
|
||||
class ImportadorCatalogo extends BaseResourceController
|
||||
{
|
||||
|
||||
protected $modelName = CatalogoLibroModel::class;
|
||||
protected $format = 'json';
|
||||
|
||||
protected static $singularObjectName = 'Importador';
|
||||
protected static $singularObjectNameCc = 'ImportadorCatalogo';
|
||||
protected static $pluralObjectName = 'Importadores';
|
||||
protected static $pluralObjectNameCc = 'importadores';
|
||||
|
||||
protected static $controllerSlug = 'importador';
|
||||
|
||||
protected static $viewPath = 'themes/vuexy/form/importador/catalogo/';
|
||||
|
||||
protected $indexRoute = 'ImportadorCatalogoTool';
|
||||
|
||||
|
||||
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
|
||||
{
|
||||
$this->viewData['pageTitle'] = lang('Importador.listingPage');
|
||||
$this->viewData['usingSweetAlert'] = true;
|
||||
|
||||
// Breadcrumbs (IMN)
|
||||
$this->viewData['breadcrumb'] = [
|
||||
['title' => lang("App.menu_importadores"), 'route' => "javascript:void(0);", 'active' => false],
|
||||
['title' => lang("App.menu_importadores_catalogo"), 'route' => route_to('importadorCatalogoTool'), 'active' => true]
|
||||
];
|
||||
|
||||
parent::initController($request, $response, $logger);
|
||||
}
|
||||
|
||||
|
||||
public function index()
|
||||
{
|
||||
checkPermission('importadores.catalogo');
|
||||
|
||||
$viewData = [
|
||||
'pageSubTitle' => lang('Basic.global.ManageAllRecords', [lang('Importador.importadorCatalogoTitle')]),
|
||||
|
||||
];
|
||||
|
||||
$viewData = array_merge($this->viewData, $viewData); // merge any possible values from the parent controller class
|
||||
|
||||
return view(static::$viewPath . 'viewImportadorCatalogoTool', $viewData);
|
||||
}
|
||||
|
||||
|
||||
public function validarFila()
|
||||
{
|
||||
checkPermission('importadores.catalogo');
|
||||
|
||||
$json = $this->request->getJSON();
|
||||
|
||||
// Validación inicial del JSON y del ISBN
|
||||
if (!$json || !isset($json->fila[0]) || empty(trim($json->fila[0]))) {
|
||||
return $this->response->setJSON([
|
||||
'apto' => false,
|
||||
'reason' => 'ISBN no proporcionado o datos inválidos'
|
||||
]);
|
||||
}
|
||||
|
||||
$input = trim($json->fila[0]); // ISBN
|
||||
$refCliente = isset($json->fila[1]) ? trim($json->fila[1]) : null;
|
||||
|
||||
// Validar formato del refCliente (esperado: idpedido-idlinea)
|
||||
if (empty($refCliente) || strpos($refCliente, '-') === false) {
|
||||
return $this->response->setJSON([
|
||||
'apto' => false,
|
||||
'reason' => 'Ref. cliente inválido'
|
||||
]);
|
||||
}
|
||||
|
||||
// 1. Comprobar duplicado en tabla de presupuestos
|
||||
$presupuestoModel = new PresupuestoModel(); // Usa el modelo real que corresponda
|
||||
$yaExiste = $presupuestoModel->where('referencia_cliente', $refCliente)->first();
|
||||
|
||||
if ($yaExiste) {
|
||||
return $this->response->setJSON([
|
||||
'apto' => false,
|
||||
'reason' => 'Referencia ya importada'
|
||||
]);
|
||||
}
|
||||
|
||||
$catalogoModel = new CatalogoLibroModel();
|
||||
|
||||
// 2. Buscar por ISBN exacto
|
||||
$libroPorIsbn = $catalogoModel->where('isbn', $input)->first();
|
||||
if ($libroPorIsbn) {
|
||||
return $this->response->setJSON([
|
||||
'apto' => true
|
||||
]);
|
||||
}
|
||||
|
||||
// 3. Buscar por EAN sin guiones
|
||||
$eanLimpio = str_replace('-', '', $input);
|
||||
$libroPorEan = $catalogoModel
|
||||
->where('REPLACE(ean, "-", "")', $eanLimpio, false) // false para evitar escapado automático
|
||||
->first();
|
||||
|
||||
if ($libroPorEan) {
|
||||
return $this->response->setJSON([
|
||||
'apto' => true
|
||||
]);
|
||||
}
|
||||
|
||||
// 4. No encontrado
|
||||
return $this->response->setJSON([
|
||||
'apto' => false,
|
||||
'reason' => 'No encontrado en catálogo'
|
||||
]);
|
||||
}
|
||||
|
||||
|
||||
public function importarFila()
|
||||
{
|
||||
checkPermission('importadores.catalogo');
|
||||
|
||||
$json = $this->request->getJSON();
|
||||
|
||||
if (!$json || !isset($json->fila[0])) {
|
||||
return $this->response->setJSON([
|
||||
'success' => false,
|
||||
'message' => 'Datos inválidos.'
|
||||
]);
|
||||
}
|
||||
|
||||
// Mapear cada columna a una variable (debe coincidir con catalogo_tool.js)
|
||||
$isbn = isset($json->fila[0]) ? trim($json->fila[0]) : null;
|
||||
$refCliente = isset($json->fila[1]) ? trim($json->fila[1]) : null;
|
||||
$tirada = isset($json->fila[3]) ? (float) $json->fila[3] : null;
|
||||
|
||||
if (empty($isbn)) {
|
||||
return $this->response->setJSON([
|
||||
'success' => false,
|
||||
'message' => 'Input vacío o no proporcionado.'
|
||||
]);
|
||||
}
|
||||
|
||||
// 0. Comprobar duplicado en tabla de presupuestos
|
||||
$presupuestoModel = new PresupuestoModel(); // Usa el modelo real que corresponda
|
||||
$yaExiste = $presupuestoModel->where('referencia_cliente', $refCliente)->first();
|
||||
|
||||
if ($yaExiste) {
|
||||
return $this->response->setJSON([
|
||||
'success' => false,
|
||||
'message' => 'Referencia ya importada'
|
||||
]);
|
||||
}
|
||||
|
||||
$catalogoModel = new CatalogoLibroModel();
|
||||
|
||||
// 1. Buscar por ISBN exacto
|
||||
$libro = $catalogoModel->where('isbn', $isbn)->first();
|
||||
|
||||
// 2. Si no, buscar por EAN sin guiones
|
||||
if (!$libro) {
|
||||
$eanLimpio = str_replace('-', '', $isbn);
|
||||
|
||||
$libro = $catalogoModel->where('REPLACE(ean, "-", "")', $eanLimpio)->first();
|
||||
}
|
||||
|
||||
if (!$libro) {
|
||||
return $this->response->setJSON([
|
||||
'success' => false,
|
||||
'message' => 'No se encontró el libro en el catálogo.'
|
||||
]);
|
||||
}
|
||||
|
||||
// Aquí ya tenemos el libro correcto.
|
||||
// Ahora se prepara la "inserción" o el "registro" a importar
|
||||
// Variables intermedias
|
||||
$colorPaginas = (int) ($libro->color_paginas ?? 0);
|
||||
$negroPaginas = (int) ($libro->negro_paginas ?? 0);
|
||||
$papelInteriorDiferente = ($colorPaginas > 0 && $negroPaginas > 0) ? 1 : 0;
|
||||
|
||||
// --- Interior (lo que cambiamos ahora)
|
||||
if ($papelInteriorDiferente) {
|
||||
// Mixto: páginas en negro + color
|
||||
$interior = [
|
||||
'papelInterior' => [
|
||||
'negro' => $libro->negro_papel_id,
|
||||
'color' => $libro->color_papel_id,
|
||||
],
|
||||
'gramajeInterior' => [
|
||||
'negro' => $libro->negro_gramaje,
|
||||
'color' => $libro->color_gramaje,
|
||||
]
|
||||
];
|
||||
} else {
|
||||
// SOLO un tipo: negro O color
|
||||
$colorPaginas = (int) ($libro->color_paginas ?? 0);
|
||||
$negroPaginas = (int) ($libro->negro_paginas ?? 0);
|
||||
|
||||
if ($colorPaginas > 0 && $negroPaginas == 0) {
|
||||
// Libro completamente en color
|
||||
$interior = [
|
||||
'papelInterior' => $libro->color_papel_id,
|
||||
'gramajeInterior' => $libro->color_gramaje,
|
||||
];
|
||||
} else {
|
||||
// Libro completamente en blanco y negro
|
||||
$interior = [
|
||||
'papelInterior' => $libro->negro_papel_id,
|
||||
'gramajeInterior' => $libro->negro_gramaje,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
// Sobrecubierta
|
||||
$sobrecubierta = [];
|
||||
if (!is_null($libro->sobrecubierta_paginas) && $libro->sobrecubierta_paginas != 0) {
|
||||
$sobrecubierta['papel'] = $libro->sobrecubierta_papel_id;
|
||||
$sobrecubierta['gramaje'] = $libro->sobrecubierta_gramaje;
|
||||
$sobrecubierta['solapas'] = $libro->sobrecubierta_solapas;
|
||||
$sobrecubierta['acabado'] = $libro->sobrecubierta_acabado_id;
|
||||
}
|
||||
|
||||
// Recalcular calidad (isColor y isHq) en funcion del cliente
|
||||
[$isColor, $isHq] = PresupuestoService::getCalidad(
|
||||
'importador-rama',
|
||||
null,
|
||||
(in_array(strtolower($libro->tipo_impresion), ['color', 'colorhq']) ? 1 : 0),
|
||||
(in_array(strtolower($libro->tipo_impresion), ['negrohq', 'colorhq']) ? 1 : 0),
|
||||
intval($tirada ?? 0)
|
||||
);
|
||||
|
||||
|
||||
$dataToImport = [
|
||||
'selectedTirada' => $tirada,
|
||||
'datosCabecera' => [
|
||||
'titulo' => $libro->titulo,
|
||||
'autor' => $libro->autor,
|
||||
'isbn' => $isbn,
|
||||
'coleccion' => $libro->coleccion,
|
||||
'referenciaCliente' => $refCliente
|
||||
],
|
||||
'tirada' => array_values(array_filter([
|
||||
$tirada,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
])),
|
||||
'tamanio' => [
|
||||
'ancho' => $libro->ancho,
|
||||
'alto' => $libro->alto
|
||||
],
|
||||
'tipo' => "",
|
||||
'tipo_presupuesto_id' => $libro->encuadernacion_id,
|
||||
'clienteId' => 251,
|
||||
'isColor' => $isColor,
|
||||
'isHq' => $isHq,
|
||||
'paginas' => $libro->paginas,
|
||||
'paginasColor' => $colorPaginas,
|
||||
'papelInteriorDiferente' => $papelInteriorDiferente,
|
||||
'paginasCuadernillo' => 32,
|
||||
|
||||
'interior' => $interior,
|
||||
|
||||
'cubierta' => [
|
||||
'papelCubierta' => $libro->cubierta_papel_id,
|
||||
'gramajeCubierta' => $libro->cubierta_gramaje,
|
||||
'solapas' => $libro->cubierta_ancho_solapas,
|
||||
'acabado' => $libro->cubierta_acabado_id,
|
||||
'cabezada' => 'WHI',
|
||||
'lomoRedondo' => 0
|
||||
],
|
||||
|
||||
'ivaReducido' => 1,
|
||||
|
||||
'guardas' => [],
|
||||
'sobrecubierta' => $sobrecubierta,
|
||||
//'faja' => null,
|
||||
|
||||
'entrega_taller' => 1,
|
||||
];
|
||||
|
||||
/*return $this->response->setJSON([
|
||||
'success' => true,
|
||||
'message' => 'Libro encontrado y preparado para importar.',
|
||||
'data' => $dataToImport
|
||||
]);*/
|
||||
|
||||
$tarifas = $this->obtenerTarifas();
|
||||
$precioDesdeTarifa = $this->calcularPrecioDesdeTarifa(
|
||||
$dataToImport['isColor'],
|
||||
$libro->encuadernacion_id,
|
||||
$libro->ancho,
|
||||
$libro->alto,
|
||||
$libro->paginas,
|
||||
$tarifas
|
||||
);
|
||||
|
||||
if (is_null($precioDesdeTarifa)) {
|
||||
return $this->response->setJSON([
|
||||
'success' => false,
|
||||
'message' => 'No se pudo calcular el precio desde las tarifas disponibles.',
|
||||
'detalle' => [
|
||||
'tinta' => $dataToImport['isColor'] ? 'color' : 'negro',
|
||||
'encuadernacion_id' => $libro->encuadernacion_id,
|
||||
'ancho' => $libro->ancho,
|
||||
'alto' => $libro->alto,
|
||||
'paginas' => $libro->paginas
|
||||
]
|
||||
]);
|
||||
}
|
||||
|
||||
// Usar precio calculado
|
||||
$precio_compra = $precioDesdeTarifa;
|
||||
|
||||
// Procedemos a intentar guardar el presupuesto
|
||||
// Instancia de presupuesto cliente
|
||||
$presupuestocliente = new Presupuestocliente();
|
||||
try {
|
||||
$response = $presupuestocliente->guardar($dataToImport);
|
||||
|
||||
// DEBUG LINE
|
||||
//return $this->respond($response);
|
||||
|
||||
if (!isset($response['sk_id'])) {
|
||||
return $this->respond([
|
||||
'status' => 400,
|
||||
'error' => 'Missing sk_id',
|
||||
'message' => 'El identificador sk_id es requerido pero no se recibió.'
|
||||
], 400);
|
||||
}
|
||||
|
||||
$response = [
|
||||
'status' => 200,
|
||||
'error' => null,
|
||||
'data' => [
|
||||
'sk_id' => $response['sk_id'],
|
||||
'sk_url' => $response['sk_url'] ?? null
|
||||
]
|
||||
];
|
||||
|
||||
// Vincular el presupuesto con el catálogo
|
||||
model('\App\Models\Presupuestos\PresupuestoModel')
|
||||
->vincularCatalogo($response['data']['sk_id'], $libro->id);
|
||||
|
||||
|
||||
// Ajuste del precio a RAMA
|
||||
$respuesta_ajuste = PresupuestoService::ajustarPresupuesto(
|
||||
$response['data']['sk_id'],
|
||||
$precio_compra,
|
||||
$tirada,
|
||||
null,
|
||||
true
|
||||
);
|
||||
if ($respuesta_ajuste['warning'] == true) {
|
||||
$response['price_warning'] = [
|
||||
'new_precio_unidad' => $respuesta_ajuste['new_precio_unidad'],
|
||||
'new_total' => $respuesta_ajuste['new_total'],
|
||||
];
|
||||
}
|
||||
|
||||
// confirmar y crear pedido y ot
|
||||
model('App\Models\Presupuestos\PresupuestoModel')->confirmarPresupuesto($response['data']['sk_id']);
|
||||
PresupuestoService::crearPedido($response['data']['sk_id'], isImported: true);
|
||||
|
||||
return $this->respond($response);
|
||||
|
||||
} catch (\Exception $e) {
|
||||
|
||||
return $this->respond([
|
||||
'status' => 500,
|
||||
'error' => 'Server error',
|
||||
'message' => 'Error inesperado durante el procesado',
|
||||
'debug' => $e->getMessage()
|
||||
]);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
private function calcularPrecioDesdeTarifa($isColor, $encuadernacionId, $ancho, $alto, $paginas, $tarifas)
|
||||
{
|
||||
// Solo aplicamos tarifa si la encuadernación es Rústica Fresada (id = 2)
|
||||
if ((int) $encuadernacionId !== 2) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$tinta = $isColor ? 'color' : 'negro';
|
||||
|
||||
foreach ($tarifas as $tarifa) {
|
||||
if (
|
||||
strtolower($tarifa['tinta']) === $tinta &&
|
||||
strtolower($tarifa['manipulado']) === 'rústica fresada' &&
|
||||
(int) $tarifa['ancho'] === (int) $ancho &&
|
||||
(int) $tarifa['alto'] === (int) $alto
|
||||
) {
|
||||
return round($tarifa['precio_fijo'] + ($tarifa['precio_variable'] * $paginas), 2);
|
||||
}
|
||||
}
|
||||
|
||||
return null; // No se encontró tarifa válida
|
||||
}
|
||||
|
||||
|
||||
private function obtenerTarifas()
|
||||
{
|
||||
return [
|
||||
[
|
||||
'tinta' => 'color',
|
||||
'manipulado' => 'Rústica Fresada',
|
||||
'ancho' => 200,
|
||||
'alto' => 245,
|
||||
'precio_fijo' => 1.15,
|
||||
'precio_variable' => 0.076
|
||||
],
|
||||
[
|
||||
'tinta' => 'negro',
|
||||
'manipulado' => 'Rústica Fresada',
|
||||
'ancho' => 200,
|
||||
'alto' => 245,
|
||||
'precio_fijo' => 1.15,
|
||||
'precio_variable' => 0.009724
|
||||
],
|
||||
[
|
||||
'tinta' => 'color',
|
||||
'manipulado' => 'Rústica Fresada',
|
||||
'ancho' => 150,
|
||||
'alto' => 210,
|
||||
'precio_fijo' => 1.15,
|
||||
'precio_variable' => 0.03217
|
||||
],
|
||||
[
|
||||
'tinta' => 'negro',
|
||||
'manipulado' => 'Rústica Fresada',
|
||||
'ancho' => 150,
|
||||
'alto' => 210,
|
||||
'precio_fijo' => 1.15,
|
||||
'precio_variable' => 0.00572
|
||||
],
|
||||
[
|
||||
'tinta' => 'negro',
|
||||
'manipulado' => 'Rústica Fresada',
|
||||
'ancho' => 170,
|
||||
'alto' => 240,
|
||||
'precio_fijo' => 1.15,
|
||||
'precio_variable' => 0.008
|
||||
]
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
@ -39,4 +39,19 @@ class Language extends BaseController
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public function file(string $file)
|
||||
{
|
||||
$locale = $this->request->getLocale(); // es, en, fr…
|
||||
$path = APPPATH."Language/{$locale}/{$file}.php";
|
||||
|
||||
if (! is_file($path)) {
|
||||
return $this->response->setStatusCode(404);
|
||||
}
|
||||
|
||||
/** @var array $lines */
|
||||
$lines = require $path; // el array que devuelve tu lang-file
|
||||
|
||||
return $this->response->setJSON($lines); // Content-Type: application/json
|
||||
}
|
||||
}
|
||||
|
||||
467
ci4/app/Controllers/Logistica/EtiquetasTitulosController.php
Normal file
467
ci4/app/Controllers/Logistica/EtiquetasTitulosController.php
Normal file
@ -0,0 +1,467 @@
|
||||
<?php
|
||||
|
||||
namespace App\Controllers\Logistica;
|
||||
|
||||
use App\Controllers\BaseController;
|
||||
use App\Services\ImpresoraEtiquetaService;
|
||||
use App\Services\EtiquetasTitulosService;
|
||||
use CodeIgniter\HTTP\RequestInterface;
|
||||
use CodeIgniter\HTTP\ResponseInterface;
|
||||
use Psr\Log\LoggerInterface;
|
||||
use Hermawan\DataTables\DataTable;
|
||||
|
||||
class EtiquetasTitulosController extends BaseController
|
||||
{
|
||||
|
||||
protected ImpresoraEtiquetaService $impresoraEtiquetaService;
|
||||
protected string $locale;
|
||||
protected array $viewData;
|
||||
|
||||
protected static $controllerSlug = 'etiquetas_titulos';
|
||||
protected static $viewPath = 'themes/vuexy/form/logistica/';
|
||||
|
||||
public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
|
||||
{
|
||||
$this->impresoraEtiquetaService = service('impresora_etiqueta');
|
||||
$this->locale = session()->get('lang');
|
||||
$this->model = model('App\Models\Etiquetas\EtiquetasTitulosModel');
|
||||
|
||||
$this->viewData['pageTitle'] = lang('Logistica.logistica');
|
||||
|
||||
// Breadcrumbs
|
||||
$this->viewData['breadcrumb'] = [
|
||||
['title' => lang("App.menu_logistica"), 'route' => route_to("LogisticaPanel"), 'active' => false],
|
||||
];
|
||||
|
||||
|
||||
parent::initController($request, $response, $logger);
|
||||
}
|
||||
|
||||
public function findOTs()
|
||||
{
|
||||
if ($this->request->isAJAX()) {
|
||||
|
||||
$query = EtiquetasTitulosService::getOtsWithTitulos();
|
||||
|
||||
if ($this->request->getGet("q")) {
|
||||
$query->groupStart()
|
||||
->orLike("ot.id", $this->request->getGet("q"))
|
||||
->orLike("pr.titulo)", $this->request->getGet("q"))
|
||||
->groupEnd();
|
||||
}
|
||||
|
||||
|
||||
$result = $query->orderBy("id", "DESC")->get()->getResultObject();
|
||||
|
||||
return $this->response->setJSON($result);
|
||||
} else {
|
||||
return $this->failUnauthorized('Invalid request', 403);
|
||||
}
|
||||
}
|
||||
|
||||
public function findAddresses()
|
||||
{
|
||||
if ($this->request->isAJAX()) {
|
||||
|
||||
$ot_id = $this->request->getGet("ot_id");
|
||||
|
||||
$query = EtiquetasTitulosService::getDireccionesOT($ot_id);
|
||||
|
||||
if ($this->request->getGet("q")) {
|
||||
$query->groupStart()
|
||||
->orLike("pd.direccion", $this->request->getGet("q"))
|
||||
->groupEnd();
|
||||
}
|
||||
|
||||
|
||||
$result = $query->orderBy("pd.direccion", "ASC")->get()->getResultObject();
|
||||
|
||||
return $this->response->setJSON($result);
|
||||
} else {
|
||||
return $this->failUnauthorized('Invalid request', 403);
|
||||
}
|
||||
}
|
||||
|
||||
public function addEtiqueta()
|
||||
{
|
||||
if ($this->request->isAJAX()) {
|
||||
|
||||
$data = [];
|
||||
$data['user_id'] = auth()->user()->id;
|
||||
$data['ot_id'] = $this->request->getPost('ot_id') ?? null;
|
||||
$data['direccion'] = $this->request->getPost('direccion') ?? null;
|
||||
$data['unidades_caja'] = $this->request->getPost('unidades_caja') ?? null;
|
||||
|
||||
if (
|
||||
$this->request->getPost('ot_id') == null ||
|
||||
$this->request->getPost('direccion') == null ||
|
||||
$this->request->getPost('unidades_caja') == null
|
||||
) {
|
||||
return [
|
||||
'status' => false,
|
||||
'message' => lang('Logistica.errorMissingData')
|
||||
];
|
||||
}
|
||||
|
||||
$result = EtiquetasTitulosService::addEtiqueta($data);
|
||||
|
||||
return $this->response->setJSON($result);
|
||||
} else {
|
||||
return $this->failUnauthorized('Invalid request', 403);
|
||||
}
|
||||
}
|
||||
|
||||
public function deleteEtiqueta($id = null)
|
||||
{
|
||||
if ($this->request->isAJAX()) {
|
||||
$id = $this->request->getPost('id') ?? null;
|
||||
|
||||
if ($id == null) {
|
||||
return [
|
||||
'status' => false,
|
||||
'message' => lang('Logistica.errorMissingData')
|
||||
];
|
||||
}
|
||||
|
||||
$modelLineas = model('App\Models\Etiquetas\EtiquetasTitulosLineasModel');
|
||||
$ids = $modelLineas->where('etiqueta_titulos_id', $id)->findColumn('id');
|
||||
if ($ids) {
|
||||
$modelLineas->delete($ids);
|
||||
}
|
||||
$model = model('App\Models\Etiquetas\EtiquetasTitulosModel');
|
||||
$id = $model->where('id', $id)->findColumn('id');
|
||||
if ($id) {
|
||||
$model->delete($id);
|
||||
}
|
||||
$result = [
|
||||
'status' => true,
|
||||
'message' => lang('Logistica.success.jhn<successDeleteEtiqueta'),
|
||||
];
|
||||
|
||||
return $this->response->setJSON($result);
|
||||
} else {
|
||||
return $this->failUnauthorized('Invalid request', 403);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
public function edit($id = null)
|
||||
{
|
||||
|
||||
if (empty($id)) {
|
||||
return redirect()->to(base_url('logistica/selectEnvios/simple'))->with('error', lang('Logistica.errors.noEnvio'));
|
||||
}
|
||||
$model = model('App\Models\Etiquetas\EtiquetasTitulosModel');
|
||||
$etiquetaEntity = $model->select('etiquetas_titulos.*, clientes.nombre as cliente')
|
||||
->join('clientes', 'clientes.id = etiquetas_titulos.cliente_id', 'left')
|
||||
->where('etiquetas_titulos.id', $id)
|
||||
->first();
|
||||
if (empty($etiquetaEntity)) {
|
||||
return redirect()->to(base_url('logistica/etiquetasLogistica'))->with('error', lang('Logistica.errors.noEnvio'));
|
||||
}
|
||||
|
||||
|
||||
$modelImpresora = model('App\Models\Configuracion\ImpresoraEtiquetaModel');
|
||||
$impresoras = $modelImpresora->select('id, name, description')
|
||||
->where('deleted_at', null)
|
||||
->where('tipo', 1)
|
||||
->orderBy('name', 'asc')
|
||||
->findAll();
|
||||
$etiquetaEntity->impresoras = $impresoras;
|
||||
|
||||
$viewData = [
|
||||
'currentModule' => static::$controllerSlug,
|
||||
'boxTitle' => '<i class="ti ti-ticket ti-xl"></i>' . ' ' . lang('Logistica.EtiquetasTitulos') . ' [' . $etiquetaEntity->id . ']: ' . $etiquetaEntity->direccion,
|
||||
'usingServerSideDataTable' => true,
|
||||
'etiquetaEntity' => $etiquetaEntity,
|
||||
];
|
||||
|
||||
$viewData = array_merge($this->viewData, $viewData); // merge any possible values from the parent controller class
|
||||
|
||||
return view(static::$viewPath . 'viewEtiquetasTitulosEdit', $viewData);
|
||||
}
|
||||
|
||||
|
||||
public function datatable()
|
||||
{
|
||||
$q = $this->model->getEtiquetasTitulos();
|
||||
|
||||
if (!empty($otsFilter)) {
|
||||
$q->groupStart();
|
||||
$q->like('etl.ot_id', $otsFilter);
|
||||
$q->groupEnd();
|
||||
}
|
||||
|
||||
$result = DataTable::of($q)
|
||||
->add("action", callback: function ($q) {
|
||||
return '
|
||||
<div class="btn-group btn-group-sm">
|
||||
<a href="javascript:void(0);"><i class="ti ti-pencil ti-sm btn-edit mx-2" data-id="' . $q->id . '"></i></a>
|
||||
<a href="javascript:void(0);"><i class="ti ti-trash ti-sm btn-delete" data-id="' . $q->id . '"></i></a>
|
||||
</div>
|
||||
';
|
||||
});
|
||||
|
||||
return $result->toJson(returnAsObject: true);
|
||||
}
|
||||
|
||||
public function findOtsWithAddress()
|
||||
{
|
||||
if ($this->request->isAJAX()) {
|
||||
$id = $this->request->getGet('id') ?? null;
|
||||
|
||||
$query = EtiquetasTitulosService::findOTsWithAddress($id);
|
||||
|
||||
if ($this->request->getGet("q")) {
|
||||
$query->groupStart()
|
||||
->orLike("name", $this->request->getGet("q"))
|
||||
->groupEnd();
|
||||
}
|
||||
|
||||
|
||||
$result = $query->orderBy("id", "DESC")->get()->getResultObject();
|
||||
|
||||
return $this->response->setJSON($result);
|
||||
|
||||
} else {
|
||||
return $this->failUnauthorized('Invalid request', 403);
|
||||
}
|
||||
}
|
||||
|
||||
public function addLineasEtiqueta()
|
||||
{
|
||||
|
||||
if ($this->request->isAJAX()) {
|
||||
|
||||
$etiqueta_id = $this->request->getPost('etiqueta_id') ?? null;
|
||||
$ot_id = $this->request->getPost('ot_id') ?? null;
|
||||
$unidades = $this->request->getPost('unidades') ?? null;
|
||||
$cajas = $this->request->getPost('cajas') ?? null;
|
||||
|
||||
$result = EtiquetasTitulosService::addLineasEtiqueta($etiqueta_id, $ot_id, $unidades, $cajas);
|
||||
return $this->response->setJSON($result);
|
||||
} else {
|
||||
return $this->failUnauthorized('Invalid request', 403);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public function datatableLineasEtiquetas($id = null)
|
||||
{
|
||||
|
||||
$model = model('App\Models\Etiquetas\EtiquetasTitulosLineasModel');
|
||||
|
||||
$id = $this->request->getGet('id') ?? null;
|
||||
$direccion = $this->request->getGet('direccion') ?? null;
|
||||
|
||||
$q = $model->getDatatableQuery($id, $direccion);
|
||||
|
||||
|
||||
$result = DataTable::of($q)
|
||||
->add(
|
||||
"rowSelected",
|
||||
callback: function ($q) {
|
||||
return '<input type="checkbox" class="form-check-input checkbox-linea-envio" name="row_selected[]" value="' . $q->id . '">';
|
||||
}
|
||||
)
|
||||
->edit(
|
||||
"ot",
|
||||
function ($row, $meta) {
|
||||
return '<a href="' . base_url('produccion/ordentrabajo/edit/' . $row->ot) . '" target="_blank">' . $row->ot . '</a>';
|
||||
}
|
||||
)
|
||||
->edit(
|
||||
"unidades",
|
||||
function ($row, $meta) {
|
||||
return '<input type="number" class="form-control input-lineas input-unidades text-center"
|
||||
data-id="' . $row->id . '" data-name="unidades" value="' . $row->unidades . '">';
|
||||
}
|
||||
)
|
||||
->edit(
|
||||
"numero_caja",
|
||||
function ($row, $meta) {
|
||||
return '<input type="number" class="form-control input-lineas input-cajas text-center"
|
||||
data-id="' . $row->id . '" data-name="numero_caja" value="' . $row->numero_caja . '">';
|
||||
}
|
||||
)
|
||||
->add("unidades_raw", fn($row) => $row->unidades)
|
||||
->add("pesoUnidad_raw", fn($row) => $row->pesoUnidad)
|
||||
->add(
|
||||
"action",
|
||||
callback: function ($q) {
|
||||
return '
|
||||
<div class="btn-group btn-group-sm">
|
||||
<a href="javascript:void(0);"><i class="ti ti-trash ti-sm btn-delete" data-id="' . $q->id . '"></i></a>
|
||||
</div>
|
||||
';
|
||||
}
|
||||
);
|
||||
|
||||
return $result->toJson(returnAsObject: true);
|
||||
}
|
||||
|
||||
public function deleteLineasEtiqueta()
|
||||
{
|
||||
if ($this->request->isAJAX()) {
|
||||
$ids = $this->request->getPost('ids') ?? [];
|
||||
|
||||
if ($ids == [] || $ids == null) {
|
||||
return [
|
||||
'status' => false,
|
||||
'message' => lang('Logistica.errors.errorMissingData')
|
||||
];
|
||||
}
|
||||
|
||||
$model = model('App\Models\Etiquetas\EtiquetasTitulosLineasModel');
|
||||
for ($i = 0; $i < count($ids); $i++) {
|
||||
$model->delete($ids[$i]);
|
||||
}
|
||||
|
||||
|
||||
$result = [
|
||||
'status' => true,
|
||||
'message' => lang('Logistica.success.successDeleteLines'),
|
||||
];
|
||||
|
||||
return $this->response->setJSON($result);
|
||||
} else {
|
||||
return $this->failUnauthorized('Invalid request', 403);
|
||||
}
|
||||
}
|
||||
|
||||
public function updateLineasEtiqueta()
|
||||
{
|
||||
|
||||
if ($this->request->isAJAX()) {
|
||||
$id = $this->request->getPost('id') ?? null;
|
||||
$name = $this->request->getPost('name') ?? null;
|
||||
$value = $this->request->getPost('value') ?? null;
|
||||
|
||||
if ($id == null || $name == null || $value == null) {
|
||||
return [
|
||||
'status' => false,
|
||||
'message' => lang('Logistica.errors.errorMissingData')
|
||||
];
|
||||
}
|
||||
|
||||
$model = model('App\Models\Etiquetas\EtiquetasTitulosLineasModel');
|
||||
$model->update($id, [$name => $value]);
|
||||
|
||||
$result = [
|
||||
'status' => true,
|
||||
'message' => lang('Logistica.success.successUpdateLine'),
|
||||
];
|
||||
|
||||
return $this->response->setJSON($result);
|
||||
} else {
|
||||
return $this->failUnauthorized('Invalid request', 403);
|
||||
}
|
||||
}
|
||||
|
||||
public function updateComentarios()
|
||||
{
|
||||
|
||||
if ($this->request->isAJAX()) {
|
||||
$id = $this->request->getPost('id') ?? null;
|
||||
$comentarios = $this->request->getPost('comentarios') ?? null;
|
||||
|
||||
if ($id == null || $comentarios == null) {
|
||||
return [
|
||||
'status' => false,
|
||||
'message' => lang('Logistica.errors.errorMissingData')
|
||||
];
|
||||
}
|
||||
|
||||
$model = model('App\Models\Etiquetas\EtiquetasTitulosModel');
|
||||
$model->update($id, ['comentarios' => $comentarios]);
|
||||
|
||||
$result = [
|
||||
'status' => true,
|
||||
'message' => lang('Logistica.success.comentariosUpdated'),
|
||||
];
|
||||
|
||||
return $this->response->setJSON($result);
|
||||
} else {
|
||||
return $this->failUnauthorized('Invalid request', 403);
|
||||
}
|
||||
}
|
||||
|
||||
public function updateOrdenCajas()
|
||||
{
|
||||
$rawInput = $this->request->getBody();
|
||||
$data = json_decode($rawInput, true);
|
||||
$orden = $data['orden'] ?? [];
|
||||
|
||||
if (!is_array($orden)) {
|
||||
return $this->response->setJSON([
|
||||
'status' => false,
|
||||
'message' => 'Datos inválidos'
|
||||
]);
|
||||
}
|
||||
|
||||
$model = model('App\Models\Etiquetas\EtiquetasTitulosLineasModel');
|
||||
|
||||
foreach ($orden as $item) {
|
||||
if (isset($item['id'], $item['numero_caja'])) {
|
||||
$model->update($item['id'], [
|
||||
'numero_caja' => $item['numero_caja'],
|
||||
'updated_at' => date('Y-m-d H:i:s') // opcional
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
return $this->response->setJSON([
|
||||
'status' => true,
|
||||
'message' => 'Orden de cajas actualizado correctamente'
|
||||
]);
|
||||
}
|
||||
|
||||
public function renumberCajas()
|
||||
{
|
||||
$id = $this->request->getPost('id') ?? null;
|
||||
|
||||
if ($id == null) {
|
||||
return [
|
||||
'status' => false,
|
||||
'message' => lang('Logistica.errors.errorMissingData')
|
||||
];
|
||||
}
|
||||
|
||||
$result = EtiquetasTitulosService::reordenarCajas($id);
|
||||
|
||||
return $this->response->setJSON($result);
|
||||
}
|
||||
|
||||
public function imprimirEtiquetas()
|
||||
{
|
||||
$etiqueta_id = $this->request->getPost('etiqueta_id') ?? null;
|
||||
$ids = $this->request->getPost('ids') ?? [];
|
||||
$impresora_id = $this->request->getPost('impresora_id') ?? null;
|
||||
|
||||
$modelImpresora = model('App\Models\Configuracion\ImpresoraEtiquetaModel');
|
||||
$impresora = $modelImpresora->select('id, name, description, ip, port, user, pass')
|
||||
->where('deleted_at', null)
|
||||
->where('id', $impresora_id)
|
||||
->orderBy('name', 'asc')
|
||||
->first();
|
||||
if ($impresora == null) {
|
||||
return $this->response->setJSON([
|
||||
'status' => false,
|
||||
'message' => 'Impresora no válida'
|
||||
]);
|
||||
}
|
||||
|
||||
if ($etiqueta_id == null || $ids == []) {
|
||||
return [
|
||||
'status' => false,
|
||||
'message' => lang('Logistica.errors.errorMissingData')
|
||||
];
|
||||
}
|
||||
|
||||
$result = EtiquetasTitulosService::imprimirEtiquetas($etiqueta_id, $ids, $impresora);
|
||||
|
||||
return $this->response->setJSON($result);
|
||||
}
|
||||
|
||||
}
|
||||
579
ci4/app/Controllers/Logistica/LogisticaController.php
Normal file → Executable file
579
ci4/app/Controllers/Logistica/LogisticaController.php
Normal file → Executable file
@ -4,9 +4,11 @@ namespace App\Controllers\Logistica;
|
||||
|
||||
use App\Controllers\BaseController;
|
||||
use App\Services\ImpresoraEtiquetaService;
|
||||
use App\Services\LogisticaService;
|
||||
use CodeIgniter\HTTP\RequestInterface;
|
||||
use CodeIgniter\HTTP\ResponseInterface;
|
||||
use Psr\Log\LoggerInterface;
|
||||
use Hermawan\DataTables\DataTable;
|
||||
|
||||
class LogisticaController extends BaseController
|
||||
{
|
||||
@ -15,11 +17,22 @@ class LogisticaController extends BaseController
|
||||
protected string $locale;
|
||||
protected array $viewData;
|
||||
|
||||
protected static $controllerSlug = 'logistica';
|
||||
protected static $viewPath = 'themes/vuexy/form/logistica/';
|
||||
|
||||
public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
|
||||
{
|
||||
$this->impresoraEtiquetaService = service('impresora_etiqueta');
|
||||
$this->locale = session()->get('lang');
|
||||
|
||||
$this->viewData['pageTitle'] = lang('Logistica.logistica');
|
||||
|
||||
// Breadcrumbs
|
||||
$this->viewData['breadcrumb'] = [
|
||||
['title' => lang("App.menu_logistica"), 'route' => route_to("LogisticaPanel"), 'active' => false],
|
||||
];
|
||||
|
||||
|
||||
parent::initController($request, $response, $logger);
|
||||
}
|
||||
public function print_test_label()
|
||||
@ -28,4 +41,570 @@ class LogisticaController extends BaseController
|
||||
$responseMessage = $etiquetaData["status"] ? "OK" : "ERROR";
|
||||
return $this->response->setJSON(["message" => $responseMessage, "data" => $etiquetaData, "status" => $etiquetaData["status"]]);
|
||||
}
|
||||
|
||||
public function panel()
|
||||
{
|
||||
checkPermission('logistica.logistica');
|
||||
|
||||
$viewData = [
|
||||
'currentModule' => static::$controllerSlug,
|
||||
'boxTitle' => lang('Logistica.panel'),
|
||||
'pageSubTitle' => 'Panel',
|
||||
'usingServerSideDataTable' => true,
|
||||
];
|
||||
|
||||
$viewData = array_merge($this->viewData, $viewData); // merge any possible values from the parent controller class
|
||||
|
||||
return view(static::$viewPath . 'viewPanelLogistica', $viewData);
|
||||
}
|
||||
|
||||
public function gestionEnvios()
|
||||
{
|
||||
checkPermission('logistica.logistica');
|
||||
|
||||
$viewData = [
|
||||
'currentModule' => static::$controllerSlug,
|
||||
'boxTitle' => lang('Logistica.gestionEnvios'),
|
||||
'usingServerSideDataTable' => true,
|
||||
'tipo_envio' => 'estandar',
|
||||
];
|
||||
|
||||
$viewData = array_merge($this->viewData, $viewData); // merge any possible values from the parent controller class
|
||||
|
||||
return view(static::$viewPath . 'viewLogisticaSelectEnvios', $viewData);
|
||||
}
|
||||
|
||||
|
||||
public function gestionEnviosFerros()
|
||||
{
|
||||
checkPermission('logistica.logistica');
|
||||
|
||||
$viewData = [
|
||||
'currentModule' => static::$controllerSlug,
|
||||
'boxTitle' => lang('Logistica.envioFerros'),
|
||||
'usingServerSideDataTable' => true,
|
||||
'tipo_envio' => 'ferro_prototipo',
|
||||
];
|
||||
|
||||
$viewData = array_merge($this->viewData, $viewData); // merge any possible values from the parent controller class
|
||||
|
||||
return view(static::$viewPath . 'viewLogisticaSelectEnvios', $viewData);
|
||||
}
|
||||
|
||||
public function etiquetasLogistica()
|
||||
{
|
||||
checkPermission('logistica.logistica');
|
||||
|
||||
$viewData = [
|
||||
'currentModule' => static::$controllerSlug,
|
||||
'boxTitle' => lang('Logistica.etiquetasTitulos'),
|
||||
'usingServerSideDataTable' => true,
|
||||
];
|
||||
|
||||
$viewData = array_merge($this->viewData, $viewData); // merge any possible values from the parent controller class
|
||||
|
||||
return view(static::$viewPath . 'viewImpresionEtiquetas', $viewData);
|
||||
}
|
||||
|
||||
public function listAlbaranes()
|
||||
{
|
||||
checkPermission('logistica.logistica');
|
||||
|
||||
$viewData = [
|
||||
'currentModule' => static::$controllerSlug,
|
||||
'boxTitle' => lang('Albaran.albaranes'),
|
||||
'usingServerSideDataTable' => true,
|
||||
];
|
||||
|
||||
$viewData = array_merge($this->viewData, $viewData); // merge any possible values from the parent controller class
|
||||
|
||||
return view(static::$viewPath . '/albaranes/viewAlbaranesList', $viewData);
|
||||
}
|
||||
|
||||
public function findForNewEnvio()
|
||||
{
|
||||
|
||||
if ($this->request->isAJAX()) {
|
||||
|
||||
$tipo_envio = $this->request->getGet('tipo_envio') ?? 'estandar';
|
||||
|
||||
if ($tipo_envio == 'ferro_prototipo') {
|
||||
$query = LogisticaService::findForNewEnvioFerro();
|
||||
} else {
|
||||
$query = LogisticaService::findForNewEnvio();
|
||||
}
|
||||
if ($this->request->getGet("q")) {
|
||||
$query->groupStart()
|
||||
->orLike("id", $this->request->getGet("q"))
|
||||
->orLike("name", $this->request->getGet("q"))
|
||||
->groupEnd();
|
||||
}
|
||||
|
||||
|
||||
$result = $query->orderBy("name", "asc")->get()->getResultObject();
|
||||
|
||||
$query = model('App\Models\Logistica\EnvioModel')->db->getLastQuery();
|
||||
|
||||
return $this->response->setJSON($result);
|
||||
} else {
|
||||
return $this->failUnauthorized('Invalid request', 403);
|
||||
}
|
||||
}
|
||||
|
||||
public function selectDireccionForEnvio()
|
||||
{
|
||||
|
||||
if ($this->request->isAJAX()) {
|
||||
$ot = $this->request->getGet('ot_id');
|
||||
if ($ot == null || $ot == 0) {
|
||||
return [];
|
||||
}
|
||||
$searchVal = $this->request->getGet("q") ?? "";
|
||||
$result = LogisticaService::findDireccionesNewEnvio($ot, $searchVal);
|
||||
|
||||
return $this->response->setJSON($result);
|
||||
} else {
|
||||
return $this->failUnauthorized('Invalid request', 403);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
public function generarEnvio()
|
||||
{
|
||||
if ($this->request->isAJAX()) {
|
||||
|
||||
$ot_id = $this->request->getPost('ot_id');
|
||||
$direccion = $this->request->getPost('direccion') ?? "";
|
||||
$result = LogisticaService::generateEnvio($ot_id, $direccion);
|
||||
return $this->response->setJSON($result);
|
||||
} else {
|
||||
return $this->failUnauthorized('Invalid request', 403);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public function generarEnvioFerro()
|
||||
{
|
||||
if ($this->request->isAJAX()) {
|
||||
|
||||
$ot_id = $this->request->getPost('ot_id');
|
||||
$result = LogisticaService::generateEnvioFerro($ot_id);
|
||||
return $this->response->setJSON($result);
|
||||
} else {
|
||||
return $this->failUnauthorized('Invalid request', 403);
|
||||
}
|
||||
}
|
||||
|
||||
public function imprimirEtiquetas()
|
||||
{
|
||||
if ($this->request->isAJAX()) {
|
||||
$envio_id = $this->request->getPost('envio_id');
|
||||
$ids = $this->request->getPost('envio_lineas');
|
||||
$cajas = $this->request->getPost('cajas');
|
||||
$printer_id = $this->request->getPost('printer_id');
|
||||
|
||||
if ($cajas == null || $cajas == 0) {
|
||||
return $this->response->setJSON([
|
||||
'status' => false,
|
||||
'message' => 'Cajas no válidas'
|
||||
]);
|
||||
}
|
||||
|
||||
$model = model('App\Models\Logistica\EnvioModel');
|
||||
$envio = $model->select('envios.*, clientes.nombre as cliente')
|
||||
->join('clientes', 'clientes.id = envios.cliente_id', 'left')
|
||||
->where('envios.id', $envio_id)
|
||||
->first();
|
||||
if ($envio == null) {
|
||||
return $this->response->setJSON([
|
||||
'status' => false,
|
||||
'message' => 'Envio no válido'
|
||||
]);
|
||||
}
|
||||
|
||||
$model = model('App\Models\Logistica\EnvioLineaModel');
|
||||
$lineas = $model->select('envios_lineas.*, presupuestos.titulo as titulo, presupuestos.referencia_cliente as referencia_cliente')
|
||||
->join('presupuestos', 'presupuestos.id = envios_lineas.presupuesto_id', 'left')
|
||||
->whereIn('envios_lineas.id', $ids)->findAll();
|
||||
if ($lineas == null) {
|
||||
return $this->response->setJSON([
|
||||
'status' => false,
|
||||
'message' => 'Lineas no válidas'
|
||||
]);
|
||||
}
|
||||
|
||||
$modelImpresora = model('App\Models\Configuracion\ImpresoraEtiquetaModel');
|
||||
$impresora = $modelImpresora->select('id, name, description, ip, port, user, pass')
|
||||
->where('deleted_at', null)
|
||||
->where('id', $printer_id)
|
||||
->orderBy('name', 'asc')
|
||||
->first();
|
||||
if ($impresora == null) {
|
||||
return $this->response->setJSON([
|
||||
'status' => false,
|
||||
'message' => 'Impresora no válida'
|
||||
]);
|
||||
}
|
||||
|
||||
$response = LogisticaService::generateEtiquetasTitulos($envio, $lineas, $impresora, $cajas);
|
||||
return $this->response->setJSON($response);
|
||||
|
||||
} else {
|
||||
return $this->failUnauthorized('Invalid request', 403);
|
||||
}
|
||||
}
|
||||
|
||||
public function selectAddEnvioLinea()
|
||||
{
|
||||
|
||||
if ($this->request->isAJAX()) {
|
||||
$query = LogisticaService::findLineaEnvioPorEnvio($this->request->getGet('envio'));
|
||||
if ($this->request->getGet("q")) {
|
||||
$query->groupStart()
|
||||
->orLike("id", $this->request->getGet("q"))
|
||||
->orLike("name", $this->request->getGet("q"))
|
||||
->groupEnd();
|
||||
}
|
||||
|
||||
|
||||
$result = $query->orderBy("name", "asc")->get()->getResultObject();
|
||||
|
||||
return $this->response->setJSON($result);
|
||||
} else {
|
||||
return $this->failUnauthorized('Invalid request', 403);
|
||||
}
|
||||
}
|
||||
|
||||
public function addEnvioLinea()
|
||||
{
|
||||
|
||||
if ($this->request->isAJAX()) {
|
||||
$pedido_id = $this->request->getGet('pedido_id');
|
||||
$envio_id = $this->request->getGet('envio_id');
|
||||
$envioModel = model('App\Models\Logistica\EnvioModel');
|
||||
$direccion = $envioModel->find($envio_id)->direccion;
|
||||
|
||||
$result = LogisticaService::addLineaEnvio($envio_id, $pedido_id, $direccion);
|
||||
return $this->response->setJSON($result);
|
||||
} else {
|
||||
return $this->failUnauthorized('Invalid request', 403);
|
||||
}
|
||||
}
|
||||
|
||||
public function datatable_envios()
|
||||
{
|
||||
|
||||
$otsFilter = $this->request->getGetPost('otsFilter');
|
||||
$tipo_envio = $this->request->getGetPost('tipo_envio') ?? 'estandar';
|
||||
|
||||
$model = model('App\Models\Logistica\EnvioModel');
|
||||
$q = $model->getDatatableQuery($tipo_envio);
|
||||
|
||||
if (!empty($otsFilter)) {
|
||||
$q->groupStart();
|
||||
$q->like('t5.id', $otsFilter);
|
||||
$q->groupEnd();
|
||||
}
|
||||
|
||||
|
||||
$result = DataTable::of($q)
|
||||
->edit(
|
||||
"finalizado",
|
||||
function ($row, $meta) {
|
||||
if ($row->finalizado == 1)
|
||||
return '<i class="ti ti-check"></i>';
|
||||
else
|
||||
return '<i class="ti ti-x"></i>';
|
||||
}
|
||||
)
|
||||
->add("action", callback: function ($q) {
|
||||
|
||||
return '
|
||||
<div class="btn-group btn-group-sm">
|
||||
<a href="javascript:void(0);"><i class="ti ti-eye ti-sm btn-edit mx-2" data-id="' . $q->id . '"></i></a>
|
||||
</div>
|
||||
';
|
||||
});
|
||||
|
||||
return $result->toJson(returnAsObject: true);
|
||||
}
|
||||
|
||||
public function editEnvio($id = null)
|
||||
{
|
||||
|
||||
if (empty($id)) {
|
||||
return redirect()->to(base_url('logistica/selectEnvios/simple'))->with('error', lang('Logistica.errors.noEnvio'));
|
||||
}
|
||||
$model = model('App\Models\Logistica\EnvioModel');
|
||||
$envioEntity = $model->select('envios.*, lg_paises.nombre as pais')
|
||||
->join('lg_paises', 'lg_paises.id = envios.pais_id', 'left')
|
||||
->where('envios.id', $id)
|
||||
->first();
|
||||
if (empty($envioEntity)) {
|
||||
return redirect()->to(base_url('logistica/selectEnvios/simple'))->with('error', lang('Logistica.errors.noEnvio'));
|
||||
}
|
||||
|
||||
$modelProveedor = model('App\Models\Compras\ProveedorModel');
|
||||
$proveedor = $modelProveedor->select('id, nombre')
|
||||
->where('deleted_at', null)
|
||||
->where('id', $envioEntity->proveedor_id)
|
||||
->orderBy('nombre', 'asc')
|
||||
->first();
|
||||
if (!empty($proveedor)) {
|
||||
$envioEntity->proveedor_nombre = $proveedor->nombre;
|
||||
}
|
||||
|
||||
$modelImpresora = model('App\Models\Configuracion\ImpresoraEtiquetaModel');
|
||||
$impresoras = $modelImpresora->select('id, name, description')
|
||||
->where('deleted_at', null)
|
||||
->where('tipo', 1)
|
||||
->orderBy('name', 'asc')
|
||||
->findAll();
|
||||
$envioEntity->impresoras = $impresoras;
|
||||
|
||||
$viewData = [
|
||||
'currentModule' => static::$controllerSlug,
|
||||
'boxTitle' => '<i class="ti ti-truck ti-xl"></i>' . ' ' . lang('Logistica.envio') . ' [' . $envioEntity->id . ']: ' . $envioEntity->direccion,
|
||||
'usingServerSideDataTable' => true,
|
||||
'envioEntity' => $envioEntity,
|
||||
];
|
||||
|
||||
$viewData = array_merge($this->viewData, $viewData); // merge any possible values from the parent controller class
|
||||
|
||||
return view(static::$viewPath . 'viewEnvioEditForm', $viewData);
|
||||
}
|
||||
|
||||
public function updateCajasEnvio()
|
||||
{
|
||||
if ($this->request->isAJAX()) {
|
||||
$id = $this->request->getPost('id');
|
||||
$cajas = $this->request->getPost('cajas');
|
||||
$model = model('App\Models\Logistica\EnvioModel');
|
||||
$result = $model->update($id, [
|
||||
'cajas' => $cajas,
|
||||
]);
|
||||
return $this->response->setJSON([
|
||||
"status" => $result,
|
||||
]);
|
||||
} else {
|
||||
return $this->failUnauthorized('Invalid request', 403);
|
||||
}
|
||||
}
|
||||
|
||||
public function finalizarEnvio()
|
||||
{
|
||||
if ($this->request->isAJAX()) {
|
||||
|
||||
$id = $this->request->getPost('id') ?? null;
|
||||
$finalizar_ots = $this->request->getPost('finalizar_ots') ?? false;
|
||||
|
||||
$result = LogisticaService::finalizarEnvio($id, $finalizar_ots);
|
||||
return $this->response->setJSON($result);
|
||||
} else {
|
||||
return $this->failUnauthorized('Invalid request', 403);
|
||||
}
|
||||
}
|
||||
|
||||
public function ficharEmbalaje()
|
||||
{
|
||||
if ($this->request->isAJAX()) {
|
||||
|
||||
$ids = $this->request->getPost('ids') ?? [];
|
||||
$result = LogisticaService::ficharEmbalaje($ids);
|
||||
return $this->response->setJSON($result);
|
||||
} else {
|
||||
return $this->failUnauthorized('Invalid request', 403);
|
||||
}
|
||||
}
|
||||
|
||||
public function datatable_enviosEdit($idEnvio)
|
||||
{
|
||||
$model = model('App\Models\Logistica\EnvioLineaModel');
|
||||
$q = $model->getDatatableQuery($idEnvio);
|
||||
|
||||
|
||||
$result = DataTable::of($q)
|
||||
->add(
|
||||
"rowSelected",
|
||||
callback: function ($q) {
|
||||
return '<input type="checkbox" class="form-check-input checkbox-linea-envio" name="row_selected[]" value="' . $q->id . '">';
|
||||
}
|
||||
)
|
||||
->edit(
|
||||
"ordenTrabajo",
|
||||
function ($row, $meta) {
|
||||
return '<a href="' . base_url('produccion/ordentrabajo/edit/' . $row->ordenTrabajo) . '" target="_blank">' . $row->ordenTrabajo . '</a>';
|
||||
}
|
||||
)
|
||||
->edit(
|
||||
"pedido",
|
||||
function ($row, $meta) {
|
||||
return '<a href="' . base_url('pedidos/edit/' . $row->pedido) . '" target="_blank">' . $row->pedido . '</a>';
|
||||
}
|
||||
)
|
||||
->edit(
|
||||
"presupuesto",
|
||||
function ($row, $meta) {
|
||||
return '<a href="' . base_url('presupuestoadmin/edit/' . $row->presupuesto) . '" target="_blank">' . $row->presupuesto . '</a>';
|
||||
}
|
||||
)->edit(
|
||||
"unidadesEnvio",
|
||||
function ($row, $meta) {
|
||||
if ($row->finalizado == 1 || $row->tipo_envio == 'ferro_prototipo') {
|
||||
return $row->unidadesEnvio;
|
||||
}
|
||||
return '<input type="number" class="form-control input-lineas input-unidades text-center"
|
||||
data-id="' . $row->id . '" data-name="unidades_envio" value="' . $row->unidadesEnvio . '">';
|
||||
}
|
||||
);
|
||||
|
||||
return $result->toJson(returnAsObject: true);
|
||||
}
|
||||
|
||||
public function datatable_proximosEnvios($envio_id = null)
|
||||
{
|
||||
$q = LogisticaService::findNextEnvios($envio_id);
|
||||
|
||||
$result = DataTable::of($q)
|
||||
->edit(
|
||||
"ot",
|
||||
function ($row, $meta) {
|
||||
return '<a href="' . base_url('produccion/ordentrabajo/edit/' . $row->ot) . '" target="_blank">' . $row->ot . '</a>';
|
||||
}
|
||||
);
|
||||
|
||||
$result = $result->toJson(returnAsObject: true);
|
||||
$query = model('App\Models\Logistica\EnvioModel')->db->getLastQuery();
|
||||
return $result;
|
||||
|
||||
}
|
||||
|
||||
public function setCajaLinea()
|
||||
{
|
||||
|
||||
if ($this->request->isAJAX()) {
|
||||
$id = $this->request->getPost('id');
|
||||
$caja = $this->request->getPost('caja');
|
||||
|
||||
|
||||
$model = model('App\Models\Logistica\EnvioLineaModel');
|
||||
$result = $model->update($id, [
|
||||
'cajas' => $caja,
|
||||
]);
|
||||
return $this->response->setJSON([
|
||||
"status" => $result,
|
||||
]);
|
||||
} else {
|
||||
return $this->failUnauthorized('Invalid request', 403);
|
||||
}
|
||||
}
|
||||
|
||||
public function deleteLineas()
|
||||
{
|
||||
if ($this->request->isAJAX()) {
|
||||
$ids = $this->request->getPost('ids');
|
||||
$model = model('App\Models\Logistica\EnvioLineaModel');
|
||||
$result = $model->delete($ids);
|
||||
return $this->response->setJSON([
|
||||
"status" => $result,
|
||||
]);
|
||||
} else {
|
||||
return $this->failUnauthorized('Invalid request', 403);
|
||||
}
|
||||
}
|
||||
|
||||
public function updateLineaEnvio()
|
||||
{
|
||||
$id = $this->request->getPost('id');
|
||||
$fieldName = $this->request->getPost('name');
|
||||
$fieldValue = $this->request->getPost('value');
|
||||
|
||||
if (!$id || !$fieldName || ($fieldName == 'unidades_envio' && !$fieldValue)) {
|
||||
return $this->response->setJSON([
|
||||
'status' => false,
|
||||
'message' => 'Datos inválidos'
|
||||
]);
|
||||
}
|
||||
|
||||
$model = model('App\Models\Logistica\EnvioLineaModel');
|
||||
$updated = $model->update($id, [
|
||||
"" . $fieldName => $fieldValue == "" ? null : $fieldValue,
|
||||
]);
|
||||
|
||||
return $this->response->setJSON([
|
||||
'status' => $updated,
|
||||
'message' => $updated ? 'Actualizado' : 'Error al actualizar'
|
||||
]);
|
||||
}
|
||||
|
||||
public function updateCodigoSeguimiento()
|
||||
{
|
||||
$id = $this->request->getPost('id');
|
||||
$fieldValue = $this->request->getPost('codigo_seguimiento');
|
||||
|
||||
if (!$id) {
|
||||
return $this->response->setJSON([
|
||||
'status' => false,
|
||||
'message' => 'Datos inválidos'
|
||||
]);
|
||||
}
|
||||
|
||||
$model = model('App\Models\Logistica\EnvioModel');
|
||||
$updated = $model->update($id, [
|
||||
"codigo_seguimiento" => $fieldValue == "" ? null : $fieldValue,
|
||||
]);
|
||||
|
||||
return $this->response->setJSON([
|
||||
'status' => $updated,
|
||||
'message' => $updated ? 'Actualizado' : 'Error al actualizar'
|
||||
]);
|
||||
}
|
||||
|
||||
public function updateProveedorEnvio()
|
||||
{
|
||||
$id = $this->request->getPost('id');
|
||||
$fieldValue = $this->request->getPost('proveedor_id');
|
||||
|
||||
if (!$id) {
|
||||
return $this->response->setJSON([
|
||||
'status' => false,
|
||||
'message' => 'Datos inválidos'
|
||||
]);
|
||||
}
|
||||
|
||||
$model = model('App\Models\Logistica\EnvioModel');
|
||||
$updated = $model->update($id, [
|
||||
"proveedor_id" => $fieldValue == "" ? null : $fieldValue,
|
||||
]);
|
||||
|
||||
return $this->response->setJSON([
|
||||
'status' => $updated,
|
||||
'message' => $updated ? 'Actualizado' : 'Error al actualizar'
|
||||
]);
|
||||
}
|
||||
|
||||
public function saveComments()
|
||||
{
|
||||
$id = $this->request->getPost('id');
|
||||
$comments = $this->request->getPost('comentarios');
|
||||
|
||||
if (!$id || !$comments) {
|
||||
return $this->response->setJSON([
|
||||
'status' => false,
|
||||
'message' => 'Datos inválidos'
|
||||
]);
|
||||
}
|
||||
|
||||
$model = model('App\Models\Logistica\EnvioModel');
|
||||
$updated = $model->update($id, [
|
||||
'comentarios' => $comments,
|
||||
]);
|
||||
|
||||
return $this->response->setJSON([
|
||||
'status' => $updated,
|
||||
'message' => $updated ? 'Actualizado' : 'Error al actualizar'
|
||||
]);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
0
ci4/app/Controllers/Mensajeria/MensajesDirectos.php
Normal file → Executable file
0
ci4/app/Controllers/Mensajeria/MensajesDirectos.php
Normal file → Executable file
69
ci4/app/Controllers/Pdf/PrintAlbaranes.php
Normal file → Executable file
69
ci4/app/Controllers/Pdf/PrintAlbaranes.php
Normal file → Executable file
@ -11,8 +11,8 @@ class PrintAlbaranes extends BaseController
|
||||
public function index($albaran_id)
|
||||
{
|
||||
|
||||
$albaranModel = model('App\Models\Pedidos\AlbaranModel');
|
||||
$lineasAlbaranModel = model('App\Models\Pedidos\AlbaranLineaModel');
|
||||
$albaranModel = model('App\Models\Albaranes\AlbaranModel');
|
||||
$lineasAlbaranModel = model('App\Models\Albaranes\AlbaranLineaModel');
|
||||
|
||||
$data['albaran'] = $albaranModel->getResourceForPdf($albaran_id)->get()->getRow();
|
||||
$data['albaranLineas'] = $lineasAlbaranModel->getResourceForPdf($albaran_id)->get()->getResultObject();
|
||||
@ -25,14 +25,22 @@ class PrintAlbaranes extends BaseController
|
||||
{
|
||||
|
||||
// Cargar modelos
|
||||
$albaranModel = model('App\Models\Pedidos\AlbaranModel');
|
||||
$lineasAlbaranModel = model('App\Models\Pedidos\AlbaranLineaModel');
|
||||
$albaranModel = model('App\Models\Albaranes\AlbaranModel');
|
||||
$lineasAlbaranModel = model('App\Models\Albaranes\AlbaranLineaModel');
|
||||
|
||||
// Informacion del presupuesto
|
||||
$data['albaran'] = $albaranModel->getResourceForPdf($albaran_id)->get()->getRow();
|
||||
$data['albaranLineas'] = $lineasAlbaranModel->getResourceForPdf($albaran_id)->get()->getResultObject();
|
||||
|
||||
|
||||
// Obtener contenido HTML de la vista
|
||||
$html = view(getenv('theme.path') . 'pdfs/albaran', $data);
|
||||
|
||||
// Cargar CSS desde archivo local
|
||||
$css = file_get_contents(FCPATH . 'themes/vuexy/css/pdf.albaran.css');
|
||||
// Combinar CSS y HTML
|
||||
$html_con_css = "<style>$css</style>" . $html;
|
||||
|
||||
// Crear una instancia de Dompdf
|
||||
$options = new \Dompdf\Options();
|
||||
$options->set('isHtml5ParserEnabled', true);
|
||||
@ -41,7 +49,7 @@ class PrintAlbaranes extends BaseController
|
||||
$dompdf = new \Dompdf\Dompdf($options);
|
||||
|
||||
// Contenido HTML del documento
|
||||
$dompdf->loadHtml(view(getenv('theme.path').'pdfs/albaran', $data));
|
||||
$dompdf->loadHtml($html_con_css);
|
||||
|
||||
// Establecer el tamaño del papel
|
||||
$dompdf->setPaper('A4', 'portrait');
|
||||
@ -63,4 +71,55 @@ class PrintAlbaranes extends BaseController
|
||||
->setHeader('Content-Length', strlen($output))
|
||||
->setBody($output);
|
||||
}
|
||||
|
||||
public function generarAnonimo($albaran_id)
|
||||
{
|
||||
|
||||
// Cargar modelos
|
||||
$albaranModel = model('App\Models\Albaranes\AlbaranModel');
|
||||
$lineasAlbaranModel = model('App\Models\Albaranes\AlbaranLineaModel');
|
||||
|
||||
// Informacion del presupuesto
|
||||
$data['albaran'] = $albaranModel->getResourceForPdf($albaran_id)->get()->getRow();
|
||||
$data['albaranLineas'] = $lineasAlbaranModel->getResourceForPdf($albaran_id)->get()->getResultObject();
|
||||
|
||||
|
||||
// Obtener contenido HTML de la vista
|
||||
$html = view(getenv('theme.path') . 'pdfs/albaran-anonimo', $data);
|
||||
|
||||
// Cargar CSS desde archivo local
|
||||
$css = file_get_contents(FCPATH . 'themes/vuexy/css/pdf.albaran.css');
|
||||
// Combinar CSS y HTML
|
||||
$html_con_css = "<style>$css</style>" . $html;
|
||||
|
||||
// Crear una instancia de Dompdf
|
||||
$options = new \Dompdf\Options();
|
||||
$options->set('isHtml5ParserEnabled', true);
|
||||
$options->set('isPhpEnabled', true);
|
||||
$options->set('isRemoteEnabled', true);
|
||||
$dompdf = new \Dompdf\Dompdf($options);
|
||||
|
||||
// Contenido HTML del documento
|
||||
$dompdf->loadHtml($html_con_css);
|
||||
|
||||
// Establecer el tamaño del papel
|
||||
$dompdf->setPaper('A4', 'portrait');
|
||||
|
||||
// Renderizar el PDF
|
||||
$dompdf->render();
|
||||
|
||||
// Obtener el contenido generado
|
||||
$output = $dompdf->output();
|
||||
|
||||
// Establecer las cabeceras para visualizar en lugar de descargar
|
||||
$file_name = "alabaran-$albaran_id.pdf";
|
||||
return $this->response
|
||||
->setStatusCode(200)
|
||||
->setHeader('Content-Type', 'application/pdf')
|
||||
->setHeader('Content-Disposition', 'inline; filename="' . $file_name . '"')
|
||||
->setHeader('Cache-Control', 'private, max-age=0, must-revalidate')
|
||||
->setHeader('Pragma', 'public')
|
||||
->setHeader('Content-Length', strlen($output))
|
||||
->setBody($output);
|
||||
}
|
||||
}
|
||||
0
ci4/app/Controllers/Pdf/PrintFacturas.php
Normal file → Executable file
0
ci4/app/Controllers/Pdf/PrintFacturas.php
Normal file → Executable file
@ -1,388 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Controllers\Pedidos;
|
||||
use App\Entities\Pedidos\AlbaranEntity;
|
||||
use App\Models\Pedidos\AlbaranModel;
|
||||
|
||||
|
||||
class Albaran extends \App\Controllers\BaseResourceController
|
||||
{
|
||||
protected $modelName = AlbaranModel::class;
|
||||
protected $format = 'json';
|
||||
|
||||
protected static $singularObjectNameCc = 'albaran';
|
||||
protected static $singularObjectName = 'Albaran';
|
||||
protected static $pluralObjectName = 'Albaranes';
|
||||
protected static $controllerSlug = 'albaran';
|
||||
|
||||
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
|
||||
{
|
||||
parent::initController($request, $response, $logger);
|
||||
}
|
||||
|
||||
public function index()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
public function delete($id = null)
|
||||
{
|
||||
if ($this->request->isAJAX()) {
|
||||
|
||||
$newTokenHash = csrf_hash();
|
||||
$csrfTokenName = csrf_token();
|
||||
|
||||
$model_linea = model('App\Models\Pedidos\AlbaranLineaModel');
|
||||
$model_linea->where('albaran_id', $id)->delete();
|
||||
|
||||
$this->model->where('id', $id)->delete();
|
||||
|
||||
$data = [
|
||||
'error' => 0,
|
||||
$csrfTokenName => $newTokenHash
|
||||
];
|
||||
return $this->respond($data);
|
||||
}
|
||||
else {
|
||||
return $this->failUnauthorized('Invalid request', 403);
|
||||
}
|
||||
}
|
||||
|
||||
public function addLinea($albaran_id){
|
||||
|
||||
if ($this->request->isAJAX()) {
|
||||
|
||||
$model_linea = model('App\Models\Pedidos\AlbaranLineaModel');
|
||||
$newTokenHash = csrf_hash();
|
||||
$csrfTokenName = csrf_token();
|
||||
|
||||
// si es un post, es el iva
|
||||
if($this->request->getPost()){
|
||||
$reqData = $this->request->getPost();
|
||||
$albaran_id = $reqData['albaran_id'] ?? 0;
|
||||
|
||||
$albaran = $this->model->find($albaran_id);
|
||||
if($albaran == false){
|
||||
$data = [
|
||||
'error' => 'Albaran no encontrado',
|
||||
$csrfTokenName => $newTokenHash
|
||||
];
|
||||
return $this->respond($data);
|
||||
}
|
||||
$presupuesto_model = model('App\Models\Presupuestos\PresupuestoModel');
|
||||
$presupuesto = $presupuesto_model->find($albaran->presupuesto_id);
|
||||
if($presupuesto == false){
|
||||
$data = [
|
||||
'error' => 'Presupuesto no encontrado',
|
||||
$csrfTokenName => $newTokenHash
|
||||
];
|
||||
return $this->respond($data);
|
||||
}
|
||||
$iva_reducido = $presupuesto->iva_reducido;
|
||||
$lineas = $model_linea->where('albaran_id', $albaran_id)->findAll();
|
||||
$total = 0;
|
||||
foreach($lineas as $linea){
|
||||
$total += $linea->total;
|
||||
}
|
||||
$iva = $iva_reducido? $total * 4.0 / 100: $total * 21.0 / 100;
|
||||
$data_linea= [
|
||||
'albaran_id' => $albaran_id,
|
||||
'titulo' => $iva_reducido?lang('Pedidos.iva4'):lang('Pedidos.iva21'),
|
||||
'cantidad' => 1,
|
||||
'precio_unidad' => round($iva,2),
|
||||
'total' => round($iva,2),
|
||||
'user_created_id' => auth()->user()->id,
|
||||
'user_updated_id' => auth()->user()->id
|
||||
];
|
||||
$id_linea = $model_linea->insert($data_linea);
|
||||
$linea = $model_linea->find($id_linea);
|
||||
$data = [
|
||||
'error' => 0,
|
||||
'data' => $linea,
|
||||
$csrfTokenName => $newTokenHash
|
||||
];
|
||||
return $this->respond($data);
|
||||
}
|
||||
else{
|
||||
$linea = [
|
||||
'albaran_id' => $albaran_id,
|
||||
'user_created_id' => auth()->user()->id,
|
||||
'user_updated_id' => auth()->user()->id
|
||||
];
|
||||
$id_linea = $model_linea->insert($linea);
|
||||
$data = $model_linea->find($id_linea);
|
||||
|
||||
$data = [
|
||||
'error' => 0,
|
||||
'data' => $data,
|
||||
$csrfTokenName => $newTokenHash
|
||||
];
|
||||
return $this->respond($data);
|
||||
}
|
||||
}
|
||||
else {
|
||||
return $this->failUnauthorized('Invalid request', 403);
|
||||
}
|
||||
}
|
||||
|
||||
public function add()
|
||||
{
|
||||
if ($this->request->isAJAX()) {
|
||||
|
||||
$user = auth()->user()->id;
|
||||
|
||||
$newTokenHash = csrf_hash();
|
||||
$csrfTokenName = csrf_token();
|
||||
|
||||
$reqData = $this->request->getPost();
|
||||
$pedido_id = $reqData['pedido_id'] ?? 0;
|
||||
$presupuestos_id = $reqData['presupuestos_id'] ?? 0;
|
||||
|
||||
$return_data = $this->model->generarAlbaranes($pedido_id, $presupuestos_id, $user);
|
||||
$data = [
|
||||
'data' => $return_data,
|
||||
$csrfTokenName => $newTokenHash
|
||||
];
|
||||
|
||||
return $this->respond($data);
|
||||
|
||||
}
|
||||
else {
|
||||
return $this->failUnauthorized('Invalid request', 403);
|
||||
}
|
||||
}
|
||||
|
||||
public function update($id = null){
|
||||
|
||||
if ($this->request->isAJAX()) {
|
||||
$newTokenHash = csrf_hash();
|
||||
$csrfTokenName = csrf_token();
|
||||
|
||||
if ($id == null) :
|
||||
$data = [
|
||||
'error' => 2,
|
||||
$csrfTokenName => $newTokenHash
|
||||
];
|
||||
return $this->respond($data);
|
||||
endif;
|
||||
$id = filter_var($id, FILTER_SANITIZE_URL);
|
||||
$albaranEntity = $this->model->find($id);
|
||||
|
||||
if ($albaranEntity == false) :
|
||||
$message = lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('Pedidos.albaran')), $id]);
|
||||
$data = [
|
||||
'error' => $message,
|
||||
$csrfTokenName => $newTokenHash
|
||||
];
|
||||
return $this->respond($data);
|
||||
endif;
|
||||
|
||||
if ($this->request->getPost()) :
|
||||
|
||||
$nullIfEmpty = true; // !(phpversion() >= '8.1');
|
||||
|
||||
$postData = $this->request->getPost();
|
||||
|
||||
$sanitizedData = $this->sanitized($postData, $nullIfEmpty);
|
||||
|
||||
// JJO
|
||||
$sanitizedData['user_updated_id'] = auth()->user()->id;
|
||||
|
||||
$noException = true;
|
||||
if ($successfulResult = $this->canValidate()) : // if ($successfulResult = $this->validate($this->formValidationRules) ) :
|
||||
|
||||
if ($this->canValidate()) :
|
||||
try {
|
||||
$successfulResult = $this->model->skipValidation(true)->update($id, $sanitizedData);
|
||||
} catch (\Exception $e) {
|
||||
$noException = false;
|
||||
$this->dealWithException($e);
|
||||
}
|
||||
else:
|
||||
$this->viewData['warningMessage'] = lang('Basic.global.formErr1', [mb_strtolower(lang('Pedidos.albaran'))]);
|
||||
$this->session->setFlashdata('formErrors', $this->model->errors());
|
||||
|
||||
endif;
|
||||
|
||||
$albaranEntity->fill($sanitizedData);
|
||||
|
||||
endif;
|
||||
if ($noException && $successfulResult) :
|
||||
$id = $albaranEntity->id ?? $id;
|
||||
$message = lang('Basic.global.updateSuccess', [lang('Basic.global.record')]) . '.';
|
||||
|
||||
$data = [
|
||||
'error' => 0,
|
||||
$csrfTokenName => $newTokenHash
|
||||
];
|
||||
return $this->respond($data);
|
||||
|
||||
endif; // $noException && $successfulResult
|
||||
endif; // ($requestMethod === 'post')
|
||||
|
||||
$data = [
|
||||
'error' => 1,
|
||||
$csrfTokenName => $newTokenHash
|
||||
];
|
||||
return $this->respond($data);
|
||||
}
|
||||
else {
|
||||
return $this->failUnauthorized('Invalid request', 403);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public function updateLinea($id = null){
|
||||
|
||||
if ($this->request->isAJAX()) {
|
||||
|
||||
$model_linea = model('App\Models\Pedidos\AlbaranLineaModel');
|
||||
$newTokenHash = csrf_hash();
|
||||
$csrfTokenName = csrf_token();
|
||||
|
||||
if ($id == null) :
|
||||
$data = [
|
||||
'error' => 2,
|
||||
$csrfTokenName => $newTokenHash
|
||||
];
|
||||
return $this->respond($data);
|
||||
endif;
|
||||
$id = filter_var($id, FILTER_SANITIZE_URL);
|
||||
$albaranEntity = $model_linea->find($id);
|
||||
|
||||
if ($albaranEntity == false) :
|
||||
$message = lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('Pedidos.albaran')), $id]);
|
||||
$data = [
|
||||
'error' => $message,
|
||||
$csrfTokenName => $newTokenHash
|
||||
];
|
||||
return $this->respond($data);
|
||||
endif;
|
||||
|
||||
if ($this->request->getPost()) :
|
||||
|
||||
$nullIfEmpty = true; // !(phpversion() >= '8.1');
|
||||
|
||||
$postData = $this->request->getPost();
|
||||
|
||||
$sanitizedData = $this->sanitized($postData, $nullIfEmpty);
|
||||
|
||||
// JJO
|
||||
$sanitizedData['user_updated_id'] = auth()->user()->id;
|
||||
|
||||
$noException = true;
|
||||
if ($successfulResult = $this->canValidate()) : // if ($successfulResult = $this->validate($this->formValidationRules) ) :
|
||||
|
||||
if ($this->canValidate()) :
|
||||
try {
|
||||
$successfulResult = $model_linea->skipValidation(true)->update($id, $sanitizedData);
|
||||
} catch (\Exception $e) {
|
||||
$noException = false;
|
||||
$this->dealWithException($e);
|
||||
}
|
||||
else:
|
||||
$this->viewData['warningMessage'] = lang('Basic.global.formErr1', [mb_strtolower(lang('Pedidos.albaran'))]);
|
||||
$this->session->setFlashdata('formErrors', $model_linea->errors());
|
||||
|
||||
endif;
|
||||
|
||||
$albaranEntity->fill($sanitizedData);
|
||||
|
||||
endif;
|
||||
if ($noException && $successfulResult) :
|
||||
$id = $albaranEntity->id ?? $id;
|
||||
$message = lang('Basic.global.updateSuccess', [lang('Basic.global.record')]) . '.';
|
||||
|
||||
$data = [
|
||||
'error' => 0,
|
||||
$csrfTokenName => $newTokenHash
|
||||
];
|
||||
return $this->respond($data);
|
||||
|
||||
endif; // $noException && $successfulResult
|
||||
endif; // ($requestMethod === 'post')
|
||||
|
||||
$data = [
|
||||
'error' => 1,
|
||||
$csrfTokenName => $newTokenHash
|
||||
];
|
||||
return $this->respond($data);
|
||||
}
|
||||
else {
|
||||
return $this->failUnauthorized('Invalid request', 403);
|
||||
}
|
||||
}
|
||||
|
||||
public function borrarLinea(){
|
||||
if ($this->request->isAJAX()) {
|
||||
|
||||
$model_linea = model('App\Models\Pedidos\AlbaranLineaModel');
|
||||
$newTokenHash = csrf_hash();
|
||||
$csrfTokenName = csrf_token();
|
||||
|
||||
$reqData = $this->request->getPost();
|
||||
$id = $reqData['id'] ?? 0;
|
||||
$id = filter_var($id, FILTER_SANITIZE_URL);
|
||||
$albaranLineaEntity = $model_linea->find($id);
|
||||
|
||||
if ($albaranLineaEntity == false) :
|
||||
$message = lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('Pedidos.albaran')), $id]);
|
||||
$message = lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('Pedidos.albaran')), $id]);
|
||||
$data = [
|
||||
'error' => $message,
|
||||
$csrfTokenName => $newTokenHash
|
||||
];
|
||||
return $this->respond($data);
|
||||
endif;
|
||||
|
||||
$successfulResult = $model_linea->skipValidation(true)->update($id, ['deleted_at' => date('Y-m-d H:i:s')]);
|
||||
|
||||
if ($successfulResult) :
|
||||
$data = [
|
||||
'error' => 0,
|
||||
$csrfTokenName => $newTokenHash
|
||||
];
|
||||
else:
|
||||
$data = [
|
||||
'error' => 1,
|
||||
$csrfTokenName => $newTokenHash
|
||||
];
|
||||
endif;
|
||||
return $this->respond($data);
|
||||
}
|
||||
else {
|
||||
return $this->failUnauthorized('Invalid request', 403);
|
||||
}
|
||||
}
|
||||
|
||||
public function getAlbaranes($pedido_id = null){
|
||||
if ($this->request->isAJAX()) {
|
||||
|
||||
$model_linea = model('App\Models\Pedidos\AlbaranLineaModel');
|
||||
$newTokenHash = csrf_hash();
|
||||
$csrfTokenName = csrf_token();
|
||||
|
||||
$returnData = [];
|
||||
$albaranes = $this->model->asArray()->where('pedido_id', $pedido_id)->findAll();
|
||||
|
||||
foreach($albaranes as $albaran){
|
||||
$albaran['fecha_albaran'] = $albaran['updated_at'];
|
||||
array_push($returnData,
|
||||
[
|
||||
'albaran' => $albaran,
|
||||
'lineas' => $model_linea->asArray()->where('albaran_id', $albaran['id'])->findAll()]
|
||||
);
|
||||
}
|
||||
|
||||
$data = [
|
||||
'data' => $returnData,
|
||||
$csrfTokenName => $newTokenHash
|
||||
];
|
||||
return $this->respond($data);
|
||||
}
|
||||
else {
|
||||
return $this->failUnauthorized('Invalid request', 403);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -12,7 +12,7 @@ use Hermawan\DataTables\DataTable;
|
||||
use CodeIgniter\I18n\Time;
|
||||
|
||||
class Pedido extends \App\Controllers\BaseResourceController
|
||||
{
|
||||
{
|
||||
protected $modelName = PedidoModel::class;
|
||||
protected $format = 'json';
|
||||
|
||||
@ -29,9 +29,9 @@ class Pedido extends \App\Controllers\BaseResourceController
|
||||
{
|
||||
$this->viewData['pageTitle'] = lang('Pedidos.moduleTitle');
|
||||
// Se indica que este controlador trabaja con soft_delete
|
||||
|
||||
|
||||
$this->viewData = ['usingServerSideDataTable' => true];
|
||||
|
||||
|
||||
// Breadcrumbs
|
||||
$this->viewData['breadcrumb'] = [
|
||||
['title' => lang("App.menu_pedidos"), 'route' => "javascript:void(0);", 'active' => false],
|
||||
@ -169,7 +169,7 @@ class Pedido extends \App\Controllers\BaseResourceController
|
||||
|
||||
public function todos()
|
||||
{
|
||||
|
||||
|
||||
$viewData = [
|
||||
'currentModule' => static::$controllerSlug,
|
||||
'pageSubTitle' => lang('Basic.global.ManageAllRecords', [lang('Pedidos.pedido')]),
|
||||
@ -195,21 +195,23 @@ class Pedido extends \App\Controllers\BaseResourceController
|
||||
|
||||
}
|
||||
|
||||
public function cambiarEstado(){
|
||||
if($this->request->isAJAX()){
|
||||
public function cambiarEstado()
|
||||
{
|
||||
if ($this->request->isAJAX()) {
|
||||
|
||||
$id = $this->request->getPost('id');
|
||||
$estado = $this->request->getPost('estado');
|
||||
|
||||
$this->model->where('id', $id)->set(['estado' => $estado])->update();
|
||||
return $this->respond(['status' => 'success', 'message' => lang('Basic.global.success')]);
|
||||
}else{
|
||||
} else {
|
||||
return $this->failUnauthorized('Invalid request', 403);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public function update($id = null){
|
||||
public function update($id = null)
|
||||
{
|
||||
|
||||
$data = [];
|
||||
|
||||
@ -217,7 +219,7 @@ class Pedido extends \App\Controllers\BaseResourceController
|
||||
$newTokenHash = csrf_hash();
|
||||
$csrfTokenName = csrf_token();
|
||||
|
||||
if ($id == null) :
|
||||
if ($id == null):
|
||||
$data = [
|
||||
'error' => 2,
|
||||
$csrfTokenName => $newTokenHash
|
||||
@ -227,7 +229,7 @@ class Pedido extends \App\Controllers\BaseResourceController
|
||||
$id = filter_var($id, FILTER_SANITIZE_URL);
|
||||
$pedidoEntity = $this->model->find($id);
|
||||
|
||||
if ($pedidoEntity == false) :
|
||||
if ($pedidoEntity == false):
|
||||
$message = lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('Pedidos.pedido')), $id]);
|
||||
$data = [
|
||||
'error' => $message,
|
||||
@ -236,19 +238,19 @@ class Pedido extends \App\Controllers\BaseResourceController
|
||||
return $this->respond($data);
|
||||
endif;
|
||||
|
||||
if ($this->request->getPost()) :
|
||||
if ($this->request->getPost()):
|
||||
|
||||
$nullIfEmpty = true; // !(phpversion() >= '8.1');
|
||||
|
||||
$postData = $this->request->getPost();
|
||||
|
||||
$sanitizedData = $this->sanitized($postData, $nullIfEmpty);
|
||||
|
||||
foreach(array_keys($sanitizedData) as $key){
|
||||
if(str_starts_with($key, "fecha_")){
|
||||
$sanitizedData[$key . "_change_user_id"] =
|
||||
|
||||
foreach (array_keys($sanitizedData) as $key) {
|
||||
if (str_starts_with($key, "fecha_")) {
|
||||
$sanitizedData[$key . "_change_user_id"] =
|
||||
auth()->user()->id;
|
||||
$data[$key . "_change_user"] =
|
||||
$data[$key . "_change_user"] =
|
||||
model('App\Models\Usuarios\UserModel')->getFullName(auth()->user()->id);
|
||||
}
|
||||
}
|
||||
@ -256,9 +258,9 @@ class Pedido extends \App\Controllers\BaseResourceController
|
||||
$sanitizedData['user_updated_id'] = auth()->user()->id;
|
||||
|
||||
$noException = true;
|
||||
if ($successfulResult = $this->canValidate()) : // if ($successfulResult = $this->validate($this->formValidationRules) ) :
|
||||
if ($successfulResult = $this->canValidate()): // if ($successfulResult = $this->validate($this->formValidationRules) ) :
|
||||
|
||||
if ($this->canValidate()) :
|
||||
if ($this->canValidate()):
|
||||
try {
|
||||
$successfulResult = $this->model->skipValidation(true)->update($id, $sanitizedData);
|
||||
} catch (\Exception $e) {
|
||||
@ -274,7 +276,7 @@ class Pedido extends \App\Controllers\BaseResourceController
|
||||
$pedidoEntity->fill($sanitizedData);
|
||||
|
||||
endif;
|
||||
if ($noException && $successfulResult) :
|
||||
if ($noException && $successfulResult):
|
||||
$id = $pedidoEntity->id ?? $id;
|
||||
$message = lang('Basic.global.updateSuccess', [lang('Basic.global.record')]) . '.';
|
||||
|
||||
@ -291,39 +293,39 @@ class Pedido extends \App\Controllers\BaseResourceController
|
||||
$csrfTokenName => $newTokenHash
|
||||
];
|
||||
return $this->respond($data);
|
||||
}
|
||||
else {
|
||||
} else {
|
||||
return $this->failUnauthorized('Invalid request', 403);
|
||||
}
|
||||
}
|
||||
|
||||
public function edit($id=null){
|
||||
|
||||
if ($id == null) :
|
||||
public function edit($id = null)
|
||||
{
|
||||
|
||||
if ($id == null):
|
||||
return $this->redirect2listView();
|
||||
endif;
|
||||
$id = filter_var($id, FILTER_SANITIZE_URL);
|
||||
$pedidoEntity = $this->model->find($id);
|
||||
|
||||
if ($pedidoEntity == false) :
|
||||
if ($pedidoEntity == false):
|
||||
$message = lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('Pedidos.pedido')), $id]);
|
||||
return $this->redirect2listView('sweet-error', $message);
|
||||
endif;
|
||||
|
||||
$this->obtenerDatosFormulario($pedidoEntity);
|
||||
|
||||
$pedidoEntity->fecha_entrega_real_change_user = $pedidoEntity->fecha_entrega_real_change_user_id?model('App\Models\Usuarios\UserModel')->
|
||||
getFullName($pedidoEntity->fecha_entrega_real_change_user_id):"";
|
||||
$pedidoEntity->fecha_impresion_change_user = $pedidoEntity->fecha_impresion_change_user_id?model('App\Models\Usuarios\UserModel')->
|
||||
getFullName($pedidoEntity->fecha_impresion_change_user_id):"";
|
||||
$pedidoEntity->fecha_encuadernado_change_user = $pedidoEntity->fecha_encuadernado_change_user_id?model('App\Models\Usuarios\UserModel')->
|
||||
getFullName($pedidoEntity->fecha_encuadernado_change_user_id):"";
|
||||
$pedidoEntity->fecha_entrega_change_externo_user = $pedidoEntity->fecha_entrega_change_externo_user_id?model('App\Models\Usuarios\UserModel')->
|
||||
getFullName($pedidoEntity->fecha_entrega_change_externo_user_id):"";
|
||||
|
||||
$pedidoEntity->fecha_entrega_real_change_user = $pedidoEntity->fecha_entrega_real_change_user_id ? model('App\Models\Usuarios\UserModel')->
|
||||
getFullName($pedidoEntity->fecha_entrega_real_change_user_id) : "";
|
||||
$pedidoEntity->fecha_impresion_change_user = $pedidoEntity->fecha_impresion_change_user_id ? model('App\Models\Usuarios\UserModel')->
|
||||
getFullName($pedidoEntity->fecha_impresion_change_user_id) : "";
|
||||
$pedidoEntity->fecha_encuadernado_change_user = $pedidoEntity->fecha_encuadernado_change_user_id ? model('App\Models\Usuarios\UserModel')->
|
||||
getFullName($pedidoEntity->fecha_encuadernado_change_user_id) : "";
|
||||
$pedidoEntity->fecha_entrega_change_externo_user = $pedidoEntity->fecha_entrega_change_externo_user_id ? model('App\Models\Usuarios\UserModel')->
|
||||
getFullName($pedidoEntity->fecha_entrega_change_externo_user_id) : "";
|
||||
|
||||
$this->viewData['pedidoEntity'] = $pedidoEntity;
|
||||
|
||||
if($pedidoEntity->estado == 'validacion'){
|
||||
if ($pedidoEntity->estado == 'validacion') {
|
||||
$clienteModel = model('App\Models\Clientes\ClienteModel');
|
||||
$pendiente = $clienteModel->getPendienteCobro($pedidoEntity->cliente_id);
|
||||
$pendiente = $pendiente[0] + $pendiente[1];
|
||||
@ -332,24 +334,25 @@ class Pedido extends \App\Controllers\BaseResourceController
|
||||
|
||||
$modelOrden = new \App\Models\OrdenTrabajo\OrdenTrabajoModel();
|
||||
$orden = $modelOrden->where('pedido_id', $pedidoEntity->id)->first();
|
||||
if($orden){
|
||||
if ($orden) {
|
||||
$this->viewData['orden_id'] = $orden->id;
|
||||
}
|
||||
|
||||
|
||||
$this->viewData['boxTitle'] = lang('Basic.global.edit2') . ' ' . lang('Pedidos.moduleTitle') . ' ' . lang('Basic.global.edit3');
|
||||
|
||||
|
||||
return $this->displayForm(__METHOD__, $id);
|
||||
}
|
||||
|
||||
public function datatable(){
|
||||
public function datatable()
|
||||
{
|
||||
|
||||
if ($this->request->isAJAX()) {
|
||||
|
||||
$reqData = $this->request->getPost();
|
||||
if (!isset($reqData['draw']) || !isset($reqData['columns']) ) {
|
||||
if (!isset($reqData['draw']) || !isset($reqData['columns'])) {
|
||||
$errstr = 'No data available in response to this specific request.';
|
||||
$response = $this->respond(Collection::datatable( [], 0, 0, $errstr ), 400, $errstr);
|
||||
$response = $this->respond(Collection::datatable([], 0, 0, $errstr), 400, $errstr);
|
||||
return $response;
|
||||
}
|
||||
$start = $reqData['start'] ?? 0;
|
||||
@ -360,7 +363,8 @@ class Pedido extends \App\Controllers\BaseResourceController
|
||||
$dir = $reqData['order']['0']['dir'] ?? 'asc';
|
||||
$estado = $reqData['estado'] ?? 'todos';
|
||||
$cliente_id = $reqData['cliente_id'] ?? -1;
|
||||
if($estado == 'todos') $estado = '';
|
||||
if ($estado == 'todos')
|
||||
$estado = '';
|
||||
|
||||
$showTotal = $reqData['showTotal'] ?? false;
|
||||
|
||||
@ -373,7 +377,7 @@ class Pedido extends \App\Controllers\BaseResourceController
|
||||
$extra_data['total_tirada'] = $totalTirada;
|
||||
$extra_data['total'] = $total;
|
||||
$total2 = 0;
|
||||
if($showTotal){
|
||||
if ($showTotal) {
|
||||
$total2 = $model_linea->getTotalOfTotalAceptado($estado);
|
||||
$tirada2 = $model_linea->getTotalTirada($estado);
|
||||
$extra_data['total2'] = $total2;
|
||||
@ -422,11 +426,11 @@ class Pedido extends \App\Controllers\BaseResourceController
|
||||
$result = DataTable::of($q)
|
||||
->edit(
|
||||
'fecha',
|
||||
fn($q) => $q->fecha?Time::createFromFormat("Y-m-d H:i:s", $q->fecha)->format("d/m/Y"):""
|
||||
fn($q) => $q->fecha ? Time::createFromFormat("Y-m-d H:i:s", $q->fecha)->format("d/m/Y") : ""
|
||||
)
|
||||
->edit(
|
||||
'fecha_entrega',
|
||||
fn($q) => $q->fecha_entrega?Time::createFromFormat("Y-m-d H:i:s", $q->fecha_entrega)->format("d/m/Y"):""
|
||||
fn($q) => $q->fecha_entrega ? Time::createFromFormat("Y-m-d H:i:s", $q->fecha_entrega)->format("d/m/Y") : ""
|
||||
)
|
||||
->edit(
|
||||
"estado",
|
||||
@ -453,13 +457,14 @@ class Pedido extends \App\Controllers\BaseResourceController
|
||||
<a href="javascript:void(0);"><i class="ti ti-eye ti-sm btn-edit mx-2" data-id="' . $q->id . '"></i></a>
|
||||
</div>
|
||||
';
|
||||
|
||||
|
||||
});
|
||||
|
||||
return $result->toJson(returnAsObject: true) ;
|
||||
|
||||
return $result->toJson(returnAsObject: true);
|
||||
}
|
||||
|
||||
public function obtenerTotalPedidosCliente($cliente_id){
|
||||
public function obtenerTotalPedidosCliente($cliente_id)
|
||||
{
|
||||
|
||||
$error = false;
|
||||
$result = [
|
||||
@ -472,37 +477,37 @@ class Pedido extends \App\Controllers\BaseResourceController
|
||||
->join('pedidos_linea', 'pedidos_linea.pedido_id = pedidos.id')
|
||||
->join('presupuestos', 'presupuestos.id = pedidos_linea.presupuesto_id')
|
||||
->groupBy('presupuestos.cliente_id')->get()->getResultObject();
|
||||
if(count($data) > 0){
|
||||
if (count($data) > 0) {
|
||||
$result['total_impresion'] = round(floatval($data[0]->total), 2);
|
||||
}
|
||||
else{
|
||||
} else {
|
||||
$error = true;
|
||||
}
|
||||
$result['total'] = $result['total_impresion'] + $result['total_maquetacion'];
|
||||
return $this->respond(['status' => $error?'error':'success', 'totales' => $result]);
|
||||
return $this->respond(['status' => $error ? 'error' : 'success', 'totales' => $result]);
|
||||
}
|
||||
|
||||
|
||||
public function obtenerPedidosForFacturas(){
|
||||
public function obtenerPedidosForFacturas()
|
||||
{
|
||||
if ($this->request->isAJAX()) {
|
||||
$reqData = $this->request->getPost();
|
||||
$start = $reqData['start'] ?? 0;
|
||||
}
|
||||
else {
|
||||
} else {
|
||||
return $this->failUnauthorized('Invalid request', 403);
|
||||
}
|
||||
}
|
||||
|
||||
public function getlineas(){
|
||||
public function getlineas()
|
||||
{
|
||||
if ($this->request->isAJAX()) {
|
||||
|
||||
$reqData = $this->request->getPost();
|
||||
if (!isset($reqData['draw']) || !isset($reqData['columns']) ) {
|
||||
if (!isset($reqData['draw']) || !isset($reqData['columns'])) {
|
||||
$errstr = 'No data available in response to this specific request.';
|
||||
$response = $this->respond(Collection::datatable( [], 0, 0, $errstr ), 400, $errstr);
|
||||
$response = $this->respond(Collection::datatable([], 0, 0, $errstr), 400, $errstr);
|
||||
return $response;
|
||||
}
|
||||
|
||||
|
||||
$id = $reqData['pedido_id'] ?? 0;
|
||||
$resourceData = $this->model->obtenerLineasPedido($id);
|
||||
|
||||
@ -517,25 +522,26 @@ class Pedido extends \App\Controllers\BaseResourceController
|
||||
}
|
||||
|
||||
|
||||
public function addFactura(){
|
||||
public function addFactura()
|
||||
{
|
||||
|
||||
if ($this->request->isAJAX()) {
|
||||
|
||||
if($this->request->isAJAX()){
|
||||
|
||||
|
||||
$modelFactura = model('App\Models\Facturas\FacturaModel');
|
||||
$modelFacturaLinea = model('App\Models\Facturas\FacturaLineaModel');
|
||||
|
||||
|
||||
$pedido_id = $this->request->getPost('pedido_id');
|
||||
$serie_id = $this->request->getPost('serie_id');
|
||||
|
||||
$datosFactura = $this->model->obtenerDatosForFactura($pedido_id);
|
||||
|
||||
if(count($datosFactura) == 0){
|
||||
if (count($datosFactura) == 0) {
|
||||
return $this->respond(['status' => 'error', 'message' => 'Error obteniendo datos de factura']);
|
||||
}
|
||||
|
||||
$datosFactura = $datosFactura[0];
|
||||
|
||||
|
||||
$modelFactura->insert([
|
||||
'cliente_id' => $datosFactura->cliente_id,
|
||||
'serie_id' => $serie_id,
|
||||
@ -555,13 +561,13 @@ class Pedido extends \App\Controllers\BaseResourceController
|
||||
|
||||
$factura_id = $modelFactura->getInsertID();
|
||||
|
||||
if($factura_id){
|
||||
if ($factura_id) {
|
||||
|
||||
$model_pedido_linea = model('\App\Models\Pedidos\PedidoLineaModel');
|
||||
$lineas = $model_pedido_linea->where('pedido_id', $pedido_id)->first();
|
||||
$facturas = new Facturas();
|
||||
$result = $facturas->addLineaPedidoImpresion($factura_id, $lineas->id);
|
||||
if($result['error'] == 0){
|
||||
if ($result['error'] == 0) {
|
||||
// Se actualiza el precio total de la factura obtenido de la linea añadida
|
||||
$linea_added = $modelFacturaLinea->where('factura_id', $factura_id)->first();
|
||||
$modelFactura->set([
|
||||
@ -570,27 +576,28 @@ class Pedido extends \App\Controllers\BaseResourceController
|
||||
'pendiente' => $linea_added->total,
|
||||
])->where('id', $factura_id)->update();
|
||||
return $this->respond(['status' => 'success', 'id' => $factura_id, 'message' => lang('Basic.global.success')]);
|
||||
}else{
|
||||
} else {
|
||||
return $this->respond(['status' => 'error', 'message' => 'Error insertando lineas de factura']);
|
||||
}
|
||||
}
|
||||
|
||||
return $this->respond(['status' => 'error', 'message' => 'Error insertando factura']);
|
||||
|
||||
}else{
|
||||
} else {
|
||||
return $this->failUnauthorized('Invalid request', 403);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
private function obtenerDatosFormulario(&$pedidoEntity){
|
||||
|
||||
private function obtenerDatosFormulario(&$pedidoEntity)
|
||||
{
|
||||
|
||||
$datos = $this->model->obtenerDatosForm($pedidoEntity->id);
|
||||
|
||||
$pedidoEntity->estadoText = lang('Pedidos.' . $pedidoEntity->estado);
|
||||
|
||||
if(count($datos) > 0){
|
||||
if (count($datos) > 0) {
|
||||
$pedidoEntity->cliente = $datos[0]->cliente;
|
||||
$pedidoEntity->cliente_id = $datos[0]->cliente_id;
|
||||
$pedidoEntity->comercial = $datos[0]->comercial;
|
||||
@ -602,8 +609,8 @@ class Pedido extends \App\Controllers\BaseResourceController
|
||||
$pedidoEntity->fecha_entrega_externo_text = $pedidoEntity->fecha_entrega_externo ? date('d/m/Y', strtotime($pedidoEntity->fecha_entrega_externo)) : '';
|
||||
|
||||
$userModel = model('App\Models\Usuarios\UserModel');
|
||||
$pedidoEntity->created_by = $userModel->getFullName($pedidoEntity->user_created_id);
|
||||
$pedidoEntity->updated_by = $userModel->getFullName($pedidoEntity->user_updated_id);
|
||||
$pedidoEntity->created_by = $userModel->getFullName($pedidoEntity->user_created_id);
|
||||
$pedidoEntity->updated_by = $userModel->getFullName($pedidoEntity->user_updated_id);
|
||||
$pedidoEntity->created_at_footer = $pedidoEntity->created_at ? date(' H:i d/m/Y', strtotime($pedidoEntity->created_at)) : '';
|
||||
$pedidoEntity->updated_at_footer = $pedidoEntity->updated_at ? date(' H:i d/m/Y', strtotime($pedidoEntity->updated_at)) : '';
|
||||
}
|
||||
@ -613,21 +620,36 @@ class Pedido extends \App\Controllers\BaseResourceController
|
||||
// $xml_service = new PedidoXMLService($this->model);
|
||||
return $this->respond($data);
|
||||
}
|
||||
|
||||
|
||||
public function to_produccion($pedido_id)
|
||||
{
|
||||
$serviceProduction = service('production');
|
||||
$pedido = $this->model->find($pedido_id);
|
||||
$cliente = $pedido->presupuesto()->cliente_id;
|
||||
$serviceProduction->setPedido($pedido);
|
||||
if($pedido->orden_trabajo()){
|
||||
return $this->response->setJSON(["status"=>false,"data"=>$pedido->orden_trabajo(),"message" => "Ya existe una orden de trabajo para este pedido"]);
|
||||
if ($pedido->orden_trabajo()) {
|
||||
return $this->response->setJSON(["status" => false, "data" => $pedido->orden_trabajo(), "message" => "Ya existe una orden de trabajo para este pedido"]);
|
||||
|
||||
}else{
|
||||
} else {
|
||||
$r = $serviceProduction->createOrdenTrabajo();
|
||||
$this->model->set(['estado' => 'produccion'])->where('id', $pedido_id)->update();
|
||||
return $this->response->setJSON(["status"=>true, "data"=>$r,"message" => "Orden trabajo creada correctamente"]);
|
||||
$clienteModel = model('App\Models\Clientes\ClienteModel');
|
||||
$cliente = $clienteModel->find($cliente);
|
||||
if ($cliente) {
|
||||
if ($cliente->tirada_flexible == 1) {
|
||||
$ejemplares_tirada_flexible = intval($pedido->total_tirada * 0.05);
|
||||
$comentario = lang('OrdenTrabajo.tiradaFlexible', [
|
||||
'unidades' => $ejemplares_tirada_flexible
|
||||
]) . "\n" . trim($cliente->comentarios_tirada_flexible);
|
||||
|
||||
$serviceProduction->init($r->id)->updateOrdenTrabajoData([
|
||||
'name' => 'comment_logistica',
|
||||
'comment_logistica' => $comentario
|
||||
]);
|
||||
}
|
||||
}
|
||||
return $this->response->setJSON(["status" => true, "data" => $r, "message" => "Orden trabajo creada correctamente"]);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
2
ci4/app/Controllers/Presupuestos/Buscador.php
Normal file → Executable file
2
ci4/app/Controllers/Presupuestos/Buscador.php
Normal file → Executable file
@ -36,6 +36,8 @@ class Buscador extends \App\Controllers\BaseResourceController
|
||||
|
||||
protected $indexRoute = 'buscadorPresupuestosList';
|
||||
|
||||
protected $deletePermission = 'presupuesto.delete';
|
||||
|
||||
|
||||
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
|
||||
{
|
||||
|
||||
9
ci4/app/Controllers/Presupuestos/Importadorpresupuestos.php
Normal file → Executable file
9
ci4/app/Controllers/Presupuestos/Importadorpresupuestos.php
Normal file → Executable file
@ -4,6 +4,7 @@ namespace App\Controllers\Presupuestos;
|
||||
|
||||
use App\Models\Presupuestos\ImportadorModel;
|
||||
use App\Models\Clientes\ClienteModel;
|
||||
use App\Services\PresupuestoService;
|
||||
use stdClass;
|
||||
|
||||
class Importadorpresupuestos extends \App\Controllers\BaseResourceController
|
||||
@ -484,6 +485,14 @@ class Importadorpresupuestos extends \App\Controllers\BaseResourceController
|
||||
$isColor = true;
|
||||
}
|
||||
|
||||
// se recalcula isColor y isHq
|
||||
[$isColor, $isHq] = PresupuestoService::getCalidad(
|
||||
'admin',
|
||||
null,
|
||||
$isColor,
|
||||
$isHq,
|
||||
intval($this->request->getPost('tirada') ?? 0));
|
||||
|
||||
$tapaCubierta = model('App\Models\Configuracion\TipoPresupuestoModel')->
|
||||
select("is_tapa_dura")->where('id', $tipo_presupuesto_id)->first();
|
||||
$tapaCubierta = $tapaCubierta->is_tapa_dura == 0 ? "tapaBlanda" : "tapaDura";
|
||||
|
||||
334
ci4/app/Controllers/Presupuestos/Presupuestoadmin.php
Normal file → Executable file
334
ci4/app/Controllers/Presupuestos/Presupuestoadmin.php
Normal file → Executable file
@ -130,11 +130,10 @@ class Presupuestoadmin extends \App\Controllers\BaseResourceController
|
||||
$POD = model('App\Models\Configuracion\ConfigVariableModel')->getVariable('POD')->value;
|
||||
$ancho = 0;
|
||||
$alto = 0;
|
||||
if(isset($sanitizedData['papel_formato_personalizado']) && $sanitizedData['papel_formato_personalizado'] == '1'){
|
||||
if (isset($sanitizedData['papel_formato_personalizado']) && $sanitizedData['papel_formato_personalizado'] == '1') {
|
||||
$ancho = $sanitizedData['papel_formato_ancho'];
|
||||
$alto = $sanitizedData['papel_formato_alto'];
|
||||
}
|
||||
else{
|
||||
} else {
|
||||
$papelFormatoModel = new PapelFormatoModel();
|
||||
$papelFormato = $papelFormatoModel->find($sanitizedData['papel_formato_id']);
|
||||
$ancho = $papelFormato->ancho;
|
||||
@ -152,7 +151,7 @@ class Presupuestoadmin extends \App\Controllers\BaseResourceController
|
||||
]);
|
||||
|
||||
$model = new PresupuestoEncuadernacionesModel();
|
||||
foreach($servDefectoEnc as $servicio){
|
||||
foreach ($servDefectoEnc as $servicio) {
|
||||
|
||||
$data = [
|
||||
'presupuesto_id' => $id,
|
||||
@ -202,6 +201,8 @@ class Presupuestoadmin extends \App\Controllers\BaseResourceController
|
||||
$this->viewData['pais_default_id'] = model('App\Models\Configuracion\ConfigVariableModel')->getVariable('id_pais_defecto')->value;
|
||||
$this->viewData['pais_default'] = model('App\Models\Configuracion\PaisModel')->find($this->viewData['pais_default_id'])->nombre;
|
||||
|
||||
$this->viewData['no_envio_base'] = 0;
|
||||
|
||||
$this->viewData['formAction'] = route_to('createPresupuestoAdmin', $tipo_impresion_id);
|
||||
|
||||
$this->viewData = array_merge($this->viewData, $this->getStringsFromTipoImpresion($tipo_impresion_id));
|
||||
@ -236,12 +237,14 @@ class Presupuestoadmin extends \App\Controllers\BaseResourceController
|
||||
$postData = $this->request->getPost();
|
||||
|
||||
$postData['updated_at'] = gmdate('Y-m-d H:m:s', time());
|
||||
|
||||
|
||||
$sanitizedData = $this->sanitized($postData, $nullIfEmpty);
|
||||
$sanitizedData['user_updated_id'] = auth()->user()->id;
|
||||
|
||||
if(isset($sanitizedData['total_aceptado_revisado']) && $sanitizedData['total_aceptado_revisado'] != 0
|
||||
&& $sanitizedData['total_aceptado_revisado'] != null && $sanitizedData['total_aceptado_revisado'] != ""){
|
||||
if (
|
||||
isset($sanitizedData['total_aceptado_revisado']) && $sanitizedData['total_aceptado_revisado'] != 0
|
||||
&& $sanitizedData['total_aceptado_revisado'] != null && $sanitizedData['total_aceptado_revisado'] != ""
|
||||
) {
|
||||
$sanitizedData['aprobado_at'] = $sanitizedData['updated_at'];
|
||||
$sanitizedData['aprobado_user_id'] = $sanitizedData['user_updated_id'];
|
||||
}
|
||||
@ -367,9 +370,9 @@ class Presupuestoadmin extends \App\Controllers\BaseResourceController
|
||||
}
|
||||
|
||||
// modificar los datos del pedido y de la factura si no está la factura validada
|
||||
if ($presupuestoEntity->estado_id == 2){
|
||||
if ($presupuestoEntity->estado_id == 2) {
|
||||
$facturaModel = model('App\Models\Facturas\FacturaModel');
|
||||
if(!$facturaModel->presupuestoHasFacturaValidada($id)){
|
||||
if (!$facturaModel->presupuestoHasFacturaValidada($id)) {
|
||||
// se actualiza primero el pedido
|
||||
$pedidoModel = model('App\Models\Pedidos\PedidoLineaModel');
|
||||
$pedidoLineaId = $pedidoModel->where('presupuesto_id', $id)->first()->id;
|
||||
@ -382,6 +385,16 @@ class Presupuestoadmin extends \App\Controllers\BaseResourceController
|
||||
'descripcion' => $linea_pedido->concepto
|
||||
]);
|
||||
|
||||
// se actualiza el totalizador del pedido
|
||||
$total_tirada = $pedidoModel
|
||||
->selectSum('cantidad')
|
||||
->where('pedido_id', $idPedido)
|
||||
->first()->cantidad;
|
||||
$pedidoModel = model('App\Models\Pedidos\PedidoModel');
|
||||
$pedidoModel->update($idPedido, [
|
||||
'total_tirada' => $total_tirada
|
||||
]);
|
||||
|
||||
// se actualiza la factura
|
||||
$linea_pedido = $this->model->generarLineaPedido($id, true, $idPedido)[0];
|
||||
$facturaLineaModel = model('App\Models\Facturas\FacturaLineaModel');
|
||||
@ -424,6 +437,10 @@ class Presupuestoadmin extends \App\Controllers\BaseResourceController
|
||||
|
||||
$this->viewData['POD'] = $this->getPOD();
|
||||
|
||||
$this->viewData['no_envio_base'] = model('App\Models\Clientes\ClienteModel')->where('id', $presupuestoEntity->cliente_id)->first();
|
||||
if ($this->viewData['no_envio_base'])
|
||||
$this->viewData['no_envio_base'] = $this->viewData['no_envio_base']->no_envio_base;
|
||||
|
||||
$this->viewData['serviciosAutomaticos'] = [
|
||||
'solapas_cubierta' => model('App\Models\Configuracion\ConfigVariableModel')->getVariable('servicio_solapas_cubierta')->value,
|
||||
'solapas_sobrecubierta' => model('App\Models\Configuracion\ConfigVariableModel')->getVariable('servicio_solapas_sobrecubierta')->value,
|
||||
@ -431,7 +448,9 @@ class Presupuestoadmin extends \App\Controllers\BaseResourceController
|
||||
'retractilado' => model('App\Models\Configuracion\ConfigVariableModel')->getVariable('id_servicio_retractilado')->value,
|
||||
'retractilado5' => model('App\Models\Configuracion\ConfigVariableModel')->getVariable('id_servicio_retractilado5')->value,
|
||||
'ferro' => model('App\Models\Configuracion\ConfigVariableModel')->getVariable('id_servicio_ferro')->value,
|
||||
'ferro_2' => model('App\Models\Configuracion\ConfigVariableModel')->getVariable('id_servicio_ferro_2')->value,
|
||||
'prototipo' => model('App\Models\Configuracion\ConfigVariableModel')->getVariable('id_servicio_prototipo')->value,
|
||||
'prototipo_2' => model('App\Models\Configuracion\ConfigVariableModel')->getVariable('id_servicio_prototipo_2')->value,
|
||||
'solapas_grandes_cubierta' => model('App\Models\Configuracion\ConfigVariableModel')->getVariable('id_servicio_plegado_exceso_solapas_cubierta')->value,
|
||||
'solapas_grandes_sobrecubierta' => model('App\Models\Configuracion\ConfigVariableModel')->getVariable('id_servicio_plegado_exceso_solapas_sobrecubierta')->value,
|
||||
'solapas_grandes_faja' => model('App\Models\Configuracion\ConfigVariableModel')->getVariable('id_servicio_plegado_exceso_solapas_faja')->value,
|
||||
@ -449,11 +468,11 @@ class Presupuestoadmin extends \App\Controllers\BaseResourceController
|
||||
|
||||
$modelPedidoLinea = new \App\Models\Pedidos\PedidoLineaModel();
|
||||
$linea = $modelPedidoLinea->where('presupuesto_id', $id)->first();
|
||||
if($linea){
|
||||
if ($linea) {
|
||||
$this->viewData['pedido_id'] = $linea->pedido_id;
|
||||
$modelOrden = new \App\Models\OrdenTrabajo\OrdenTrabajoModel();
|
||||
$orden = $modelOrden->where('pedido_id', $linea->pedido_id)->first();
|
||||
if($orden){
|
||||
if ($orden) {
|
||||
$this->viewData['orden_id'] = $orden->id;
|
||||
}
|
||||
}
|
||||
@ -548,7 +567,6 @@ class Presupuestoadmin extends \App\Controllers\BaseResourceController
|
||||
$modelCliente = new ClienteModel();
|
||||
$modelPapelGenerico = new PapelGenericoModel();
|
||||
|
||||
|
||||
$presupuesto = $this->model->find($id);
|
||||
$data = [];
|
||||
if ($presupuesto) {
|
||||
@ -613,7 +631,9 @@ class Presupuestoadmin extends \App\Controllers\BaseResourceController
|
||||
$data['datosLibro']['acabadoFaja']['text'] = $modelAcabado->find($presupuesto->acabado_faja_id)->nombre;
|
||||
}
|
||||
$data['datosLibro']['prototipo'] = $presupuesto->prototipo;
|
||||
$data['datosLibro']['prototipo2'] = $this->hasPrototipo2($id);
|
||||
$data['datosLibro']['ferro'] = $presupuesto->ferro;
|
||||
$data['datosLibro']['ferro2'] = $this->hasFerro2($id);
|
||||
$data['datosLibro']['ferroDigital'] = $presupuesto->ferro_digital;
|
||||
$data['datosLibro']['marcapaginas'] = $presupuesto->marcapaginas;
|
||||
$data['datosLibro']['retractilado'] = $presupuesto->retractilado;
|
||||
@ -623,7 +643,7 @@ class Presupuestoadmin extends \App\Controllers\BaseResourceController
|
||||
$data['comparador']['json_data'] = json_decode($presupuesto->comparador_json_data, true);
|
||||
if ($data['comparador']['json_data'] != null) {
|
||||
foreach ($data['comparador']['json_data'] as &$item) {
|
||||
if(intval($item['papel_id'])>0)
|
||||
if (intval($item['papel_id']) > 0)
|
||||
$item['papel_nombre'] = $modelPapelGenerico->getNombre($item['papel_id'])['nombre'];
|
||||
}
|
||||
}
|
||||
@ -642,12 +662,27 @@ class Presupuestoadmin extends \App\Controllers\BaseResourceController
|
||||
$data['direcciones'] = $this->obtenerDireccionesEnvio($id, $presupuesto->cliente_id);
|
||||
}
|
||||
|
||||
$data['direccionesFP'] = [];
|
||||
$direccionFP1 = $this->obtenerDireccionesEnvio($id, $presupuesto->cliente_id, true, 1);
|
||||
if(count($direccionFP1) > 0){
|
||||
$data['direccionesFP']['fp1'] = $direccionFP1;
|
||||
} else {
|
||||
$data['direccionesFP']['fp1'] = [];
|
||||
}
|
||||
$direccionFP2 = $this->obtenerDireccionesEnvio($id, $presupuesto->cliente_id, true, 2);
|
||||
if(count($direccionFP2) > 0){
|
||||
$data['direccionesFP']['fp2'] = $direccionFP2;
|
||||
} else {
|
||||
$data['direccionesFP']['fp2'] = [];
|
||||
}
|
||||
$data['direccionesFP']['checkboxes'] = json_decode($presupuesto->getDireccionFPChecks());
|
||||
|
||||
$data['comentarios_cliente'] = $presupuesto->comentarios_cliente;
|
||||
$data['comentarios_safekat'] = $presupuesto->comentarios_safekat;
|
||||
$data['comentarios_pdf'] = $presupuesto->comentarios_pdf;
|
||||
$data['comentarios_presupuesto'] = $presupuesto->comentarios_presupuesto;
|
||||
$data['comentarios_produccion'] = $presupuesto->comentarios_produccion;
|
||||
|
||||
|
||||
|
||||
$data['tiradasAlternativas'] = json_decode($presupuesto->tirada_alternativa_json_data);
|
||||
|
||||
@ -678,9 +713,9 @@ class Presupuestoadmin extends \App\Controllers\BaseResourceController
|
||||
$data['resumen']['total_factor_ponderado'] = is_numeric($presupuesto->total_factor_ponderado) ? $presupuesto->total_factor_ponderado : 0;
|
||||
|
||||
$data['total_aceptado_revisado'] = $presupuesto->total_aceptado_revisado;
|
||||
$data['aprobado_by_at'] = ($presupuesto->aprobado_user_id != null)?
|
||||
model('App\Models\Usuarios\UserModel')->getFullName($presupuesto->aprobado_user_id) . ', '
|
||||
. date('d/m/Y H:i:s', strtotime($presupuesto->aprobado_at)):'';
|
||||
$data['aprobado_by_at'] = ($presupuesto->aprobado_user_id != null) ?
|
||||
model('App\Models\Usuarios\UserModel')->getFullName($presupuesto->aprobado_user_id) . ', '
|
||||
. date('d/m/Y H:i:s', strtotime($presupuesto->aprobado_at)) : '';
|
||||
|
||||
|
||||
$data['resumen']['iva_reducido'] = $presupuesto->iva_reducido;
|
||||
@ -801,7 +836,7 @@ class Presupuestoadmin extends \App\Controllers\BaseResourceController
|
||||
$paginas_color = $sobrecubierta['datosPedido']['paginas'] ?? 0;
|
||||
$tipo_impresion_id = $sobrecubierta['tipo_impresion_id'];
|
||||
$faja = intval($sobrecubierta['faja'] ?? 0);
|
||||
$uso = $faja==1? 'faja' : $sobrecubierta['uso'];
|
||||
$uso = $faja == 1 ? 'faja' : $sobrecubierta['uso'];
|
||||
|
||||
|
||||
$data = array(
|
||||
@ -983,6 +1018,8 @@ class Presupuestoadmin extends \App\Controllers\BaseResourceController
|
||||
|
||||
$reqData = $this->request->getPost();
|
||||
|
||||
$calcular_merma = $reqData['calcular_merma'] ?? 0;
|
||||
|
||||
$type = $reqData['type'] ?? null;
|
||||
// por defecto, se deja cosido tapa blanda por ahora JJO
|
||||
$tipo_impresion_id = $reqData['tipo_impresion_id'] ?? 4;
|
||||
@ -1061,8 +1098,29 @@ class Presupuestoadmin extends \App\Controllers\BaseResourceController
|
||||
'a_favor_fibra' => $a_favor_fibra
|
||||
);
|
||||
|
||||
|
||||
$resourceData = PresupuestoService::obtenerComparadorPlana($input_data);
|
||||
|
||||
if (
|
||||
$calcular_merma == 1 && count($resourceData) > 0 &&
|
||||
count($resourceData[0]['fields']) > 0 && $resourceData[0]['fields']['num_formas'] > 0
|
||||
) {
|
||||
|
||||
usort($resourceData, function ($a, $b) {
|
||||
return $b['fields']['total_impresion'] <=> $a['fields']['total_impresion'];
|
||||
});
|
||||
|
||||
$num_formas = [];
|
||||
$formas_linea = $datosPedido->isCosido ? intval($resourceData[0]['fields']['num_formas']['value']) / 2 :
|
||||
intval($resourceData[0]['fields']['num_formas']['value']);
|
||||
array_push($num_formas, $formas_linea);
|
||||
|
||||
$POD = $this->getPOD();
|
||||
$datosPedido->merma = PresupuestoService::calcular_merma($datosPedido->tirada, $POD, $num_formas);
|
||||
|
||||
$resourceData = PresupuestoService::obtenerComparadorPlana($input_data);
|
||||
}
|
||||
|
||||
} else if ($type == 'interior_rot') {
|
||||
|
||||
$paginas = (object) array(
|
||||
@ -1095,6 +1153,26 @@ class Presupuestoadmin extends \App\Controllers\BaseResourceController
|
||||
|
||||
$resourceData = PresupuestoService::obtenerComparadorRotativa($input_data);
|
||||
|
||||
if (
|
||||
$calcular_merma == 1 && count($resourceData) > 0 &&
|
||||
count($resourceData[0]['fields']) > 0 && $resourceData[0]['fields']['num_formas'] > 0
|
||||
) {
|
||||
|
||||
usort($resourceData, function ($a, $b) {
|
||||
return $b['fields']['total_impresion'] <=> $a['fields']['total_impresion'];
|
||||
});
|
||||
|
||||
$num_formas = [];
|
||||
$formas_linea = $datosPedido->isCosido ? intval($resourceData[0]['fields']['num_formas']['value']) / 2 :
|
||||
intval($resourceData[0]['fields']['num_formas']['value']);
|
||||
array_push($num_formas, $formas_linea);
|
||||
|
||||
$POD = $this->getPOD();
|
||||
$datosPedido->merma = PresupuestoService::calcular_merma($datosPedido->tirada, $POD, $num_formas);
|
||||
|
||||
$resourceData = PresupuestoService::obtenerComparadorRotativa($input_data);
|
||||
}
|
||||
|
||||
} else if ($type == 'cubierta' || $type == 'sobrecubierta' || $type == 'faja') {
|
||||
|
||||
$datosPedido->solapas = $reqData['solapas'];
|
||||
@ -1160,7 +1238,7 @@ class Presupuestoadmin extends \App\Controllers\BaseResourceController
|
||||
return $this->respond($data);
|
||||
} else if ($tipo == 'duplicar') {
|
||||
$presupuesto_id = $reqData['presupuesto_id'] ?? -1;
|
||||
$result = $this->duplicarPresupuesto($presupuesto_id);
|
||||
$result = PresupuestoService::duplicarPresupuesto($presupuesto_id);
|
||||
$newTokenHash = csrf_hash();
|
||||
$csrfTokenName = csrf_token();
|
||||
if ($result['success']) {
|
||||
@ -1216,12 +1294,12 @@ class Presupuestoadmin extends \App\Controllers\BaseResourceController
|
||||
$cubierta = false;
|
||||
if ($uso == 'cubierta') {
|
||||
$cubierta = true;
|
||||
$anchoLibro = 2* $ancho + 2 * $solapas + $lomo;
|
||||
$anchoLibro = 2 * $ancho + 2 * $solapas + $lomo;
|
||||
}
|
||||
$sobrecubierta = false;
|
||||
if ($uso == 'sobrecubierta') {
|
||||
$sobrecubierta = true;
|
||||
$anchoLibro = 2* $ancho + 2 * $solapas + $lomo;
|
||||
$anchoLibro = 2 * $ancho + 2 * $solapas + $lomo;
|
||||
}
|
||||
$guardas = false;
|
||||
if ($uso == 'guardas') {
|
||||
@ -1245,7 +1323,8 @@ class Presupuestoadmin extends \App\Controllers\BaseResourceController
|
||||
$isPOD,
|
||||
$anchoLibro,
|
||||
$alto,
|
||||
$tirada);
|
||||
$tirada
|
||||
);
|
||||
if ($this->request->getGet("q")) {
|
||||
$query->groupStart()
|
||||
->orLike("t1.nombre", $this->request->getGet("q"))
|
||||
@ -1284,12 +1363,12 @@ class Presupuestoadmin extends \App\Controllers\BaseResourceController
|
||||
$cubierta = false;
|
||||
if ($uso == 'cubierta') {
|
||||
$cubierta = true;
|
||||
$anchoLibro = 2* $ancho + 2 * $solapas + $lomo;
|
||||
$anchoLibro = 2 * $ancho + 2 * $solapas + $lomo;
|
||||
}
|
||||
$sobrecubierta = false;
|
||||
if ($uso == 'sobrecubierta') {
|
||||
$sobrecubierta = true;
|
||||
$anchoLibro = 2* $ancho + 2 * $solapas + $lomo;
|
||||
$anchoLibro = 2 * $ancho + 2 * $solapas + $lomo;
|
||||
}
|
||||
$guardas = false;
|
||||
if ($uso == 'guardas') {
|
||||
@ -1301,7 +1380,8 @@ class Presupuestoadmin extends \App\Controllers\BaseResourceController
|
||||
}
|
||||
|
||||
$model = model('App\Models\Configuracion\PapelGenericoModel');
|
||||
$query = $model->getGramajeForComparador($tipo,
|
||||
$query = $model->getGramajeForComparador(
|
||||
$tipo,
|
||||
$papel_generico_id,
|
||||
$cubierta,
|
||||
$sobrecubierta,
|
||||
@ -1311,7 +1391,8 @@ class Presupuestoadmin extends \App\Controllers\BaseResourceController
|
||||
$isPOD,
|
||||
$anchoLibro,
|
||||
$alto,
|
||||
$tirada);
|
||||
$tirada
|
||||
);
|
||||
if ($this->request->getGet("q")) {
|
||||
$query->groupStart()
|
||||
->orLike("t2.gramaje", $this->request->getGet("q"))
|
||||
@ -1544,81 +1625,6 @@ class Presupuestoadmin extends \App\Controllers\BaseResourceController
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Duplica un presupuesto dado por su ID.
|
||||
*
|
||||
* Esta función duplica un presupuesto y todas sus entidades relacionadas como acabados, encuadernaciones, manipulados,
|
||||
* preimpresiones, direcciones y lineas. El presupuesto duplicado se marca como tal y a su título se le añade
|
||||
* una cadena 'duplicado'. La función devuelve un array con un estado de éxito y el ID del nuevo presupuesto.
|
||||
*
|
||||
* @param int $id El ID del presupuesto a duplicar.
|
||||
* @return array Un array asociativo que contiene una clave 'success' que indica el estado de éxito de la operación,
|
||||
* y una clave 'id' que contiene el ID del nuevo presupuesto si la operación fue exitosa.
|
||||
* Si ocurre una excepción, la clave 'success' será false y una clave 'message' contendrá el mensaje de la excepción.
|
||||
* @throws \Exception Si ocurre un error durante la operación.
|
||||
*/
|
||||
private function duplicarPresupuesto($id)
|
||||
{
|
||||
|
||||
try {
|
||||
|
||||
$presupuesto = $this->model->find($id);
|
||||
$presupuesto->titulo = $presupuesto->titulo . ' - ' . lang('Presupuestos.duplicado');
|
||||
$presupuesto->is_duplicado = 1;
|
||||
$presupuesto->estado_id = 1;
|
||||
$new_id = $this->model->insert($presupuesto);
|
||||
|
||||
$presupuestoAcabadosModel = model('App\Models\Presupuestos\PresupuestoAcabadosModel');
|
||||
foreach ($presupuestoAcabadosModel->where('presupuesto_id', $presupuesto->id)->findAll() as $acabado) {
|
||||
$acabado->presupuesto_id = $new_id;
|
||||
$presupuestoAcabadosModel->insert($acabado);
|
||||
}
|
||||
|
||||
$presupuestoEncuadernacionesModel = model('App\Models\Presupuestos\PresupuestoEncuadernacionesModel');
|
||||
foreach ($presupuestoEncuadernacionesModel->where('presupuesto_id', $presupuesto->id)->findAll() as $encuadernacion) {
|
||||
$encuadernacion->presupuesto_id = $new_id;
|
||||
$presupuestoEncuadernacionesModel->insert($encuadernacion);
|
||||
}
|
||||
|
||||
$presupuestoManipuladosModel = model('App\Models\Presupuestos\PresupuestoManipuladosModel');
|
||||
foreach ($presupuestoManipuladosModel->where('presupuesto_id', $presupuesto->id)->findAll() as $manipulado) {
|
||||
$manipulado->presupuesto_id = $new_id;
|
||||
$presupuestoManipuladosModel->insert($manipulado);
|
||||
}
|
||||
|
||||
$presupuestoPreimpresionesModel = model('App\Models\Presupuestos\PresupuestoPreimpresionesModel');
|
||||
foreach ($presupuestoPreimpresionesModel->where('presupuesto_id', $presupuesto->id)->findAll() as $preimpresion) {
|
||||
$preimpresion->presupuesto_id = $new_id;
|
||||
$presupuestoPreimpresionesModel->insert($preimpresion);
|
||||
}
|
||||
|
||||
$presupuestoServiciosExtraModel = model('App\Models\Presupuestos\PresupuestoServiciosExtraModel');
|
||||
foreach ($presupuestoServiciosExtraModel->where('presupuesto_id', $presupuesto->id)->findAll() as $servicioExtra) {
|
||||
$servicioExtra->presupuesto_id = $new_id;
|
||||
$presupuestoServiciosExtraModel->insert($servicioExtra);
|
||||
}
|
||||
|
||||
$presupuestoDireccionesModel = model('App\Models\Presupuestos\PresupuestoDireccionesModel');
|
||||
foreach ($presupuestoDireccionesModel->where('presupuesto_id', $presupuesto->id)->findAll() as $direccion) {
|
||||
$direccion->presupuesto_id = $new_id;
|
||||
$presupuestoDireccionesModel->insert($direccion);
|
||||
}
|
||||
|
||||
$presupuestoLineaModel = model('App\Models\Presupuestos\PresupuestoLineaModel');
|
||||
$presupuestoLineaModel->duplicateLineasPresupuesto($presupuesto->id, $new_id);
|
||||
|
||||
return [
|
||||
'success' => true,
|
||||
'id' => $new_id
|
||||
];
|
||||
|
||||
} catch (\Exception $e) {
|
||||
return [
|
||||
'success' => false,
|
||||
'message' => $e->getMessage()
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
public function allItemsSelect()
|
||||
{
|
||||
@ -1757,10 +1763,11 @@ class Presupuestoadmin extends \App\Controllers\BaseResourceController
|
||||
$result = DataTable::of($q)
|
||||
->edit(
|
||||
'fecha',
|
||||
fn($q) => $q->fecha?Time::createFromFormat("Y-m-d H:i:s", $q->fecha)->format("d/m/Y"):""
|
||||
fn($q) => $q->fecha ? Time::createFromFormat("Y-m-d H:i:s", $q->fecha)->format("d/m/Y") : ""
|
||||
)
|
||||
->edit(
|
||||
'estado', fn($q) => match ($q->estado) {
|
||||
'estado',
|
||||
fn($q) => match ($q->estado) {
|
||||
"1" => lang('Presupuestos.borrador'),
|
||||
"2" => lang('Presupuestos.confirmado'),
|
||||
default => '--'
|
||||
@ -1771,13 +1778,14 @@ class Presupuestoadmin extends \App\Controllers\BaseResourceController
|
||||
<a href="javascript:void(0);"><i class="ti ti-eye ti-sm btn-edit mx-2" data-id="' . $q->id . '"></i></a>
|
||||
</div>
|
||||
';
|
||||
|
||||
|
||||
});
|
||||
|
||||
return $result->toJson(returnAsObject: true) ;
|
||||
|
||||
return $result->toJson(returnAsObject: true);
|
||||
}
|
||||
|
||||
public function obtenerTotalPresupuestosCliente($cliente_id){
|
||||
public function obtenerTotalPresupuestosCliente($cliente_id)
|
||||
{
|
||||
|
||||
$error = false;
|
||||
$result = [
|
||||
@ -1788,17 +1796,17 @@ class Presupuestoadmin extends \App\Controllers\BaseResourceController
|
||||
->where('presupuestos.cliente_id', $cliente_id)
|
||||
->select('SUM(presupuestos.total_aceptado) as total')
|
||||
->groupBy('presupuestos.cliente_id')->get()->getResultObject();
|
||||
if(count($data) > 0){
|
||||
if (count($data) > 0) {
|
||||
$result['total_impresion'] = round(floatval($data[0]->total), 2);
|
||||
}
|
||||
else{
|
||||
} else {
|
||||
$error = true;
|
||||
}
|
||||
$result['total'] = $result['total_impresion'] + $result['total_maquetacion'];
|
||||
return $this->respond(['status' => $error?'error':'success', 'totales' => $result]);
|
||||
return $this->respond(['status' => $error ? 'error' : 'success', 'totales' => $result]);
|
||||
}
|
||||
|
||||
public function obtenerTotalPedidosCliente($cliente_id){
|
||||
public function obtenerTotalPedidosCliente($cliente_id)
|
||||
{
|
||||
|
||||
$error = false;
|
||||
$result = [
|
||||
@ -1811,14 +1819,70 @@ class Presupuestoadmin extends \App\Controllers\BaseResourceController
|
||||
->join('pedidos_linea', 'pedidos_linea.pedido_id = pedidos.id')
|
||||
->join('presupuestos', 'presupuestos.id = pedidos_linea.presupuesto_id')
|
||||
->groupBy('presupuestos.cliente_id')->get()->getResultObject();
|
||||
if(count($data) > 0){
|
||||
if (count($data) > 0) {
|
||||
$result['total_impresion'] = round(floatval($data[0]->total), 2);
|
||||
}
|
||||
else{
|
||||
} else {
|
||||
$error = true;
|
||||
}
|
||||
$result['total'] = $result['total_impresion'] + $result['total_maquetacion'];
|
||||
return $this->respond(['status' => $error?'error':'success', 'totales' => $result]);
|
||||
return $this->respond(['status' => $error ? 'error' : 'success', 'totales' => $result]);
|
||||
}
|
||||
|
||||
|
||||
public function hasFiles()
|
||||
{
|
||||
|
||||
if ($this->request->isAJAX()) {
|
||||
$id = $this->request->getGet('id');
|
||||
$presupuesto = $this->model->find($id);
|
||||
if (!$presupuesto) {
|
||||
return $this->respond([
|
||||
'status' => 'error',
|
||||
'message' => lang('Presupuestos.presupuestoNotFound'),
|
||||
]);
|
||||
}
|
||||
|
||||
$files = $presupuesto->files() ?? [];
|
||||
if (count($files) == 0) {
|
||||
return $this->respond([
|
||||
'status' => 'success',
|
||||
'hasFiles' => false,
|
||||
]);
|
||||
} else {
|
||||
return $this->respond([
|
||||
'status' => 'success',
|
||||
'hasFiles' => true,
|
||||
]);
|
||||
}
|
||||
} else {
|
||||
return $this->failUnauthorized('Invalid request', 403);
|
||||
}
|
||||
}
|
||||
|
||||
public function checkLomo()
|
||||
{
|
||||
if ($this->request->isAJAX()) {
|
||||
$tipo_impresion_id = $this->request->getGet('tipo_impresion_id');
|
||||
$lomo = $this->request->getGet('lomo') ?? 0;
|
||||
$response = PresupuestoService::check_lomo_interior($tipo_impresion_id, $lomo);
|
||||
return $this->respond($response);
|
||||
} else {
|
||||
return $this->failUnauthorized('Invalid request', 403);
|
||||
}
|
||||
}
|
||||
|
||||
public function reprintPresupuesto()
|
||||
{
|
||||
|
||||
if ($this->request->isAJAX()) {
|
||||
$id = $this->request->getPost('id');
|
||||
$duplicateFiles = $this->request->getPost('duplicateFiles') ?? false;
|
||||
$response = PresupuestoService::duplicarPresupuesto($id, true, $duplicateFiles);
|
||||
return $this->respond($response);
|
||||
|
||||
} else {
|
||||
return $this->failUnauthorized('Invalid request', 403);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -1848,7 +1912,7 @@ class Presupuestoadmin extends \App\Controllers\BaseResourceController
|
||||
$modelPapel = new PapelGenericoModel();
|
||||
foreach ($lineas as $linea) {
|
||||
$linea->papel_generico = (new PapelGenericoModel())->find($linea->papel_id)->nombre;
|
||||
if($linea->tipo == 'lp_faja'){
|
||||
if ($linea->tipo == 'lp_faja') {
|
||||
$linea->alto_faja = $presupuestoEntity->alto_faja_color;
|
||||
}
|
||||
}
|
||||
@ -1905,7 +1969,7 @@ class Presupuestoadmin extends \App\Controllers\BaseResourceController
|
||||
return PresupuestoService::checkLineasEnvios($direccionesEnvio);
|
||||
}
|
||||
|
||||
protected function obtenerDireccionesEnvio($id, $cliente_id)
|
||||
protected function obtenerDireccionesEnvio($id, $cliente_id, $is_fp = false, $num_fp = 0)
|
||||
{
|
||||
$model = model('App\Models\Presupuestos\PresupuestoDireccionesModel');
|
||||
$model_direcciones = model('App\Models\Clientes\ClienteDireccionesModel');
|
||||
@ -1913,8 +1977,38 @@ class Presupuestoadmin extends \App\Controllers\BaseResourceController
|
||||
->join('lg_proveedores', 'presupuesto_direcciones.proveedor_id = lg_proveedores.id')
|
||||
->join('lg_paises', 'presupuesto_direcciones.pais_id = lg_paises.id')
|
||||
->select('presupuesto_direcciones.*, lg_proveedores.nombre AS proveedor, lg_paises.nombre AS pais')
|
||||
->where('presupuesto_id', $id)->findAll();
|
||||
->where('presupuesto_id', $id)
|
||||
->where('is_ferro_prototipo', $is_fp);
|
||||
if ($is_fp) {
|
||||
$direcciones = $direcciones
|
||||
->where('num_ferro_prototipo', $num_fp);
|
||||
}
|
||||
|
||||
return $direcciones;
|
||||
|
||||
return $direcciones->findAll();
|
||||
}
|
||||
|
||||
protected function hasPrototipo2($presupuestoId){
|
||||
|
||||
$servicios = (new PresupuestoServiciosExtraModel())->getResource($presupuestoId)->get()->getResultObject();
|
||||
$id_servicio = model('App\Models\Configuracion\ConfigVariableModel')->getVariable('id_servicio_prototipo_2')->value;
|
||||
foreach ($servicios as $servicio) {
|
||||
if ($servicio->tarifa_extra_id == $id_servicio) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
protected function hasFerro2($presupuestoId)
|
||||
{
|
||||
$servicios = (new PresupuestoServiciosExtraModel())->getResource($presupuestoId)->get()->getResultObject();
|
||||
$id_servicio = model('App\Models\Configuracion\ConfigVariableModel')->getVariable('id_servicio_ferro_2')->value;
|
||||
foreach ($servicios as $servicio) {
|
||||
if ($servicio->tarifa_extra_id == $id_servicio) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@ -54,6 +54,8 @@ class Presupuestodirecciones extends \App\Controllers\BaseResourceController
|
||||
$proveedor = $reqData['proveedor'] ?? "";
|
||||
$proveedor_id = $reqData['proveedor_id'] ?? "";
|
||||
$entregaPieCalle = $reqData['entregaPieCalle'] ?? 0;
|
||||
$is_ferro_prototipo = $reqData['is_ferro_prototipo'] ?? 0;
|
||||
$num_ferro_prototipo = $reqData['num_ferro_prototipo'] ?? 0;
|
||||
|
||||
$data = [
|
||||
"presupuesto_id" => $presupuesto_id,
|
||||
@ -73,6 +75,8 @@ class Presupuestodirecciones extends \App\Controllers\BaseResourceController
|
||||
"proveedor" => $proveedor,
|
||||
"proveedor_id" => $proveedor_id,
|
||||
"entregaPieCalle" => $entregaPieCalle,
|
||||
"is_ferro_prototipo" => $is_ferro_prototipo,
|
||||
"num_ferro_prototipo" => $num_ferro_prototipo
|
||||
];
|
||||
$response = $this->model->insert($data);
|
||||
|
||||
|
||||
0
ci4/app/Controllers/Presupuestos/Presupuestotiradasalternativas.php
Normal file → Executable file
0
ci4/app/Controllers/Presupuestos/Presupuestotiradasalternativas.php
Normal file → Executable file
@ -1,35 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Controllers\Produccion;
|
||||
use App\Controllers\BaseController;
|
||||
|
||||
|
||||
class Ordenmaquina extends BaseController
|
||||
{
|
||||
function __construct()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
public function index()
|
||||
{
|
||||
echo 'Orden maquina';
|
||||
}
|
||||
|
||||
public function delete()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
public function add()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
public function edit()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@ -3,11 +3,16 @@
|
||||
namespace App\Controllers\Produccion;
|
||||
|
||||
use App\Controllers\BaseController;
|
||||
use App\Models\Compras\ProveedorModel;
|
||||
use App\Models\Configuracion\MaquinaModel;
|
||||
use App\Models\Configuracion\MaquinaOtTareaModel;
|
||||
use App\Models\OrdenTrabajo\OrdenTrabajoModel;
|
||||
use App\Models\OrdenTrabajo\OrdenTrabajoTarea;
|
||||
use App\Models\OrdenTrabajo\OrdenTrabajoUser;
|
||||
use App\Models\Presupuestos\PresupuestoModel;
|
||||
use App\Models\Usuarios\UserModel;
|
||||
use App\Services\EtiquetasTitulosService;
|
||||
use App\Services\ImpresoraEtiquetaService;
|
||||
use App\Services\ProductionService;
|
||||
use CodeIgniter\Files\File;
|
||||
use CodeIgniter\HTTP\RequestInterface;
|
||||
@ -19,6 +24,7 @@ use Exception;
|
||||
use Hermawan\DataTables\DataTable;
|
||||
use Psr\Log\LoggerInterface;
|
||||
|
||||
|
||||
class Ordentrabajo extends BaseController
|
||||
{
|
||||
protected $format = 'json';
|
||||
@ -27,6 +33,9 @@ class Ordentrabajo extends BaseController
|
||||
protected OrdenTrabajoModel $otModel;
|
||||
protected OrdenTrabajoUser $otUserModel;
|
||||
protected OrdenTrabajoTarea $otTarea;
|
||||
protected ProveedorModel $proveedorModel;
|
||||
protected MaquinaModel $maquinaModel;
|
||||
protected MaquinaOtTareaModel $maquinaOtTareaModel;
|
||||
protected UserModel $userModel;
|
||||
protected Validation $validation;
|
||||
protected static $viewPath = 'themes/vuexy/form/produccion/';
|
||||
@ -42,6 +51,9 @@ class Ordentrabajo extends BaseController
|
||||
$this->userModel = model(UserModel::class);
|
||||
$this->produccionService = new ProductionService();
|
||||
$this->otTarea = model(OrdenTrabajoTarea::class);
|
||||
$this->maquinaModel = model(MaquinaModel::class);
|
||||
$this->maquinaOtTareaModel = model(MaquinaOtTareaModel::class);
|
||||
$this->proveedorModel = model(ProveedorModel::class);
|
||||
$this->validation = service("validation");
|
||||
helper("time");
|
||||
parent::initController($request, $response, $logger);
|
||||
@ -67,6 +79,11 @@ class Ordentrabajo extends BaseController
|
||||
}
|
||||
|
||||
|
||||
public function find_tarea($orden_trabajo_tarea_id)
|
||||
{
|
||||
$t = $this->otTarea->find($orden_trabajo_tarea_id);
|
||||
return $this->response->setJSON($t);
|
||||
}
|
||||
public function get_orden_trabajo_summary($orden_trabajo_id)
|
||||
{
|
||||
try {
|
||||
@ -97,10 +114,24 @@ class Ordentrabajo extends BaseController
|
||||
public function update_orden_trabajo_tarea()
|
||||
{
|
||||
$bodyData = $this->request->getPost();
|
||||
// return $this->response->setJSON(["message" => lang("App.global_alert_save_success"), "data" => $bodyData]);
|
||||
$validated = $this->validation->run($bodyData, "orden_trabajo_tarea");
|
||||
if ($validated) {
|
||||
$tareaEntity = $this->otTarea->find($bodyData["orden_trabajo_tarea_id"]);
|
||||
$this->produccionService->init($tareaEntity->orden_trabajo_id);
|
||||
$r = $this->produccionService->updateOrdenTrabajoTarea($bodyData["orden_trabajo_tarea_id"], $bodyData);
|
||||
$tareaEntity = $this->otTarea->find($bodyData["orden_trabajo_tarea_id"]);
|
||||
return $this->response->setJSON(["message" => lang("App.global_alert_save_success"), "status" => $r, "data" => $tareaEntity]);
|
||||
} else {
|
||||
return $this->response->setJSON(["errors" => $this->validation->getErrors()])->setStatusCode(400);
|
||||
}
|
||||
}
|
||||
public function update_orden_trabajo_pliegos()
|
||||
{
|
||||
$bodyData = $this->request->getPost();
|
||||
// return $this->response->setJSON(["message" => lang("App.global_alert_save_success"), "data" => $bodyData]);
|
||||
$validated = $this->validation->run($bodyData, "orden_trabajo");
|
||||
if ($validated) {
|
||||
$r = $this->produccionService->init($bodyData["orden_trabajo_id"])->updateOrdenTrabajoTareaPliegos($bodyData);
|
||||
return $this->response->setJSON(["message" => lang("App.global_alert_save_success"), "status" => $r, "data" => $bodyData]);
|
||||
} else {
|
||||
return $this->response->setJSON(["errors" => $this->validation->getErrors()])->setStatusCode(400);
|
||||
@ -118,6 +149,32 @@ class Ordentrabajo extends BaseController
|
||||
return $this->response->setJSON(["errors" => $this->validation->getErrors()])->setStatusCode(400);
|
||||
}
|
||||
}
|
||||
public function update_presupuesto_tarea_proveedor()
|
||||
{
|
||||
$bodyData = $this->request->getPost();
|
||||
$validated = $this->validation->run($bodyData, "proveedor_tarea");
|
||||
if ($validated) {
|
||||
$validatedData = $this->validation->getValidated();
|
||||
$r = $this->produccionService->updateProveedorLinea($validatedData['orden_trabajo_tarea_id'], $validatedData['proveedor_id']);
|
||||
return $this->response->setJSON(["message" => lang("App.global_alert_save_success"), "status" => $r]);
|
||||
} else {
|
||||
return $this->response->setJSON(["errors" => $this->validation->getErrors()])->setStatusCode(400);
|
||||
}
|
||||
}
|
||||
public function reset_orden_trabajo_date()
|
||||
{
|
||||
$bodyData = $this->request->getPost();
|
||||
// return $this->response->setJSON(["message" => lang("App.global_alert_save_success"), "data" => $bodyData]);
|
||||
$validated = $this->validation->run($bodyData, "orden_trabajo_date");
|
||||
if ($validated) {
|
||||
$validatedData = $bodyData;
|
||||
$r = $this->produccionService->emptyOrdenTrabajoDate($validatedData['orden_trabajo_id'], $validatedData['name']);
|
||||
$this->produccionService->init($validatedData['orden_trabajo_id']); // Re-init service to update the state of the OT
|
||||
return $this->response->setJSON(["message" => lang("App.global_alert_save_success"), "status" => $r, "user" => auth()->user(), "data" => $bodyData]);
|
||||
} else {
|
||||
return $this->response->setJSON(["errors" => $this->validation->getErrors()])->setStatusCode(400);
|
||||
}
|
||||
}
|
||||
public function update_orden_trabajo_pedido_date()
|
||||
{
|
||||
try {
|
||||
@ -128,6 +185,18 @@ class Ordentrabajo extends BaseController
|
||||
return $this->response->setJSON(["errors" => $th->getMessage(), "status" => false])->setStatusCode(500);
|
||||
}
|
||||
}
|
||||
public function reset_orden_trabajo_pedido_date()
|
||||
{
|
||||
$bodyData = $this->request->getPost();
|
||||
$validated = $this->validation->run($bodyData, "orden_trabajo_date");
|
||||
if ($validated) {
|
||||
$validatedData = $bodyData;
|
||||
$r = $this->produccionService->init($bodyData['orden_trabajo_id'])->emptyOrdenTrabajoPedidoDate($validatedData['name']);
|
||||
return $this->response->setJSON(["message" => lang("App.global_alert_save_success"), "status" => $r, "user" => auth()->user(), "data" => $bodyData]);
|
||||
} else {
|
||||
return $this->response->setJSON(["errors" => $this->validation->getErrors()])->setStatusCode(400);
|
||||
}
|
||||
}
|
||||
public function update_orden_trabajo_pedido()
|
||||
{
|
||||
try {
|
||||
@ -152,12 +221,22 @@ class Ordentrabajo extends BaseController
|
||||
$this->viewData["presupuesto"] = $this->produccionService->getPresupuesto();
|
||||
$this->viewData["cliente"] = $this->produccionService->getCliente();
|
||||
$this->viewData["ot"] = $this->produccionService->getOrdenTrabajo();
|
||||
$this->viewData["is_finalizada"] = $this->produccionService->getOrdenTrabajo()->estado == "F";
|
||||
$this->viewData["user_dates"] = $this->produccionService->userDates();
|
||||
$this->viewData["pedido_user_dates"] = $this->produccionService->pedidoUserDates();
|
||||
$this->viewData["colors"] = $this->produccionService->getPdfColors();
|
||||
$this->viewData["tiempo_estimado"] = $this->produccionService->getTiempoProcesamientoHHMMSS();
|
||||
$this->viewData["flags"] = $this->produccionService->getFlags();
|
||||
$this->viewData["tareaCosido"] = $this->produccionService->getTareaCosido();
|
||||
|
||||
|
||||
return view(static::$viewPath . $this->editRoute, $this->viewData);
|
||||
}
|
||||
|
||||
/**
|
||||
* DataTable for Ordenes de Trabajo Finalizadas
|
||||
* @return \CodeIgniter\HTTP\ResponseInterface
|
||||
*/
|
||||
public function datatable()
|
||||
{
|
||||
$logo = config(LogoImpresion::class);
|
||||
@ -165,57 +244,134 @@ class Ordentrabajo extends BaseController
|
||||
$q = $this->otModel->getDatatableQuery()->where("ordenes_trabajo.estado", "F");
|
||||
// return $this->response->setJSON($q->get()->getResultArray());
|
||||
return DataTable::of($q)
|
||||
->add("logo", fn($q) => ["logo" => site_url($logo->get_logo_path($q->presupuesto_linea_tipo)), "imposicion" => $q->imposicion_name,"color" => $this->produccionService->init($q->id)->getOtColorStatus()])
|
||||
->add("logo", fn($q) => ["logo" => site_url($logo->get_logo_path($q->presupuesto_linea_tipo)), "imposicion" => $q->imposicion_name, "color" => $this->produccionService->init($q->id)->getOtColorStatus()])
|
||||
->edit(
|
||||
"fecha_encuadernado_at",
|
||||
fn($q) => $q->fecha_encuadernado_at ? Time::createFromFormat("Y-m-d H:i:s", $q->fecha_encuadernado_at)->format("d/m/Y") : ""
|
||||
)
|
||||
->add("action", fn($q) => $q->id)
|
||||
->add("pdf_check", fn($q) => $q->id)
|
||||
->toJson(true);
|
||||
}
|
||||
public function datatable_pendientes()
|
||||
{
|
||||
$logo = config(LogoImpresion::class);
|
||||
|
||||
$q = $this->otModel->getDatatableQuery()->whereIn("ordenes_trabajo.estado", ["I", "PM"]);
|
||||
// return $this->response->setJSON($q->get()->getResultArray());
|
||||
$q = $this->otModel->getDatatableQuery()
|
||||
->whereIn("ordenes_trabajo.estado", ["I", "PM"])
|
||||
->where('ordenes_trabajo.preimpresion_revisada', true)
|
||||
->where('ordenes_trabajo.is_pedido_espera', false)
|
||||
->where('ordenes_trabajo.progreso <=', 0);
|
||||
return DataTable::of($q)
|
||||
->add("logo", fn($q) => ["logo" => site_url($logo->get_logo_path($q->presupuesto_linea_tipo)), "imposicion" => $q->imposicion_name,"color" => $this->produccionService->init($q->id)->getOtColorStatus()])
|
||||
->add("logo", fn($q) => ["logo" => site_url($logo->get_logo_path($q->presupuesto_linea_tipo)), "imposicion" => $q->imposicion_name, "color" => $this->produccionService->init($q->id)->getOtColorStatus()])
|
||||
->edit(
|
||||
"fecha_encuadernado_at",
|
||||
fn($q) => $q->fecha_encuadernado_at ? Time::createFromFormat("Y-m-d H:i:s", $q->fecha_encuadernado_at)->format("d/m/Y") : ""
|
||||
)
|
||||
->add("action", fn($q) => $q->id)
|
||||
->add("pdf_check", fn($q) => $q->id)
|
||||
->toJson(true);
|
||||
}
|
||||
public function datatable_ferro_pendiente()
|
||||
{
|
||||
$logo = config(LogoImpresion::class);
|
||||
|
||||
$q = $this->otModel->getDatatableQuery()->where("ferro_ok_at", null);
|
||||
$q = $this->otModel->getDatatableQuery()->where('presupuestos.ferro', 1)->where("ferro_ok_at", null);
|
||||
// return $this->response->setJSON($q->get()->getResultArray());
|
||||
return DataTable::of($q)
|
||||
->add("logo", fn($q) => ["logo" => site_url($logo->get_logo_path($q->presupuesto_linea_tipo)), "imposicion" => $q->imposicion_name,"color" => $this->produccionService->init($q->id)->getOtColorStatus()])
|
||||
->add("logo", fn($q) => ["logo" => site_url($logo->get_logo_path($q->presupuesto_linea_tipo)), "imposicion" => $q->imposicion_name, "color" => $this->produccionService->init($q->id)->getOtColorStatus()])
|
||||
->edit(
|
||||
"fecha_encuadernado_at",
|
||||
fn($q) => $q->fecha_encuadernado_at ? Time::createFromFormat("Y-m-d H:i:s", $q->fecha_encuadernado_at)->format("d/m/Y") : ""
|
||||
)
|
||||
->add("action", fn($q) => $q->id)
|
||||
->add("pdf_check", fn($q) => $q->id)
|
||||
->toJson(true);
|
||||
}
|
||||
public function datatable_ferro_ok()
|
||||
{
|
||||
$logo = config(LogoImpresion::class);
|
||||
|
||||
$q = $this->otModel->getDatatableQuery()->where("ferro_ok_at is NOT NULL", NULL, FALSE);
|
||||
$q = $this->otModel->getDatatableQuery()->where('presupuestos.ferro', 1)->where("ferro_ok_at is NOT NULL", NULL, FALSE);
|
||||
// return $this->response->setJSON($q->get()->getResultArray());
|
||||
return DataTable::of($q)
|
||||
->add("logo", fn($q) => ["logo" => site_url($logo->get_logo_path($q->presupuesto_linea_tipo)), "imposicion" => $q->imposicion_name,"color" => $this->produccionService->init($q->id)->getOtColorStatus()])
|
||||
->add("logo", fn($q) => ["logo" => site_url($logo->get_logo_path($q->presupuesto_linea_tipo)), "imposicion" => $q->imposicion_name, "color" => $this->produccionService->init($q->id)->getOtColorStatus()])
|
||||
->edit(
|
||||
"fecha_encuadernado_at",
|
||||
fn($q) => $q->fecha_encuadernado_at ? Time::createFromFormat("Y-m-d H:i:s", $q->fecha_encuadernado_at)->format("d/m/Y") : ""
|
||||
)
|
||||
->add("action", fn($q) => $q->id)
|
||||
->add("pdf_check", fn($q) => $q->id)
|
||||
->toJson(true);
|
||||
}
|
||||
public function datatable_news()
|
||||
{
|
||||
$logo = config(LogoImpresion::class);
|
||||
|
||||
$q = $this->otModel->getDatatableQuery()
|
||||
->whereIn("ordenes_trabajo.estado", ["I", "PM"])
|
||||
->where('ordenes_trabajo.preimpresion_revisada', false)
|
||||
->where('ordenes_trabajo.is_pedido_espera', false);
|
||||
return DataTable::of($q)
|
||||
->add("logo", fn($q) => ["logo" => site_url($logo->get_logo_path($q->presupuesto_linea_tipo)), "imposicion" => $q->imposicion_name, "color" => $this->produccionService->init($q->id)->getOtColorStatus()])
|
||||
->edit(
|
||||
"fecha_encuadernado_at",
|
||||
fn($q) => $q->fecha_encuadernado_at ? Time::createFromFormat("Y-m-d H:i:s", $q->fecha_encuadernado_at)->format("d/m/Y") : ""
|
||||
)
|
||||
->add("action", fn($q) => $q->id)
|
||||
->add("pdf_check", fn($q) => $q->id)
|
||||
->toJson(true);
|
||||
}
|
||||
public function datatable_prod()
|
||||
{
|
||||
$logo = config(LogoImpresion::class);
|
||||
|
||||
$q = $this->otModel->getDatatableQuery()
|
||||
->whereIn("ordenes_trabajo.estado", ["I", "PM"])
|
||||
->where('ordenes_trabajo.preimpresion_revisada', true)
|
||||
->where('ordenes_trabajo.is_pedido_espera', false)
|
||||
->where('ordenes_trabajo.progreso >', 0)
|
||||
->where('pedidos.estado', 'produccion');
|
||||
return DataTable::of($q)
|
||||
->add("logo", fn($q) => ["logo" => site_url($logo->get_logo_path($q->presupuesto_linea_tipo)), "imposicion" => $q->imposicion_name, "color" => $this->produccionService->init($q->id)->getOtColorStatus()])
|
||||
->edit(
|
||||
"fecha_encuadernado_at",
|
||||
fn($q) => $q->fecha_encuadernado_at ? Time::createFromFormat("Y-m-d H:i:s", $q->fecha_encuadernado_at)->format("d/m/Y") : ""
|
||||
)
|
||||
->add("action", fn($q) => $q->id)
|
||||
->add("pdf_check", fn($q) => $q->id)
|
||||
->toJson(true);
|
||||
}
|
||||
public function datatable_waiting()
|
||||
{
|
||||
$logo = config(LogoImpresion::class);
|
||||
|
||||
$q = $this->otModel->getDatatableQuery()
|
||||
->whereIn("ordenes_trabajo.estado", ["I", "PM"])
|
||||
->where('ordenes_trabajo.is_pedido_espera', 1);
|
||||
return DataTable::of($q)
|
||||
->add("logo", fn($q) => ["logo" => site_url($logo->get_logo_path($q->presupuesto_linea_tipo)), "imposicion" => $q->imposicion_name, "color" => $this->produccionService->init($q->id)->getOtColorStatus()])
|
||||
->edit(
|
||||
"fecha_encuadernado_at",
|
||||
fn($q) => $q->fecha_encuadernado_at ? Time::createFromFormat("Y-m-d H:i:s", $q->fecha_encuadernado_at)->format("d/m/Y") : ""
|
||||
)
|
||||
->add("action", fn($q) => $q->id)
|
||||
->add("pdf_check", fn($q) => $q->id)
|
||||
->toJson(true);
|
||||
}
|
||||
public function datatable_revision_com()
|
||||
{
|
||||
$logo = config(LogoImpresion::class);
|
||||
|
||||
$q = $this->otModel->getDatatableQuery()->where('presupuestos.ferro', 1)->where("ferro_ok_at is NOT NULL", NULL, FALSE);
|
||||
return DataTable::of($q)
|
||||
->add("logo", fn($q) => ["logo" => site_url($logo->get_logo_path($q->presupuesto_linea_tipo)), "imposicion" => $q->imposicion_name, "color" => $this->produccionService->init($q->id)->getOtColorStatus()])
|
||||
->edit(
|
||||
"fecha_encuadernado_at",
|
||||
fn($q) => $q->fecha_encuadernado_at ? Time::createFromFormat("Y-m-d H:i:s", $q->fecha_encuadernado_at)->format("d/m/Y") : ""
|
||||
)
|
||||
->add("action", fn($q) => $q->id)
|
||||
->add("pdf_check", fn($q) => $q->id)
|
||||
->toJson(true);
|
||||
}
|
||||
public function papel_gramaje_datatable()
|
||||
@ -236,9 +392,23 @@ class Ordentrabajo extends BaseController
|
||||
->add("action", fn($q) => ["title" => lang('Produccion.datatable.filter_by_paper'), 'data' => $q])
|
||||
->toJson(true);
|
||||
}
|
||||
public function maquina_plana_datatable()
|
||||
{
|
||||
// return $this->response->setStatusCode(400);
|
||||
$padreId = $this->request->getGet('padre_id');
|
||||
$q = $this->produccionService->maquinaPlanaDatatableQuery();
|
||||
if ($padreId) {
|
||||
$q->where('lg_maquinas.padre_id', $padreId);
|
||||
}
|
||||
return DataTable::of($q)
|
||||
->edit("tiempoReal", fn($q) => $q->tiempoReal)
|
||||
->add("action", fn($q) => ["title" => lang('Produccion.datatable.filter_by_machine'), 'data' => $q])
|
||||
->toJson(true);
|
||||
}
|
||||
public function reset_tareas(int $orden_trabajo_id)
|
||||
{
|
||||
$r = $this->produccionService->init($orden_trabajo_id)->resetAllTareas();
|
||||
$this->produccionService->init($orden_trabajo_id); // Re-init service to update the state of the OT
|
||||
return $this->response->setJSON(["message" => "Tareas reseteadas", "status" => $r]);
|
||||
}
|
||||
public function delete_tarea(int $orden_trabajo_tarea_id)
|
||||
@ -253,8 +423,10 @@ class Ordentrabajo extends BaseController
|
||||
return DataTable::of($q)
|
||||
->add("action", fn($q) => $q)
|
||||
->edit("orden", fn($q) => ["id" => $q->id, "orden" => $q->orden])
|
||||
->edit("tiempo_estimado", fn($q) => float_seconds_to_hhmm_string($q->tiempo_estimado))
|
||||
->edit("tiempo_real", fn($q) => float_seconds_to_hhmm_string($q->tiempo_real))
|
||||
->add("tarea_estado", fn($q) => $this->produccionService->getTitleTareaEstado($q->id))
|
||||
->edit("tiempo_estimado", fn($q) => float_seconds_to_hhmmss_string($q->tiempo_estimado))
|
||||
->edit("tiempo_real", fn($q) => float_seconds_to_hhmmss_string($q->tiempo_real))
|
||||
->add("proveedor", fn($q) => $this->produccionService->getProveedorTarea($q->id))
|
||||
->edit("maquina_tarea", fn($q) => ["id" => $q->id, "maquina_id" => $q->maquina_tarea, "maquina_name" => $q->maquina_nombre])
|
||||
->add("imposicion", fn($q) => ["id" => $q->id, "imposicion_id" => $q->imposicion_id, "name" => $q->imposicion_name, "is_presupuesto_linea" => $q->presupuesto_linea_id ? true : false])
|
||||
->toJson(true);
|
||||
@ -263,6 +435,14 @@ class Ordentrabajo extends BaseController
|
||||
{
|
||||
return $this->produccionService->init($orden_trabajo_id)->getPdf();
|
||||
}
|
||||
public function get_ferro_pdf($orden_trabajo_id)
|
||||
{
|
||||
return $this->produccionService->init($orden_trabajo_id)->getFerroPdf();
|
||||
}
|
||||
public function get_prototipo_pdf($orden_trabajo_id)
|
||||
{
|
||||
return $this->produccionService->init($orden_trabajo_id)->getPrototipoPdf();
|
||||
}
|
||||
public function upload_orden_trabajo_portada()
|
||||
{
|
||||
try {
|
||||
@ -341,15 +521,12 @@ class Ordentrabajo extends BaseController
|
||||
public function planning_plana_datatable()
|
||||
{
|
||||
$query = $this->produccionService->planningPlanaQueryDatatable();
|
||||
$padreId = $this->request->getGet('padre_id');
|
||||
if ($padreId) {
|
||||
$query->where('lg_maquinas.padre_id', $padreId);
|
||||
}
|
||||
|
||||
return DataTable::of($query)
|
||||
->edit("tiempo_real_sum", fn($q) => $q->tiempo_real_sum)
|
||||
->edit("fecha_entrega_real_at", fn($q) => $q->fecha_entrega_real_at ? Time::createFromFormat("Y-m-d", $q->fecha_entrega_real_at)->format("d/m/Y") : "")
|
||||
->add("pliegos_check", fn($q) => $q->otId)
|
||||
->add("action", fn($q) => ["data" => $q ])
|
||||
->add("action", fn($q) => ["data" => $q])
|
||||
->toJson(true);
|
||||
}
|
||||
public function select_maquina_planning_rot()
|
||||
@ -367,7 +544,8 @@ class Ordentrabajo extends BaseController
|
||||
public function select_maquina_planning_plana()
|
||||
{
|
||||
$q = $this->request->getGet('q');
|
||||
$result = $this->produccionService->querySelectMaquinaPlanningPlana($q);
|
||||
$padreId = $this->request->getGet('padre_id');
|
||||
$result = $this->produccionService->querySelectMaquinaPlanningPlana($q, $padreId);
|
||||
return $this->response->setJSON($result);
|
||||
}
|
||||
public function select_maquina_padre_planning_plana()
|
||||
@ -379,7 +557,8 @@ class Ordentrabajo extends BaseController
|
||||
public function select_papel_planning_plana()
|
||||
{
|
||||
$q = $this->request->getGet('q');
|
||||
$result = $this->produccionService->querySelectPapelPlanningPlana($q);
|
||||
$maquinaId = $this->request->getGet('maquina_id');
|
||||
$result = $this->produccionService->querySelectPapelPlanningPlana($q,$maquinaId);
|
||||
return $this->response->setJSON($result);
|
||||
}
|
||||
public function tarea_toggle_corte($orden_trabajo_id)
|
||||
@ -438,4 +617,392 @@ class Ordentrabajo extends BaseController
|
||||
$color = $this->produccionService->init($orden_trabajo_id)->getOtColorStatus();
|
||||
return $this->response->setJSON(["color" => $color]);
|
||||
}
|
||||
public function imprimir_codigo_safekat(int $orden_trabajo_id)
|
||||
{
|
||||
helper('file');
|
||||
$barcode = $this->produccionService->init($orden_trabajo_id)->getFileBarCode();
|
||||
return $this->response
|
||||
->setHeader('Content-Type', 'image/png')
|
||||
->setHeader('Content-Disposition', "attachment; filename=CodigoBarrasOT_{$orden_trabajo_id}.png")
|
||||
->setBody($barcode);
|
||||
}
|
||||
|
||||
public function maquinista_maquinas_view()
|
||||
{
|
||||
// Breadcrumbs
|
||||
$this->viewData['breadcrumb'] = [
|
||||
['title' => lang("Produccion.maquinista.maquinas"), 'route' => route_to("viewProduccionMaquinistaMaquinas"), 'active' => true],
|
||||
];
|
||||
$data = [
|
||||
"impresion" => $this->maquinaModel->queryViewMaquinistaMaquinas('impresion')->get()->getResultArray(),
|
||||
"manipulado" => $this->maquinaModel->queryViewMaquinistaMaquinas('manipulado')->get()->getResultArray(),
|
||||
"acabado" => $this->maquinaModel->queryViewMaquinistaMaquinas('acabado')->get()->getResultArray(),
|
||||
];
|
||||
$this->viewData["maquinas"] = $data;
|
||||
return view(static::$viewPath . '/maquinista/viewMaquinistaMaquinaList', $this->viewData);
|
||||
}
|
||||
public function maquinista_maquina_tareas_list(int $maquina_id)
|
||||
{
|
||||
$maquina = $this->maquinaModel->find($maquina_id);
|
||||
$this->viewData['breadcrumb'] = [
|
||||
['title' => lang("Produccion.maquinista.maquinas"), 'route' => route_to("viewProduccionMaquinistaMaquinas"), 'active' => false],
|
||||
['title' => $maquina->nombre, 'route' => route_to("viewProduccionMaquinistaMaquina", $maquina_id), 'active' => true],
|
||||
];
|
||||
$this->viewData["maquinaEntity"] = $maquina;
|
||||
$tareasRunning = $this->maquinaOtTareaModel->queryDatatableJoinOrdenTrabajo($maquina->id)->countAllResults();
|
||||
if ($tareasRunning) {
|
||||
return view(static::$viewPath . '/maquinista/viewProduccionMaquinistaOtTareasView', $this->viewData);
|
||||
} else {
|
||||
return view(static::$viewPath . '/maquinista/viewMaquinistaMaquinaTareas', $this->viewData);
|
||||
}
|
||||
}
|
||||
public function maquinista_maquina_tareas_fichaje_automatico(int $maquina_id)
|
||||
{
|
||||
$maquina = $this->maquinaModel->find($maquina_id);
|
||||
$this->viewData["maquinaEntity"] = $maquina;
|
||||
return view(static::$viewPath . '/maquinista/viewMaquinistaFichajeAutomatico', $this->viewData);
|
||||
}
|
||||
public function maquinista_maquina_tareas_scan(int $maquina_id)
|
||||
{
|
||||
$maquina = $this->maquinaModel->find($maquina_id);
|
||||
$this->viewData["maquinaEntity"] = $maquina;
|
||||
return view(static::$viewPath . '/maquinista/viewMaquinistaTareaScan', $this->viewData);
|
||||
}
|
||||
|
||||
public function maquinista_maquina_tarea_view(int $orden_trabajo_tarea_id)
|
||||
{
|
||||
$modelImpresoras = model('App\Models\Configuracion\ImpresoraEtiquetaModel');
|
||||
$impresoras = $modelImpresoras->select('id, name')
|
||||
->where('deleted_at', null)
|
||||
->where('tipo', 1)
|
||||
->orderBy('name', 'asc')
|
||||
->findAll();
|
||||
$impresoras = array_map(fn($impresora) => $impresora->toArray(), $impresoras);
|
||||
$otTareaEntity = $this->otTarea->find($orden_trabajo_tarea_id);
|
||||
$this->viewData['ot_tarea'] = $otTareaEntity;
|
||||
$this->viewData['ot'] = $otTareaEntity->orden_trabajo();
|
||||
$this->viewData['presupuesto'] = $this->viewData['ot']->presupuesto();
|
||||
|
||||
$this->viewData['impresoras'] = $impresoras;
|
||||
$this->viewData['breadcrumb'] = [
|
||||
['title' => lang("Produccion.maquinista.maquinas"), 'route' => route_to("viewProduccionMaquinistaMaquinas"), 'active' => false],
|
||||
['title' => $otTareaEntity->maquina_actual()->nombre, 'route' => route_to("viewProduccionMaquinaTareasList", $otTareaEntity?->maquina_actual()?->id), 'active' => true],
|
||||
['title' => $otTareaEntity->nombre, 'route' => route_to("viewProduccionMaquinistaTareaView", $otTareaEntity->id), 'active' => true]
|
||||
|
||||
];
|
||||
return view(static::$viewPath . '/maquinista/viewMaquinistaMaquinaTarea', $this->viewData);
|
||||
}
|
||||
public function maquinista_maquina_ot_tareas_view(int $maquina_id)
|
||||
{
|
||||
$maquinaEntity = $this->maquinaModel->find($maquina_id);
|
||||
$this->viewData['maquinaEntity'] = $maquinaEntity;
|
||||
$tareasRunning = $this->maquinaOtTareaModel->queryDatatableJoinOrdenTrabajo($maquina_id)->countAllResults();
|
||||
if ($tareasRunning) {
|
||||
return view(static::$viewPath . '/maquinista/viewProduccionMaquinistaOtTareasView', $this->viewData);
|
||||
} else {
|
||||
return view(static::$viewPath . '/maquinista/viewMaquinistaMaquinaTareas', $this->viewData);
|
||||
}
|
||||
}
|
||||
public function maquinista_colas_view()
|
||||
{
|
||||
return view(static::$viewPath . '/maquinista/viewMaquinistaPlanningList', $this->viewData);
|
||||
}
|
||||
public function maquinista_maquina_tareas_datatable(string $content, int $maquina_id)
|
||||
{
|
||||
$pm = $this->produccionService->getMaquinaImpresionTareasList($maquina_id);
|
||||
if ($content == 'today') {
|
||||
$pm->like('pedidos.fecha_impresion', Time::now()->format('Y-m-d'));
|
||||
}
|
||||
return DataTable::of($pm)
|
||||
->edit('fecha_impresion', fn($q) => $q->fecha_impresion ? Time::createFromFormat('Y-m-d H:i:s', $q->fecha_impresion)->format('d/m/Y') : '')
|
||||
->add("tareaEstado", fn($q) => $this->produccionService->getTitleTareaEstado($q->ot_tarea_id))
|
||||
->add('action', fn($q) => $this->produccionService->buttonActionDatatableTareaList($q->ot_tarea_id))
|
||||
->toJson(true);
|
||||
}
|
||||
public function maquinista_maquina_tareas_aplazada_datatable(int $maquina_id)
|
||||
{
|
||||
$pm = $this->produccionService->getMaquinaImpresionTareasList($maquina_id)->where("tarea_progress.estado", 'D');
|
||||
return DataTable::of($pm)
|
||||
->edit('fecha_impresion', fn($q) => $q->fecha_impresion ? Time::createFromFormat('Y-m-d H:i:s', $q->fecha_impresion)->format('d/m/Y') : '')
|
||||
->add("tareaEstado", fn($q) => $this->produccionService->getTitleTareaEstado($q->ot_tarea_id))
|
||||
->add('action', fn($q) => $this->produccionService->buttonActionDatatableTareaList($q->ot_tarea_id))
|
||||
->toJson(true);
|
||||
}
|
||||
|
||||
|
||||
public function store_orden_trabajo_progress_date()
|
||||
{
|
||||
try {
|
||||
$bodyData = $this->request->getPost();
|
||||
$validated = $this->validation->run($bodyData, "orden_trabajo_tarea_progress_date");
|
||||
if ($validated) {
|
||||
$validatedData = $this->validation->getValidated();
|
||||
$r = $this->produccionService->storeOrdenTrabajoTareaProgressDate($validatedData);
|
||||
$otTareaEntity = $this->otTarea->find($validatedData['ot_tarea_id']);
|
||||
$data = [
|
||||
"tiempo_trabajado" => float_seconds_to_hhmmss_string($otTareaEntity->tiempo_real),
|
||||
"tarea" => $otTareaEntity,
|
||||
"estado" => $validatedData['estado'],
|
||||
];
|
||||
return $this->response->setJSON(["message" => lang("App.global_alert_save_success"), "status" => $r, "data" => $data]);
|
||||
} else {
|
||||
return $this->response->setJSON(["errors" => $this->validation->getErrors()])->setStatusCode(400);
|
||||
}
|
||||
} catch (\Throwable $th) {
|
||||
return $this->response->setJSON(["status" => false, "error" => $th->getMessage()])->setStatusCode(500);
|
||||
}
|
||||
}
|
||||
public function delete_orden_trabajo_progress_date(int $orden_trabajo_tarea_id)
|
||||
{
|
||||
$status = $this->produccionService->deleteOrdenTrabajoTareaProgressDates($orden_trabajo_tarea_id);
|
||||
return $this->response->setJSON(["message" => lang("App.global_alert_save_success"), "status" => $status]);
|
||||
}
|
||||
public function get_orden_trabajo_progress_date(int $orden_trabajo_tarea_id)
|
||||
{
|
||||
$otTareaEntity = $this->otTarea->find($orden_trabajo_tarea_id);
|
||||
$data = [
|
||||
"tiempo_trabajado" => float_seconds_to_hhmmss_string($otTareaEntity->tiempo_trabajado()),
|
||||
"progress_dates" => $otTareaEntity->progress_dates(),
|
||||
];
|
||||
return $this->response->setJSON($data);
|
||||
}
|
||||
public function update_pod_pedido_dates($orden_trabajo_id)
|
||||
{
|
||||
|
||||
$this->produccionService->init($orden_trabajo_id);
|
||||
if ($this->produccionService->isPOD) {
|
||||
$status = $this->produccionService->updatePodDates();
|
||||
return $this->response->setJSON(["message" => lang("App.global_alert_save_success"), "status" => $status, "data" => $this->produccionService->getPedido()]);
|
||||
} else {
|
||||
return $this->response->setJSON(["message" => lang("App.global_alert_save_success"), "status" => false, "data" => $this->produccionService->getPedido()]);
|
||||
}
|
||||
}
|
||||
public function get_orden_trabajo_tareas_dates($orden_trabajo_id)
|
||||
{
|
||||
$data = $this->produccionService->init($orden_trabajo_id)->getOrdenTrabajoTareaDates();
|
||||
return $this->response->setJSON(["data" => $data]);
|
||||
}
|
||||
public function get_tareas_ot_maquina(int $orden_trabajo_id, int $maquina_id)
|
||||
{
|
||||
$tareasWithMaquina = $this->produccionService->init($orden_trabajo_id)->getTareasWithMaquina($maquina_id, ['P', 'I', 'S', 'D']);
|
||||
if ($tareasWithMaquina) {
|
||||
$data = [
|
||||
'tareas' => $tareasWithMaquina,
|
||||
'ot' => $this->produccionService->getOrdenTrabajo(),
|
||||
'presupuesto' => $this->produccionService->getPresupuesto()
|
||||
];
|
||||
return $this->response->setJSON(["message" => lang("App.global_alert_fetch_success"), "data" => $data]);
|
||||
} else {
|
||||
$tareasWithMaquina = $this->produccionService->init($orden_trabajo_id)->getTareasWithMaquina($maquina_id, ['F']);
|
||||
if ($tareasWithMaquina) {
|
||||
return $this->response->setJSON(["message" => lang("Produccion.errors.tareas_finalizadas"), "data" => $tareasWithMaquina])->setStatusCode(400);
|
||||
} else {
|
||||
return $this->response->setJSON(["message" => lang("Produccion.errors.maquina_not_in_ot"), "data" => null])->setStatusCode(400);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public function update_orden_trabajo_fa_tareas()
|
||||
{
|
||||
$responseData = [
|
||||
"tiempo_total_estimado" => 0,
|
||||
"tiempo_total_real" => 0,
|
||||
"clicks_total" => 0,
|
||||
"tirada_total" => 0,
|
||||
"estado" => "P",
|
||||
];
|
||||
$bodyData = $this->request->getPost();
|
||||
$validated = $this->validation->run($bodyData, "orden_trabajo_fichaje_auto");
|
||||
if ($validated) {
|
||||
$validatedData = $this->validation->getValidated();
|
||||
$this->produccionService->init($validatedData['orden_trabajo_id']);
|
||||
foreach ($validatedData['tareas'] as $key => $tareaId) {
|
||||
$this->produccionService->storeOrdenTrabajoTareaProgressDate(
|
||||
[
|
||||
'estado' => $validatedData['estado'],
|
||||
'ot_tarea_id' => $tareaId
|
||||
]
|
||||
);
|
||||
$tareaEntity = $this->otTarea->find($tareaId);
|
||||
$tiempo_trabajado = $tareaEntity->tiempo_trabajado();
|
||||
$responseData['tiempo_total_estimado'] += $tareaEntity->tiempo_estimado;
|
||||
$responseData['tiempo_total_real'] += $tiempo_trabajado;
|
||||
$responseData["estado"] = $validatedData["estado"];
|
||||
$tareaEntity->tiempo_real = $tiempo_trabajado / count($validatedData['tareas']);
|
||||
$tareaEntity->click_init = $validatedData['click_init'] / count($validatedData['tareas']);
|
||||
$tareaEntity->click_end = $validatedData['click_end'] / count($validatedData['tareas']);
|
||||
|
||||
$this->otTarea->save($tareaEntity);
|
||||
}
|
||||
$responseData['tiempo_total_estimado'] = float_seconds_to_hhmmss_string($responseData['tiempo_total_estimado']);
|
||||
$responseData['tiempo_total_real'] = float_seconds_to_hhmmss_string($responseData['tiempo_total_real']);
|
||||
return $this->response->setJSON(["message" => lang("App.global_alert_save_success"), "status" => true, "data" => $responseData]);
|
||||
} else {
|
||||
return $this->response->setJSON(["errors" => $this->validation->getErrors()])->setStatusCode(400);
|
||||
}
|
||||
}
|
||||
public function delete_orden_trabajo_fa_tareas()
|
||||
{
|
||||
$bodyData = $this->request->getPost();
|
||||
$validated = $this->validation->run($bodyData, "orden_trabajo_fichaje_auto");
|
||||
if ($validated) {
|
||||
$validatedData = $this->validation->getValidated();
|
||||
$this->produccionService->init($validatedData['orden_trabajo_id']);
|
||||
foreach ($validatedData['tareas'] as $key => $tareaId) {
|
||||
$this->produccionService->deleteOrdenTrabajoTareaProgressDates($tareaId);
|
||||
}
|
||||
return $this->response->setJSON(["message" => lang("App.global_alert_save_success"), "status" => true, "data" => $validatedData]);
|
||||
} else {
|
||||
return $this->response->setJSON(["errors" => $this->validation->getErrors()])->setStatusCode(400);
|
||||
}
|
||||
}
|
||||
public function store_maquina_ordenes_trabajo()
|
||||
{
|
||||
$bodyData = $this->request->getPost();
|
||||
$validated = $this->validation->run($bodyData, "maquina_ordenes_trabajo");
|
||||
if ($validated) {
|
||||
$validatedData = $this->validation->getValidated();
|
||||
|
||||
foreach ($validatedData['ordenes_trabajo'] as $key => $orden_trabajo_id) {
|
||||
$maquinaOtTarea = $this->maquinaOtTareaModel->where('orden_trabajo_id', $orden_trabajo_id)->where('maquina_id', $validatedData['maquina_id'])->where('deleted_at', null)->countAllResults();
|
||||
if ($maquinaOtTarea) {
|
||||
continue;
|
||||
}
|
||||
$this->maquinaOtTareaModel->insert(['maquina_id' => $validatedData['maquina_id'], 'orden_trabajo_id' => $orden_trabajo_id]);
|
||||
}
|
||||
return $this->response->setJSON(["message" => lang("App.global_alert_save_success"), "status" => true, "data" => $validatedData]);
|
||||
} else {
|
||||
return $this->response->setJSON(["errors" => $this->validation->getErrors()])->setStatusCode(400);
|
||||
}
|
||||
}
|
||||
public function update_maquina_ordenes_trabajo_estado()
|
||||
{
|
||||
$bodyData = $this->request->getPost();
|
||||
$maquina_id = $bodyData['maquina_id'];
|
||||
$estado = $bodyData['estado'];
|
||||
$maquina_ots = $this->maquinaOtTareaModel->where('maquina_id', $maquina_id)->findAll();
|
||||
$totalTareas = [];
|
||||
|
||||
foreach ($maquina_ots as $key => $maquina_ot) {
|
||||
$tareas = $this->produccionService->init($maquina_ot->orden_trabajo_id)
|
||||
->getTareasWithMaquina($maquina_id, ['P', 'I', 'S', 'D']);
|
||||
foreach ($tareas as $key => $tarea) {
|
||||
$this->produccionService->storeOrdenTrabajoTareaProgressDate(
|
||||
[
|
||||
'estado' => $estado,
|
||||
'ot_tarea_id' => $tarea->id
|
||||
]
|
||||
);
|
||||
$tarea->click_init = $bodyData['click_init'];
|
||||
$tarea->click_end = $bodyData['click_end'];
|
||||
$totalTareas[] = $tarea;
|
||||
}
|
||||
}
|
||||
foreach ($totalTareas as $key => $tarea) {
|
||||
$tiempo_trabajado = $tarea->tiempo_trabajado();
|
||||
$tarea->tiempo_real = $tiempo_trabajado / count($totalTareas);
|
||||
$tarea->click_init = $tarea->click_init / count($totalTareas);
|
||||
$tarea->click_end = $tarea->click_end / count($totalTareas);
|
||||
|
||||
$this->otTarea->save($tarea);
|
||||
}
|
||||
if ($estado == "F") {
|
||||
$this->maquinaOtTareaModel->where('maquina_id', $maquina_id)->delete();
|
||||
}
|
||||
|
||||
return $this->response->setJSON(["message" => lang("Produccion.responses.update_maquina_ordenes_trabajo_estado")]);
|
||||
}
|
||||
public function delete_maquina_orden_trabajo_tarea($maquina_orden_trabajo_tarea_id)
|
||||
{
|
||||
|
||||
$status = $this->maquinaOtTareaModel->delete($maquina_orden_trabajo_tarea_id);
|
||||
return $this->response->setJSON(["message" => lang("App.user_alert_delete"), "status" => $status]);
|
||||
}
|
||||
public function delete_maquina_orden_trabajo_all($maquina_id)
|
||||
{
|
||||
$maquina_ots = $this->maquinaOtTareaModel->where('maquina_id', $maquina_id)->findAll();
|
||||
foreach ($maquina_ots as $key => $maquina_ot) {
|
||||
$tareas = $this->produccionService->init($maquina_ot->orden_trabajo_id)
|
||||
->getTareasWithMaquina($maquina_id, ['P', 'I', 'S', 'D']);
|
||||
foreach ($tareas as $key => $tarea) {
|
||||
$this->produccionService->deleteOrdenTrabajoTareaProgressDates($tarea->id);
|
||||
}
|
||||
}
|
||||
$status = $this->maquinaOtTareaModel->where('maquina_id', $maquina_id)->delete();
|
||||
return $this->response->setJSON(["message" => lang("App.user_alert_delete"), "status" => $status]);
|
||||
}
|
||||
|
||||
public function datatable_maquina_ordenes_trabajo($maquina_id)
|
||||
{
|
||||
$query = $this->maquinaOtTareaModel->queryDatatableJoinOrdenTrabajo($maquina_id);
|
||||
return DataTable::of($query)
|
||||
->add('action', fn($q) => $q->otId)
|
||||
->add('titulo', fn($q) => $this->otModel->find($q->otId)->presupuesto()->titulo)
|
||||
->add('barcode', fn($q) => $this->otModel->find($q->otId)->getBarCode())
|
||||
->toJson(true);
|
||||
}
|
||||
public function get_maquina_ots($maquina_id)
|
||||
{
|
||||
$responseData = [
|
||||
"tiempo_total_estimado" => 0,
|
||||
"tiempo_total_real" => 0,
|
||||
"clicks_total" => 0,
|
||||
"tirada_total" => 0,
|
||||
"estado" => "P",
|
||||
];
|
||||
$maquina_ots = $this->maquinaOtTareaModel->where('maquina_id', $maquina_id)->findAll();
|
||||
foreach ($maquina_ots as $key => $maquina_ot) {
|
||||
$tareas = $this->produccionService->init($maquina_ot->orden_trabajo_id)
|
||||
->getTareasWithMaquina($maquina_id, ['P', 'I', 'S', 'D']);
|
||||
foreach ($tareas as $key => $tarea) {
|
||||
$responseData['tiempo_total_estimado'] += $tarea->tiempo_estimado;
|
||||
$responseData['tiempo_total_real'] += $tarea->tiempo_real;
|
||||
$responseData["estado"] = $tarea->lastState()->estado;
|
||||
if ($tarea->presupuesto_linea_id) {
|
||||
$responseData["clicks_total"] += $tarea->presupuesto_linea()->rotativa_clicks_total;
|
||||
$responseData["tirada_total"] += $tarea->orden_trabajo()->presupuesto()->tirada;
|
||||
}
|
||||
}
|
||||
}
|
||||
$responseData['tiempo_total_estimado'] = float_seconds_to_hhmmss_string($responseData['tiempo_total_estimado']);
|
||||
$responseData['tiempo_total_real'] = float_seconds_to_hhmmss_string($responseData['tiempo_total_real']);
|
||||
return $this->response->setJSON($responseData);
|
||||
}
|
||||
|
||||
public function printPackagingLabels()
|
||||
{
|
||||
|
||||
$ot_id = $this->request->getPost('ot_id') ?? null;
|
||||
$unidades_caja = $this->request->getPost('unidades_caja') ?? null;
|
||||
$impresora_id = $this->request->getPost('impresora_id') ?? null;
|
||||
|
||||
if ($ot_id == null || $impresora_id == null) {
|
||||
return [
|
||||
'status' => false,
|
||||
'message' => lang('Logistica.errors.errorMissingData')
|
||||
];
|
||||
}
|
||||
|
||||
$modelImpresora = model('App\Models\Configuracion\ImpresoraEtiquetaModel');
|
||||
$impresora = $modelImpresora->select('id, name, description, ip, port, user, pass')
|
||||
->where('deleted_at', null)
|
||||
->where('id', $impresora_id)
|
||||
->orderBy('name', 'asc')
|
||||
->first();
|
||||
if ($impresora == null) {
|
||||
return $this->response->setJSON([
|
||||
'status' => false,
|
||||
'message' => 'Impresora no válida'
|
||||
]);
|
||||
}
|
||||
|
||||
$printerService = new ImpresoraEtiquetaService();
|
||||
$result = $printerService->generateEtiquetasEmbalaje($ot_id, $unidades_caja, $impresora);
|
||||
|
||||
return $this->response->setJSON($result);
|
||||
}
|
||||
public function get_ot_pdf_content($orden_trabajo_id)
|
||||
{
|
||||
return $this->produccionService->init($orden_trabajo_id)->getPdfContent();
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,35 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Controllers\Produccion;
|
||||
use App\Controllers\BaseController;
|
||||
|
||||
|
||||
class Ordentrabajomaquetacion extends BaseController
|
||||
{
|
||||
function __construct()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
public function index()
|
||||
{
|
||||
echo 'Orden maquetación';
|
||||
}
|
||||
|
||||
public function delete()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
public function add()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
public function edit()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@ -1,35 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Controllers\Produccion;
|
||||
use App\Controllers\BaseController;
|
||||
|
||||
|
||||
class Pedidoproduccion extends BaseController
|
||||
{
|
||||
function __construct()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
public function index()
|
||||
{
|
||||
echo 'Pedido produccion';
|
||||
}
|
||||
|
||||
public function delete()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
public function add()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
public function edit()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
76
ci4/app/Controllers/Scripts/UsersIntegrity.php
Normal file
76
ci4/app/Controllers/Scripts/UsersIntegrity.php
Normal file
@ -0,0 +1,76 @@
|
||||
<?php
|
||||
|
||||
namespace App\Controllers\Scripts;
|
||||
|
||||
use App\Controllers\BaseController;
|
||||
use App\Models\Usuarios\UserModel;
|
||||
use App\Entities\Usuarios\UserEntity;
|
||||
use CodeIgniter\Shield\Authentication\Passwords\IdentityModel;
|
||||
|
||||
class UsersIntegrity extends BaseController
|
||||
{
|
||||
public function completarIdentidades()
|
||||
{
|
||||
$userModel = new UserModel();
|
||||
|
||||
|
||||
// Buscar usuarios safekat.com no eliminados
|
||||
$usuarios = $userModel
|
||||
->where('deleted_at', null)
|
||||
//->like('username', '@safekat.com')
|
||||
->findAll();
|
||||
|
||||
$resultados = [];
|
||||
|
||||
foreach ($usuarios as $usuario) {
|
||||
$email = $usuario->username . "@safekat.com";
|
||||
|
||||
// 1. Verificar si el usuario ya tiene identidad tipo email_password
|
||||
$tieneIdentidad = array_filter(
|
||||
$usuario->getIdentities(),
|
||||
fn($identity) => $identity->type === 'email_password'
|
||||
);
|
||||
|
||||
if (!empty($tieneIdentidad)) {
|
||||
$resultados[] = "✅ Ya tiene identidad: {$email}";
|
||||
continue;
|
||||
}
|
||||
|
||||
// 2. Verificar si ya existe una identidad globalmente con ese email
|
||||
$db = db_connect();
|
||||
|
||||
$builder = $db->table('auth_identities');
|
||||
|
||||
$existeGlobal = $builder
|
||||
->where('type', 'email_password')
|
||||
->where('secret', $email)
|
||||
->get()
|
||||
->getFirstRow();
|
||||
|
||||
if ($existeGlobal) {
|
||||
$resultados[] = "⚠️ Email ya registrado en otra identidad: {$email}";
|
||||
continue;
|
||||
}
|
||||
|
||||
// 3. Crear y guardar identidad
|
||||
try {
|
||||
$identity = $usuario->createEmailIdentity([
|
||||
'email' => $email,
|
||||
'password' => 'Temporal123!', // reemplazar por valor real si lo tenés
|
||||
]);
|
||||
|
||||
//$userModel->saveEmailIdentity($identity);
|
||||
|
||||
$resultados[] = "➕ Identidad creada: {$email}";
|
||||
} catch (\Throwable $e) {
|
||||
$resultados[] = "❌ Error con {$email}: " . $e->getMessage();
|
||||
}
|
||||
}
|
||||
|
||||
return $this->response->setJSON([
|
||||
'status' => 'completado',
|
||||
'procesados' => count($usuarios),
|
||||
'resultados' => $resultados,
|
||||
]);
|
||||
}
|
||||
}
|
||||
0
ci4/app/Controllers/Sistema/Actividad.php
Normal file → Executable file
0
ci4/app/Controllers/Sistema/Actividad.php
Normal file → Executable file
0
ci4/app/Controllers/Sistema/AuthAPIController.php
Normal file → Executable file
0
ci4/app/Controllers/Sistema/AuthAPIController.php
Normal file → Executable file
534
ci4/app/Controllers/Sistema/Backups.php
Normal file
534
ci4/app/Controllers/Sistema/Backups.php
Normal file
@ -0,0 +1,534 @@
|
||||
<?php
|
||||
namespace App\Controllers\Sistema;
|
||||
|
||||
use App\Controllers\BaseController;
|
||||
use App\Models\Sistema\BackupModel;
|
||||
use phpseclib3\Net\SFTP;
|
||||
use ZipArchive;
|
||||
|
||||
class Backups extends BaseController
|
||||
{
|
||||
protected $backupModel;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->backupModel = new BackupModel();
|
||||
}
|
||||
|
||||
public function index()
|
||||
{
|
||||
helper('filesystem');
|
||||
|
||||
$entorno = getenv('SK_ENVIRONMENT');
|
||||
$backups = [];
|
||||
|
||||
if ($entorno === 'development') {
|
||||
// Leer archivos directamente del disco en entorno de desarrollo
|
||||
$backups = [];
|
||||
|
||||
// === 1. Backups locales ===
|
||||
$localDir = WRITEPATH . 'backups/';
|
||||
$localFiles = get_filenames($localDir);
|
||||
|
||||
foreach ($localFiles as $file) {
|
||||
if (!str_ends_with($file, '.zip') || !str_starts_with($file, 'backup_dev_')) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$localPath = $localDir . $file;
|
||||
|
||||
$fecha = date('Y-m-d H:i', filemtime($localPath));
|
||||
$tamano = filesize($localPath);
|
||||
$tamanoFmt = $tamano > 1048576
|
||||
? number_format($tamano / 1048576, 2) . ' MB'
|
||||
: number_format($tamano / 1024, 2) . ' KB';
|
||||
|
||||
$backups[$file] = [
|
||||
'id' => null,
|
||||
'filename' => $file,
|
||||
'fecha' => $fecha,
|
||||
'tamano' => $tamanoFmt,
|
||||
'local' => true,
|
||||
'remoto' => false,
|
||||
];
|
||||
}
|
||||
|
||||
// === 2. Backups remotos en SFTP ===
|
||||
$sftpHost = getenv('HIDRIVE_BK_HOST');
|
||||
$sftpUser = getenv('HIDRIVE_BK_USER');
|
||||
$sftpPass = getenv('HIDRIVE_BK_PASS');
|
||||
$remoteDir = getenv('HIDRIVE_BK_PATH_ROOT');
|
||||
|
||||
$sftp = new SFTP($sftpHost);
|
||||
if ($sftp->login($sftpUser, $sftpPass)) {
|
||||
$remoteFiles = $sftp->nlist($remoteDir);
|
||||
|
||||
foreach ($remoteFiles as $file) {
|
||||
if (!str_ends_with($file, '.zip') || !str_starts_with($file, 'backup_')) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Verificar si ya se cargó como local
|
||||
$alreadyLocal = isset($backups[$file]);
|
||||
|
||||
// Obtener info de archivo remoto
|
||||
$stat = $sftp->stat($remoteDir . $file);
|
||||
$fecha = isset($stat['mtime']) ? date('Y-m-d H:i', $stat['mtime']) : '-';
|
||||
$tamano = $stat['size'] ?? null;
|
||||
$tamanoFmt = $tamano > 1048576
|
||||
? number_format($tamano / 1048576, 2) . ' MB'
|
||||
: number_format($tamano / 1024, 2) . ' KB';
|
||||
|
||||
$backups[$file] = [
|
||||
'id' => null,
|
||||
'filename' => $file,
|
||||
'fecha' => $fecha,
|
||||
'tamano' => $tamanoFmt,
|
||||
'local' => $alreadyLocal,
|
||||
'remoto' => true,
|
||||
];
|
||||
}
|
||||
} else {
|
||||
// Opcional: mostrar un error o dejarlo pasar silenciosamente
|
||||
session()->setFlashdata('warning', 'No se pudo conectar al servidor SFTP para obtener backups remotos.');
|
||||
}
|
||||
|
||||
// Convertir a lista (por si se usó índice por filename)
|
||||
$backups = array_values($backups);
|
||||
|
||||
} else {
|
||||
// En producción: seguir usando la base de datos
|
||||
$entries = $this->backupModel->orderBy('created_at', 'DESC')->findAll();
|
||||
|
||||
foreach ($entries as $entry) {
|
||||
$file = $entry['filename'];
|
||||
|
||||
if (!str_ends_with($file, '.zip')) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$localPath = $entry['path_local'];
|
||||
$remotePath = $entry['path_remote'];
|
||||
|
||||
$isLocal = $localPath && file_exists($localPath);
|
||||
$isRemote = !empty($remotePath);
|
||||
|
||||
if ($isLocal) {
|
||||
$fecha = date('Y-m-d H:i', filemtime($localPath));
|
||||
$tamano = filesize($localPath);
|
||||
$tamanoFmt = $tamano > 1048576
|
||||
? number_format($tamano / 1048576, 2) . ' MB'
|
||||
: number_format($tamano / 1024, 2) . ' KB';
|
||||
|
||||
if ($entry['size'] != $tamano) {
|
||||
$this->backupModel->update($entry['id'], [
|
||||
'size' => $tamano,
|
||||
]);
|
||||
}
|
||||
|
||||
} else {
|
||||
$fecha = $entry['created_at'] ?? '-';
|
||||
$tamano = $entry['size'] ?? null;
|
||||
$tamanoFmt = $tamano > 1048576
|
||||
? number_format($tamano / 1048576, 2) . ' MB'
|
||||
: number_format($tamano / 1024, 2) . ' KB';
|
||||
}
|
||||
|
||||
$backups[] = [
|
||||
'id' => $entry['id'],
|
||||
'filename' => $file,
|
||||
'fecha' => $fecha,
|
||||
'tamano' => $tamanoFmt,
|
||||
'local' => $isLocal,
|
||||
'remoto' => $isRemote,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
return view('themes/vuexy/form/backups/backupList', ['backups' => $backups]);
|
||||
}
|
||||
|
||||
public function create()
|
||||
{
|
||||
if (getenv('SK_ENVIRONMENT') !== 'production') {
|
||||
return redirect()->to(route_to('backupsList'))->with('error', 'No permitido en entorno de desarrollo.');
|
||||
}
|
||||
|
||||
helper('filesystem');
|
||||
|
||||
$timestamp = date('Ymd_His');
|
||||
$sqlFilename = "backup_{$timestamp}.sql";
|
||||
$zipFilename = "backup_{$timestamp}.zip";
|
||||
$sqlPath = WRITEPATH . 'backups/' . $sqlFilename;
|
||||
$zipPath = WRITEPATH . 'backups/' . $zipFilename;
|
||||
|
||||
$dbConfig = config('Database')->default;
|
||||
$host = $dbConfig['hostname'];
|
||||
$username = $dbConfig['username'];
|
||||
$password = $dbConfig['password'];
|
||||
$database = $dbConfig['database'];
|
||||
|
||||
$command = "mysqldump -h {$host} -u" . escapeshellarg($username) . " -p'" . addslashes($password) . "' {$database} > {$sqlPath}";
|
||||
|
||||
system($command, $retval);
|
||||
|
||||
if ($retval !== 0) {
|
||||
throw new \RuntimeException("Error al crear el backup.");
|
||||
}
|
||||
|
||||
// Crear el zip
|
||||
$zip = new ZipArchive();
|
||||
if ($zip->open($zipPath, ZipArchive::CREATE) === TRUE) {
|
||||
$zip->addFile($sqlPath, $sqlFilename);
|
||||
$zip->close();
|
||||
unlink($sqlPath); // eliminar el .sql original
|
||||
} else {
|
||||
throw new \RuntimeException("Error al comprimir el backup.");
|
||||
}
|
||||
|
||||
// Insertar en BD
|
||||
$backupId = $this->backupModel->insert([
|
||||
'filename' => $zipFilename,
|
||||
'type' => 'manual',
|
||||
'path_local' => $zipPath,
|
||||
'path_remote' => null,
|
||||
'size' => filesize($zipPath),
|
||||
'status' => 'pendiente',
|
||||
'created_at' => date('Y-m-d H:i:s')
|
||||
], true);
|
||||
|
||||
// Enviar a SFTP
|
||||
$this->sendToSFTP($zipPath, $zipFilename);
|
||||
|
||||
// Actualizar BD
|
||||
$remotePath = "/users/erp2019/backups_erp/" . $zipFilename;
|
||||
$this->backupModel->update($backupId, [
|
||||
'path_remote' => $remotePath,
|
||||
'status' => 'subido'
|
||||
]);
|
||||
|
||||
return redirect()->to(route_to('backupsList'))->with('message', 'Backup del entorno de produccion creado, comprimido y enviado al remoto.');
|
||||
}
|
||||
|
||||
public function createDevelopment()
|
||||
{
|
||||
if (getenv('SK_ENVIRONMENT') !== 'development') {
|
||||
return redirect()->to(route_to('backupsList'))->with('error', 'Esta acción solo está permitida en desarrollo.');
|
||||
}
|
||||
|
||||
helper('filesystem');
|
||||
|
||||
$timestamp = date('Ymd_His');
|
||||
$sqlFilename = "backup_dev_{$timestamp}.sql";
|
||||
$zipFilename = "backup_dev_{$timestamp}.zip";
|
||||
$sqlPath = WRITEPATH . 'backups/' . $sqlFilename;
|
||||
$zipPath = WRITEPATH . 'backups/' . $zipFilename;
|
||||
|
||||
$dbConfig = config('Database')->default;
|
||||
$host = $dbConfig['hostname'];
|
||||
$username = $dbConfig['username'];
|
||||
$password = $dbConfig['password'];
|
||||
$database = $dbConfig['database'];
|
||||
|
||||
$command = "mysqldump -h {$host} -u{$username} -p'{$password}' {$database} > {$sqlPath}";
|
||||
system($command, $retval);
|
||||
|
||||
if ($retval !== 0) {
|
||||
throw new \RuntimeException("Error al crear el backup local.");
|
||||
}
|
||||
|
||||
$zip = new \ZipArchive();
|
||||
if ($zip->open($zipPath, \ZipArchive::CREATE) === TRUE) {
|
||||
$zip->addFile($sqlPath, $sqlFilename);
|
||||
$zip->close();
|
||||
unlink($sqlPath);
|
||||
} else {
|
||||
throw new \RuntimeException("Error al comprimir el backup local.");
|
||||
}
|
||||
|
||||
// Ya no insertamos en la base de datos; el archivo queda en disco y se listará dinámicamente
|
||||
return redirect()->to(route_to('backupsList'))->with('message', 'Backup local del entorno de desarrollo creado.');
|
||||
}
|
||||
|
||||
|
||||
public function download($filename)
|
||||
{
|
||||
helper('filesystem');
|
||||
|
||||
$entorno = getenv('SK_ENVIRONMENT');
|
||||
|
||||
$backup = $this->backupModel->where('filename', $filename)->first();
|
||||
|
||||
// 1. Si hay entrada en la base de datos
|
||||
if ($backup) {
|
||||
$localPath = $backup['path_local'];
|
||||
$remotePath = $backup['path_remote'];
|
||||
|
||||
if ($localPath && file_exists($localPath)) {
|
||||
return $this->response->download($localPath, null)->setFileName($filename);
|
||||
}
|
||||
|
||||
if (!empty($remotePath)) {
|
||||
$sftpHost = getenv('HIDRIVE_BK_HOST');
|
||||
$sftpUser = getenv('HIDRIVE_BK_USER');
|
||||
$sftpPass = getenv('HIDRIVE_BK_PASS');
|
||||
|
||||
|
||||
$sftp = new SFTP($sftpHost);
|
||||
|
||||
if (!$sftp->login($sftpUser, $sftpPass)) {
|
||||
return redirect()->to(route_to('backupsList'))->with('error', 'No se pudo conectar al servidor SFTP.');
|
||||
}
|
||||
|
||||
$fileContents = $sftp->get($remotePath);
|
||||
if ($fileContents === false) {
|
||||
return redirect()->to(route_to('backupsList'))->with('error', 'Error al descargar desde SFTP.');
|
||||
}
|
||||
|
||||
$newLocalPath = WRITEPATH . 'backups/' . $filename;
|
||||
write_file($newLocalPath, $fileContents);
|
||||
|
||||
// Omitimos update() si estamos en desarrollo sin base de datos
|
||||
if ($entorno === 'production') {
|
||||
$this->backupModel->update($backup['id'], ['path_local' => $newLocalPath]);
|
||||
}
|
||||
|
||||
return $this->response->download($newLocalPath, null)->setFileName($filename);
|
||||
}
|
||||
|
||||
return redirect()->to(route_to('backupsList'))->with('error', 'No se pudo encontrar el archivo ni local ni remoto.');
|
||||
}
|
||||
|
||||
// 2. Si NO hay entrada en la BD y estamos en desarrollo
|
||||
if ($entorno === 'development') {
|
||||
$localPath = WRITEPATH . 'backups/' . $filename;
|
||||
|
||||
if (file_exists($localPath)) {
|
||||
return $this->response->download($localPath, null)->setFileName($filename);
|
||||
}
|
||||
|
||||
// También se puede intentar buscar en el SFTP si quieres
|
||||
$sftpHost = getenv('HIDRIVE_BK_HOST');
|
||||
$sftpUser = getenv('HIDRIVE_BK_USER');
|
||||
$sftpPass = getenv('HIDRIVE_BK_PASS');
|
||||
$remotePath = getenv('HIDRIVE_BK_PATH_ROOT') . $filename;
|
||||
|
||||
$sftp = new SFTP($sftpHost);
|
||||
if ($sftp->login($sftpUser, $sftpPass)) {
|
||||
$fileContents = $sftp->get($remotePath);
|
||||
if ($fileContents !== false) {
|
||||
$newLocalPath = WRITEPATH . 'backups/' . $filename;
|
||||
write_file($newLocalPath, $fileContents);
|
||||
return $this->response->download($newLocalPath, null)->setFileName($filename);
|
||||
}
|
||||
}
|
||||
|
||||
return redirect()->to(route_to('backupsList'))->with('error', 'Archivo no encontrado local ni remoto (sin base de datos).');
|
||||
}
|
||||
|
||||
return redirect()->to(route_to('backupsList'))->with('error', 'Backup no encontrado.');
|
||||
}
|
||||
|
||||
|
||||
|
||||
public function deleteLocal($id)
|
||||
{
|
||||
$entorno = getenv('SK_ENVIRONMENT');
|
||||
$backup = $this->backupModel->find($id);
|
||||
|
||||
if (!$backup) {
|
||||
return redirect()->to(route_to('backupsList'))->with('error', 'Backup no encontrado en la base de datos.');
|
||||
}
|
||||
|
||||
$localPath = $backup['path_local'];
|
||||
|
||||
// Si existe el archivo, intentamos borrarlo
|
||||
if ($localPath && file_exists($localPath)) {
|
||||
unlink($localPath);
|
||||
}
|
||||
|
||||
if ($entorno === 'production') {
|
||||
// Solo desvincular el archivo local
|
||||
$this->backupModel->update($id, ['path_local' => null]);
|
||||
return redirect()->to(route_to('backupsList'))->with('message', 'Archivo local eliminado (registro conservado).');
|
||||
} else {
|
||||
// Eliminar completamente en desarrollo
|
||||
$this->backupModel->delete($id);
|
||||
return redirect()->to(route_to('backupsList'))->with('message', 'Backup de desarrollo eliminado completamente.');
|
||||
}
|
||||
}
|
||||
|
||||
public function deleteLocalDevelopment($filename)
|
||||
{
|
||||
$entorno = getenv('SK_ENVIRONMENT');
|
||||
if ($entorno !== 'development') {
|
||||
return redirect()->to(route_to('backupsList'))->with('error', 'Solo permitido en desarrollo.');
|
||||
}
|
||||
|
||||
$path = WRITEPATH . 'backups/' . $filename;
|
||||
|
||||
if (file_exists($path)) {
|
||||
unlink($path);
|
||||
return redirect()->to(route_to('backupsList'))->with('message', "Archivo '$filename' eliminado del sistema de archivos.");
|
||||
}
|
||||
|
||||
return redirect()->to(route_to('backupsList'))->with('error', "Archivo '$filename' no encontrado en el sistema.");
|
||||
}
|
||||
|
||||
|
||||
|
||||
public function restoreLocal($file)
|
||||
{
|
||||
$path = WRITEPATH . 'backups/' . $file;
|
||||
|
||||
if (!file_exists($path)) {
|
||||
throw new \CodeIgniter\Exceptions\PageNotFoundException("Backup no encontrado.");
|
||||
}
|
||||
|
||||
$zip = new \ZipArchive();
|
||||
if ($zip->open($path) === TRUE) {
|
||||
$extractPath = WRITEPATH . 'backups/tmp_restore/';
|
||||
if (!is_dir($extractPath)) {
|
||||
mkdir($extractPath, 0775, true);
|
||||
}
|
||||
$zip->extractTo($extractPath);
|
||||
$zip->close();
|
||||
|
||||
$sqlFiles = glob($extractPath . '*.sql');
|
||||
if (count($sqlFiles) === 0) {
|
||||
throw new \RuntimeException("No se encontró ningún archivo .sql en el ZIP");
|
||||
}
|
||||
|
||||
$sqlFile = $sqlFiles[0];
|
||||
|
||||
// === Verificar que el archivo SQL existe y tiene contenido
|
||||
if (!file_exists($sqlFile)) {
|
||||
throw new \RuntimeException("Archivo SQL no encontrado.");
|
||||
}
|
||||
|
||||
if (filesize($sqlFile) === 0) {
|
||||
throw new \RuntimeException("El archivo SQL está vacío.");
|
||||
}
|
||||
|
||||
// === Configuración de base de datos
|
||||
$dbConfig = config('Database')->default;
|
||||
$host = escapeshellarg($dbConfig['hostname']);
|
||||
$username = escapeshellarg($dbConfig['username']);
|
||||
$password = escapeshellarg($dbConfig['password']);
|
||||
$database = escapeshellarg($dbConfig['database']);
|
||||
|
||||
// === Construcción del comando con stderr redirigido
|
||||
$cmd = "mysql -h $host -u $username -p$password $database -e \"source $sqlFile\" 2>&1";
|
||||
|
||||
// === Ejecutar y capturar la salida
|
||||
exec($cmd, $output, $retval);
|
||||
|
||||
// === Verificar resultado
|
||||
if ($retval !== 0) {
|
||||
throw new \RuntimeException("Error al restaurar la base de datos:\n" . implode("\n", $output));
|
||||
}
|
||||
|
||||
// === Limpieza
|
||||
helper('filesystem');
|
||||
delete_files($extractPath, true); // elimina contenido
|
||||
rmdir($extractPath); // elimina el directorio
|
||||
|
||||
return redirect()->to(route_to('backupsList'))->with('message', 'Backup restaurado correctamente (vía sistema).');
|
||||
} else {
|
||||
throw new \RuntimeException("No se pudo abrir el archivo ZIP");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
public function restoreRemote($filename)
|
||||
{
|
||||
helper('filesystem');
|
||||
|
||||
$entorno = getenv('SK_ENVIRONMENT');
|
||||
|
||||
if ($entorno === 'development') {
|
||||
// Construir ruta remota directamente
|
||||
$remotePath = '/users/erp2019/backups_erp/' . $filename;
|
||||
$localPath = WRITEPATH . 'backups/' . $filename;
|
||||
|
||||
$sftpHost = getenv('HIDRIVE_BK_HOST');
|
||||
$sftpUser = getenv('HIDRIVE_BK_USER');
|
||||
$sftpPass = getenv('HIDRIVE_BK_PASS');
|
||||
|
||||
$sftp = new SFTP($sftpHost);
|
||||
if (!$sftp->login($sftpUser, $sftpPass)) {
|
||||
return redirect()->to(route_to('backupsList'))->with('error', 'No se pudo autenticar en el servidor SFTP.');
|
||||
}
|
||||
|
||||
$fileContents = $sftp->get($remotePath);
|
||||
if ($fileContents === false) {
|
||||
return redirect()->to(route_to('backupsList'))->with('error', 'No se pudo descargar el archivo remoto.');
|
||||
}
|
||||
|
||||
if (write_file($localPath, $fileContents) === false) {
|
||||
return redirect()->to(route_to('backupsList'))->with('error', 'No se pudo guardar el archivo localmente.');
|
||||
}
|
||||
|
||||
// Restaurar directamente
|
||||
return $this->restoreLocal($filename);
|
||||
}
|
||||
|
||||
// Producción: flujo normal con base de datos
|
||||
$backup = $this->backupModel->where('filename', $filename)->first();
|
||||
|
||||
if (!$backup || empty($backup['path_remote'])) {
|
||||
return redirect()->to(route_to('backupsList'))->with('error', 'Backup remoto no encontrado en la base de datos.');
|
||||
}
|
||||
|
||||
$remotePath = $backup['path_remote'];
|
||||
$localPath = WRITEPATH . 'backups/' . $filename;
|
||||
|
||||
$sftpHost = getenv('HIDRIVE_BK_HOST');
|
||||
$sftpUser = getenv('HIDRIVE_BK_USER');
|
||||
$sftpPass = getenv('HIDRIVE_BK_PASS');
|
||||
|
||||
$sftp = new SFTP($sftpHost);
|
||||
if (!$sftp->login($sftpUser, $sftpPass)) {
|
||||
return redirect()->to(route_to('backupsList'))->with('error', 'No se pudo autenticar en el servidor SFTP.');
|
||||
}
|
||||
|
||||
$fileContents = $sftp->get($remotePath);
|
||||
if ($fileContents === false) {
|
||||
return redirect()->to(route_to('backupsList'))->with('error', 'No se pudo descargar el archivo remoto.');
|
||||
}
|
||||
|
||||
if (write_file($localPath, $fileContents) === false) {
|
||||
return redirect()->to(route_to('backupsList'))->with('error', 'No se pudo guardar el archivo localmente.');
|
||||
}
|
||||
|
||||
$this->backupModel->update($backup['id'], ['path_local' => $localPath]);
|
||||
|
||||
return $this->restoreLocal($filename);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
private function sendToSFTP($localPath, $remoteFilename)
|
||||
{
|
||||
$sftpHost = getenv('HIDRIVE_BK_HOST');
|
||||
$sftpUser = getenv('HIDRIVE_BK_USER');
|
||||
$sftpPass = getenv('HIDRIVE_BK_PASS');
|
||||
$remotePath = getenv('HIDRIVE_BK_PATH_ROOT') . $remoteFilename;
|
||||
|
||||
$sftp = new SFTP($sftpHost);
|
||||
|
||||
if (!$sftp->login($sftpUser, $sftpPass)) {
|
||||
throw new \RuntimeException('Error de autenticación SFTP');
|
||||
}
|
||||
|
||||
$fileContents = file_get_contents($localPath);
|
||||
|
||||
if (!$sftp->put($remotePath, $fileContents)) {
|
||||
throw new \RuntimeException("No se pudo subir el backup al servidor SFTP.");
|
||||
}
|
||||
}
|
||||
}
|
||||
27
ci4/app/Controllers/Sistema/Intranet.php
Normal file → Executable file
27
ci4/app/Controllers/Sistema/Intranet.php
Normal file → Executable file
@ -56,10 +56,33 @@ class Intranet extends Controller
|
||||
}
|
||||
|
||||
}
|
||||
function orden_trabajo($ot_id,$resource_name)
|
||||
function orden_trabajo($ot_id, $resource_name)
|
||||
{
|
||||
helper('file');
|
||||
$resource_path = WRITEPATH . 'uploads/orden_trabajo/'.$ot_id. '/' . $resource_name;
|
||||
$resource_path = WRITEPATH . 'uploads/orden_trabajo/' . $ot_id . '/' . $resource_name;
|
||||
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();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
function catalogo($catalogo_id, $resource_name)
|
||||
{
|
||||
helper('file');
|
||||
$resource_path = WRITEPATH . 'uploads/catalogo/' . $catalogo_id . '/' . $resource_name;
|
||||
if (file_exists($resource_path)) {
|
||||
// Get the mime type of the file
|
||||
$mime_type = mime_content_type($resource_path);
|
||||
|
||||
7
ci4/app/Controllers/Soporte/Ticketcontroller.php
Normal file → Executable file
7
ci4/app/Controllers/Soporte/Ticketcontroller.php
Normal file → Executable file
@ -153,7 +153,10 @@ class Ticketcontroller extends \App\Controllers\BaseResourceController
|
||||
return $this->redirect2listView();
|
||||
endif;
|
||||
$id = filter_var($requestedId, FILTER_SANITIZE_URL);
|
||||
$ticket = $this->model->find($id);
|
||||
$ticket = $this->model->select("tickets.*, CONCAT(users.first_name, ' ',users.last_name) as usuario_ticket")
|
||||
->join('users', 'users.id = tickets.usuario_id', 'left')
|
||||
->where('tickets.id', $id)->first();
|
||||
|
||||
|
||||
if ($ticket == false):
|
||||
$message = lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('Tickets.ticket')), $id]);
|
||||
@ -275,7 +278,7 @@ class Ticketcontroller extends \App\Controllers\BaseResourceController
|
||||
|
||||
$searchValues = get_filter_datatables_columns($reqData);
|
||||
|
||||
if (auth()->user()->can('tickets.edit')) {
|
||||
if (auth()->user()->can('tickets.edit') && auth()->user()->inGroup('admin')) {
|
||||
$user_id = null;
|
||||
} else {
|
||||
$user_id = auth()->user()->id;
|
||||
|
||||
6
ci4/app/Controllers/Tarifas/Acabados/ServiciosAcabado.php
Normal file → Executable file
6
ci4/app/Controllers/Tarifas/Acabados/ServiciosAcabado.php
Normal file → Executable file
@ -25,6 +25,8 @@ class ServiciosAcabado extends BaseResourceController
|
||||
|
||||
protected $indexRoute = 'serviciosAcabadoList';
|
||||
|
||||
protected $deletePermission = 'tarifa-acabado.delete';
|
||||
|
||||
|
||||
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
|
||||
{
|
||||
@ -80,7 +82,7 @@ class ServiciosAcabado extends BaseResourceController
|
||||
$sanitizedData['user_updated_id'] = auth()->user()->id;
|
||||
|
||||
if ($this->request->getPost('mostrar_en_presupuesto_cliente') == null) {
|
||||
$sanitizedData['mostrar_en_presupuesto'] = false;
|
||||
$sanitizedData['mostrar_en_presupuesto_cliente'] = false;
|
||||
}
|
||||
|
||||
if ($this->request->getPost('acabado_cubierta') == null) {
|
||||
@ -174,7 +176,7 @@ class ServiciosAcabado extends BaseResourceController
|
||||
$sanitizedData['user_updated_id'] = auth()->user()->id;
|
||||
|
||||
if ($this->request->getPost('mostrar_en_presupuesto_cliente') == null) {
|
||||
$sanitizedData['mostrar_en_presupuesto'] = false;
|
||||
$sanitizedData['mostrar_en_presupuesto_cliente'] = false;
|
||||
}
|
||||
|
||||
if ($this->request->getPost('acabado_cubierta') == null) {
|
||||
|
||||
2
ci4/app/Controllers/Tarifas/Acabados/TarifaAcabados.php
Normal file → Executable file
2
ci4/app/Controllers/Tarifas/Acabados/TarifaAcabados.php
Normal file → Executable file
@ -28,6 +28,8 @@ class TarifaAcabados extends BaseResourceController
|
||||
|
||||
protected $indexRoute = 'tarifaAcabadoList';
|
||||
|
||||
protected $deletePermission = 'tarifa-acabado.delete';
|
||||
|
||||
|
||||
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
|
||||
{
|
||||
|
||||
0
ci4/app/Controllers/Tarifas/Acabados/TarifaAcabadosLineas.php
Normal file → Executable file
0
ci4/app/Controllers/Tarifas/Acabados/TarifaAcabadosLineas.php
Normal file → Executable file
0
ci4/app/Controllers/Tarifas/Maquinas/TarifaMaquinas.php
Normal file → Executable file
0
ci4/app/Controllers/Tarifas/Maquinas/TarifaMaquinas.php
Normal file → Executable file
@ -19,6 +19,8 @@ class Tarifaextra extends \App\Controllers\GoBaseController
|
||||
|
||||
protected $indexRoute = 'tarifaextraList';
|
||||
|
||||
protected $deletePermission = 'tarifa-extra.delete';
|
||||
|
||||
|
||||
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
|
||||
{
|
||||
|
||||
@ -19,6 +19,8 @@ class Tarifapreimpresion extends \App\Controllers\GoBaseController
|
||||
|
||||
protected $indexRoute = 'tarifapreimpresionList';
|
||||
|
||||
protected $deletePermission = 'tarifa-preimpresion.delete';
|
||||
|
||||
|
||||
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
|
||||
{
|
||||
|
||||
@ -32,6 +32,8 @@ class Tarifasencuadernacion extends \App\Controllers\BaseResourceController
|
||||
|
||||
protected $indexRoute = 'tarifaEncuadernacionList';
|
||||
|
||||
protected $deletePermission = 'tarifa-encuadernacion.delete';
|
||||
|
||||
|
||||
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
|
||||
{
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user