26 Commits

Author SHA1 Message Date
2e80fddfb6 añadidos más formatos a tarifas encuadernacion lineas (dimensiones) 2024-11-07 14:15:14 +01:00
1e2d550301 archivos resumen 2024-11-06 22:10:09 +01:00
0a3618cd00 Merge branch 'fix/message-notification' into 'dev/presu_cliente_v2'
Fix/message notification

See merge request jjimenez/safekat!359
2024-11-06 21:09:05 +00:00
33fbfc1a5d Merge branch 'dev/presu_cliente_v2' into fix/message-notification 2024-11-06 22:06:02 +01:00
a8612f64a4 fix : notification clientes add where chat_department_id is not NULL 2024-11-06 19:56:20 +01:00
0b614d4d58 bug para presupuesto cliente (en direcciones) 2024-11-06 17:15:41 +01:00
55b225ab49 errata de 109 en encuadernaciones model 2024-11-05 17:47:30 +01:00
315d2a3acd arreglado carga de cliente 2024-11-04 23:58:18 +01:00
83c8628645 presupuesto cliente para perfil cliente 2024-10-31 08:42:41 +01:00
d0ee0b27bc precio minimo en tarifa encuadernacion a nivel de lineas 2024-10-30 18:36:35 +01:00
8556887567 vuelta a importe minimo en tiradas 2024-10-30 17:46:35 +01:00
f50987dc2b arreglado bug con tamaño personalizado en presupuesto admin 2024-10-28 18:52:06 +01:00
4180cea16a Merge branch 'fix/message-notification' into 'dev/presu_cliente_v2'
refactor : in message notification send client to presupuestocliente and admin...

See merge request jjimenez/safekat!357
2024-10-26 11:15:09 +00:00
0b3bf0ed85 refactor : in message notification send client to presupuestocliente and admin or beta to presupuesto admin 2024-10-26 08:56:18 +02:00
14fe3b1461 refactor : in message notification send client to presupuestocliente and admin or beta to presupuesto admin 2024-10-26 08:56:06 +02:00
58ab81d8e8 arreglado el poder guardar sin direcciones 2024-10-25 13:59:23 +02:00
cdb9afc290 arreglando el lomo de cubierta cuando cambias de fresado a cosido 2024-10-25 13:56:37 +02:00
adcf2fbec3 arreglado grapado 2024-10-25 13:42:09 +02:00
eb806621c6 preview
terminada
2024-10-25 12:30:38 +02:00
0963fae240 preview 2024-10-25 12:12:16 +02:00
daa10420c7 Merge branch 'fix/datatable-error-presupuesto' into 'dev/presu_cliente_v2'
default sort error presupuestos datatable,set pagination to 50 and add page selector

See merge request jjimenez/safekat!356
2024-10-25 09:29:30 +00:00
716019bf81 default sort error presupuestos datatable,set pagination to 50 and add page selector 2024-10-25 11:27:27 +02:00
2ac99d14c0 click para moverse del menu 2024-10-24 21:05:59 +02:00
0f00649f99 corregidos errores 2024-10-24 08:50:13 +02:00
3dd9f8f7e3 fix notification chat error cuando cliente no tiene facturas asociadas 2024-10-23 05:48:06 +00:00
c79bc4343f Merge branch 'feat/add-chat-presupuesto-cliente' into 'dev/presu_cliente_v2'
Feat/add chat presupuesto cliente

See merge request jjimenez/safekat!354
2024-10-23 05:19:36 +00:00
2254 changed files with 41127 additions and 71586 deletions

View File

@ -1,42 +0,0 @@
# Indica que este es el archivo de configuración raíz
root = true
# Configuración global para todos los archivos
[*]
charset = utf-8 # Codificación UTF-8
end_of_line = lf # Saltos de línea tipo Unix (LF)
trim_trailing_whitespace = true # Eliminar espacios en blanco finales
insert_final_newline = true # Asegura una nueva línea al final del archivo
# Configuración para archivos PHP
[*.php]
indent_style = space # Usar espacios en lugar de tabulaciones
indent_size = 4 # Tamaño de indentación de 4 espacios
# Configuración para archivos JavaScript
[*.js]
indent_style = space # Usar espacios en lugar de tabulaciones
indent_size = 2 # Tamaño de indentación de 2 espacios
quote_type = single # Usar comillas simples por defecto
trim_trailing_whitespace = true # Eliminar espacios en blanco finales
# Configuración para archivos de estilos CSS
[*.css]
indent_style = space # Usar espacios en lugar de tabulaciones
indent_size = 2 # Tamaño de indentación de 2 espacios
# Configuración para archivos JSON
[*.json]
indent_style = space # Usar espacios en lugar de tabulaciones
indent_size = 2 # Tamaño de indentación de 2 espacios
# Configuración para archivos de vista (HTML y Blade)
[*.{html,blade.php}]
indent_style = space # Usar espacios en lugar de tabulaciones
indent_size = 4 # Tamaño de indentación de 4 espacios
trim_trailing_whitespace = true # Eliminar espacios en blanco finales
# Configuración para archivos Markdown
[*.md]
trim_trailing_whitespace = false # No eliminar espacios en blanco finales
insert_final_newline = false # No agregar una nueva línea al final del archivo

6
.gitignore vendored
View File

@ -1,5 +1,5 @@
ci4/.env
.vscode/
launch.json
*xdebug*.log*
ci4/app/Config/RBAC/*
xdebug.log
xdebug.*

44
.idea/deployment.xml generated Executable file
View File

@ -0,0 +1,44 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="PublishConfigData" autoUpload="Always" serverName="SK-IMN" remoteFilesAllowedToDisappearOnAutoupload="false" confirmBeforeUploading="false">
<option name="confirmBeforeUploading" value="false" />
<serverData>
<paths name="ERP-DEMO">
<serverdata>
<mappings>
<mapping local="$PROJECT_DIR$" web="/" />
</mappings>
</serverdata>
</paths>
<paths name="SK-DEV">
<serverdata>
<mappings>
<mapping local="$PROJECT_DIR$" web="/" />
</mappings>
</serverdata>
</paths>
<paths name="SK-IMN">
<serverdata>
<mappings>
<mapping deploy="/" local="$PROJECT_DIR$" web="/" />
</mappings>
</serverdata>
</paths>
<paths name="SK-JJO">
<serverdata>
<mappings>
<mapping deploy="/" local="$PROJECT_DIR$" web="/" />
</mappings>
</serverdata>
</paths>
<paths name="SK-MAIN">
<serverdata>
<mappings>
<mapping deploy="/" local="$PROJECT_DIR$" web="/" />
</mappings>
</serverdata>
</paths>
</serverData>
<option name="myAutoUpload" value="ALWAYS" />
</component>
</project>

6
.idea/inspectionProfiles/Project_Default.xml generated Executable file
View File

@ -0,0 +1,6 @@
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="Eslint" enabled="true" level="WARNING" enabled_by_default="true" />
</profile>
</component>

8
.idea/modules.xml generated Executable file
View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/safekat.iml" filepath="$PROJECT_DIR$/.idea/safekat.iml" />
</modules>
</component>
</project>

74
.idea/php.xml generated Executable file
View File

@ -0,0 +1,74 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="MessDetectorOptionsConfiguration">
<option name="transferred" value="true" />
</component>
<component name="PHPCSFixerOptionsConfiguration">
<option name="transferred" value="true" />
</component>
<component name="PHPCodeSnifferOptionsConfiguration">
<option name="highlightLevel" value="WARNING" />
<option name="transferred" value="true" />
</component>
<component name="PhpIncludePathManager">
<include_path>
<path value="$PROJECT_DIR$/ci4/vendor/psr/log" />
<path value="$PROJECT_DIR$/ci4/vendor/psr/container" />
<path value="$PROJECT_DIR$/ci4/vendor/nikic/php-parser" />
<path value="$PROJECT_DIR$/ci4/vendor/phenx/php-svg-lib" />
<path value="$PROJECT_DIR$/ci4/vendor/phenx/php-font-lib" />
<path value="$PROJECT_DIR$/ci4/vendor/dompdf/dompdf" />
<path value="$PROJECT_DIR$/ci4/vendor/laminas/laminas-escaper" />
<path value="$PROJECT_DIR$/ci4/vendor/myclabs/deep-copy" />
<path value="$PROJECT_DIR$/ci4/vendor/phar-io/version" />
<path value="$PROJECT_DIR$/ci4/vendor/phar-io/manifest" />
<path value="$PROJECT_DIR$/ci4/vendor/phpunit/phpunit" />
<path value="$PROJECT_DIR$/ci4/vendor/phpunit/php-timer" />
<path value="$PROJECT_DIR$/ci4/vendor/phpunit/php-invoker" />
<path value="$PROJECT_DIR$/ci4/vendor/phpunit/php-code-coverage" />
<path value="$PROJECT_DIR$/ci4/vendor/phpunit/php-file-iterator" />
<path value="$PROJECT_DIR$/ci4/vendor/phpunit/php-text-template" />
<path value="$PROJECT_DIR$/ci4/vendor/symfony/deprecation-contracts" />
<path value="$PROJECT_DIR$/ci4/vendor/theseer/tokenizer" />
<path value="$PROJECT_DIR$/ci4/vendor/composer" />
<path value="$PROJECT_DIR$/ci4/vendor/doctrine/instantiator" />
<path value="$PROJECT_DIR$/ci4/vendor/fakerphp/faker" />
<path value="$PROJECT_DIR$/ci4/vendor/mikey179/vfsstream" />
<path value="$PROJECT_DIR$/ci4/vendor/sebastian/diff" />
<path value="$PROJECT_DIR$/ci4/vendor/sebastian/type" />
<path value="$PROJECT_DIR$/ci4/vendor/sebastian/version" />
<path value="$PROJECT_DIR$/ci4/vendor/sebastian/exporter" />
<path value="$PROJECT_DIR$/ci4/vendor/sebastian/code-unit" />
<path value="$PROJECT_DIR$/ci4/vendor/sebastian/cli-parser" />
<path value="$PROJECT_DIR$/ci4/vendor/sebastian/comparator" />
<path value="$PROJECT_DIR$/ci4/vendor/sebastian/complexity" />
<path value="$PROJECT_DIR$/ci4/vendor/sebastian/environment" />
<path value="$PROJECT_DIR$/ci4/vendor/sebastian/global-state" />
<path value="$PROJECT_DIR$/ci4/vendor/sebastian/lines-of-code" />
<path value="$PROJECT_DIR$/ci4/vendor/sebastian/object-reflector" />
<path value="$PROJECT_DIR$/ci4/vendor/sebastian/object-enumerator" />
<path value="$PROJECT_DIR$/ci4/vendor/sebastian/recursion-context" />
<path value="$PROJECT_DIR$/ci4/vendor/sebastian/resource-operations" />
<path value="$PROJECT_DIR$/ci4/vendor/sebastian/code-unit-reverse-lookup" />
<path value="$PROJECT_DIR$/ci4/vendor/sabberworm/php-css-parser" />
<path value="$PROJECT_DIR$/ci4/vendor/masterminds/html5" />
<path value="$PROJECT_DIR$/ci4/vendor/codeigniter4/shield" />
<path value="$PROJECT_DIR$/ci4/vendor/codeigniter4/settings" />
<path value="$PROJECT_DIR$/ci4/vendor/codeigniter4/framework" />
</include_path>
</component>
<component name="PhpProjectSharedConfiguration" php_language_level="8.2">
<option name="suggestChangeDefaultLanguageLevel" value="false" />
</component>
<component name="PhpStanOptionsConfiguration">
<option name="transferred" value="true" />
</component>
<component name="PhpUnit">
<phpunit_settings>
<PhpUnitSettings custom_loader_path="$PROJECT_DIR$/ci4/vendor/autoload.php" />
</phpunit_settings>
</component>
<component name="PsalmOptionsConfiguration">
<option name="transferred" value="true" />
</component>
</project>

10
.idea/phpunit.xml generated Executable file
View File

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="PHPUnit">
<option name="directories">
<list>
<option value="$PROJECT_DIR$/ci4/tests" />
</list>
</option>
</component>
</project>

14
.idea/safekat.iml generated Executable file
View File

@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="WEB_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/ci4/app" isTestSource="false" packagePrefix="App\" />
<sourceFolder url="file://$MODULE_DIR$/ci4/app/Config" isTestSource="false" packagePrefix="Config\" />
<sourceFolder url="file://$MODULE_DIR$/ci4/app/ThirdParty/DatatablesEditor/" isTestSource="false" packagePrefix="DataTables\" />
<sourceFolder url="file://$MODULE_DIR$/ci4/tests" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/ci4/tests/_support" isTestSource="true" packagePrefix="Tests\Support\" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

6
.idea/vcs.xml generated Executable file
View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
</component>
</project>

51
.idea/webServers.xml generated Executable file
View File

@ -0,0 +1,51 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="WebServers">
<option name="servers">
<webServer id="b340ea2c-6cfa-4862-a020-5d4f6e482cc1" name="SK-MAIN" url="http://sk-main.imnavajas.es">
<fileTransfer host="sk-main.imnavajas.es" port="21">
<advancedOptions>
<advancedOptions dataProtectionLevel="Private" passiveMode="true" shareSSLContext="true" />
</advancedOptions>
</fileTransfer>
</webServer>
<webServer id="c01b8916-f9bb-46f4-a585-5f4f4064aa87" name="SK-IMN" url="http://sk-imn.imnavajas.es">
<fileTransfer host="sk-imn.imnavajas.es" port="21">
<advancedOptions>
<advancedOptions dataProtectionLevel="Private" passiveMode="true" shareSSLContext="true" />
</advancedOptions>
</fileTransfer>
</webServer>
<webServer id="36de594c-5db8-413e-b1a1-cd035ebed2f1" name="SK-JJO" url="http://sk-jjo.imnavajas.es">
<fileTransfer host="sk-jjo.imnavajas.es" port="21">
<advancedOptions>
<advancedOptions dataProtectionLevel="Private" passiveMode="true" shareSSLContext="true" />
</advancedOptions>
</fileTransfer>
</webServer>
<webServer id="85f139d9-24ee-421b-b3fa-c8b68aa8f4ef" name="SK-DEV" url="http://sk-dev.imnavajas.es">
<fileTransfer host="sk-dev.imnavajas.es" port="21">
<advancedOptions>
<advancedOptions dataProtectionLevel="Private" passiveMode="true" shareSSLContext="true" />
</advancedOptions>
</fileTransfer>
</webServer>
<webServer id="94314164-bdb5-40a0-a28a-8d8dc3915eed" name="ERP-DEMO" url="http://erp.safekat.es">
<fileTransfer host="erp.safekat.es" port="21">
<advancedOptions>
<advancedOptions dataProtectionLevel="Private" passiveMode="true" shareSSLContext="true" />
</advancedOptions>
</fileTransfer>
</webServer>
</option>
<groups>
<group>
<name>DEV/UI</name>
<servers>
<name value="SK-MAIN" />
<name value="SK-IMN" />
</servers>
</group>
</groups>
</component>
</project>

188
.idea/workspace.xml generated Executable file
View File

@ -0,0 +1,188 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="AutoImportSettings">
<option name="autoReloadType" value="SELECTIVE" />
</component>
<component name="ChangeListManager">
<list default="true" id="7c8f7059-cd40-417c-936e-48dbc0507d86" name="Changes" comment="Add static Vuexy files">
<<<<<<< HEAD
<change afterPath="$PROJECT_DIR$/ci4/app/Controllers/Compras/Compras.php" afterDir="false" />
<change afterPath="$PROJECT_DIR$/ci4/app/Controllers/Compras/Productos.php" afterDir="false" />
<change afterPath="$PROJECT_DIR$/ci4/app/Controllers/Importacion/Importar.php" afterDir="false" />
<change afterPath="$PROJECT_DIR$/ci4/app/Views/themes/backend/vuexy/main/menu_impresion.php" afterDir="false" />
<change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/ci4/.env" beforeDir="false" afterPath="$PROJECT_DIR$/ci4/.env" afterDir="false" />
<change beforePath="$PROJECT_DIR$/ci4/app/Controllers/Catalogo/Catalogo.php" beforeDir="false" afterPath="$PROJECT_DIR$/ci4/app/Controllers/Catalogo/Catalogo.php" afterDir="false" />
<change beforePath="$PROJECT_DIR$/ci4/app/Controllers/Envioslogistica/Logistica.php" beforeDir="false" afterPath="$PROJECT_DIR$/ci4/app/Controllers/Envioslogistica/Logistica.php" afterDir="false" />
<change beforePath="$PROJECT_DIR$/ci4/app/Controllers/Facturacion/Factura.php" beforeDir="false" afterPath="$PROJECT_DIR$/ci4/app/Controllers/Facturacion/Factura.php" afterDir="false" />
<change beforePath="$PROJECT_DIR$/ci4/app/Controllers/Pedidos/Pedido.php" beforeDir="false" afterPath="$PROJECT_DIR$/ci4/app/Controllers/Pedidos/Pedido.php" afterDir="false" />
<change beforePath="$PROJECT_DIR$/ci4/app/Controllers/Produccion/Ordentrabajo.php" beforeDir="false" afterPath="$PROJECT_DIR$/ci4/app/Controllers/Produccion/Ordentrabajo.php" afterDir="false" />
<change beforePath="$PROJECT_DIR$/ci4/app/Controllers/Proveedores/Proveedor.php" beforeDir="false" afterPath="$PROJECT_DIR$/ci4/app/Controllers/Compras/Proveedor.php" afterDir="false" />
<change beforePath="$PROJECT_DIR$/ci4/app/Filters/LoginAuthFilter.php" beforeDir="false" afterPath="$PROJECT_DIR$/ci4/app/Filters/LoginAuthFilter.php" afterDir="false" />
<change beforePath="$PROJECT_DIR$/ci4/app/Language/en/App.php" beforeDir="false" afterPath="$PROJECT_DIR$/ci4/app/Language/en/App.php" afterDir="false" />
<change beforePath="$PROJECT_DIR$/ci4/app/Language/es/App.php" beforeDir="false" afterPath="$PROJECT_DIR$/ci4/app/Language/es/App.php" afterDir="false" />
<change beforePath="$PROJECT_DIR$/ci4/app/Views/themes/backend/vuexy/form/settings/index.php" beforeDir="false" afterPath="$PROJECT_DIR$/ci4/app/Views/themes/backend/vuexy/form/settings/index.php" afterDir="false" />
<change beforePath="$PROJECT_DIR$/ci4/app/Views/themes/backend/vuexy/main/all.php" beforeDir="false" afterPath="$PROJECT_DIR$/ci4/app/Views/themes/backend/vuexy/main/all.php" afterDir="false" />
<change beforePath="$PROJECT_DIR$/ci4/app/Views/themes/backend/vuexy/main/defaultlayout.php" beforeDir="false" afterPath="$PROJECT_DIR$/ci4/app/Views/themes/backend/vuexy/main/defaultlayout.php" afterDir="false" />
=======
<change beforePath="$PROJECT_DIR$/.idea/webServers.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/webServers.xml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/ci4/app/Language/en/Users.php" beforeDir="false" afterPath="$PROJECT_DIR$/ci4/app/Language/en/Users.php" afterDir="false" />
<change beforePath="$PROJECT_DIR$/ci4/app/Language/es/Users.php" beforeDir="false" afterPath="$PROJECT_DIR$/ci4/app/Language/es/Users.php" afterDir="false" />
<change beforePath="$PROJECT_DIR$/ci4/app/Views/themes/backend/vuexy/form/configuracion/paises/viewPaisForm.php" beforeDir="false" afterPath="$PROJECT_DIR$/ci4/app/Views/themes/backend/vuexy/form/configuracion/paises/viewPaisForm.php" afterDir="false" />
<change beforePath="$PROJECT_DIR$/ci4/app/Views/themes/backend/vuexy/form/configuracion/paises/viewPaisList.php" beforeDir="false" afterPath="$PROJECT_DIR$/ci4/app/Views/themes/backend/vuexy/form/configuracion/paises/viewPaisList.php" afterDir="false" />
<change beforePath="$PROJECT_DIR$/ci4/app/Views/themes/backend/vuexy/form/configuracion/papel/viewPapelGenericoForm.php" beforeDir="false" afterPath="$PROJECT_DIR$/ci4/app/Views/themes/backend/vuexy/form/configuracion/papel/viewPapelGenericoForm.php" afterDir="false" />
<change beforePath="$PROJECT_DIR$/ci4/app/Views/themes/backend/vuexy/form/configuracion/papel/viewPapelImpresionForm.php" beforeDir="false" afterPath="$PROJECT_DIR$/ci4/app/Views/themes/backend/vuexy/form/configuracion/papel/viewPapelImpresionForm.php" afterDir="false" />
<change beforePath="$PROJECT_DIR$/ci4/app/Views/themes/backend/vuexy/form/user/_userFormItems.php" beforeDir="false" afterPath="$PROJECT_DIR$/ci4/app/Views/themes/backend/vuexy/form/user/_userFormItems.php" afterDir="false" />
>>>>>>> 38e9feb4c8537689e5d266a1dbe3371003d2457f
</list>
<option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" />
<option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
<option name="LAST_RESOLUTION" value="IGNORE" />
</component>
<component name="ComposerSettings" doNotAsk="true" synchronizationState="SYNCHRONIZE">
<pharConfigPath>$PROJECT_DIR$/ci4/composer.json</pharConfigPath>
<execution />
</component>
<component name="Git.Settings">
<option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$" />
</component>
<component name="MarkdownSettingsMigration">
<option name="stateVersion" value="1" />
</component>
<component name="ProjectId" id="2OsCE3jXyiqpYISC6WI6TMJusA2" />
<component name="ProjectViewState">
<option name="hideEmptyMiddlePackages" value="true" />
<option name="showLibraryContents" value="true" />
</component>
<component name="PropertiesComponent"><![CDATA[{
"keyToString": {
"RunOnceActivity.OpenProjectViewOnStart": "true",
"RunOnceActivity.ShowReadmeOnStart": "true",
"WebServerToolWindowFactoryState": "false",
"last_opened_file_path": "C:/temp-sk/safekat/ci4/app/Views/themes/backend/vuexy/main",
"node.js.detected.package.eslint": "true",
"node.js.detected.package.tslint": "true",
"node.js.selected.package.eslint": "(autodetect)",
"node.js.selected.package.tslint": "(autodetect)",
"nodejs_package_manager_path": "npm",
"settings.editor.selected.configurable": "preferences.pluginManager",
"vue.rearranger.settings.migration": "true"
}
}]]></component>
<component name="RecentsManager">
<key name="CopyFile.RECENT_KEYS">
<recent name="C:\temp-sk\safekat\ci4\app\Views\themes\backend\vuexy\main" />
<recent name="C:\temp-sk\safekat\ci4\app\Views\themes\backend\vuexy\form\settings" />
<recent name="C:\temp-sk\safekat\ci4\app\Views\themes\backend\vuexy\form\profile" />
<recent name="D:\Safekat\safekat\ci4\app\Views\themes\_commonPartialsBs" />
<recent name="C:\temp-sk\safekat\httpdocs\themes\vuexy\vendor\libs\toastr" />
</key>
<key name="MoveFile.RECENT_KEYS">
<recent name="C:\temp-sk\safekat\ci4\app\Controllers\Usuarios" />
<recent name="C:\temp-sk\safekat\ci4" />
<recent name="C:\temp-sk\safekat\httpdocs\themes\vuexy" />
</key>
</component>
<component name="SpellCheckerSettings" RuntimeDictionaries="0" Folders="0" CustomDictionaries="0" DefaultDictionary="application-level" UseSingleDictionary="true" transferred="true" />
<component name="TaskManager">
<task active="true" id="Default" summary="Default task">
<changelist id="7c8f7059-cd40-417c-936e-48dbc0507d86" name="Changes" comment="" />
<created>1682339793915</created>
<option name="number" value="Default" />
<option name="presentableId" value="Default" />
<updated>1682339793915</updated>
<workItem from="1682339796150" duration="1274000" />
<workItem from="1682412462416" duration="9540000" />
<workItem from="1682492106609" duration="7922000" />
<workItem from="1683530628259" duration="12043000" />
<workItem from="1683618855414" duration="183000" />
<workItem from="1683619057531" duration="16014000" />
<workItem from="1683715799575" duration="151000" />
<workItem from="1683716769681" duration="8512000" />
<workItem from="1683796910193" duration="12918000" />
<workItem from="1684147458134" duration="7379000" />
<workItem from="1684221025785" duration="2261000" />
<workItem from="1684226343116" duration="4598000" />
<workItem from="1684236911941" duration="2213000" />
<workItem from="1684239429024" duration="2049000" />
<workItem from="1684313352573" duration="9284000" />
<workItem from="1684350581362" duration="2244000" />
<workItem from="1684415370137" duration="889000" />
<workItem from="1684761592479" duration="626000" />
<workItem from="1684829967827" duration="8241000" />
<workItem from="1684869825991" duration="3082000" />
<workItem from="1684910640450" duration="14817000" />
<workItem from="1685018778974" duration="1905000" />
<workItem from="1685038598644" duration="6958000" />
<workItem from="1685102978387" duration="3272000" />
<workItem from="1685266094611" duration="3469000" />
<<<<<<< HEAD
<workItem from="1685365444846" duration="191000" />
<workItem from="1685689980219" duration="12098000" />
=======
<workItem from="1685564762632" duration="2787000" />
>>>>>>> 38e9feb4c8537689e5d266a1dbe3371003d2457f
</task>
<task id="LOCAL-00001" summary="Starting Vuexy Theme creation">
<created>1682339938559</created>
<option name="number" value="00001" />
<option name="presentableId" value="LOCAL-00001" />
<option name="project" value="LOCAL" />
<updated>1682339938559</updated>
</task>
<task id="LOCAL-00002" summary="Add static Vuexy files">
<created>1682420504675</created>
<option name="number" value="00002" />
<option name="presentableId" value="LOCAL-00002" />
<option name="project" value="LOCAL" />
<updated>1682420504675</updated>
</task>
<option name="localTasksCounter" value="3" />
<servers />
</component>
<component name="TypeScriptGeneratedFilesManager">
<option name="version" value="3" />
</component>
<component name="Vcs.Log.Tabs.Properties">
<option name="TAB_STATES">
<map>
<entry key="MAIN">
<value>
<State>
<option name="FILTERS">
<map>
<entry key="branch">
<value>
<list>
<option value="origin/dev/vuexy" />
</list>
</value>
</entry>
</map>
</option>
</State>
</value>
</entry>
</map>
</option>
</component>
<component name="VcsManagerConfiguration">
<option name="CHECK_CODE_SMELLS_BEFORE_PROJECT_COMMIT" value="false" />
<MESSAGE value="Starting Vuexy Theme creation" />
<MESSAGE value="Add static Vuexy files" />
<option name="LAST_COMMIT_MESSAGE" value="Add static Vuexy files" />
</component>
<component name="XDebuggerManager">
<breakpoint-manager>
<breakpoints>
<line-breakpoint enabled="true" type="php">
<url>file://$PROJECT_DIR$/ci4/app/Views/themes/backend/vuexy/main/all.php</url>
<line>371</line>
<option name="timeStamp" value="1" />
</line-breakpoint>
</breakpoints>
</breakpoint-manager>
</component>
</project>

View File

@ -1,4 +1,5 @@
{
"clockify.tracking.workspaceId": "6464949facab6237e1538c14",
"sqltools.connections": [
{
"mysqlOptions": {

17
.vscode/sftp.json vendored
View File

@ -5,29 +5,18 @@
"remotePath": "/",
"uploadOnSave": true,
"useTempFile": false,
"openSsh": false,
"openSsh": false,
"profiles": {
"jjo": {
"jjo": {
"host": "sk-jjo.imnavajas.es",
"username": "sk-jjo",
"password": "Snwi1660%"
},
"imn": {
"host": "sk-imn.imnavajas.es",
"username": "sk-imn",
"password": "GVBbgdwlvn7_p02?"
},
"dev":{
"host": "sk-dev.imnavajas.es",
"username": "sk-dev",
"password": "KXvYsubai9v*g61~"
},
"prod":{
"host": "erp.safekat.es",
"username": "erp-demo",
"password": "lNkEyukTc1~*3yy9"
}
}

View File

@ -1,92 +0,0 @@
# safekat
## Getting started
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
## Add your files
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
```
cd existing_repo
git remote add origin https://git.imnavajas.es/jjimenez/safekat.git
git branch -M main
git push -uf origin main
```
## Integrate with your tools
- [ ] [Set up project integrations](https://git.imnavajas.es/jjimenez/safekat/-/settings/integrations)
## Collaborate with your team
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
- [ ] [Automatically merge when pipeline succeeds](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
## Test and Deploy
Use the built-in continuous integration in GitLab.
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing(SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
***
# Editing this README
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thank you to [makeareadme.com](https://www.makeareadme.com/) for this template.
## Suggestions for a good README
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
## Name
Choose a self-explaining name for your project.
## Description
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
## Badges
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
## Visuals
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
## Installation
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
## Usage
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
## Support
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
## Roadmap
If you have ideas for releases in the future, it is a good idea to list them in the README.
## Contributing
State if you are open to contributions and what your requirements are for accepting them.
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
## Authors and acknowledgment
Show your appreciation to those who have contributed to the project.
## License
For open source projects, say how it is licensed.
## Project status
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.

2014
backups_bbdd/04252023_sk_main.sql Executable file

File diff suppressed because it is too large Load Diff

3405
backups_bbdd/29052023_sk-jjo.sql Executable file

File diff suppressed because it is too large Load Diff

View File

@ -13,7 +13,8 @@ declare(strict_types=1);
namespace Config;
use App\Models\Usuarios\UserModel;
use App\Entities\Usuarios\UsersEntity;
use App\Models\UserModel;
use CodeIgniter\Shield\Authentication\Authenticators\JWT;
use CodeIgniter\Shield\Authentication\Passwords\ValidationRules;
use CodeIgniter\Shield\Config\Auth as ShieldAuth;
@ -439,14 +440,8 @@ class Auth extends ShieldAuth
public function loginRedirect(): string
{
$session = session();
$url = setting('Auth.redirects')['login'];
if(isset($_SERVER['HTTP_X_REQUESTED_WITH'])){
if($_SERVER['HTTP_X_REQUESTED_WITH'] == "xmlhttprequest"){
$url = setting('Auth.redirects')['login'];
}
}else{
$url = $session->getTempdata('beforeLoginUrl') ?? setting('Auth.redirects')['login'];
}
$url = $session->getTempdata('beforeLoginUrl') ?? setting('Auth.redirects')['login'];
return $this->getUrl($url);
}

View File

@ -71,32 +71,6 @@ class Database extends Config
'busyTimeout' => 1000,
];
public array $old_erp = [
'DSN' => '',
'hostname' => 'localhost',
'username' => '',
'password' => '',
'database' => '',
'DBDriver' => 'MySQLi',
'DBPrefix' => '',
'pConnect' => false,
'DBDebug' => true,
'charset' => 'utf8mb4',
'DBCollat' => 'utf8mb4_general_ci',
'swapPre' => '',
'encrypt' => false,
'compress' => false,
'strictOn' => false,
'failover' => [],
'port' => 3306,
'numberNative' => false,
'dateFormat' => [
'date' => 'Y-m-d',
'datetime' => 'Y-m-d H:i:s',
'time' => 'H:i:s',
],
];
public function __construct()
{
parent::__construct();

View File

@ -6,7 +6,7 @@ use CodeIgniter\Config\BaseConfig;
class Email extends BaseConfig
{
public string $fromEmail = 'soporte_erp@safekat.es';
public string $fromEmail = 'safekat@imnavajas.es';
public string $fromName = 'Safekat ERP';
public string $recipients = '';
@ -28,27 +28,27 @@ class Email extends BaseConfig
/**
* SMTP Server Hostname
*/
public string $SMTPHost = 'localhost';
public string $SMTPHost = 'imnavajas.es';
/**
* SMTP Username
*/
public string $SMTPUser = 'soporte_erp@safekat.es';
public string $SMTPUser = 'safekat@imnavajas.es';
/**
* SMTP Password
*/
public string $SMTPPass = '';
public string $SMTPPass = 'Etkd9~448';
/**
* SMTP Port
*/
public int $SMTPPort = 465;
public int $SMTPPort = 25;
/**
* SMTP Timeout (in seconds)
*/
public int $SMTPTimeout = 15;
public int $SMTPTimeout = 5;
/**
* Enable persistent SMTP connections

View File

@ -26,7 +26,6 @@ class Filters extends BaseConfig
'honeypot' => Honeypot::class,
'invalidchars' => InvalidChars::class,
'secureheaders' => SecureHeaders::class,
'cors' => \App\Filters\Cors::class
];
/**
@ -81,6 +80,5 @@ class Filters extends BaseConfig
/*'jwt' => [
'before' => ['api', 'api/*']
],*/
];
}

View File

@ -1,31 +0,0 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
class LogoImpresion extends BaseConfig
{
public array $TIPO_IMPRESION_MAPPING = [
"lp_bn" => "icon_bn",
"lp_bnhq" => "icon_bnhq",
"lp_color" => "icon_color",
"lp_colorhq" => "icon_colorhq",
"lp_cubierta" => "icon_cubierta",
"lp_sobrecubierta" => "icon_sobrecubierta",
"lp_rot_bn" => "icon_rotativa_bn",
"lp_rot_color" => "icon_rotativa_color",
"lp_guardas" => "icon_cuardas"
];
public function __construct()
{
parent::__construct();
}
public function get_logo_path(string $tipo): string
{
return "themes/vuexy/img/safekat/presupuestos/" . $this->TIPO_IMPRESION_MAPPING[$tipo] . ".png";
}
}

View File

@ -1,68 +0,0 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
class OrdenTrabajo extends BaseConfig
{
public array $DATE_USER_MAPPING = [
//IMPRESION
"interior_bn_at" => "interior_bn_user_id",
"interior_color_at" => "interior_color_user_id",
"cubierta_at" => "cubierta_user_id",
//ACABADO
"plastificado_at" => "plastificado_user_id",
"encuadernacion_at" => "encuadernacion_user_id",
"corte_at" => "corte_user_id",
"preparacion_interiores_at" => "preparacion_interior_user_id",
"entrada_manipulado_at" => "entrada_manipulado_user_id",
"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",
//FERRO
"pendiente_ferro_at" => "pendiente_ferro_user_id",
"ferro_en_cliente_at" => "ferro_en_cliente_user_id",
"ferro_ok_at" => "ferro_ok_user_id",
//ENVIO
"embalaje_at" => "embalaje_user_id",
"envio_at" => "envio_user_id",
//PREIMPRESION
"pre_formato_at" => "pre_formato_user_id",
"pre_lomo_at" => "pre_lomo_user_id",
"pre_solapa_at" => "pre_solapa_user_id",
"pre_codbarras_at" => "pre_codbarras_user_id",
"pre_imposicion_at" => "pre_imposicion_user_id",
];
public array $DATE_USER_MAPPING_PEDIDO = [
"inaplazable" => "inaplazable_change_user_id",
"fecha_entrega_real" => "fecha_entrega_real_change_user_id",
"fecha_impresion" => "fecha_impresion_change_user_id",
"fecha_encuadernado" => "fecha_encuadernado_change_user_id",
"fecha_entrega_externo" => "fecha_entrega_externo_change_user_id",
];
public array $OT_COLORS = [
"sin_imprimir" => "#FF6363",
"impreso_int" => "#AFDDFF",
"impreso_cub" => "#3A59D1",
"plastificado" => "#FFD63A",
"preparado" => "#FF0B55",
"solapa" => "#4F1C51",
"cosido" => "#FF0B55",
"grapado" => "#FEBA17",
"encuadernado" => "#FEBA17",
"corte" => "#67AE6E"
];
public function __construct()
{
parent::__construct();
}
}

View File

@ -13,7 +13,6 @@ class PedidoXML extends BaseConfig
public string $password;
public string $base_dir; # FTP server directory
public bool $xml_enabled;
public int $id_offset;
public function __construct() {
parent::__construct();
@ -23,7 +22,6 @@ class PedidoXML extends BaseConfig
$this->password = env("HIDRIVE_PASS","A77h3b0X4OA2rOYAf4w2");
$this->base_dir = env("HIDRIVE_PATH_ROOT","/home/admin/safekat"); # FTP server directory
$this->xml_enabled = env("FTP_XML_ENABLED",false);
$this->id_offset = env("XML_OFFSET_CUSTOMER_ID",1000000);
}
}

View File

@ -0,0 +1,251 @@
<?php
const SK_PERMISSION_MATRIX = [
"admin" => [
"clientes.create",
"clientes.edit",
"clientes.delete",
"clientes.menu",
"plantilla-tarifa.create",
"plantilla-tarifa.edit",
"plantilla-tarifa.delete",
"plantilla-tarifa.menu",
"perfil.create",
"perfil.edit",
"perfil.delete",
"perfil.menu",
"presupuesto.create",
"presupuesto.edit",
"presupuesto.delete",
"presupuesto.menu",
"presupuesto-cliente.create",
"presupuesto-cliente.edit",
"presupuesto-cliente.delete",
"presupuesto-cliente.menu",
"tarifa-preimpresion.create",
"tarifa-preimpresion.edit",
"tarifa-preimpresion.delete",
"tarifa-preimpresion.menu",
"tarifa-manipulado.create",
"tarifa-manipulado.edit",
"tarifa-manipulado.delete",
"tarifa-manipulado.menu",
"tarifa-acabado.create",
"tarifa-acabado.edit",
"tarifa-acabado.delete",
"tarifa-acabado.menu",
"tarifa-encuadernacion.create",
"tarifa-encuadernacion.edit",
"tarifa-encuadernacion.delete",
"tarifa-encuadernacion.menu",
"tarifa-envio.create",
"tarifa-envio.edit",
"tarifa-envio.delete",
"tarifa-envio.menu",
"tarifa-extra.create",
"tarifa-extra.edit",
"tarifa-extra.delete",
"tarifa-extra.menu",
"proveedores.create",
"proveedores.edit",
"proveedores.delete",
"proveedores.menu",
"ajustes.create",
"ajustes.edit",
"ajustes.delete",
"ajustes.menu",
"actividad.create",
"actividad.edit",
"actividad.delete",
"actividad.menu",
"paises.create",
"paises.edit",
"paises.delete",
"paises.menu",
"formas-pago.create",
"formas-pago.edit",
"formas-pago.delete",
"formas-pago.menu",
"maquinas.create",
"maquinas.edit",
"maquinas.delete",
"maquinas.menu",
"maquinas-defecto.create",
"maquinas-defecto.edit",
"maquinas-defecto.delete",
"maquinas-defecto.menu",
"papel-generico.create",
"papel-generico.edit",
"papel-generico.delete",
"papel-generico.menu",
"papel-impresion.create",
"papel-impresion.edit",
"papel-impresion.delete",
"papel-impresion.menu",
"usuarios.create",
"usuarios.edit",
"usuarios.delete",
"usuarios.menu",
"roles-permisos.create",
"roles-permisos.edit",
"roles-permisos.delete",
"roles-permisos.menu",
"ubicaciones.create",
"ubicaciones.edit",
"ubicaciones.delete",
"ubicaciones.menu",
"series-facturas.create",
"series-facturas.edit",
"series-facturas.delete",
"series-facturas.menu",
],
"cliente-admin" => [
"perfil.edit",
"perfil.menu",
"direcciones.create",
"direcciones.edit",
"direcciones.delete",
"direcciones.menu",
"presupuesto-cliente.create",
"presupuesto-cliente.edit",
"presupuesto-cliente.delete",
"presupuesto-cliente.menu",
],
"cliente-editor" => [
"perfil.create",
"perfil.edit",
"perfil.delete",
"perfil.menu",
"direcciones.create",
"direcciones.edit",
"direcciones.delete",
"direcciones.menu",
"presupuesto-cliente.create",
"presupuesto-cliente.edit",
"presupuesto-cliente.delete",
"presupuesto-cliente.menu",
],
"comercial" => [
"token.token",
"token.menu",
],
"produccion" => [
"token.token",
"token.menu",
],
"maquina" => [
"token.token",
"token.menu",
],
"maquetador" => [
"token.token",
"token.menu",
],
"director" => [
"token.token",
"token.menu",
],
"contabilidad" => [
"token.token",
"token.menu",
],
"editor" => [
"token.token",
"token.menu",
"Profile.index",
"Profile.menu",
],
"beta" => [
"clientes.create",
"clientes.edit",
"clientes.delete",
"clientes.menu",
"plantilla-tarifa.create",
"plantilla-tarifa.edit",
"plantilla-tarifa.delete",
"plantilla-tarifa.menu",
"perfil.create",
"perfil.edit",
"perfil.delete",
"perfil.menu",
"presupuesto.create",
"presupuesto.edit",
"presupuesto.delete",
"presupuesto.menu",
"presupuesto-cliente.create",
"presupuesto-cliente.edit",
"presupuesto-cliente.delete",
"presupuesto-cliente.menu",
"tarifa-preimpresion.create",
"tarifa-preimpresion.edit",
"tarifa-preimpresion.delete",
"tarifa-preimpresion.menu",
"tarifa-manipulado.create",
"tarifa-manipulado.edit",
"tarifa-manipulado.delete",
"tarifa-manipulado.menu",
"tarifa-acabado.create",
"tarifa-acabado.edit",
"tarifa-acabado.delete",
"tarifa-acabado.menu",
"tarifa-encuadernacion.create",
"tarifa-encuadernacion.edit",
"tarifa-encuadernacion.delete",
"tarifa-encuadernacion.menu",
"tarifa-envio.create",
"tarifa-envio.edit",
"tarifa-envio.delete",
"tarifa-envio.menu",
"tarifa-extra.create",
"tarifa-extra.edit",
"tarifa-extra.delete",
"tarifa-extra.menu",
"proveedores.create",
"proveedores.edit",
"proveedores.delete",
"proveedores.menu",
"ajustes.create",
"ajustes.edit",
"ajustes.delete",
"ajustes.menu",
"actividad.create",
"actividad.edit",
"actividad.delete",
"actividad.menu",
"paises.create",
"paises.edit",
"paises.delete",
"paises.menu",
"maquinas.create",
"maquinas.edit",
"maquinas.delete",
"maquinas.menu",
"maquinas-defecto.create",
"maquinas-defecto.edit",
"maquinas-defecto.delete",
"maquinas-defecto.menu",
"papel-generico.create",
"papel-generico.edit",
"papel-generico.delete",
"papel-generico.menu",
"papel-impresion.create",
"papel-impresion.edit",
"papel-impresion.delete",
"papel-impresion.menu",
"usuarios.create",
"usuarios.edit",
"usuarios.delete",
"usuarios.menu",
"roles-permisos.create",
"roles-permisos.edit",
"roles-permisos.delete",
"roles-permisos.menu",
"ubicaciones.create",
"ubicaciones.edit",
"ubicaciones.delete",
"ubicaciones.menu",
"series-facturas.create",
"series-facturas.edit",
"series-facturas.delete",
"series-facturas.menu",
],
];

View File

@ -0,0 +1,104 @@
<?php
const SK_PERMISSIONS = [
'clientes.create' => 'Can create',
'clientes.edit' => 'Can edit',
'clientes.delete' => 'Can delete',
'clientes.menu' => 'Menu shall be visualize',
'plantilla-tarifa.create' => 'Can create',
'plantilla-tarifa.edit' => 'Can edit',
'plantilla-tarifa.delete' => 'Can delete',
'plantilla-tarifa.menu' => 'Menu shall be visualize',
'perfil.create' => 'Can create',
'perfil.edit' => 'Can edit',
'perfil.delete' => 'Can delete',
'perfil.menu' => 'Menu shall be visualize',
'direcciones.create' => 'Can create',
'direcciones.edit' => 'Can edit',
'direcciones.delete' => 'Can delete',
'direcciones.menu' => 'Menu shall be visualize',
'presupuesto.create' => 'Can create',
'presupuesto.edit' => 'Can edit',
'presupuesto.delete' => 'Can delete',
'presupuesto.menu' => 'Menu shall be visualize',
'presupuesto-cliente.create' => 'Can create',
'presupuesto-cliente.edit' => 'Can edit',
'presupuesto-cliente.delete' => 'Can delete',
'presupuesto-cliente.menu' => 'Menu shall be visualize',
'tarifa-preimpresion.create' => 'Can create',
'tarifa-preimpresion.edit' => 'Can edit',
'tarifa-preimpresion.delete' => 'Can delete',
'tarifa-preimpresion.menu' => 'Menu shall be visualize',
'tarifa-manipulado.create' => 'Can create',
'tarifa-manipulado.edit' => 'Can edit',
'tarifa-manipulado.delete' => 'Can delete',
'tarifa-manipulado.menu' => 'Menu shall be visualize',
'tarifa-acabado.create' => 'Can create',
'tarifa-acabado.edit' => 'Can edit',
'tarifa-acabado.delete' => 'Can delete',
'tarifa-acabado.menu' => 'Menu shall be visualize',
'tarifa-encuadernacion.create' => 'Can create',
'tarifa-encuadernacion.edit' => 'Can edit',
'tarifa-encuadernacion.delete' => 'Can delete',
'tarifa-encuadernacion.menu' => 'Menu shall be visualize',
'tarifa-envio.create' => 'Can create',
'tarifa-envio.edit' => 'Can edit',
'tarifa-envio.delete' => 'Can delete',
'tarifa-envio.menu' => 'Menu shall be visualize',
'tarifa-extra.create' => 'Can create',
'tarifa-extra.edit' => 'Can edit',
'tarifa-extra.delete' => 'Can delete',
'tarifa-extra.menu' => 'Menu shall be visualize',
'proveedores.create' => 'Can create',
'proveedores.edit' => 'Can edit',
'proveedores.delete' => 'Can delete',
'proveedores.menu' => 'Menu shall be visualize',
'ajustes.create' => 'Can create',
'ajustes.edit' => 'Can edit',
'ajustes.delete' => 'Can delete',
'ajustes.menu' => 'Menu shall be visualize',
'actividad.create' => 'Can create',
'actividad.edit' => 'Can edit',
'actividad.delete' => 'Can delete',
'actividad.menu' => 'Menu shall be visualize',
'paises.create' => 'Can create',
'paises.edit' => 'Can edit',
'paises.delete' => 'Can delete',
'paises.menu' => 'Menu shall be visualize',
'formas-pago.create' => 'Can create',
'formas-pago.edit' => 'Can edit',
'formas-pago.delete' => 'Can delete',
'formas-pago.menu' => 'Menu shall be visualize',
'maquinas.create' => 'Can create',
'maquinas.edit' => 'Can edit',
'maquinas.delete' => 'Can delete',
'maquinas.menu' => 'Menu shall be visualize',
'maquinas-defecto.create' => 'Can create',
'maquinas-defecto.edit' => 'Can edit',
'maquinas-defecto.delete' => 'Can delete',
'maquinas-defecto.menu' => 'Menu shall be visualize',
'papel-generico.create' => 'Can create',
'papel-generico.edit' => 'Can edit',
'papel-generico.delete' => 'Can delete',
'papel-generico.menu' => 'Menu shall be visualize',
'papel-impresion.create' => 'Can create',
'papel-impresion.edit' => 'Can edit',
'papel-impresion.delete' => 'Can delete',
'papel-impresion.menu' => 'Menu shall be visualize',
'usuarios.create' => 'Can create',
'usuarios.edit' => 'Can edit',
'usuarios.delete' => 'Can delete',
'usuarios.menu' => 'Menu shall be visualize',
'roles-permisos.create' => 'Can create',
'roles-permisos.edit' => 'Can edit',
'roles-permisos.delete' => 'Can delete',
'roles-permisos.menu' => 'Menu shall be visualize',
'ubicaciones.create' => 'Can create',
'ubicaciones.edit' => 'Can edit',
'ubicaciones.delete' => 'Can delete',
'ubicaciones.menu' => 'Menu shall be visualize',
'series-facturas.create' => 'Can create',
'series-facturas.edit' => 'Can edit',
'series-facturas.delete' => 'Can delete',
'series-facturas.menu' => 'Menu shall be visualize',
];

View File

@ -0,0 +1,22 @@
{
"superadmin": {
"title": "Super Admin",
"description": "Complete control of the site."
},
"admin": {
"title": "Admin",
"description": "Day to day administrators of the site."
},
"developer": {
"title": "Developer",
"description": "Site programmers."
},
"user": {
"title": "User",
"description": "General users of the site. Often customers."
},
"beta": {
"title": "Beta User",
"description": "Has access to beta-level features."
}
}

View File

@ -0,0 +1,48 @@
<?php
const SK_ROLES = [
'admin' => [
'title' => 'Administrador',
'description' => 'Administrador del ERP',
],
'cliente-admin' => [
'title' => 'Cliente administrador',
'description' => 'Rol de cliente con permisos de administración',
],
'cliente-editor' => [
'title' => 'Cliente editor',
'description' => 'Rol de cliente con permisos de edición',
],
'comercial' => [
'title' => 'Comercial',
'description' => '',
],
'produccion' => [
'title' => 'Producción',
'description' => '',
],
'maquina' => [
'title' => 'Máquina',
'description' => '',
],
'maquetador' => [
'title' => 'Maquetador',
'description' => '',
],
'director' => [
'title' => 'Director',
'description' => '',
],
'contabilidad' => [
'title' => 'Contabilidad',
'description' => '',
],
'editor' => [
'title' => 'Editor',
'description' => '',
],
'beta' => [
'title' => 'Beta',
'description' => '',
],
];

View File

@ -16,15 +16,17 @@ $routes->get('/', 'Home::index', ['as' => 'home']);
$routes->get('lang/{locale}', 'Language::index');
$routes->get('viewmode/(:alpha)', 'Viewmode::index/$1');
/* URL FOR TESTS */
$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']);
});
$routes->group('settings', ['namespace' => 'App\Controllers\Sistema'], function ($routes) {
$routes->get('', 'Ajustes::settings', ['as' => 'ajustesList']);
$routes->post('', 'Ajustes::settings', ['as' => 'ajustesEdit']);
});
/*
* --------------------------------------------------------------------
@ -32,14 +34,77 @@ $routes->group('activity', ['namespace' => 'App\Controllers\Sistema'], function
* --------------------------------------------------------------------
*/
// Carga archivos de rutas por dominio
foreach (glob(APPPATH . 'Config/Routes/*Routes.php') as $routeFile) {
require $routeFile;
}
/* Rutas para tarifas */
$routes->group('tarifas', ['namespace' => 'App\Controllers\Tarifas'], function ($routes) {
/* Cliente */
$routes->group('acabados', ['namespace' => 'App\Controllers\Tarifas\Acabados'], function ($routes) {
$routes->get('', 'TarifaAcabados::index', ['as' => 'tarifaAcabadoList']);
$routes->match(['get', 'post'], 'add', 'TarifaAcabados::add', ['as' => 'tarifaAcabadoAdd']);
$routes->match(['get', 'post'], 'edit/(:num)', 'TarifaAcabados::edit/$1', ['as' => 'tarifaAcabadoEdit']);
$routes->get('delete/(:num)', 'TarifaAcabados::delete/$1', ['as' => 'tarifaAcabadoDelete']);
$routes->post('datatable', 'TarifaAcabados::datatable', ['as' => 'tarifaAcabadoDT']);
$routes->group('lineas', ['namespace' => 'App\Controllers\Tarifas\Acabados'], function ($routes) {
$routes->post('datatable', 'TarifaAcabadosLineas::datatable', ['as' => 'tarifaAcabadoLineasDT']);
$routes->post('datatable_editor', 'TarifaAcabadosLineas::datatable_editor', ['as' => 'tarifaAcabadoLineasDTE']);
$routes->get('delete/(:num)', 'TarifaAcabadosLineas::delete/$1', ['as' => 'tarifaAcabadoLineasDelete']);
});
});
});
/* Rutas para configuraciones */
$routes->group('configuracion', ['namespace' => 'App\Controllers\Configuracion'], function ($routes) {
/* Ubicaciones */
$routes->group('ubicaciones', ['namespace' => 'App\Controllers\Configuracion'], function ($routes) {
$routes->get('', 'Ubicaciones::index', ['as' => 'ubicacionesList']);
$routes->match(['get', 'post'], 'add', 'Ubicaciones::add', ['as' => 'ubicacionesAdd']);
$routes->match(['get', 'post'], 'edit/(:num)', 'Ubicaciones::edit/$1', ['as' => 'ubicacionesEdit']);
$routes->get('delete/(:num)', 'Ubicaciones::delete/$1', ['as' => 'ubicacionesDelete']);
$routes->post('datatable', 'Ubicaciones::datatable', ['as' => 'ubicacionesDT']);
});
/* Series Factura */
$routes->group('series-facturas', ['namespace' => 'App\Controllers\Configuracion'], function ($routes) {
$routes->get('', 'SeriesFacturas::index', ['as' => 'seriesFacturasList']);
$routes->match(['get', 'post'], 'add', 'SeriesFacturas::add', ['as' => 'seriesFacturasAdd']);
$routes->match(['get', 'post'], 'edit/(:num)', 'SeriesFacturas::edit/$1', ['as' => 'seriesFacturasEdit']);
$routes->get('delete/(:num)', 'SeriesFacturas::delete/$1', ['as' => 'seriesFacturasDelete']);
$routes->post('datatable', 'SeriesFacturas::datatable', ['as' => 'seriesFacturasDT']);
$routes->post('menuitemsFacturas', 'SeriesFacturas::menuItemsFacturas', ['as' => 'menuItemsOfSeriesFacturas']);
});
/* Formas de Pago */
$routes->group('formas-pago', ['namespace' => 'App\Controllers\Configuracion'], function ($routes) {
$routes->get('', 'FormasPago::index', ['as' => 'formasPagoList']);
$routes->match(['get', 'post'], 'add', 'FormasPago::add', ['as' => 'formasPagoAdd']);
$routes->match(['get', 'post'], 'edit/(:num)', 'FormasPago::edit/$1', ['as' => 'formasPagoEdit']);
$routes->get('delete/(:num)', 'FormasPago::delete/$1', ['as' => 'formasPagoDelete']);
$routes->post('datatable', 'FormasPago::datatable', ['as' => 'formasPagoDT']);
});
$routes->group("variables", ["namespace" => 'App\Controllers\Configuracion'], function ($routes) {
$routes->get('', 'ConfigVariables::index', ['as' => 'variablesIndex']);
$routes->get('find/(:num)', 'ConfigVariables::get/$1', ['as' => 'variablesFind']);
$routes->post('edit/(:num)', 'ConfigVariables::updateVariable/$1', ['as' => 'updateVariable']);
$routes->delete('delete/(:num)', 'ConfigVariables::delete/$1', ['as' => 'deleteVariable']);
$routes->get('datatable', 'ConfigVariables::datatable', ['as' => 'datatableVariables']);
});
$routes->group("errores-presupuesto", ["namespace" => 'App\Controllers\Configuracion'], function ($routes) {
$routes->get('', 'ConfigErrores::index', ['as' => 'erroresPresupuestoIndex']);
$routes->get('edit/(:num)', 'ConfigErrores::viewForm/$1', ['as' => 'erroresPresupuestoViewForm']);
$routes->get('get/(:num)', 'ConfigErrores::get_error_presupuesto/$1', ['as' => 'erroresPresupuestoGetErrorPresupuesto']);
$routes->get('datatable', 'ConfigErrores::datatable', ['as' => 'erroresPresupuestoDatatable']);
$routes->post('edit/(:num)', 'ConfigErrores::update_error_presupuesto/$1', ['as' => 'erroresPresupuestoUpdate']);
});
});
$routes->group('users', ['namespace' => 'App\Controllers\Configuracion'], function ($routes) {
$routes->get('', 'Users::index', ['as' => 'userList']);
$routes->get('index', 'Users::index', ['as' => 'userIndex']);
$routes->get('list', 'Users::index', ['as' => 'userList2']);
$routes->get('add', 'Users::add', ['as' => 'newUser']);
$routes->post('add', 'Users::add', ['as' => 'createUser']);
@ -48,12 +113,18 @@ $routes->group('users', ['namespace' => 'App\Controllers\Configuracion'], functi
$routes->get('delete/(:num)', 'Users::delete/$1', ['as' => 'deleteUser']);
$routes->post('allmenuitems', 'Users::allItemsSelect', ['as' => 'select2ItemsOfUsers']);
$routes->post('menuitems', 'Users::menuItems', ['as' => 'menuItemsOfUsers']);
$routes->post('datatable', 'Users::datatable', ['as' => 'datatableOfUsers']);
$routes->get('getMenuComerciales', 'Users::getMenuComerciales', ['as' => 'menuItemsComerciales']);
$routes->post('getMenuComerciales', 'Users::getMenuComerciales', ['as' => 'menuItemsComerciales']);
});
$routes->resource('users', ['namespace' => 'App\Controllers\Configuracion', 'controller' => 'Users', 'except' => 'show,new,create,update']);
$routes->group('group', ['namespace' => 'App\Controllers\Configuracion'], function ($routes) {
$routes->get('', 'Group::index', ['as' => 'userGroupList']);
$routes->get('index', 'Group::index', ['as' => 'groupIndex']);
$routes->post('edit/(:num)', 'Group::edit/$1', ['as' => 'updateGroup']);
$routes->get('edit/(:num)', 'Group::edit/$1', ['as' => 'editGroup']);
$routes->get('delete/(:num)', 'Group::delete/$1', ['as' => 'deleteGroup']);
$routes->get('add', 'Group::add', ['as' => 'newGroup']);
$routes->post('add', 'Group::add', ['as' => 'createGroup']);
});
$routes->group('tarifapreimpresion', ['namespace' => 'App\Controllers\Tarifas'], function ($routes) {
$routes->get('', 'Tarifapreimpresion::index', ['as' => 'tarifapreimpresionList']);
@ -66,7 +137,6 @@ $routes->group('tarifapreimpresion', ['namespace' => 'App\Controllers\Tarifas'],
$routes->get('delete/(:num)', 'Tarifapreimpresion::delete/$1', ['as' => 'deleteTarifapreimpresion']);
$routes->post('allmenuitems', 'Tarifapreimpresion::allItemsSelect', ['as' => 'select2ItemsOfTarifaspreimpresion']);
$routes->post('menuitems', 'Tarifapreimpresion::menuItems', ['as' => 'menuItemsOfTarifaspreimpresion']);
$routes->get('gettarifas', 'Tarifapreimpresion::getSelect2');
});
@ -81,7 +151,6 @@ $routes->group('tarifaextra', ['namespace' => 'App\Controllers\Tarifas'], functi
$routes->get('delete/(:num)', 'Tarifaextra::delete/$1', ['as' => 'deleteTarifaextra']);
$routes->post('allmenuitems', 'Tarifaextra::allItemsSelect', ['as' => 'select2ItemsOfTarifasextra']);
$routes->post('menuitems', 'Tarifaextra::menuItems', ['as' => 'menuItemsOfTarifasextra']);
$routes->get('gettarifas', 'Tarifaextra::getSelect2');
});
@ -96,25 +165,10 @@ $routes->group('tarifasmanipulado', ['namespace' => 'App\Controllers\Tarifas'],
$routes->post('datatable', 'Tarifasmanipulado::datatable', ['as' => 'dataTableOfTarifasManipulado']);
$routes->post('allmenuitems', 'Tarifasmanipulado::allItemsSelect', ['as' => 'select2ItemsOfTarifasManipulado']);
$routes->post('menuitems', 'Tarifasmanipulado::menuItems', ['as' => 'menuItemsOfTarifasManipulado']);
$routes->get('select', 'Tarifasmanipulado::show_select', ["as" => "showSelectTarifaManipulado"]);
$routes->get('gettarifas', 'Tarifasmanipulado::getSelect2');
});
$routes->resource('tarifasmanipulado', ['namespace' => 'App\Controllers\Tarifas', 'controller' => 'Tarifasmanipulado', 'except' => 'show,new,create,update']);
$routes->group('serviciosacabado', ['namespace' => 'App\Controllers\Tarifas\Acabados'], function ($routes) {
$routes->get('', 'ServiciosAcabado::index', ['as' => 'serviciosAcabadoList']);
$routes->get('add', 'ServiciosAcabado::add', ['as' => 'newServicioAcabado']);
$routes->post('add', 'ServiciosAcabado::add', ['as' => 'createServicioAcabado']);
$routes->get('edit/(:num)', 'ServiciosAcabado::edit/$1', ['as' => 'editServicioAcabado']);
$routes->post('edit/(:num)', 'ServiciosAcabado::edit/$1', ['as' => 'updateServicioAcabado']);
$routes->get('datatable', 'ServiciosAcabado::datatable');
$routes->get('getselectedtarifas', 'ServiciosAcabado::getTarifasSeleccionadas');
$routes->get('gettarifas', 'ServiciosAcabado::getTarifas');
});
$routes->resource('tarifasmanipulado', ['namespace' => 'App\Controllers\Tarifas\Acabados', 'controller' => 'ServiciosAcabado', 'except' => 'show,new,create,update']);
$routes->group('tarifamanipuladolineas', ['namespace' => 'App\Controllers\Tarifas'], function ($routes) {
$routes->get('', 'Tarifamanipuladolineas::index', ['as' => 'tarifaManipuladoLineaList']);
$routes->get('add', 'Tarifamanipuladolineas::add', ['as' => 'newTarifaManipuladoLinea']);
@ -153,11 +207,36 @@ $routes->group('imposiciones', ['namespace' => 'App\Controllers\Configuracion'],
$routes->post('datatable', 'Imposiciones::datatable', ['as' => 'dataTableOfImposiciones']);
$routes->post('allmenuitems', 'Imposiciones::allItemsSelect', ['as' => 'select2ItemsOfImposiciones']);
$routes->post('menuitems', 'Imposiciones::menuItems', ['as' => 'menuItemsOfImposiciones']);
$routes->get('select', 'Imposiciones::selectImposicion', ['as' => 'selectImposicion']);
});
$routes->resource('imposiciones', ['namespace' => 'App\Controllers\Configuracion', 'controller' => 'Imposiciones', 'except' => 'show,new,create,update']);
$routes->group('papelesgenericos', ['namespace' => 'App\Controllers\Configuracion'], function ($routes) {
$routes->get('', 'Papelesgenericos::index', ['as' => 'papelGenericoList']);
$routes->delete('', 'Papelesgenericos::index', ['as' => 'papelGenericoList2']);
$routes->get('add', 'Papelesgenericos::add', ['as' => 'newPapelGenerico']);
$routes->post('add', 'Papelesgenericos::add', ['as' => 'createPapelGenerico']);
$routes->post('create', 'Papelesgenericos::create', ['as' => 'ajaxCreatePapelGenerico']);
$routes->put('(:num)/update', 'Papelesgenericos::update/$1', ['as' => 'ajaxUpdatePapelGenerico']);
$routes->post('edit/(:num)', 'Papelesgenericos::edit/$1', ['as' => 'updatePapelGenerico']);
$routes->post('datatable', 'Papelesgenericos::datatable', ['as' => 'dataTableOfPapelesGenericos']);
$routes->post('allmenuitems', 'Papelesgenericos::allItemsSelect', ['as' => 'select2ItemsOfPapelesGenericos']);
$routes->post('menuitems', 'Papelesgenericos::menuItems', ['as' => 'menuItemsOfPapelesGenericos']);
});
$routes->resource('papelesgenericos', ['namespace' => 'App\Controllers\Configuracion', 'controller' => 'Papelesgenericos', 'except' => 'show,new,create,update']);
$routes->group('papelesimpresion', ['namespace' => 'App\Controllers\Configuracion'], function ($routes) {
$routes->get('', 'Papelesimpresion::index', ['as' => 'papelImpresionList']);
$routes->get('add', 'Papelesimpresion::add', ['as' => 'newPapelImpresion']);
$routes->post('add', 'Papelesimpresion::add', ['as' => 'createPapelImpresion']);
$routes->post('create', 'Papelesimpresion::create', ['as' => 'ajaxCreatePapelImpresion']);
$routes->put('(:num)/update', 'Papelesimpresion::update/$1', ['as' => 'ajaxUpdatePapelImpresion']);
$routes->post('edit/(:num)', 'Papelesimpresion::edit/$1', ['as' => 'updatePapelImpresion']);
$routes->post('datatable', 'Papelesimpresion::datatable', ['as' => 'dataTableOfPapelesImpresion']);
$routes->post('allmenuitems', 'Papelesimpresion::allItemsSelect', ['as' => 'select2ItemsOfPapelesImpresion']);
$routes->post('menuitems', 'Papelesimpresion::menuItems', ['as' => 'menuItemsOfPapelesImpresion']);
});
$routes->resource('papelesimpresion', ['namespace' => 'App\Controllers\Configuracion', 'controller' => 'Papelesimpresion', 'except' => 'show,new,create,update']);
$routes->group('papelimpresiontipologias', ['namespace' => 'App\Controllers\Configuracion'], function ($routes) {
$routes->get('add', 'Papelimpresiontipologias::add', ['as' => 'newPapelImpresionTipologia']);
$routes->post('add', 'Papelimpresiontipologias::add', ['as' => 'createPapelImpresionTipologia']);
@ -175,6 +254,20 @@ $routes->group('papelesimpresionmargenes', ['namespace' => 'App\Controllers\Conf
});
$routes->resource('papelesimpresionmargenes', ['namespace' => 'App\Controllers\Configuracion', 'controller' => 'Papelimpresionmargenes', 'except' => 'show,new,create,update']);
$routes->group('maquinas', ['namespace' => 'App\Controllers\Configuracion'], function ($routes) {
$routes->get('', 'Maquinas::index', ['as' => 'maquinaList']);
$routes->get('add', 'Maquinas::add', ['as' => 'newMaquina']);
$routes->post('add', 'Maquinas::add', ['as' => 'createMaquina']);
$routes->post('create', 'Maquinas::create', ['as' => 'ajaxCreateMaquina']);
$routes->put('update/(:num)', 'Maquinas::update/$1', ['as' => 'ajaxUpdateMaquina']);
$routes->post('edit/(:num)', 'Maquinas::edit/$1', ['as' => 'updateMaquina']);
$routes->post('datatable', 'Maquinas::datatable', ['as' => 'dataTableOfMaquinas']);
$routes->post('allmenuitems', 'Maquinas::allItemsSelect', ['as' => 'select2ItemsOfMaquinas']);
$routes->post('menuitems', 'Maquinas::menuItems', ['as' => 'menuItemsOfMaquinas']);
});
$routes->resource('maquinas', ['namespace' => 'App\Controllers\Configuracion', 'controller' => 'Maquinas', 'except' => 'show,new,create,update']);
$routes->group('maquinastarifasimpresion', ['namespace' => 'App\Controllers\Configuracion'], function ($routes) {
$routes->get('', 'Maquinastarifasimpresion::index', ['as' => 'maquinasTarifaImpresionList']);
$routes->get('add', 'Maquinastarifasimpresion::add', ['as' => 'newMaquinasTarifaImpresion']);
@ -208,11 +301,24 @@ $routes->group('maquinaspapelesimpresion', ['namespace' => 'App\Controllers\Conf
$routes->resource('maquinastarifasimpresion', ['namespace' => 'App\Controllers\Configuracion', 'controller' => 'Maquinastarifasimpresion', 'except' => 'show,new,create,update']);
$routes->group('maquinasdefecto', ['namespace' => 'App\Controllers\Configuracion'], function ($routes) {
$routes->get('', 'Maquinasdefecto::index', ['as' => 'maquinaPorDefectoList']);
$routes->get('add', 'Maquinasdefecto::add', ['as' => 'newMaquinaPorDefecto']);
$routes->post('add', 'Maquinasdefecto::add', ['as' => 'createMaquinaPorDefecto']);
$routes->post('create', 'Maquinasdefecto::create', ['as' => 'ajaxCreateMaquinaPorDefecto']);
$routes->put('(:num)/update', 'Maquinasdefecto::update/$1', ['as' => 'ajaxUpdateMaquinaPorDefecto']);
$routes->post('edit/(:num)', 'Maquinasdefecto::edit/$1', ['as' => 'updateMaquinaPorDefecto']);
$routes->post('datatable', 'Maquinasdefecto::datatable', ['as' => 'dataTableOfMaquinasPorDefecto']);
$routes->post('allmenuitems', 'Maquinasdefecto::allItemsSelect', ['as' => 'select2ItemsOfMaquinasPorDefecto']);
$routes->post('menuitems', 'Maquinasdefecto::menuItems', ['as' => 'menuItemsOfMaquinasPorDefecto']);
});
$routes->resource('maquinasdefecto', ['namespace' => 'App\Controllers\Configuracion', 'controller' => 'Maquinasdefecto', 'except' => 'show,new,create,update']);
$routes->group('profile', ['namespace' => 'App\Controllers'], function ($routes) {
$routes->get('', 'Profile::index', ['as' => 'profileList']);
$routes->get('index', 'Profile::index', ['as' => 'profileIndex']);
$routes->get('list', 'Profile::index', ['as' => 'profileList2']);
$routes->match(['get', 'post'], 'store', 'Profile::store', ['as' => 'profileStore']);
});
@ -226,20 +332,22 @@ $routes->group('comunidades-autonomas', ['namespace' => 'App\Controllers\Configu
$routes->post('datatable', 'Comunidadesautonomas::datatable', ['as' => 'dataTableOfComunidadesAutonomas']);
$routes->post('allmenuitems', 'Comunidadesautonomas::allItemsSelect', ['as' => 'select2ItemsOfComunidadesAutonomas']);
$routes->post('menuitems', 'Comunidadesautonomas::menuItems', ['as' => 'menuItemsOfComunidadesAutonomas']);
$routes->get('menuitems2', 'Comunidadesautonomas::menuItems2', ['as' => 'menuItemsOfComunidadesAutonomas2']);
});
$routes->resource('comunidades-autonomas', ['namespace' => 'App\Controllers\Configuracion', 'controller' => 'Comunidadesautonomas', 'except' => 'show,new,create,update']);
$routes->group('formas-pago', ['namespace' => 'App\Controllers\Configuracion'], function ($routes) {
$routes->get('', 'FormasPago::index', ['as' => 'formasPagoList']);
$routes->match(['get', 'post'], 'add', 'FormasPago::add', ['as' => 'formasPagoAdd']);
$routes->match(['get', 'post'], 'edit/(:num)', 'FormasPago::edit/$1', ['as' => 'formasPagoEdit']);
$routes->get('delete/(:num)', 'FormasPago::delete/$1', ['as' => 'formasPagoDelete']);
$routes->post('datatable', 'FormasPago::datatable', ['as' => 'formasPagoDT']);
$routes->get('menuitems', 'FormasPago::menuItems', ['as' => 'menuItemsOfFormasDePagos']);
$routes->group('paises', ['namespace' => 'App\Controllers\Configuracion'], function ($routes) {
$routes->get('', 'Paises::index', ['as' => 'paisList']);
$routes->get('add', 'Paises::add', ['as' => 'newPais']);
$routes->post('add', 'Paises::add', ['as' => 'createPais']);
$routes->post('create', 'Paises::create', ['as' => 'ajaxCreatePais']);
$routes->put('(:num)/update', 'Paises::update/$1', ['as' => 'ajaxUpdatePais']);
$routes->post('(:num)/edit', 'Paises::edit/$1', ['as' => 'updatePais']);
$routes->post('datatable', 'Paises::datatable', ['as' => 'dataTableOfPaises']);
$routes->post('allmenuitems', 'Paises::allItemsSelect', ['as' => 'select2ItemsOfPaises']);
$routes->post('menuitems', 'Paises::menuItems', ['as' => 'menuItemsOfPaises']);
});
$routes->resource('formas-pago', ['namespace' => 'App\Controllers\Configuracion', 'controller' => 'FormasPago', 'except' => 'show,new,create,update']);
$routes->resource('paises', ['namespace' => 'App\Controllers\Configuracion', 'controller' => 'Paises', 'except' => 'show,new,create,update']);
$routes->group('provincias', ['namespace' => 'App\Controllers\Configuracion'], function ($routes) {
@ -252,7 +360,6 @@ $routes->group('provincias', ['namespace' => 'App\Controllers\Configuracion'], f
$routes->post('datatable', 'Provincias::datatable', ['as' => 'dataTableOfProvincias']);
$routes->post('allmenuitems', 'Provincias::allItemsSelect', ['as' => 'select2ItemsOfProvincias']);
$routes->post('menuitems', 'Provincias::menuItems', ['as' => 'menuItemsOfProvincias']);
$routes->get('menuitems2', 'Provincias::menuItems2', ['as' => 'menuItemsOfProvincias2']);
});
$routes->resource('provincias', ['namespace' => 'App\Controllers\Configuracion', 'controller' => 'Provincias', 'except' => 'show,new,create,update']);
@ -277,9 +384,6 @@ $routes->group('clientes', ['namespace' => 'App\Controllers\Clientes'], function
$routes->group('clienteprecios', ['namespace' => 'App\Controllers\Clientes'], function ($routes) {
$routes->post('datatable', 'ClientePrecios::datatable', ['as' => 'dataTableOfClienteprecios']);
$routes->post('datatable_editor', 'ClientePrecios::datatable_editor', ['as' => 'editorOfClienteprecios']);
$routes->post('changeplantilla', 'ClientePrecios::updatePlantilla', ['as' => 'changePlantillaOfClienteprecios']);
$routes->get('getplantilla', 'ClientePrecios::getCurrentPlantilla', ['as' => 'getPlantillaOfClienteprecios']);
$routes->post('update', 'ClientePrecios::updatePlantilla', ['as' => 'updateClienteprecios']);
});
$routes->resource('clienteprecios', ['namespace' => 'App\Controllers\Clientes', 'controller' => 'ClientePrecios', 'except' => 'show,new,create,update']);
@ -289,27 +393,21 @@ $routes->group('clienteplantillaprecios', ['namespace' => 'App\Controllers\Clien
$routes->get('add', 'Clienteplantillaprecios::add', ['as' => 'newClienteplantillaprecios']);
$routes->post('add', 'Clienteplantillaprecios::add', ['as' => 'createClienteplantillaprecios']);
$routes->post('edit/(:num)', 'Clienteplantillaprecios::edit/$1', ['as' => 'updateClienteplantillaprecios']);
$routes->get('edit/(:num)', 'Clienteplantillaprecios::edit/$1', ['as' => 'updateClienteplantillaprecios']);
$routes->get('delete/(:num)', 'Clienteplantillaprecios::delete/$1', ['as' => 'deleteClienteplantillaprecios']);
$routes->post('datatable', 'Clienteplantillaprecios::datatable', ['as' => 'dataTableOfClientesplantillaprecios']);
$routes->get('menuitems', 'Clienteplantillaprecios::menuItems', ['as' => 'menuItemsOfClienteplantillaprecios']);
$routes->post('update/(:num)', 'Clienteplantillaprecios::update/$1', ['as' => 'updateClienteplantillaprecios']);
$routes->post('menuitems', 'Clienteplantillaprecios::menuItems', ['as' => 'menuItemsOfClienteplantillaprecios']);
});
$routes->resource('clienteplantillaprecios', ['namespace' => 'App\Controllers\Clientes', 'controller' => 'Clienteplantillaprecios', 'except' => 'show,new,create']);
$routes->resource('clienteplantillaprecios', ['namespace' => 'App\Controllers\Clientes', 'controller' => 'Clienteplantillaprecios', 'except' => 'show,new,create,update']);
$routes->group('clienteplantillaprecioslineas', ['namespace' => 'App\Controllers\Clientes'], function ($routes) {
$routes->post('datatable', 'Clienteplantillaprecioslineas::datatable', ['as' => 'dataTableOfClientesplantillaprecioslineas']);
$routes->post('datatable_editor', 'Clienteplantillaprecioslineas::datatable_editor', ['as' => 'editorOfClienteplantillaprecioslineas']);
$routes->post('getrows', 'Clienteplantillaprecioslineas::getStoredRows', ['as' => 'getStoredRowsOfClienteplantillaprecioslineas']);
});
$routes->resource('clienteplantillaprecioslineas', ['namespace' => 'App\Controllers\Clientes', 'controller' => 'clienteplantillaprecioslineas', 'except' => 'show,new,create,update']);
$routes->group('clienteusuarios', ['namespace' => 'App\Controllers\Clientes'], function ($routes) {
$routes->post('datatable', 'Clienteusuarios::datatable', ['as' => 'dataTableOfClienteUsuarios']);
$routes->post('adduser', 'Clienteusuarios::addUserToClient');
$routes->get('delete/(:num)', 'Clienteusuarios::removeClienteFromUser/$1');
$routes->get('getusers', 'Clienteusuarios::getAvailableUsers');
});
@ -322,6 +420,18 @@ $routes->group('misdirecciones', ['namespace' => 'App\Controllers\Clientes'], fu
});
$routes->group('formas-pagos', ['namespace' => 'App\Controllers\Configuracion'], function ($routes) {
$routes->get('', 'Formaspagos::index', ['as' => 'formaDePagoList']);
$routes->get('add', 'Formaspagos::add', ['as' => 'newFormaDePago']);
$routes->post('add', 'Formaspagos::add', ['as' => 'createFormaDePago']);
$routes->post('create', 'Formaspagos::create', ['as' => 'ajaxCreateFormaDePago']);
$routes->put('(:num)/update', 'Formaspagos::update/$1', ['as' => 'ajaxUpdateFormaDePago']);
$routes->post('(:num)/edit', 'Formaspagos::edit/$1', ['as' => 'updateFormaDePago']);
$routes->post('datatable', 'Formaspagos::datatable', ['as' => 'dataTableOfFormasDePagos']);
$routes->post('allmenuitems', 'Formaspagos::allItemsSelect', ['as' => 'select2ItemsOfFormasDePagos']);
$routes->post('menuitems', 'Formaspagos::menuItems', ['as' => 'menuItemsOfFormasDePagos']);
});
$routes->resource('formas-pagos', ['namespace' => 'App\Controllers\Configuracion', 'controller' => 'Formaspagos', 'except' => 'show,new,create,update']);
$routes->group('tarifasencuadernacion', ['namespace' => 'App\Controllers\Tarifas'], function ($routes) {
$routes->get('', 'Tarifasencuadernacion::index', ['as' => 'tarifaEncuadernacionList']);
@ -334,7 +444,6 @@ $routes->group('tarifasencuadernacion', ['namespace' => 'App\Controllers\Tarifas
$routes->post('datatable', 'Tarifasencuadernacion::datatable', ['as' => 'dataTableOfTarifasEncuadernacion']);
$routes->post('allmenuitems', 'Tarifasencuadernacion::allItemsSelect', ['as' => 'select2ItemsOfTarifasEncuadernacion']);
$routes->post('menuitems', 'Tarifasencuadernacion::menuItems', ['as' => 'menuItemsOfTarifasEncuadernacion']);
$routes->get('gettarifas', 'Tarifasencuadernacion::getSelect2');
});
$routes->resource('tarifasencuadernacion', ['namespace' => 'App\Controllers\Tarifas', 'controller' => 'Tarifasencuadernacion', 'except' => 'show,new,create,update']);
@ -403,7 +512,22 @@ $routes->group('tarifasenvioszonas', ['namespace' => 'App\Controllers\Tarifas'],
$routes->resource('tarifasenvioszonas', ['namespace' => 'App\Controllers\Tarifas', 'controller' => 'Tarifasenvioszonas', 'except' => 'show,new,create,update']);
$routes->group('proveedores', ['namespace' => 'App\Controllers\Compras'], function ($routes) {
$routes->get('', 'Proveedores::index', ['as' => 'proveedorList']);
$routes->get('add', 'Proveedores::add', ['as' => 'newProveedor']);
$routes->post('add', 'Proveedores::add', ['as' => 'createProveedor']);
$routes->post('create', 'Proveedores::create', ['as' => 'ajaxCreateProveedor']);
$routes->put('(:num)/update', 'Proveedores::update/$1', ['as' => 'ajaxUpdateProveedor']);
$routes->post('edit/(:num)', 'Proveedores::edit/$1', ['as' => 'updateProveedor']);
$routes->post('datatable', 'Proveedores::datatable', ['as' => 'dataTableOfProveedores']);
$routes->post('allmenuitems', 'Proveedores::allItemsSelect', ['as' => 'select2ItemsOfProveedores']);
$routes->post('menuitems', 'Proveedores::menuItems', ['as' => 'menuItemsOfProveedores']);
});
$routes->resource('proveedores', ['namespace' => 'App\Controllers\Compras', 'controller' => 'Proveedores', 'except' => 'show,new,create,update']);
$routes->group('proveedorestipos', ['namespace' => 'App\Controllers\Compras'], function ($routes) {
$routes->post('menuitems', 'ProveedoresTipos::menuItems', ['as' => 'menuItemsOfProveedoresTipos']);
});
$routes->resource('proveedorestipos', ['namespace' => 'App\Controllers\Compras', 'controller' => 'ProveedoresTipos', 'except' => 'show,new,create,update']);
@ -432,45 +556,65 @@ $routes->group('clientedirecciones', ['namespace' => 'App\Controllers\Clientes']
$routes->resource('clientedirecciones', ['namespace' => 'App\Controllers\Clientes', 'controller' => 'Clientedirecciones', 'except' => 'show,new,create,update']);
$routes->group('cosidotapablanda', ['namespace' => 'App\Controllers\Presupuestos'], function ($routes) {
$routes->get('list/(:num)', 'Cosidotapablanda::list/$1', ['as' => 'cosidotapablandaList']); // HOMOGENIZAR CON ARGS DINAMICOS!!!
$routes->get('add/(:num)', 'Cosidotapablanda::add/$1', ['as' => 'newCosidotapablanda']);
$routes->get('edit/(:any)', 'Cosidotapablanda::edit/$1', ['as' => 'editarPresupuesto']);
$routes->post('add/(:num)', 'Cosidotapablanda::add/$1', ['as' => 'createCosidotapablanda']);
$routes->post('create', 'Cosidotapablanda::create', ['as' => 'ajaxCreateCosidotapablanda']);
$routes->put('(:num)/update', 'Cosidotapablanda::update/$1', ['as' => 'ajaxUpdateCosidotapablanda']);
$routes->post('edit/(:num)', 'Cosidotapablanda::edit/$1', ['as' => 'updateCosidotapablanda']);
$routes->post('datatable', 'Cosidotapablanda::datatable', ['as' => 'dataTableOfCosidotapablanda']);
$routes->post('datatable_2', 'Cosidotapablanda::datatable_2', ['as' => 'updateDataOfCosidotapablanda']);
$routes->post('allmenuitems', 'Cosidotapablanda::allItemsSelect', ['as' => 'select2ItemsOfCosidotapablanda']);
$routes->post('menuitems', 'Cosidotapablanda::menuItems', ['as' => 'menuItemsOfCosidotapablanda']);
});
$routes->resource('cosidotapablanda', ['namespace' => 'App\Controllers\Presupuestos', 'controller' => 'Cosidotapablanda', 'except' => 'show,new,create,update']);
$routes->group('presupuestocliente', ['namespace' => 'App\Controllers\Presupuestos'], function ($routes) {
$routes->get('list', 'Presupuestocliente::list', ['as' => 'listaPresupuestos']);
$routes->post('datatable', 'Presupuestocliente::datatable', ['as' => 'datatableOfPresupuestos']);
$routes->get('add', 'Presupuestocliente::add', ['as' => 'nuevoPresupuestoCliente']);
$routes->post('add', 'Presupuestocliente::add', ['as' => 'crearPresupuestoCliente']);
$routes->post('edit/(:num)', 'Presupuestocliente::edit/$1', ['as' => 'editarPresupuestoCliente']);
$routes->get('edit/(:any)', 'Presupuestocliente::edit/$1', ['as' => 'editarPresupuestoCliente2']);
$routes->post('getgramaje', 'Presupuestocliente::getGramaje', ['as' => 'obtenerGramaje']);
$routes->post('presupuesto', 'Presupuestocliente::presupuesto', ['as' => 'presupuestoCliente']);
$routes->post('getDireccionesCliente', 'Presupuestocliente::getDireccionesCliente', ['as' => 'getDirecciones']);
$routes->post('getNuevaDireccion', 'Presupuestocliente::getNuevaDireccion', ['as' => 'nuevaDireccion']);
$routes->post('guardar', 'Presupuestocliente::guardar', ['as' => 'guardar']);
$routes->get('cargar/(:num)', 'Presupuestocliente::cargar/$1', ['as' => 'cargarPresupuesto']);
$routes->post('duplicarPresupuesto', 'Presupuestocliente::duplicarPresupuesto', ['as' => 'duplicarPresupuesto']);
$routes->post('calcular', 'Presupuestocliente::calcular', ['as' => 'calcularPresupuesto']);
});
$routes->resource('presupuestocliente', ['namespace' => 'App\Controllers\Presupuestos', 'controller' => 'Presupuestocliente', 'except' => 'show,new,create,update']);
$routes->group('serviciosacabados', ['namespace' => 'App\Controllers\Presupuestos'], function ($routes) {
$routes->get('getacabados', 'Presupuestoacabados::getAcabados');
$routes->post('getvalues', 'Presupuestoacabados::getRowValues');
$routes->post('datatable', 'Presupuestoacabados::datatable', ['as' => 'dataTableOfPresupuestoAcabados']);
$routes->post('menuitems', 'Presupuestoacabados::menuItems', ['as' => 'menuItemsOfPresupuestoAcabados']);
$routes->post('edit/(:num)', 'Presupuestoacabados::edit/$1', ['as' => 'updatePresupuestoacabados']);
$routes->get('cargar', 'Presupuestoacabados::cargar');
$routes->post('update/(:num)', 'Presupuestoacabados::update/$1');
});
$routes->group('serviciosencuadernaciones', ['namespace' => 'App\Controllers\Presupuestos'], function ($routes) {
$routes->post('datatable', 'Presupuestoencuadernaciones::datatable', ['as' => 'dataTableOfPresupuestoEncuadernaciones']);
$routes->post('getvalues', 'Presupuestoencuadernaciones::getRowValues');
$routes->post('menuitems', 'Presupuestoencuadernaciones::menuItems', ['as' => 'menuItemsOfPresupuestoEncuadernaciones']);
$routes->get('delete/(:num)', 'Presupuestoencuadernaciones::delete/$1', ['as' => 'deletePresupuestoencuadernaciones']);
$routes->post('edit/(:num)', 'Presupuestoencuadernaciones::edit/$1', ['as' => 'updatePresupuestoencuadernaciones']);
$routes->post('update/(:num)', 'Presupuestoencuadernaciones::update/$1');
});
$routes->group('serviciosmanipulados', ['namespace' => 'App\Controllers\Presupuestos'], function ($routes) {
$routes->post('getvalues', 'Presupuestomanipulados::getRowValues');
$routes->post('datatable', 'Presupuestomanipulados::datatable', ['as' => 'dataTableOfPresupuestoManipulados']);
$routes->post('edit/(:num)', 'Presupuestomanipulados::edit/$1', ['as' => 'updatePresupuestomanipulados']);
$routes->post('update/(:num)', 'Presupuestomanipulados::update/$1');
$routes->get('serviciosolapas', 'Presupuestomanipulados::getServicioSolapas');
});
$routes->group('serviciospreimpresiones', ['namespace' => 'App\Controllers\Presupuestos'], function ($routes) {
$routes->post('getvalues', 'Presupuestopreimpresiones::getRowValues');
$routes->post('datatable', 'Presupuestopreimpresiones::datatable', ['as' => 'dataTableOfPresupuestoPreimpresiones']);
$routes->post('edit/(:num)', 'Presupuestopreimpresiones::edit/$1', ['as' => 'updatePresupuestopreimpresiones']);
$routes->get('cargar', 'Presupuestopreimpresiones::getSelect2');
});
$routes->group('serviciosextra', ['namespace' => 'App\Controllers\Presupuestos'], function ($routes) {
$routes->post('datatable', 'Presupuestoserviciosextra::datatable', ['as' => 'dataTableOfPresupuestoServiciosExtra']);
$routes->post('edit/(:num)', 'Presupuestoserviciosextra::edit/$1', ['as' => 'updatePresupuestoServiciosExtra']);
$routes->post('getvalues', 'Presupuestoserviciosextra::getRowValues');
});
$routes->group('presupuestodirecciones', ['namespace' => 'App\Controllers\Presupuestos'], function ($routes) {
@ -484,10 +628,10 @@ $routes->group('presupuestotiradasalternativas', ['namespace' => 'App\Controller
});
$routes->group('pedidos', ['namespace' => 'App\Controllers\Pedidos'], function ($routes) {
$routes->get('list', 'Pedido::todos', ['as' => 'listaPedidos']);
$routes->get('activos', 'Pedido::activos', ['as' => 'listaPedidosActivos']);
$routes->get('finalizados', 'Pedido::finalizados', ['as' => 'listaPedidosFinalizados']);
$routes->get('cancelados', 'Pedido::cancelados', ['as' => 'listaPedidosCancelados']);
$routes->get('list', 'Pedido::todos', ['as' => 'listaPresupuestos']);
$routes->get('listActivos', 'Pedido::activos', ['as' => 'listaPresupuestosActivos']);
$routes->get('listFinalizados', 'Pedido::finalizados', ['as' => 'listaFinalizados']);
$routes->get('listCancelados', 'Pedido::cancelados', ['as' => 'listaCancelados']);
$routes->post('datatable', 'Pedido::datatable', ['as' => 'dataTableOfPedidos']);
$routes->get('add', 'Pedido::add', ['as' => 'nuevoPedido']);
$routes->post('add', 'Pedido::add', ['as' => 'crearPedido']);
@ -495,12 +639,7 @@ $routes->group('pedidos', ['namespace' => 'App\Controllers\Pedidos'], function (
$routes->post('getlineas', 'Pedido::getLineas', ['as' => 'tablaLineasPedido']);
$routes->post('cambiarestado', 'Pedido::cambiarEstado', ['as' => 'cambiarEstadoPedido']);
$routes->post('update/(:any)', 'Pedido::update/$1', ['as' => 'actualizarPedido']);
$routes->post('insertfactura', 'Pedido::addFactura');
$routes->get('xml/(:num)', 'Pedido::get_xml_pedido/$1', ['as' => 'getXMLPedido']);
$routes->post('produccion/(:num)', 'Pedido::to_produccion/$1', ['as' => 'toProduccion']);
$routes->get('pedidosCliente', 'Pedido::tablaClienteForm');
$routes->get('getSumCliente/(:num)', 'Pedido::obtenerTotalPedidosCliente/$1');
$routes->get('validacion', 'Pedido::validacion', ['as' => 'validacionView']);
});
$routes->resource('pedidos', ['namespace' => 'App\Controllers\Pedidos', 'controller' => 'Pedido', 'except' => 'show,new,create,update']);
@ -521,7 +660,7 @@ $routes->resource('albaranes', ['namespace' => 'App\Controllers\Pedidos', 'contr
$routes->group('facturas', ['namespace' => 'App\Controllers\Facturacion'], function ($routes) {
$routes->get('list', 'Facturas::list', ['as' => 'facturasList']);
$routes->get('datatable', 'Facturas::datatable', ['as' => 'dataTableOfFacturas']);
$routes->post('datatable', 'Facturas::datatable', ['as' => 'dataTableOfFacturas']);
$routes->get('add', 'Facturas::add', ['as' => 'newFactura']);
$routes->post('add', 'Facturas::add', ['as' => 'createFactura']);
$routes->get('edit/(:any)', 'Facturas::edit/$1', ['as' => 'editarFactura']);
@ -541,7 +680,6 @@ $routes->group('facturas', ['namespace' => 'App\Controllers\Facturacion'], funct
$routes->post('datatablePagos/(:any)', 'FacturasPagos::datatable/$1', ['as' => 'dataTableOfPagosFacturas']);
$routes->post('editorPagos', 'FacturasPagos::datatable_editor', ['as' => 'editorOfPagosFacturas']);
$routes->post('datatablePedidos', 'Facturas::datatablePedidos', ['as' => 'dataTableOfFacturasPedido']);
$routes->get('getdatoscliente/(:any)', 'Facturas::getDatosFacturacionClienteForm/$1');
});
@ -589,10 +727,10 @@ $routes->group(
);
$routes->group(
'presupuestos',
'buscadorpresupuestos',
['namespace' => 'App\Controllers\Presupuestos'],
function ($routes) {
$routes->get('buscador', 'Buscador::index', ['as' => 'buscadorPresupuestosList']);
$routes->get('', 'Buscador::list', ['as' => 'buscadorPresupuestosList']);
$routes->post('datatable', 'Buscador::datatable', ['as' => 'dataTableOfBuscador']);
}
);
@ -625,165 +763,49 @@ $routes->group('mensajes', ['namespace' => 'App\Controllers\Mensajeria'], functi
$routes->post('datatable', 'TarifaAcabados::datatable', ['as' => 'tarifaAcabadoDT']);*/
});
});
$routes->group('messages', ['namespace' => 'App\Controllers\Chat'], function ($routes) {
$routes->get('datatable', 'ChatController::datatable_messages', ['as' => 'getDatatableMessages']);
$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->post('direct', 'ChatController::store_new_direct_message', ['as' => 'storeNewDirectMessage']);
$routes->post('direct/client', 'ChatController::store_new_direct_message_client', ['as' => 'storeNewDirectMessageClient']);
});
$routes->group('chat', ['namespace' => 'App\Controllers\Chat'], function ($routes) {
$routes->get('direct/(:num)', 'ChatController::get_chat_direct_view/$1', ['as' => 'getChatDirectView']);
$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('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']);
$routes->get('direct/client/users/select/presupuesto/(:num)', 'ChatController::get_presupuesto_client_users/$1/$2', ['as' => 'getPresupuestoClientUsers']);
$routes->get('direct/client/users/select/pedido/(:num)', 'ChatController::get_pedido_client_users/$1/$2', ['as' => 'getPedidoClientUsers']);
$routes->get('direct/client/users/select/factura/(:num)', 'ChatController::get_factura_client_users/$1/$2', ['as' => 'getFacturaClientUsers']);
$routes->get('direct/client/users/select/ot/(:num)', 'ChatController::get_orden_trabajo_client_users/$1/$2', ['as' => 'getOrdenTrabajoClientUsers']);
$routes->get('direct/users/(:num)', 'ChatController::get_chat_direct_users', ['as' => 'getChatDirectUsers']);
$routes->post('direct/users/(:num)', 'ChatController::store_chat_direct_users/$1', ['as' => 'storeChatDirectUsers']);
$routes->get('direct/messages/(:num)', 'ChatController::get_chat_direct_messages/$1', ['as' => 'getChatDirectMessages']);
$routes->post('direct/messages/(:num)', 'ChatController::store_chat_direct_message/$1', ['as' => 'storeChatDirectMessages']);
$routes->post('direct/messages/unread/(:num)', 'ChatController::update_chat_direct_message_unread/$1', ['as' => 'updateChatDirectMessageUnread']);
$routes->post('department', 'ChatController::store_chat_department', ['as' => 'storeChatDepartment']);
$routes->delete('department/(:num)', 'ChatController::delete_chat_department/$1', ['as' => 'deleteChatDepartment']);
$routes->post('department/update/(:num)', 'ChatController::update_chat_department/$1', ['as' => 'updateChatDepartment']);
$routes->get('departments/(:alpha)/(:num)', 'ChatController::get_chat_departments/$1/$2', ['as' => 'getChatDepartments']);
$routes->get('departments/select', 'ChatController::get_chat_department_select', ['as' => 'getChatDepartmentSelect']);
$routes->get('departments', 'ChatController::get_chat_departments', ['as' => 'getChatDepartments']);
$routes->get('department/presupuesto/(:num)/(:num)', 'ChatController::get_chat_presupuesto/$1/$2', ['as' => 'getChatPresupuesto']);
$routes->get('department/pedido/(:num)/(:num)', 'ChatController::get_chat_pedido/$1/$2', ['as' => 'getChatPedido']);
$routes->get('department/factura/(:num)/(:num)', 'ChatController::get_chat_factura/$1/$2', ['as' => 'getChatFactura']);
$routes->get('department/ot/(:num)/(:num)', 'ChatController::get_chat_orden_trabajo/$1/$2', ['as' => 'getChatOrdenTrabajo']);
$routes->get('department/users/presupuesto/(:num)/(:num)', 'ChatController::get_chat_department_presupuesto_users/$1/$2', ['as' => 'getPresupuestoChatDepartmentUsers']);
$routes->get('department/users/ot/(:num)/(:num)', 'ChatController::get_chat_department_orden_trabajo_users/$1/$2', ['as' => 'getOrdenTrabajoChatDepartmentUsers']);
$routes->get('department/datatable', 'ChatController::chat_department_datatable', ['as' => 'chatDepartmentDatatable']);
$routes->get('department/edit/(:num)', 'ChatController::chat_department_edit/$1', ['as' => 'chatDepartmentEditView']);
$routes->get('department/users/datatable/(:num)', 'ChatController::chat_department_user_datatable/$1', ['as' => 'chatDepartmentUsersDatatable']);
$routes->get('department/users/pedido/(:num)/(:num)', 'ChatController::get_chat_department_pedido_users/$1/$2', ['as' => 'getPedidoChatDepartmentUsers']);
$routes->get('department/users/factura/(:num)/(:num)', 'ChatController::get_chat_department_factura_users/$1/$2', ['as' => 'getFacturaChatDepartmentUsers']);
$routes->get('department/users/select/add/(:num)', 'ChatController::select_users_not_in_chat_department/$1', ['as' => 'selectUsersNotInChatDepartment']);
$routes->post('department/user', 'ChatController::subscribe_to_chat_deparment/$1', ['as' => 'subscribeToChatDepartment']);
$routes->post('department/subscribe/admin/user', 'ChatController::subscribe_admin_to_department', ['as' => 'subscribeAdminToChatDepartment']);
$routes->delete('department/user/(:num)', 'ChatController::delete_user_from_department/$1', ['as' => 'deleteUserFromDepartment']);
$routes->delete('department/admin/user/(:num)/(:num)', 'ChatController::delete_user_admin_from_department/$1/$2', ['as' => 'deleteUserAdminFromDepartment']);
$routes->get('department/(:num)/users', 'ChatController::get_chat_department_users/$1', ['as' => 'getChatDepartmentUsers']);
$routes->get('(:num)', 'ChatController::get_chat/$1', ['as' => 'getChat']);
$routes->post('message/error/presupuesto', 'ChatController::store_chat_error_message', ['as' => 'storeChatErrorMessage']);
$routes->post('message/(:alpha)', 'ChatController::store_message/$1', ['as' => 'storeChatMessage']);
$routes->post('message/presupuesto', 'ChatController::store_chat_message_presupuesto', ['as' => 'storeChatMessagePresupuesto']);
$routes->post('message/pedido', 'ChatController::store_chat_message_pedido', ['as' => 'storeChatMessagePedido']);
$routes->post('message/factura', 'ChatController::store_chat_message_factura', ['as' => 'storeChatMessageFactura']);
$routes->post('message/internal', 'ChatController::store_chat_message_single', ['as' => 'storeChatMessageSingle']);
$routes->get('contacts', 'ChatController::get_chat_internal_contacts', ['as' => 'getChatInternalContacts']);
$routes->get('contacts/(:num)', 'ChatController::get_chat_internal_contact/$1', ['as' => 'getChatInternalContact']);
$routes->get('contact/(:num)/messages', 'ChatController::get_chat_internal_messages/$1', ['as' => 'getChatInternalMessages']);
$routes->get('notifications', 'ChatController::get_chat_cliente/$1', ['as' => 'getChatCliente']);
$routes->get('users/internal', 'ChatController::get_chat_users_internal', ['as' => 'getChatUsersInternal']);
$routes->get('users/all', 'ChatController::get_chat_users_all', ['as' => 'getChatUsersAll']);
$routes->post('hebra/(:alpha)', 'ChatController::store_hebra/$1', ['as' => 'storeHebra']);
$routes->post('hebra/presupuesto', 'ChatController::store_hebra_presupuesto', ['as' => 'storeHebraPresupuesto']);
$routes->post('hebra/pedido', 'ChatController::store_hebra_pedido', ['as' => 'storeHebraPedido']);
$routes->post('hebra/factura', 'ChatController::store_hebra_factura', ['as' => 'storeHebraFactura']);
$routes->post('hebra/(:num)', 'ChatController::update_hebra/$1', ['as' => 'updateHebra']);
$routes->get('hebra/(:alpha)/(:num)', "ChatController::get_hebra/$1/$2", ["as" => "getHebra"]);
$routes->get('users/message/notifications-unviewed/(:num)', 'ChatController::get_notifications_not_viewed_from_message/$1');
$routes->get('hebra/presupuesto/(:num)', "ChatController::get_hebra_presupuesto/$1", ["as" => "getHebraPresupuesto"]);
$routes->get('hebra/pedido/(:num)', "ChatController::get_hebra_pedido/$1", ["as" => "getHebraPedido"]);
$routes->get('hebra/factura/(:num)', "ChatController::get_hebra_factura/$1", ["as" => "getHebraFactura"]);
});
$routes->group('messages', ['namespace' => 'App\Controllers\Chat'], function ($routes) {
$routes->get('datatable', 'ChatController::datatable_messages', ['as' => 'getDatatableMessages']);
$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->post('direct', 'ChatController::store_new_direct_message', ['as' => 'storeNewDirectMessage']);
$routes->post('direct/client', 'ChatController::store_new_direct_message_client', ['as' => 'storeNewDirectMessageClient']);
});
$routes->group('soporte', ['namespace' => 'App\Controllers\Soporte'], function ($routes) {
$routes->get('', 'Ticketcontroller::index', ['as' => 'TicketIndex']);
$routes->get('add', 'Ticketcontroller::add', ['as' => 'NewTicket']);
$routes->post('add', 'Ticketcontroller::add', ['as' => 'createTicket']);
$routes->get('edit/(:num)', 'Ticketcontroller::edit/$1', ['as' => 'editTicket']);
$routes->post('edit/(:num)', 'Ticketcontroller::edit/$1', ['as' => 'updateTicket']);
$routes->post('ticketlist', 'Ticketcontroller::datatable');
$routes->get('image/(:segment)', 'Ticketcontroller::image/$1');
});
$routes->group('produccion', ['namespace' => 'App\Controllers\Produccion'], function ($routes) {
$routes->group('ordentrabajo', ['namespace' => 'App\Controllers\Produccion'], function ($routes) {
$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');
$routes->get('summary/(:num)', 'Ordentrabajo::get_orden_trabajo_summary/$1', ['as' => 'getOrdenTrabajoSumary']);
$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('tareas/datatable/(:num)', 'Ordentrabajo::tareas_datatable/$1', ['as' => 'datatableTareasOrdenTrabajo']);
/**======================
* UPDATES
*========================**/
$routes->post("update/tarea", 'Ordentrabajo::update_orden_trabajo_tarea');
$routes->post("update/date", 'Ordentrabajo::update_orden_trabajo_date');
$routes->post("update/pedido/date", 'Ordentrabajo::update_orden_trabajo_pedido_date');
$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');
/**======================
* FILES
*========================**/
$routes->post('get_files', 'Ordentrabajo::get_files');
$routes->post('upload_files', 'Ordentrabajo::upload_files');
/**======================
* PDF
*========================**/
$routes->get('pdf/(:num)', 'Ordentrabajo::get_pdf/$1');
$routes->get('portada/(:num)', 'Ordentrabajo::get_portada_img/$1');
$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');
$routes->get('select/maquina/plana', 'Ordentrabajo::select_maquina_planning_plana');
$routes->get('select/maquina/padre/plana', 'Ordentrabajo::select_maquina_padre_planning_plana');
$routes->get('select/papel/plana', 'Ordentrabajo::select_papel_planning_plana');
$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('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('logistica', ['namespace' => 'App\Controllers\Logistica'], function ($routes) {
$routes->get('print/label/test', 'LogisticaController::print_test_label');
/*
* --------------------------------------------------------------------
* APIs Route Definitions
* --------------------------------------------------------------------
*/
$routes->post('auth/jwt', '\App\Controllers\Sistema\AuthAPIController::jwtLogin');
$routes->group('api', ['filter' => 'jwt'], static function ($routes) {
$routes->get('test', 'Test::echo');
// ...
});
/*
* --------------------------------------------------------------------
* Translation
* Translation
* --------------------------------------------------------------------
*/
$routes->group('translate', ['namespace' => 'App\Controllers'], function ($routes) {
@ -807,4 +829,4 @@ $routes->resource('translate', ['namespace' => 'App\Controllers', 'controller' =
*/
if (file_exists(APPPATH . 'Config/' . ENVIRONMENT . '/Routes.php')) {
require APPPATH . 'Config/' . ENVIRONMENT . '/Routes.php';
}
}

View File

@ -1,27 +0,0 @@
<?php
use CodeIgniter\Router\RouteCollection;
/** @var RouteCollection $routes */
/*
* --------------------------------------------------------------------
* APIs Route Definitions
* --------------------------------------------------------------------
*/
$routes->post('auth/jwt', '\App\Controllers\Sistema\AuthAPIController::jwtLogin');
$routes->group(
'api',
[
'namespace' => 'App\Controllers\API',
'filter' => 'jwt'
],
static function ($routes) {
$routes->post("calcular", 'ImprimelibrosApi::calcular');
$routes->post("guardar", 'ImprimelibrosApi::guardar');
// ...
}
);

View File

@ -1,27 +0,0 @@
<?php
use CodeIgniter\Router\RouteCollection;
/** @var RouteCollection $routes */
/* Compras */
$routes->group('compras', ['namespace' => 'App\Controllers\Compras'], function ($routes) {
$routes->group('proveedores', ['namespace' => 'App\Controllers\Compras'], function ($routes) {
$routes->get('', 'Proveedores::index', ['as' => 'proveedorList']);
$routes->get('add', 'Proveedores::add', ['as' => 'newProveedor']);
$routes->post('add', 'Proveedores::add', ['as' => 'createProveedor']);
$routes->post('create', 'Proveedores::create', ['as' => 'ajaxCreateProveedor']);
$routes->put('(:num)/update', 'Proveedores::update/$1', ['as' => 'ajaxUpdateProveedor']);
$routes->get('edit/(:num)', 'Proveedores::edit/$1', ['as' => 'editProveedor']);
$routes->post('edit/(:num)', 'Proveedores::edit/$1', ['as' => 'updateProveedor']);
$routes->post('datatable', 'Proveedores::datatable', ['as' => 'dataTableOfProveedores']);
$routes->get('delete/(:num)', 'Proveedores::delete/$1', ['as' => 'deleteProveedores']);
$routes->post('allmenuitems', 'Proveedores::allItemsSelect', ['as' => 'select2ItemsOfProveedores']);
$routes->post('menuitems', 'Proveedores::menuItems', ['as' => 'menuItemsOfProveedores']);
});
});
$routes->group('proveedorestipos', ['namespace' => 'App\Controllers\Compras'], function ($routes) {
$routes->post('menuitems', 'ProveedoresTipos::menuItems', ['as' => 'menuItemsOfProveedoresTipos']);
});

View File

@ -1,153 +0,0 @@
<?php
use CodeIgniter\Router\RouteCollection;
/** @var RouteCollection $routes */
/* Rutas para configuraciones */
$routes->group('configuracion', ['namespace' => 'App\Controllers\Configuracion'], function ($routes) {
/* Paises */
$routes->group('paises', ['namespace' => 'App\Controllers\Configuracion'], function ($routes) {
$routes->get('', 'Paises::index', ['as' => 'paisList']);
$routes->get('add', 'Paises::add', ['as' => 'newPais']);
$routes->post('add', 'Paises::add', ['as' => 'createPais']);
$routes->get('delete/(:num)', 'Paises::delete/$1');
$routes->post('create', 'Paises::create', ['as' => 'ajaxCreatePais']);
$routes->put('update/(:num)', 'Paises::update/$1', ['as' => 'ajaxUpdatePais']);
$routes->match(['get', 'post'], 'edit/(:num)', 'Paises::edit/$1', ['as' => 'updatePais']);
$routes->get('datatable', 'Paises::datatable', ['as' => 'dataTableOfPaises']);
$routes->post('allmenuitems', 'Paises::allItemsSelect', ['as' => 'select2ItemsOfPaises']);
$routes->post('menuitems', 'Paises::menuItems', ['as' => 'menuItemsOfPaises']);
$routes->get('menuitems2', 'Paises::menuItems2', ['as' => 'menuItemsOfPaises2']);
});
/* Papeles genericos */
$routes->group('papelesgenericos', ['namespace' => 'App\Controllers\Configuracion'], function ($routes) {
$routes->get('', 'Papelesgenericos::index', ['as' => 'papelGenericoList']);
$routes->delete('', 'Papelesgenericos::index', ['as' => 'papelGenericoList2']);
$routes->get('add', 'Papelesgenericos::add', ['as' => 'newPapelGenerico']);
$routes->post('add', 'Papelesgenericos::add', ['as' => 'createPapelGenerico']);
$routes->post('create', 'Papelesgenericos::create', ['as' => 'ajaxCreatePapelGenerico']);
$routes->put('(:num)/update', 'Papelesgenericos::update/$1', ['as' => 'ajaxUpdatePapelGenerico']);
$routes->match(['get', 'post'], 'edit/(:num)', 'Papelesgenericos::edit/$1', ['as' => 'updatePapelGenerico']);
$routes->post('datatable', 'Papelesgenericos::datatable', ['as' => 'dataTableOfPapelesGenericos']);
$routes->post('allmenuitems', 'Papelesgenericos::allItemsSelect', ['as' => 'select2ItemsOfPapelesGenericos']);
$routes->post('menuitems', 'Papelesgenericos::menuItems', ['as' => 'menuItemsOfPapelesGenericos']);
$routes->get('getpapelcliente', 'Papelesgenericos::getPapelCliente', ['as' => 'getPapelCliente']);
$routes->get('selectpapelespecial', 'Papelesgenericos::selectPapelEspecial', ['as' => 'selectPapelEspecial']);
});
/* Papeles impresion */
$routes->group('papelesimpresion', ['namespace' => 'App\Controllers\Configuracion'], function ($routes) {
$routes->get('', 'Papelesimpresion::index', ['as' => 'papelImpresionList']);
$routes->get('add', 'Papelesimpresion::add', ['as' => 'newPapelImpresion']);
$routes->post('add', 'Papelesimpresion::add', ['as' => 'createPapelImpresion']);
$routes->post('create', 'Papelesimpresion::create', ['as' => 'ajaxCreatePapelImpresion']);
$routes->put('(:num)/update', 'Papelesimpresion::update/$1', ['as' => 'ajaxUpdatePapelImpresion']);
$routes->match(['get', 'post'], 'edit/(:num)', 'Papelesimpresion::edit/$1', ['as' => 'updatePapelImpresion']);
$routes->post('datatable', 'Papelesimpresion::datatable', ['as' => 'dataTableOfPapelesImpresion']);
$routes->post('allmenuitems', 'Papelesimpresion::allItemsSelect', ['as' => 'select2ItemsOfPapelesImpresion']);
$routes->post('menuitems', 'Papelesimpresion::menuItems', ['as' => 'menuItemsOfPapelesImpresion']);
$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 */
$routes->group('maquinas', ['namespace' => 'App\Controllers\Configuracion'], function ($routes) {
$routes->get('', 'Maquinas::index', ['as' => 'maquinaList']);
$routes->get('add', 'Maquinas::add', ['as' => 'newMaquina']);
$routes->get('edit/(:num)', 'Maquinas::edit/$1');
$routes->get('delete/(:num)', 'Maquinas::delete/$1');
$routes->post('add', 'Maquinas::add', ['as' => 'createMaquina']);
$routes->post('create', 'Maquinas::create', ['as' => 'ajaxCreateMaquina']);
$routes->put('update/(:num)', 'Maquinas::update/$1', ['as' => 'ajaxUpdateMaquina']);
$routes->match(['get', 'post'], 'edit/(:num)', 'Maquinas::edit/$1', ['as' => 'updateMaquina']);
$routes->post('datatable', 'Maquinas::datatable', ['as' => 'dataTableOfMaquinas']);
$routes->post('allmenuitems', 'Maquinas::allItemsSelect', ['as' => 'select2ItemsOfMaquinas']);
$routes->post('menuitems', 'Maquinas::menuItems', ['as' => 'menuItemsOfMaquinas']);
$routes->post('duplicate/(:num)', 'Maquinas::duplicate/$1', ['as' => 'duplicateMaquina']);
$routes->get('(:num)', 'Maquinas::find_maquina/$1', ['as' => 'findMaquina']);
$routes->get('select', 'Maquinas::select', ['as' => 'selectMaquinas']);
});
/* Maquinas por defecto */
$routes->group('maquinasdefecto', ['namespace' => 'App\Controllers\Configuracion'], function ($routes) {
$routes->get('', 'Maquinasdefecto::index', ['as' => 'maquinaPorDefectoList']);
$routes->get('add', 'Maquinasdefecto::add', ['as' => 'newMaquinaPorDefecto']);
$routes->post('add', 'Maquinasdefecto::add', ['as' => 'createMaquinaPorDefecto']);
$routes->post('create', 'Maquinasdefecto::create', ['as' => 'ajaxCreateMaquinaPorDefecto']);
$routes->put('(:num)/update', 'Maquinasdefecto::update/$1', ['as' => 'ajaxUpdateMaquinaPorDefecto']);
$routes->match(['get', 'post'], 'edit/(:num)', 'Maquinasdefecto::edit/$1', ['as' => 'updateMaquinaPorDefecto']);
$routes->post('datatable', 'Maquinasdefecto::datatable', ['as' => 'dataTableOfMaquinasPorDefecto']);
$routes->post('allmenuitems', 'Maquinasdefecto::allItemsSelect', ['as' => 'select2ItemsOfMaquinasPorDefecto']);
$routes->post('menuitems', 'Maquinasdefecto::menuItems', ['as' => 'menuItemsOfMaquinasPorDefecto']);
});
/* Ubicaciones */
$routes->group('ubicaciones', ['namespace' => 'App\Controllers\Configuracion'], function ($routes) {
$routes->get('', 'Ubicaciones::index', ['as' => 'ubicacionesList']);
$routes->match(['get', 'post'], 'add', 'Ubicaciones::add', ['as' => 'ubicacionesAdd']);
$routes->match(['get', 'post'], 'edit/(:num)', 'Ubicaciones::edit/$1', ['as' => 'ubicacionesEdit']);
$routes->get('delete/(:num)', 'Ubicaciones::delete/$1', ['as' => 'ubicacionesDelete']);
$routes->post('datatable', 'Ubicaciones::datatable', ['as' => 'ubicacionesDT']);
});
/* Permisos y roles */
$routes->group('group', ['namespace' => 'App\Controllers\Configuracion'], function ($routes) {
$routes->get('', 'Group::index', ['as' => 'userGroupList']);
$routes->get('index', 'Group::index', ['as' => 'groupIndex']);
$routes->post('edit/(:num)', 'Group::edit/$1', ['as' => 'updateGroup']);
$routes->get('edit/(:num)', 'Group::edit/$1', ['as' => 'editGroup']);
$routes->get('delete/(:num)', 'Group::delete/$1', ['as' => 'deleteGroup']);
$routes->get('add', 'Group::add', ['as' => 'newGroup']);
$routes->post('add', 'Group::add', ['as' => 'createGroup']);
});
/* Series Factura */
$routes->group('series-facturas', ['namespace' => 'App\Controllers\Configuracion'], function ($routes) {
$routes->get('', 'SeriesFacturas::index', ['as' => 'seriesFacturasList']);
$routes->match(['get', 'post'], 'add', 'SeriesFacturas::add', ['as' => 'seriesFacturasAdd']);
$routes->match(['get', 'post'], 'edit/(:num)', 'SeriesFacturas::edit/$1', ['as' => 'seriesFacturasEdit']);
$routes->get('delete/(:num)', 'SeriesFacturas::delete/$1', ['as' => 'seriesFacturasDelete']);
$routes->post('datatable', 'SeriesFacturas::datatable', ['as' => 'seriesFacturasDT']);
$routes->post('menuitemsFacturas', 'SeriesFacturas::menuItemsFacturas', ['as' => 'menuItemsOfSeriesFacturas']);
});
/* Variables del sistema */
$routes->group("variables", ["namespace" => 'App\Controllers\Configuracion'], function ($routes) {
$routes->get('', 'ConfigVariables::index', ['as' => 'variablesIndex']);
$routes->get('find/(:num)', 'ConfigVariables::get/$1', ['as' => 'variablesFind']);
$routes->post('edit/(:num)', 'ConfigVariables::updateVariable/$1', ['as' => 'updateVariable']);
$routes->delete('delete/(:num)', 'ConfigVariables::delete/$1', ['as' => 'deleteVariable']);
$routes->get('datatable', 'ConfigVariables::datatable', ['as' => 'datatableVariables']);
});
/* Errores en presupuestos */
$routes->group("errores-presupuesto", ["namespace" => 'App\Controllers\Configuracion'], function ($routes) {
$routes->get('', 'ConfigErrores::index', ['as' => 'erroresPresupuestoIndex']);
$routes->get('edit/(:num)', 'ConfigErrores::viewForm/$1', ['as' => 'erroresPresupuestoViewForm']);
$routes->get('get/(:num)', 'ConfigErrores::get_error_presupuesto/$1', ['as' => 'erroresPresupuestoGetErrorPresupuesto']);
$routes->get('datatable', 'ConfigErrores::datatable', ['as' => 'erroresPresupuestoDatatable']);
$routes->post('edit/(:num)', 'ConfigErrores::update_error_presupuesto/$1', ['as' => 'erroresPresupuestoUpdate']);
});
$routes->group("maquina-tareas", ["namespace" => 'App\Controllers\Configuracion'], function ($routes) {
$routes->get('', 'MaquinaTarea::index', ['as' => 'maquinaTareaList']);
$routes->get('(:num)', 'MaquinaTarea::show/$1', ['as' => 'maquinaTareaShow']);
$routes->delete('(:num)', 'MaquinaTarea::delete/$1', ['as' => 'maquinaTareaDelete']);
$routes->post('', 'MaquinaTarea::store/$1', ['as' => 'maquinaTareaStore']);
$routes->post('update/(:num)', 'MaquinaTarea::update_servicio_cliente/$1', ['as' => 'maquinaTareaUpdate']);
$routes->get('edit/(:num)', 'MaquinaTarea::viewForm/$1', ['as' => 'maquinaTareaViewForm']);
$routes->get('datatable', 'MaquinaTarea::datatable', ['as' => 'maquinaTareaDatatable']);
});
$routes->group("messages", ["namespace" => 'App\Controllers\Chat'], function ($routes) {
$routes->get('', 'ChatController::config_view', ['as' => 'configMessagesIndex']);
});
});

View File

@ -1,64 +0,0 @@
<?php
use CodeIgniter\Router\RouteCollection;
/** @var RouteCollection $routes */
$routes->group('presupuestoadmin', ['namespace' => 'App\Controllers\Presupuestos'], function ($routes) {
$routes->get('list/(:num)', 'Presupuestoadmin::list/$1', ['as' => 'presupuestoAdminList']); // HOMOGENIZAR CON ARGS DINAMICOS!!!
$routes->get('add/(:num)', 'Presupuestoadmin::add/$1', ['as' => 'newPresupuestoAdmin']);
$routes->get('edit/(:any)', 'Presupuestoadmin::edit/$1', ['as' => 'editarPresupuestoAdmin']);
$routes->post('add/(:num)', 'Presupuestoadmin::add/$1', ['as' => 'createPresupuestoAdmin']);
$routes->post('create', 'Presupuestoadmin::create', ['as' => 'ajaxCreatePresupuestoAdmin']);
$routes->put('(:num)/update', 'Presupuestoadmin::update/$1', ['as' => 'ajaxUpdatePresupuestoAdmin']);
$routes->post('edit/(:num)', 'Presupuestoadmin::edit/$1', ['as' => 'updatePresupuestoAdmin']);
$routes->post('datatable', 'Presupuestoadmin::datatable', ['as' => 'dataTableOfPresupuestoAdmin']);
$routes->post('datatable_2', 'Presupuestoadmin::datatable_2', ['as' => 'updateDataOfPresupuestoAdmin']);
$routes->post('allmenuitems', 'Presupuestoadmin::allItemsSelect', ['as' => 'select2ItemsOfPresupuestoAdmin']);
$routes->post('menuitems', 'Presupuestoadmin::menuItems', ['as' => 'menuItemsOfPresupuestoAdmin']);
$routes->get('cargar/(:any)', 'Presupuestoadmin::cargar/$1');
$routes->post('comparadorinterior', 'Presupuestoadmin::obtenerComparadorInterior');
$routes->post('comparadorexteriores', 'Presupuestoadmin::obtenerComparadorExteriores');
$routes->post('comparadorguardas', 'Presupuestoadmin::obtenerComparadorGuardas');
$routes->get('papelgenerico', 'Presupuestoadmin::getPapelGenerico');
$routes->get('papelgramaje', 'Presupuestoadmin::getGramaje');
$routes->get('papelimpresion', 'Presupuestoadmin::getPapelImpresion');
$routes->get('maquinas', 'Presupuestoadmin::getMaquinas');
$routes->post('getlinea', 'Presupuestoadmin::getLineaPresupuesto');
$routes->post('clone', 'Presupuestoadmin::datatable_2');
$routes->get('presupuestosCliente', 'Presupuestoadmin::tablaClienteForm');
$routes->get('getSumCliente/(:num)', 'Presupuestoadmin::obtenerTotalPresupuestosCliente/$1');
});
//$routes->resource('presupuestoadmin', ['namespace' => 'App\Controllers\Presupuestos', 'controller' => 'Presupuestoadmin', 'except' => 'show,new,create,update']);
$routes->group('presupuestocliente', ['namespace' => 'App\Controllers\Presupuestos'], function ($routes) {
$routes->get('list', 'Presupuestocliente::list', ['as' => 'listaPresupuestos']);
$routes->post('datatable', 'Presupuestocliente::datatable', ['as' => 'datatableOfPresupuestos']);
$routes->get('add', 'Presupuestocliente::add', ['as' => 'nuevoPresupuestoCliente']);
$routes->post('add', 'Presupuestocliente::add', ['as' => 'crearPresupuestoCliente']);
$routes->post('edit/(:num)', 'Presupuestocliente::edit/$1', ['as' => 'editarPresupuestoCliente']);
$routes->get('edit/(:any)', 'Presupuestocliente::edit/$1', ['as' => 'editarPresupuestoCliente2']);
$routes->post('getgramaje', 'Presupuestocliente::getGramaje', ['as' => 'obtenerGramaje']);
$routes->post('presupuesto', 'Presupuestocliente::presupuesto', ['as' => 'presupuestoCliente']);
$routes->post('getDireccionesCliente', 'Presupuestocliente::getDireccionesCliente', ['as' => 'getDirecciones']);
$routes->post('getNuevaDireccion', 'Presupuestocliente::getNuevaDireccion', ['as' => 'nuevaDireccion']);
$routes->post('guardar', 'Presupuestocliente::guardar', ['as' => 'guardar']);
$routes->get('cargar/(:num)', 'Presupuestocliente::cargar/$1', ['as' => 'cargarPresupuesto']);
$routes->post('duplicarPresupuesto', 'Presupuestocliente::duplicarPresupuesto', ['as' => 'duplicarPresupuesto']);
$routes->post('calcular', 'Presupuestocliente::calcular', ['as' => 'calcularPresupuesto']);
$routes->post('calcularsolapas', 'Presupuestocliente::calcularMaxSolapas', ['as' => 'calcularSolapas']);
$routes->post('checklomo', 'Presupuestocliente::check_lomo_interior');
});
//$routes->resource('presupuestocliente', ['namespace' => 'App\Controllers\Presupuestos', 'controller' => 'Presupuestocliente', 'except' => 'show,new,create,update']);
$routes->group('importador', ['namespace' => 'App\Controllers\Presupuestos'], function ($routes) {
$routes->get('', 'Importadorpresupuestos::index', ['as' => 'importadorPresupuestos']);
$routes->get('clientlist', 'Importadorpresupuestos::getClientList', ['as' => 'clientList']);
$routes->get('presupuestoslist', 'Importadorpresupuestos::getPresupuestosList', ['as' => 'presupuestosList']);
$routes->get('getencuadernacion', 'Importadorpresupuestos::getEncuadernacionList');
$routes->get('getpresupuestodata', 'Importadorpresupuestos::getPresupuesto', ['as' => 'getPresupuesto']);
$routes->post('importar', 'Importadorpresupuestos::importarPresupuesto');
});

View File

@ -1,55 +0,0 @@
<?php
use CodeIgniter\Router\RouteCollection;
/** @var RouteCollection $routes */
/* Rutas para tarifas */
$routes->group('tarifas', ['namespace' => 'App\Controllers\Tarifas'], function ($routes) {
/* Maquinas */
$routes->group('maquinas', ['namespace' => 'App\Controllers\Tarifas\Maquinas'], function ($routes) {
$routes->post('acabado', 'TarifaMaquinas::add_tarifa_acabado_maquina_with_tarea');
$routes->post('manipulado', 'TarifaMaquinas::add_tarifa_manipulado_maquina_with_tarea');
$routes->post('preimpresion', 'TarifaMaquinas::add_tarifa_preimpresion_maquina_with_tarea');
$routes->post('encuadernacion', 'TarifaMaquinas::add_tarifa_encuadernacion_maquina_with_tarea');
$routes->post('extra', 'TarifaMaquinas::add_tarifa_extra_maquina_with_tarea');
$routes->delete('acabado/(:num)', 'TarifaMaquinas::delete_tarifa_acabado_maquina_with_tarea/$1');
$routes->delete('manipulado/(:num)', 'TarifaMaquinas::delete_tarifa_manipulado_maquina_with_tarea/$1');
$routes->delete('preimpresion/(:num)', 'TarifaMaquinas::delete_tarifa_preimpresion_maquina_with_tarea/$1');
$routes->delete('encuadernacion/(:num)', 'TarifaMaquinas::delete_tarifa_encuadernacion_maquina_with_tarea/$1');
$routes->delete('extra/(:num)', 'TarifaMaquinas::delete_tarifa_extra_maquina_with_tarea/$1');
$routes->get('acabado/select', 'TarifaMaquinas::get_select_maquina_acabado');
$routes->get('manipulado/select', 'TarifaMaquinas::get_select_maquina_manipulado');
$routes->get('impresion/select', 'TarifaMaquinas::get_select_maquina_impresion');
$routes->get('encuadernacion/select', 'TarifaMaquinas::get_select_maquina_manipulado');
$routes->get('tareas/select', 'TarifaMaquinas::get_select_maquina_tareas');
$routes->get('acabado/datatable/(:num)', 'TarifaMaquinas::get_datatable_tarifa_acabado_maquina/$1');
$routes->get('manipulado/datatable/(:num)', 'TarifaMaquinas::get_datatable_tarifa_manipulado_maquina/$1');
$routes->get('preimpresion/datatable/(:num)', 'TarifaMaquinas::get_datatable_tarifa_preimpresion_maquina/$1');
$routes->get('encuadernacion/datatable/(:num)', 'TarifaMaquinas::get_datatable_tarifa_encuadernacion_maquina/$1');
$routes->get('extra/datatable/(:num)', 'TarifaMaquinas::get_datatable_tarifa_extra_maquina/$1');
});
/* Acabados */
$routes->group('acabados', ['namespace' => 'App\Controllers\Tarifas\Acabados'], function ($routes) {
$routes->get('', 'TarifaAcabados::index', ['as' => 'tarifaAcabadoList']);
$routes->get('gettarifas', 'TarifaAcabados::getSelect2');
$routes->match(['get', 'post'], 'add', 'TarifaAcabados::add', ['as' => 'tarifaAcabadoAdd']);
$routes->match(['get', 'post'], 'edit/(:num)', 'TarifaAcabados::edit/$1', ['as' => 'tarifaAcabadoEdit']);
$routes->get('delete/(:num)', 'TarifaAcabados::delete/$1', ['as' => 'tarifaAcabadoDelete']);
$routes->post('datatable', 'TarifaAcabados::datatable', ['as' => 'tarifaAcabadoDT']);
$routes->get('select', 'TarifaAcabados::show_select', ["as" => "showSelectTarifaAcabado"]);
$routes->group('lineas', ['namespace' => 'App\Controllers\Tarifas\Acabados'], function ($routes) {
$routes->post('datatable', 'TarifaAcabadosLineas::datatable', ['as' => 'tarifaAcabadoLineasDT']);
$routes->post('datatable_editor', 'TarifaAcabadosLineas::datatable_editor', ['as' => 'tarifaAcabadoLineasDTE']);
$routes->get('delete/(:num)', 'TarifaAcabadosLineas::delete/$1', ['as' => 'tarifaAcabadoLineasDelete']);
});
});
});

View File

@ -27,7 +27,6 @@ class Routing extends BaseRouting
*/
public array $routeFiles = [
APPPATH . 'Config/Routes.php',
APPPATH . 'Config/Wiki/WikiRoutes.php',
];
/**
@ -96,7 +95,7 @@ class Routing extends BaseRouting
*
* Default: false
*/
public bool $prioritize = true;
public bool $prioritize = false;
/**
* Map of URI segments and namespaces. For Auto Routing (Improved).

View File

@ -2,16 +2,8 @@
namespace Config;
use App\Services\ChatService;
use App\Services\FTPService;
use App\Services\ImpresoraEtiquetaService;
use App\Services\MaquinaService;
use App\Services\MessageService;
use App\Services\PapelImpresionService;
use CodeIgniter\Config\BaseService;
use App\Services\ProductionService;
use App\Services\TarifaMaquinaService;
use CodeIgniter\Email\Email;
/**
* Services Configuration file.
@ -38,40 +30,4 @@ class Services extends BaseService
* return new \CodeIgniter\Example();
* }
*/
public static function production(){
return new ProductionService();
}
public static function tarifa_maquina(){
return new TarifaMaquinaService();
}
public static function papel_impresion()
{
return new PapelImpresionService();
}
public static function maquina()
{
return new MaquinaService();
}
public static function messages()
{
return new MessageService();
}
public static function chat()
{
return new ChatService();
}
public static function impresora_etiqueta()
{
return new ImpresoraEtiquetaService();
}
public static function emailService($getShared = true)
{
if ($getShared) {
return static::getSharedInstance('emailService');
}
return new \App\Services\EmailService();
}
}

View File

@ -34,7 +34,7 @@ class Validation extends BaseConfig
* @var array<string, string>
*/
public array $templates = [
'list' => 'CodeIgniter\Validation\Views\list',
'list' => 'CodeIgniter\Validation\Views\list',
'single' => 'CodeIgniter\Validation\Views\single',
'bootstrap_style' => 'themes/_commonPartialsBs/_form_validation_errors',
];
@ -42,135 +42,4 @@ class Validation extends BaseConfig
// --------------------------------------------------------------------
// Rules
// --------------------------------------------------------------------
/**
* Maquina duplicate validation
*
* @var array
*/
public array $maquina_duplicate = [
"name" => "required|string"
];
/**
* PapelImpresion duplicate validation
*
* @var array
*/
public array $papel_impresion_duplicate = [
"name" => "required|string"
];
/**========================================================================
* TARIFA MAQUINA ACABADO
*========================================================================**/
public array $tarifa_maquina_acabado =
[
"tarifa_acabado_id" => [
"rules" => "required|integer",
"label" => "tarifa acabado",
],
"maquina_id" => [
"rules" => "required|integer",
"label" => "maquina",
],
"maquina_tarea_id" => [
"rules" => "required|integer",
"label" => "tarea",
],
];
public array $tarifa_maquina_manipulado =
[
"tarifa_manipulado_id" => [
"rules" => "required|integer",
"label" => "tarifa acabado",
],
"maquina_id" => [
"rules" => "required|integer",
"label" => "maquina",
],
"maquina_tarea_id" => [
"rules" => "required|integer",
"label" => "tarea",
],
];
public array $tarifa_maquina_preimpresion =
[
"tarifa_preimpresion_id" => [
"rules" => "required|integer",
"label" => "tarifa acabado",
],
"maquina_id" => [
"rules" => "required|integer",
"label" => "maquina",
],
"maquina_tarea_id" => [
"rules" => "required|integer",
"label" => "tarea",
],
];
public array $tarifa_maquina_encuadernacion =
[
"tarifa_encuadernacion_id" => [
"rules" => "required|integer",
"label" => "tarifa acabado",
],
"maquina_id" => [
"rules" => "required|integer",
"label" => "maquina",
],
"maquina_tarea_id" => [
"rules" => "required|integer",
"label" => "tarea",
],
];
public array $tarifa_maquina_extra =
[
"tarifa_extra_id" => [
"rules" => "required|integer",
"label" => "tarifa acabado",
],
"maquina_id" => [
"rules" => "required|integer",
"label" => "maquina",
],
"maquina_tarea_id" => [
"rules" => "required|integer",
"label" => "tarea",
],
];
public array $orden_trabajo_tarea = [
"orden_trabajo_tarea_id" => [
"rules" => "required|integer",
"label" => "tarea"
],
// "tiempo_real" => [
// "rules" => "required|float",
// "label" => "tiempo real"
// ]
];
public array $orden_trabajo_date = [
"orden_trabajo_id" => [
"rules" => "required|integer",
"label" => "tarea"
],
];
public array $orden_trabajo = [
"orden_trabajo_id" => [
"rules" => "required|integer",
"label" => "Orden trabajo"
],
];
public array $chat_department =
[
"display" => [
"rules" => "required|string",
"label" => "tarifa acabado",
],
"description" => [
"rules" => "permit_empty",
"label" => "maquina",
],
];
}

View File

@ -1,20 +0,0 @@
<?php
use CodeIgniter\Router\RouteCollection;
$routes->group('wiki', ['namespace' => 'App\Controllers\Wiki'], function ($routes) {
$routes->get('','WikiController::index',["as" => "wikiIndex"]);
$routes->get('view/(:segment)','WikiController::show_page/$1',["as" => "showWikiPage"]);
$routes->get('section/(:num)','WikiController::get_section/$1',["as" => "getWikiSection"]);
$routes->post('section','WikiController::store_section',["as" => "storeWikiSection"]);
$routes->delete('section/(:num)','WikiController::delete_section/$1',["as" => "deleteWikiSection"]);
$routes->post('update/section','WikiController::update_section',["as" => "updateWikiSection"]);
$routes->post('save/(:num)','WikiController::store_save_page/$1',["as" => "storeWikiSavePage"]);
$routes->post('publish/(:num)','WikiController::store_publish_page/$1',["as" => "storeWikiPublishPage"]);
$routes->post('file/upload/(:num)','WikiController::wiki_file_upload/$1',["as" => "storeWikiFileUpload"]);
$routes->get('file/(:num)','WikiController::get_wiki_file/$1',["as" => "getWikiFile"]);
$routes->post('section/update/order','WikiController::wiki_section_update_order',["as" => "updateWikiSectionOrder"]);
});

View File

@ -1,119 +0,0 @@
<?php
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']);
$jsonData = json_decode($this->request->getBody(), true);
if (json_last_error() !== JSON_ERROR_NONE) {
return $this->respond(
[
'status' => 400,
'error' => 'Invalid JSON format'
],
400
);
}
// Access the entire POST data
$post_data = $jsonData;
//return $this->respond(var_dump($post_data));
// Instancia de presupuesto cliente
$presupuestocliente = new Presupuestocliente();
$response = $presupuestocliente->calcular($post_data);
if (isset($response['tiradas'])) {
$response = [
'status' => 200,
'error' => null,
'data' => [
'tiradas' => $response['tiradas'],
'precios' => $response['precio_u']
]
];
} else {
$response = [
'status' => 400,
'error' => $response
];
}
return $this->respond($response);
}
public function guardar()
{
helper(['form']);
// Access the entire POST data
$post_data = $this->request->getJSON(true);
//return $this->respond(var_dump($post_data));
// Instancia de presupuesto cliente
$presupuestocliente = new Presupuestocliente();
try {
$response = $presupuestocliente->guardar($post_data);
// 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
]
];
return $this->respond($response);
} catch (\Exception $e) {
return $this->respond([
'status' => 500,
'error' => 'Server error',
'message' => 'Error inesperado durante el procesado'
]);
}
}
}

507
ci4/app/Controllers/Ajax.php Executable file
View File

@ -0,0 +1,507 @@
<?php
namespace App\Controllers;
use App\Models\CronTabModel;
use App\Models\NotificationModel;
use App\Models\Usuarios\UserModel;
use App\Models\Usuarios\GroupModel;
use App\Models\Usuarios\GroupsUsersModel;
use App\Models\ActivityModel;
use CodeIgniter\RESTful\ResourceController;
class Ajax extends ResourceController
{
private $user_model;
private $group_model;
private $group_user_model;
private $activity_model;
private $crontab_model;
private $notification_model;
private $id_user;
private $token_user;
function __construct()
{
$this->user_model = new UserModel();
$this->group_model = new GroupModel();
$this->group_user_model = new GroupsUsersModel();
$this->activity_model = new ActivityModel();
$this->crontab_model = new CronTabModel();
$this->notification_model = new NotificationModel();
$this->id_user = session()->get('id_user');
$this->token_user = session()->get('token');
$language = \Config\Services::language();
$language->setLocale(session()->lang);
}
public function index()
{
return redirect()->to('/home');
}
public function getUsers(){
$postData = service('request')->getVar();
if($postData != null && isset($postData->data)){
$dtpostData = $postData->data;
//Read value
$draw = $dtpostData->draw;
$start = $dtpostData->start;
$rowperpage = $dtpostData->length; // Rows display per page
$columnIndex = $dtpostData->order[0]->column; // Column index
$columnName = $dtpostData->columns[$columnIndex]->data; // Column name
$columnSortOrder = $dtpostData->order[0]->dir; // asc or desc
$searchValue = $dtpostData->search->value; // Search value
//Total number of records without filtering
$totalRecords = $this->user_model->select('id_user')
//->join('auth_groups','auth_groups.token = auth_user.group')
->countAllResults();
//Total number of records with filtering
$totalRecordwithFilter = $this->user_model->select('id_user')
//->join('auth_groups','auth_groups.token = auth_user.group')
->orLike('first_name', $searchValue)
->orLike('email', $searchValue)
->countAllResults();
//Fetch records
//$records = $this->user_model->select('auth_user.*,auth_groups.title')
$records = $this->user_model->select('auth_user.*')
//->join('auth_groups','auth_groups.token = auth_user.group')
->orLike('first_name', $searchValue)
->orLike('email', $searchValue)
->orderBy($columnName,$columnSortOrder)
->findAll($rowperpage, $start);
//Format records
foreach ($records as $key => $value){
if($records[$key]['email_confirmed'] == 1){
$records[$key]['email'] = $records[$key]['email'].' '.'<span class="text-success"><i class="fas fa-check-circle"></i></span>';
}
$editLink = site_url('usuarios/user/edit/').$records[$key]['token'];
$records[$key]['options'] = ''.
'<div class="btn-group mr-1 mb-1" xmlns="http://www.w3.org/1999/html">
<button type="button" class="btn btn-primary btn-block dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
'.lang("App.user_grid_options").'
</button>
<div class="dropdown-menu">
<a class="dropdown-item" href="'.$editLink.'"><i class="fas fa-edit"></i> '.lang("App.user_btn_edit").'</a>
<button type="button" class="dropdown-item" onclick="delete_user(\''.$records[$key]['token'].'\');"><i class="fas fa-trash"></i> '.lang("App.user_btn_delete").'</button>
</div>
</div>
';
}
//Data records
$data = array();
foreach($records as $record ){
$groups_token = $this->group_user_model->select('token_group')
->where('token_user',$record['token'])
->findAll();
$groups_names = [];
foreach($groups_token as $g_t){
$title = $this->group_model->select('title')
->where('token',$g_t)
->first()['title'];
array_push($groups_names, $title);
}
$data[] = array(
"first_name"=>$record['first_name'],
"email"=>$record['email'],
"group"=>$groups_names,//JJO$record['title'],
"mobile"=>$record['mobile'],
"last_access"=>$record['last_access'],
"last_ip"=>$record['last_ip'],
"created_at"=>$record['created_at'],
"options"=>$record['options']
);
}
//Response
$response = array(
"draw" => intval($draw),
"iTotalRecords" => $totalRecords,
"iTotalDisplayRecords" => $totalRecordwithFilter,
"aaData" => $data,
"token" => csrf_hash() // New token hash
);
return $this->response->setJSON($response);
}else{
return $this->response->setJSON(["error"=>true]);
}
}
public function getGroups(){
$postData = service('request')->getVar();
if($postData != null && isset($postData->data)){
$dtpostData = $postData->data;
//Read value
$draw = $dtpostData->draw;
$start = $dtpostData->start;
$rowperpage = $dtpostData->length; // Rows display per page
$columnIndex = $dtpostData->order[0]->column; // Column index
$columnName = $dtpostData->columns[$columnIndex]->data; // Column name
$columnSortOrder = $dtpostData->order[0]->dir; // asc or desc
$searchValue = $dtpostData->search->value; // Search value
//Total number of records without filtering
$totalRecords = $this->group_model->select('id_group')
->countAllResults();
//Total number of records with filtering
$totalRecordwithFilter = $this->group_model->select('id_group')
->orLike('title', $searchValue)
->countAllResults();
//Fetch records
$records = $this->group_model->select('*')
->orLike('title', $searchValue)
->orderBy($columnName,$columnSortOrder)
->findAll($rowperpage, $start);
//Format records
foreach ($records as $key => $value){
$editLink = site_url('usuarios/group/edit/').$records[$key]['token'];
$records[$key]['options'] = ''.
'<div class="btn-group mr-1 mb-1" xmlns="http://www.w3.org/1999/html">
<button type="button" class="btn btn-primary btn-block dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
'.lang("App.group_grid_options").'
</button>
<div class="dropdown-menu">
<a class="dropdown-item" href="'.$editLink.'"><i class="fas fa-edit"></i> '.lang("App.group_btn_edit").'</a>
<button type="button" class="dropdown-item" onclick="delete_group(\''.$records[$key]['token'].'\');"><i class="fas fa-trash"></i> '.lang("App.group_btn_delete").'</button>
</div>
</div>
';
}
//Data records
$data = array();
foreach($records as $record ){
$data[] = array(
"title"=>$record['title'],
"dashboard"=>$record['dashboard'],
"created_at"=>$record['created_at'],
"updated_at"=>$record['updated_at'],
"options"=>$record['options']
);
}
//Response
$response = array(
"draw" => intval($draw),
"iTotalRecords" => $totalRecords,
"iTotalDisplayRecords" => $totalRecordwithFilter,
"aaData" => $data,
"token" => csrf_hash() // New token hash
);
return $this->response->setJSON($response);
}else{
return $this->response->setJSON(["error"=>true]);
}
}
public function getActivities($all=""){
$postData = service('request')->getVar();
if($postData != null && isset($postData->data)){
$dtpostData = $postData->data;
//Read value
$draw = $dtpostData->draw;
$start = $dtpostData->start;
$rowperpage = $dtpostData->length; // Rows display per page
$columnIndex = $dtpostData->order[0]->column; // Column index
$columnName = $dtpostData->columns[$columnIndex]->data; // Column name
$columnSortOrder = $dtpostData->order[0]->dir; // asc or desc
$searchValue = $dtpostData->search->value; // Search value
$session = session();
//Total number of records without filtering
if($session->get('dashboard')=='admin' && !empty($all)){
$totalRecords = $this->activity_model->select('id_activity')
->join('auth_user','auth_user.token = auth_activity.user')
->countAllResults();
}else{
$totalRecords = $this->activity_model->select('id_activity')
->join('auth_user','auth_user.token = auth_activity.user')
->where('auth_activity.user',$session->get('token'))
->countAllResults();
}
//Total number of records with filtering
if($session->get('dashboard')=='admin' && !empty($all)){
$totalRecordwithFilter = $this->activity_model->select('id_activity')
->join('auth_user','auth_user.token = auth_activity.user')
->orLike('first_name', $searchValue)
->countAllResults();
}else{
$totalRecordwithFilter = $this->activity_model->select('id_activity')
->join('auth_user','auth_user.token = auth_activity.user')
->orLike('first_name', $searchValue)
->where('auth_activity.user',$session->get('token'))
->countAllResults();
}
//Fetch records
if($session->get('dashboard')=='admin' && !empty($all)){
$records = $this->activity_model->select('auth_activity.*,concat(first_name, " (",email, ")") AS name')
->join('auth_user','auth_user.token = auth_activity.user')
->orLike('first_name', $searchValue)
->orderBy($columnName,$columnSortOrder)
->findAll($rowperpage, $start);
}else{
$records = $this->activity_model->select('auth_activity.*,concat(first_name, " (",email, ")") AS name')
->join('auth_user','auth_user.token = auth_activity.user')
->orLike('first_name', $searchValue)
->where('auth_activity.user',$session->get('token'))
->orderBy($columnName,$columnSortOrder)
->findAll($rowperpage, $start);
}
//Data records
$data = array();
foreach($records as $record ){
$data[] = array(
"name"=>$record['name'],
"level"=>$record['level'],
"event"=>$record['event'],
"ip"=>$record['ip'],
"os"=>$record['os'],
"browser"=>$record['browser'],
"created_at"=>$record['created_at']
);
}
//Response
$response = array(
"draw" => intval($draw),
"iTotalRecords" => $totalRecords,
"iTotalDisplayRecords" => $totalRecordwithFilter,
"aaData" => $data,
"token" => csrf_hash() // New token hash
);
return $this->response->setJSON($response);
}else{
return $this->response->setJSON(["error"=>true]);
}
}
public function getCronHistory(){
$postData = service('request')->getVar();
if($postData != null && isset($postData->data)){
$dtpostData = $postData->data;
//Read value
$draw = $dtpostData->draw;
$start = $dtpostData->start;
$rowperpage = $dtpostData->length; // Rows display per page
$columnIndex = $dtpostData->order[0]->column; // Column index
$columnName = $dtpostData->columns[$columnIndex]->data; // Column name
$columnSortOrder = $dtpostData->order[0]->dir; // asc or desc
$searchValue = $dtpostData->search->value; // Search value
//Total number of records without filtering
$totalRecords = $this->crontab_model->select('id_crontab')
->countAllResults();
//Total number of records with filtering
$totalRecordwithFilter = $this->crontab_model->select('id_crontab')
->orLike('routine', $searchValue)
->orLike('error', $searchValue)
->countAllResults();
//Fetch records
$records = $this->crontab_model->select('*')
->orLike('routine', $searchValue)
->orLike('error', $searchValue)
->orderBy($columnName,$columnSortOrder)
->findAll($rowperpage, $start);
//Data records
$data = array();
foreach($records as $record ){
$data[] = array(
"routine"=>$record['routine'],
"error"=>$record['error'],
"created_at"=>$record['created_at']
);
}
//Response
$response = array(
"draw" => intval($draw),
"iTotalRecords" => $totalRecords,
"iTotalDisplayRecords" => $totalRecordwithFilter,
"aaData" => $data,
"token" => csrf_hash() // New token hash
);
return $this->response->setJSON($response);
}else{
return $this->response->setJSON(["error"=>true]);
}
}
public function getNotification(){
$postData = service('request')->getVar();
if($postData != null && isset($postData->data)){
$dtpostData = $postData->data;
//Read value
$draw = $dtpostData->draw;
$start = $dtpostData->start;
$rowperpage = $dtpostData->length; // Rows display per page
$columnIndex = $dtpostData->order[0]->column; // Column index
$columnName = $dtpostData->columns[$columnIndex]->data; // Column name
$columnSortOrder = $dtpostData->order[0]->dir; // asc or desc
$searchValue = $dtpostData->search->value; // Search value
//Total number of records without filtering
$totalRecords = $this->notification_model->select('id_notification')
->join('user AS sender','notification.user_sender = sender.token','left')
->join('user AS recipient','notification.user_recipient = recipient.token','left')
->countAllResults();
//Total number of records with filtering
$totalRecordwithFilter = $this->notification_model->select('id_notification')
->join('user AS sender','notification.user_sender = sender.token','left')
->join('user AS recipient','notification.user_recipient = recipient.token','left')
->orLike('title', $searchValue)
->orLike('sender.first_name', $searchValue)
->orLike('recipient.first_name', $searchValue)
->countAllResults();
//Fetch records
$records = $this->notification_model->select('notification.token, sender.first_name AS sender, recipient.first_name AS recipient, notification.title, is_send_email, is_read, notification.created_at')
->join('user AS sender','notification.user_sender = sender.token','left')
->join('user AS recipient','notification.user_recipient = recipient.token','left')
->orLike('title', $searchValue)
->orLike('sender.first_name', $searchValue)
->orLike('recipient.first_name', $searchValue)
->orderBy($columnName,$columnSortOrder)
->findAll($rowperpage, $start);
//Format records
foreach ($records as $key => $value){
$records[$key]['options'] = ''.
'<div class="btn-group mr-1 mb-1" xmlns="http://www.w3.org/1999/html">
<button type="button" class="btn btn-primary btn-block dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
'.lang("App.notification_grid_options").'
</button>
<div class="dropdown-menu">
<button type="button" class="dropdown-item" onclick="delete_this(\''.$records[$key]['token'].'\');"><i class="fas fa-trash"></i> '.lang("App.user_btn_delete").'</button>
</div>
</div>
';
}
//Data records
$data = array();
foreach($records as $record ){
$data[] = array(
"sender"=>$record['sender'],
"recipient"=>$record['recipient'],
"title"=>$record['title'],
"is_send_email"=>$record['is_send_email'],
"is_read"=>$record['is_read'],
"created_at"=>$record['created_at'],
"options"=>$record['options']
);
}
//Response
$response = array(
"draw" => intval($draw),
"iTotalRecords" => $totalRecords,
"iTotalDisplayRecords" => $totalRecordwithFilter,
"aaData" => $data,
"token" => csrf_hash() // New token hash
);
return $this->response->setJSON($response);
}else{
return $this->response->setJSON(["error"=>true]);
}
}
public function getMyNotification(){
$postData = service('request')->getVar();
if($postData != null && isset($postData->data)){
$dtpostData = $postData->data;
//Read value
$draw = $dtpostData->draw;
$start = $dtpostData->start;
$rowperpage = $dtpostData->length; // Rows display per page
$columnIndex = $dtpostData->order[0]->column; // Column index
$columnName = $dtpostData->columns[$columnIndex]->data; // Column name
$columnSortOrder = $dtpostData->order[0]->dir; // asc or desc
$searchValue = $dtpostData->search->value; // Search value
//Total number of records without filtering
$totalRecords = $this->notification_model->select('id_notification')
->join('user AS sender','notification.user_sender = sender.token','left')
->join('user AS recipient','notification.user_recipient = recipient.token','left')
->where('user_recipient',$this->token_user)
->countAllResults();
//Total number of records with filtering
$totalRecordwithFilter = $this->notification_model->select('id_notification')
->join('user AS sender','notification.user_sender = sender.token','left')
->join('user AS recipient','notification.user_recipient = recipient.token','left')
->orLike('title', $searchValue)
->where('user_recipient',$this->token_user)
->countAllResults();
//Fetch records
$records = $this->notification_model->select('notification.token, sender.first_name AS sender, recipient.first_name AS recipient, notification.title, is_read, notification.created_at')
->join('user AS sender','notification.user_sender = sender.token','left')
->join('user AS recipient','notification.user_recipient = recipient.token','left')
->orLike('title', $searchValue)
->where('user_recipient',$this->token_user)
->orderBy($columnName,$columnSortOrder)
->findAll($rowperpage, $start);
//Format records
foreach ($records as $key => $value){
$records[$key]['options'] = '<a class="btn btn-primary" href="/my/notification_view/'.$records[$key]['token'].'"><i class="fas fa-eye"></i> '.lang("App.notification_view_btn").'</a>';
}
//Data records
$data = array();
foreach($records as $record ){
$data[] = array(
"sender"=>$record['sender'],
"recipient"=>$record['recipient'],
"title"=>$record['title'],
"created_at"=>$record['created_at'],
"is_read"=>$record['is_read'],
"options"=>$record['options']
);
}
//Response
$response = array(
"draw" => intval($draw),
"iTotalRecords" => $totalRecords,
"iTotalDisplayRecords" => $totalRecordwithFilter,
"aaData" => $data,
"token" => csrf_hash() // New token hash
);
return $this->response->setJSON($response);
}else{
return $this->response->setJSON(["error"=>true]);
}
}
}

View File

@ -2,6 +2,8 @@
namespace App\Controllers;
use App\Models\NotificationModel;
use App\Models\SettingsModel;
use CodeIgniter\Controller;
use CodeIgniter\HTTP\CLIRequest;
use CodeIgniter\HTTP\IncomingRequest;

View File

@ -10,20 +10,11 @@ use App\Models\Chat\ChatModel;
use App\Models\ChatNotification;
use App\Models\ChatUser;
use App\Models\Clientes\ClienteModel;
use App\Models\Facturas\FacturaModel;
use App\Models\OrdenTrabajo\OrdenTrabajoModel;
use App\Models\Pedidos\PedidoModel;
use App\Models\Presupuestos\PresupuestoModel;
use App\Models\Usuarios\UserModel;
use App\Services\ChatService;
use App\Services\MessageService;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\Log\Logger;
use Psr\Log\LoggerInterface;
use Hermawan\DataTables\DataTable;
use CodeIgniter\I18n\Time;
use CodeIgniter\Validation\Validation;
class ChatController extends BaseController
{
@ -35,10 +26,8 @@ class ChatController extends BaseController
protected ClienteModel $clienteModel;
protected ChatUser $chatUserModel;
protected ChatNotification $chatNotificationModel;
protected Validation $validation;
protected ChatService $chatService;
protected array $viewData;
protected static $viewPath = 'themes/vuexy/form/mensajes/';
public function initController(
@ -57,28 +46,20 @@ class ChatController extends BaseController
$this->clienteModel = model(ClienteModel::class);
$this->chatUserModel = model(ChatUser::class);
$this->chatNotificationModel = model(ChatNotification::class);
$this->validation = service("validation");
$this->chatService = service("chat");
}
public function index() {}
public function get_chat_departments(string $model,int $modelId)
public function get_chat_departments()
{
$data = $this->chatService->getChatDepartments($model,$modelId);
$data = $this->chatDeparmentModel->getChatDepartments();
return $this->response->setJSON($data);
}
public function get_chat_department_select()
{
$query = $this->chatDeparmentModel->getChatDepartmentSelect($this->request->getGet("q"));
return $this->response->setJSON($query->get()->getResultObject());
}
public function get_chat_presupuesto(int $chat_department_id, int $presupuesto_id)
{
$data = [
"department" => $this->chatDeparmentModel->find($chat_department_id),
"chat" => null,
"messages" => null,
"count" => 0,
@ -87,8 +68,6 @@ class ChatController extends BaseController
if ($chat) {
$data["messages"] = $this->chatMessageModel->get_chat_messages($chat->id);
$this->chatMessageModel->set_chat_department_messages_as_read($chat->id);
$this->chatModel->setAsViewedChatUserNotifications($chat->id, auth()->user()->id);
$data["count"] = count($data["messages"]);
}
$data["chat"] = $chat;
@ -98,7 +77,6 @@ class ChatController extends BaseController
{
$data = [
"department" => $this->chatDeparmentModel->find($chat_department_id),
"chat" => null,
"messages" => null,
"count" => 0,
@ -107,9 +85,8 @@ class ChatController extends BaseController
if ($chat) {
$data["messages"] = $this->chatMessageModel->get_chat_messages($chat->id);
$this->chatMessageModel->set_chat_department_messages_as_read($chat->id);
$this->chatModel->setAsViewedChatUserNotifications($chat->id, auth()->user()->id);
$data["count"] = count($data["messages"]);
}
$data["chat"] = $chat;
return $this->response->setJSON($data);
@ -118,7 +95,6 @@ class ChatController extends BaseController
{
$data = [
"department" => $this->chatDeparmentModel->find($chat_department_id),
"chat" => null,
"messages" => null,
"count" => 0,
@ -127,115 +103,63 @@ class ChatController extends BaseController
if ($chat) {
$data["messages"] = $this->chatMessageModel->get_chat_messages($chat->id);
$this->chatMessageModel->set_chat_department_messages_as_read($chat->id);
$this->chatModel->setAsViewedChatUserNotifications($chat->id, auth()->user()->id);
$data["count"] = count($data["messages"]);
}
$data["chat"] = $chat;
return $this->response->setJSON($data);
}
public function get_chat_orden_trabajo(int $chat_department_id, int $orden_trabajo_id)
{
$data = [
"department" => $this->chatDeparmentModel->find($chat_department_id),
"chat" => null,
"messages" => null,
"count" => 0,
];
$chat = $this->chatModel->getChatOrdenTrabajo($chat_department_id, $orden_trabajo_id);
if ($chat) {
$data["messages"] = $this->chatMessageModel->get_chat_messages($chat->id);
$this->chatMessageModel->set_chat_department_messages_as_read($chat->id);
$this->chatModel->setAsViewedChatUserNotifications($chat->id, auth()->user()->id);
$data["count"] = count($data["messages"]);
}
$data["chat"] = $chat;
return $this->response->setJSON($data);
}
public function get_chat_direct_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["chatId"] = $chat_id;
$auth_user = auth()->user();
$this->chatModel->setAsViewedChatUserNotifications($chat_id, $auth_user->id);
$this->chatModel->setAsUnviewedChatUserMessages($chat_id, $auth_user->id);
return view(static::$viewPath . 'messageChat', $this->viewData);
}
public function get_chat_presupuesto_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->presupuesto_id;
$this->viewData["type"] = "presupuesto";
$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 . 'messageChatPresupuesto', $this->viewData);
} else {
return view(static::$viewPath . 'messageChatInternal', $this->viewData);
}
}
public function get_chat_pedido_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->pedido_id;
$this->viewData["type"] = "pedido";
$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 . 'messageChatPedido', $this->viewData);
} else {
return view(static::$viewPath . 'messageChatInternal', $this->viewData);
}
}
public function get_chat_factura_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->factura_id;
$this->viewData["type"] = "factura";
$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)
{
$data = $this->chatModel->getChat($chat_id);
return $this->response->setJSON($data);
}
public function store_message($model)
public function store_chat_message_presupuesto()
{
$data = $this->request->getPost();
$chatMessageEntity = $this->chatService->storeChatMessage($data["chat_department_id"],$model,$data["model_id"],$data);
return $this->response->setJSON($chatMessageEntity);
// $data = $this->chatModel->createChatPresupuesto();
$existChat = $this->chatModel->existChatPresupuesto($data["chat_department_id"], $data["model_id"]);
if ($existChat == false) {
$chatId = $this->chatModel->createChatPresupuesto($data["chat_department_id"], $data["model_id"]);
} else {
$chat = $this->chatModel->getChatPresupuesto($data["chat_department_id"], $data["model_id"]);
$chatId = $chat->id;
}
$chat_message_id = $this->chatMessageModel->insert(["chat_id" => $chatId, "sender_id" => auth()->user()->id, "message" => $data["message"]]);
$dataResponse = $this->chatMessageModel->find($chat_message_id);
return $this->response->setJSON($dataResponse);
}
public function store_chat_message_pedido()
{
$data = $this->request->getPost();
$existChat = $this->chatModel->existChatPedido($data["chat_department_id"], $data["model_id"]);
if ($existChat == false) {
$chatId = $this->chatModel->createChatPedido($data["chat_department_id"], $data["model_id"]);
} else {
$chat = $this->chatModel->getChatPedido($data["chat_department_id"], $data["model_id"]);
$chatId = $chat->id;
}
$chat_message_id = $this->chatMessageModel->insert(["chat_id" => $chatId, "sender_id" => auth()->user()->id, "message" => $data["message"]]);
$dataResponse = $this->chatMessageModel->find($chat_message_id);
return $this->response->setJSON($dataResponse);
}
public function store_chat_message_factura()
{
$data = $this->request->getPost();
$existChat = $this->chatModel->existChatFactura($data["chat_department_id"], $data["model_id"]);
if ($existChat == false) {
$chatId = $this->chatModel->createChatFactura($data["chat_department_id"], $data["model_id"]);
} else {
$chat = $this->chatModel->getChatFactura($data["chat_department_id"], $data["model_id"]);
$chatId = $chat->id;
}
$chat_message_id = $this->chatMessageModel->insert(["chat_id" => $chatId, "sender_id" => auth()->user()->id, "message" => $data["message"]]);
$dataResponse = $this->chatMessageModel->find($chat_message_id);
return $this->response->setJSON($dataResponse);
}
public function store_chat_message_single()
{
$data = $this->request->getPost();
@ -251,73 +175,83 @@ class ChatController extends BaseController
"chat_id" => $chatId,
"sender_id" => auth()->user()->id,
"message" => $data["message"],
"receiver_id" => $data["receiver_id"],
"receiver_id" => $data["receiver_id"]
]
);
$this->chatNotificationModel->insert(["chat_message_id" => $chat_message_id, "user_id" => $data["receiver_id"]]);
$dataResponse = $this->chatMessageModel->find($chat_message_id);
return $this->response->setJSON($dataResponse);
}
public function get_chat_internal_contacts()
{
$auth_user = auth()->user();
if ($auth_user->cliente_id) {
$users = $this->chatModel->getOpenChatCliente($auth_user->id);
} else {
$users = $this->userModel->builder()
->whereNotIn("id", [$auth_user->id])
->where("deleted_at", null)
->get()->getResultObject();
if (auth()->user()->cliente_id) {
return $this->response->setJSON([]);
}
$users = $this->userModel->builder()
->where("cliente_id", null)
->whereNotIn("id", [auth()->user()->id])
->where("deleted_at", null)
->get()->getResultObject();
foreach ($users as $user) {
$user->unreadMessages = $this->chatMessageModel->get_chat_messages_count($user->id);
$user->unreadMessages = $this->chatMessageModel->get_chat_unread_messages_count($user->id);
}
usort($users, fn($a, $b) => $a->unreadMessages < $b->unreadMessages);
return $this->response->setJSON($users);
}
public function get_chat_internal_contact(int $user_id)
{
$auth_user = auth()->user();
// if ($auth_user->cliente_id) {
// return $this->response->setJSON([]);
// }
if (auth()->user()->cliente_id) {
return $this->response->setJSON([]);
}
$users = $this->userModel->builder()
->where("cliente_id", null)
->where("deleted_at", null)
->where("id", $user_id)
->get()->getFirstRow();
$this->chatMessageModel->set_chat_messages_as_read($user_id);
return $this->response->setJSON($users);
}
public function get_chat_internal_messages(int $user_id)
{
$conversation = $this->chatMessageModel->get_chat_contact_messages($user_id);
return $this->response->setJSON($conversation);
}
public function get_chat_cliente()
{
$cliente_id = auth()->user()->cliente_id;
$response = $this->chatService->getAuthUserNotifications();
$response = [];
if ($cliente_id) {
$data = $this->clienteModel->getClienteDataPresupuestoPedidoFactura($cliente_id);
$response["totalMessages"] = 0;
$response["chatFacturas"] = $this->chatModel->getClienteChatFacturas($data["facturas"]);
foreach ($response["chatFacturas"] as $key => $value) {
$response["totalMessages"] += $value->unreadMessages;
}
$response["chatPresupuestos"] = $this->chatModel->getClienteChatPresupuestos($data["presupuestos"]);
foreach ($response["chatPresupuestos"] as $key => $value) {
$response["totalMessages"] += $value->unreadMessages;
}
$response["chatPedidos"] = $this->chatModel->getClienteChatPedidos($data["pedidos"]);
foreach ($response["chatPedidos"] as $key => $value) {
$response["totalMessages"] += $value->unreadMessages;
}
$response["data"] = $data;
} else {
$response["internals"] = $this->chatModel->getChatDepartmentNotifications();
$internal_notifications = $this->chatModel->getChatInternalNotifications();
foreach ($internal_notifications as $value) {
$response["internals"][] = $value;
}
$response["totalMessages"] = 0;
foreach ($response["internals"] as $key => $value) {
$response["totalMessages"] += $value->unreadMessages;
}
}
return $this->response->setJSON($response);
}
public function get_chat_department_presupuesto_users(int $chat_department_id, int $presupuesto_id)
public function get_chat_department_users(int $chat_department_id)
{
$data = $this->chatDeparmentModel->find($chat_department_id)->withUsers($presupuesto_id, 'presupuesto');
return $this->response->setJSON($data);
}
public function get_chat_department_pedido_users(int $chat_department_id, $pedido_id)
{
$data = $this->chatDeparmentModel->find($chat_department_id)->withUsers($pedido_id, 'pedido');
return $this->response->setJSON($data);
}
public function get_chat_department_factura_users(int $chat_department_id, $factura_id)
{
$data = $this->chatDeparmentModel->find($chat_department_id)->withUsers($factura_id, 'factura');
return $this->response->setJSON($data);
}
public function get_chat_department_orden_trabajo_users(int $chat_department_id, $orden_trabajo_id)
{
$data = $this->chatDeparmentModel->find($chat_department_id)->withUsers($orden_trabajo_id, 'ot');
$data = $this->chatDeparmentModel->getChatDepartmentUsers($chat_department_id);
return $this->response->setJSON($data);
}
public function get_chat_users_internal()
@ -329,7 +263,7 @@ class ChatController extends BaseController
]
)->where("cliente_id", null)
->where("deleted_at", null)
->whereNotIn("id", [auth()->user()->id]);
->whereNotIn("id",[auth()->user()->id]);
if ($this->request->getGet("q")) {
$query->groupStart()
->orLike("users.username", $this->request->getGet("q"))
@ -339,428 +273,148 @@ class ChatController extends BaseController
return $this->response->setJSON($query->get()->getResultObject());
}
public function get_chat_users_all()
{
$query = $this->userModel->builder()->select(
[
"id",
"CONCAT(first_name,' ',last_name,'(',username,')') 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();
}
return $this->response->setJSON($query->get()->getResultObject());
}
public function get_presupuesto_client_users(int $presupuesto_id)
{
$pm = model(PresupuestoModel::class);
$p = $pm->find($presupuesto_id);
$cm = model(ClienteModel::class);
$clienteContactos = $cm->querySelectClienteContacto($p->cliente_id,$this->request->getGet('q'));
return $this->response->setJSON($clienteContactos);
}
public function get_pedido_client_users(int $pedido_id)
{
$pm = model(PedidoModel::class);
$p = $pm->find($pedido_id);
$cm = model(ClienteModel::class);
$clienteContactos = $cm->querySelectClienteContacto($p->cliente()->id,$this->request->getGet('q'));
return $this->response->setJSON($clienteContactos);
}
public function get_factura_client_users(int $factura_id)
{
$fm = model(FacturaModel::class);
$f = $fm->find($factura_id);
$cm = model(ClienteModel::class);
$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)
{
$otm = model(OrdenTrabajoModel::class);
$ot = $otm->find($orden_trabajo_id);
$cm = model(ClienteModel::class);
$cliente = $ot->pedido()->cliente();
$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);
return $this->response->setJSON(["message" => "Hebra creada correctamente", "status" => $status]);
}
public function update_hebra($chat_id)
public function store_hebra_presupuesto()
{
$bodyData = $this->request->getPost();
$chatMessageId = $this->chatMessageModel->insert([
$chat_id = $this->chatModel->insert([
"presupuesto_id" => $bodyData["modelId"],
"title" => $bodyData["title"]
]);
$chatMessageId = $this->chatMessageModel->insert([
"chat_id" => $chat_id,
"message" => $bodyData["message"],
"sender_id" => auth()->user()->id
]);
$actualUsers = $this->chatUserModel->builder()->select("user_id")->where("chat_id", $chat_id)->get()->getResultArray();
$actualUsersArray = array_map(fn($x) => $x["user_id"], $actualUsers);
if (isset($bodyData["users"])) {
if(isset($bodyData["users"])){
$chatUserData = array_map(fn($x) => ["user_id" => $x,"chat_id" => $chat_id],$bodyData["users"]);
$this->chatUserModel->insertBatch($chatUserData);
foreach ($bodyData["users"] as $userId) {
if (in_array($userId, $actualUsersArray) == false) {
$chatUserData = ["user_id" => $userId, "chat_id" => $chat_id];
$this->chatNotificationModel->insert(
["chat_message_id" => $chatMessageId,"user_id" => $userId]);
}
}
return $this->response->setJSON(["message" => "Hebra creada correctamente","status" => true]);
}
public function store_hebra_pedido()
{
$bodyData = $this->request->getPost();
$chat_id = $this->chatModel->insert([
"pedido_id" => $bodyData["modelId"],
"title" => $bodyData["title"]
]);
$chatMessageId = $this->chatMessageModel->insert([
"chat_id" => $chat_id,
"message" => $bodyData["message"],
"sender_id" => auth()->user()->id
]);
if(isset($bodyData["users"])){
$chatUserData = array_map(fn($x) => ["user_id" => $x,"chat_id" => $chat_id],$bodyData["users"]);
$this->chatUserModel->insertBatch($chatUserData);
foreach ($bodyData["users"] as $userId) {
$this->chatNotificationModel->insert(
["chat_message_id" => $chatMessageId,"user_id" => $userId]);
}
}
return $this->response->setJSON(["message" => "Hebra creada correctamente","status" => true]);
}
public function store_hebra_factura()
{
$bodyData = $this->request->getPost();
$chat_id = $this->chatModel->insert([
"factura_id" => $bodyData["modelId"],
"title" => $bodyData["title"]
]);
$chatMessageId = $this->chatMessageModel->insert([
"chat_id" => $chat_id,
"message" => $bodyData["message"],
"sender_id" => auth()->user()->id
]);
if(isset($bodyData["users"])){
$chatUserData = array_map(fn($x) => ["user_id" => $x,"chat_id" => $chat_id],$bodyData["users"]);
$this->chatUserModel->insertBatch($chatUserData);
foreach ($bodyData["users"] as $userId) {
$this->chatNotificationModel->insert(
["chat_message_id" => $chatMessageId,"user_id" => $userId]);
}
}
return $this->response->setJSON(["message" => "Hebra creada correctamente","status" => true]);
}
public function update_hebra($chat_id)
{
$bodyData = $this->request->getPost();
$chatMessageId = $this->chatMessageModel->insert([
"chat_id" => $chat_id,
"message" => $bodyData["message"],
"sender_id" => auth()->user()->id
]);
$actualUsers = $this->chatUserModel->builder()->select("user_id")->where("chat_id",$chat_id)->get()->getResultArray();
$actualUsersArray = array_map(fn($x) => $x["user_id"],$actualUsers);
foreach ($actualUsersArray as $key => $user_id) {
$this->chatNotificationModel->insert(
["chat_message_id" => $chatMessageId,"user_id" => $user_id]);
}
if(isset($bodyData["users"])){
foreach ($bodyData["users"] as $userId) {
if(in_array($userId,$actualUsersArray) == false){
$chatUserData = ["user_id" => $userId,"chat_id" => $chat_id];
$this->chatUserModel->insert($chatUserData);
}
$this->chatNotificationModel->insert(
["chat_message_id" => $chatMessageId, "user_id" => $userId]
);
["chat_message_id" => $chatMessageId,"user_id" => $userId]);
}
}
return $this->response->setJSON(["message" => "Hebra actualizada correctamente", "status" => true]);
return $this->response->setJSON(["message" => "Hebra actualizada correctamente","status" => true]);
}
public function get_hebra(string $model,int $modelId)
{
$data = $this->chatService->getHebras($model,$modelId);
public function get_hebra_presupuesto($presupuesto_id){
$data = $this->chatModel->getPresupuestoHebras($presupuesto_id);
$notifications = $this->chatModel->builder()->select([
"chat_notifications.id"
])
->join("chat_messages","chat_messages.chat_id = chats.id","left")
->join("chat_notifications","chat_notifications.chat_message_id = chat_messages.id","left")
->where("chats.presupuesto_id",$presupuesto_id)
->where("chat_notifications.user_id",auth()->user()->id)
->get()->getResultArray();
foreach ($notifications as $notification) {
$this->chatNotificationModel->update($notification["id"],["viewed" => true]);
}
return $this->response->setJSON($data);
}
public function get_hebra_pedido($pedido_id){
$data = $this->chatModel->getPedidoHebras($pedido_id);
$notifications = $this->chatModel->builder()->select([
"chat_notifications.id"
])
->join("chat_messages","chat_messages.chat_id = chats.id","left")
->join("chat_notifications","chat_notifications.chat_message_id = chat_messages.id","left")
->where("chats.pedido_id",$pedido_id)
->where("chat_notifications.user_id",auth()->user()->id)
->get()->getResultArray();
foreach ($notifications as $notification) {
$this->chatNotificationModel->update($notification["id"],["viewed" => true]);
}
return $this->response->setJSON($data);
}
public function get_hebra_factura($factura_id){
$data = $this->chatModel->getFacturaHebras($factura_id);
$notifications = $this->chatModel->builder()->select([
"chat_notifications.id"
])
->join("chat_messages","chat_messages.chat_id = chats.id","left")
->join("chat_notifications","chat_notifications.chat_message_id = chat_messages.id","left")
->where("chats.factura_id",$factura_id)
->where("chat_notifications.user_id",auth()->user()->id)
->get()->getResultArray();
foreach ($notifications as $notification) {
$this->chatNotificationModel->update($notification["id"],["viewed" => true]);
}
return $this->response->setJSON($data);
}
public function datatable_messages()
{
$auth_user_id = auth()->user()->id;
$isAdmin = auth()->user()->inGroup('admin');
$query = $this->chatModel->getQueryDatatable();
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))
->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);
}
public function datatable_presupuesto_messages()
{
$auth_user_id = auth()->user()->id;
$isAdmin = auth()->user()->inGroup('admin');
$query = $this->chatModel->getQueryDatatableMessagePresupuesto($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") : "")
->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()
{
$auth_user_id = auth()->user()->id;
$isAdmin = auth()->user()->inGroup('admin');
$query = $this->chatModel->getQueryDatatableMessagePedido($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" => "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);
}
public function datatable_factura_messages()
{
$auth_user_id = auth()->user()->id;
$isAdmin = auth()->user()->inGroup('admin');
$query = $this->chatModel->getQueryDatatableMessageFactura($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" => "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 get_notifications_not_viewed_from_message(int $chat_message_id)
{
$unviewedNotifications = $this->chatModel->getUsersNotificationNotViewedFromChat($chat_message_id);
// $viewedNotifications = $this->chatModel->getUsersNotificationViewedFromChat($chat_message_id);
return $this->response->setJSON(
[
"data" => [
"notifications" => $unviewedNotifications,
],
"chat_message_id" => $chat_message_id
]
);
}
public function store_new_direct_message()
{
$bodyData = $this->request->getPost();
$rules = [
"title" => "required|string",
"message" => "required|string",
"users" => "required",
];
if (!$this->validate($rules)) {
return $this->response->setStatusCode(400)->setJSON([
'message' => lang('App.global_alert_save_error'),
'status' => 'error',
'errors' => $this->validator->getErrors(),
]);
}
$this->chatModel->createNewDirectChat(...$bodyData);
return $this->response->setJSON(["message" => lang("Chat.new_message_ok"), "status" => true]);
}
public function store_new_direct_message_client()
{
$bodyData = $this->request->getPost();
$rules = [
"title" => "required|string",
"message" => "required|string",
"chat_department_id" => "required",
];
if (!$this->validate($rules)) {
return $this->response->setStatusCode(400)->setJSON([
'message' => lang('App.global_alert_save_error'),
'status' => 'error',
'errors' => $this->validator->getErrors(),
]);
}
$users = $this->chatDeparmentModel->getChatDepartmentUsers($bodyData["chat_department_id"]);
$bodyData["users"] = array_map(fn($q) => $q->id, $users);
dd(1);
$this->chatModel->createNewDirectChat(...$bodyData);
return $this->response->setJSON(["message" => lang("Chat.new_message_ok"), "status" => true]);
}
public function get_chat_direct($chat_id)
{
$chatData = $this->chatModel->getChatDirect($chat_id);
return $this->response->setJSON($chatData);
}
public function get_chat_direct_select_users($chat_id)
{
$chat_users_id = $this->chatUserModel->getChatUserArrayId($chat_id);
$query = $this->userModel->builder()->select(
[
"id",
"CONCAT(first_name,' ',last_name,'(',username,')') 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();
}
return $this->response->setJSON($query->get()->getResultObject());
}
public function store_chat_direct_users($chat_id)
{
$bodyData = $this->request->getPost();
$chat_users = [];
foreach ($bodyData["users"] as $user_id) {
$chat_users[] = ["chat_id" => $chat_id, "user_id" => $user_id];
if ($bodyData["notification"]) {
$this->chatModel->createNotificationsToNewChatUser($chat_id, $user_id);
}
}
$this->chatUserModel->insertBatch($chat_users);
return $this->response->setJSON(["message" => "ok", "status" => true]);
}
public function store_chat_direct_message(int $chat_id)
{
$bodyData = $this->request->getPost();
$auth_user = auth()->user();
$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);
}
public function update_chat_direct_message_unread($chat_id)
{
$this->chatModel->setAsUnviewedChatUserNotifications($chat_id, auth()->user()->id);
return $this->response->setJSON(["message" => "ok", "status" => true]);
}
public function store_chat_error_message()
{
$bodyData = $this->request->getPost();
$messageService = service('messages');
$r = $messageService->createErrorMessagePresupuesto("Error", $bodyData['presupuesto_id']);
return $this->response->setJSON(["message" => "ok", "data" => $r]);
}
public function delete_user_from_department($chat_department_id)
{
$data = $this->request->getRawInput();
$user_id = auth()->user()->id;
$adminExist = $this->chatDeparmentUserModel->where('chat_department_id', $chat_department_id)
->where('user_id', $user_id)
->where('pedido_id', null)
->where('factura_id', null)
->where('presupuesto_id', null)->countAllResults();
if ($adminExist) {
return $this->response->setJSON(["message" => lang('Chat.exit_admin_chat_wrong'), "status" => false]);
}
$chatDepartmentUserEntity = $this->chatDeparmentUserModel->where('chat_department_id', $chat_department_id)->where('user_id', $user_id)->where($data['model_fk'], $data['model_id_fk']);
if ($chatDepartmentUserEntity->countAllResults() > 0) {
$deleted = $this->chatDeparmentUserModel->where('chat_department_id', $chat_department_id)->where('user_id', $user_id)->delete(purge: true);
return $this->response->setJSON(["message" => lang('Chat.exit_chat_ok'), "status" => true]);
} else {
return $this->response->setJSON(["message" => lang('Chat.exit_chat_wrong'), "status" => false]);
}
}
public function delete_user_admin_from_department($chat_department_id, $user_id)
{
$this->chatDeparmentUserModel->where('chat_department_id', $chat_department_id)->where('user_id', $user_id)->delete();
return $this->response->setJSON(["message" => lang('Chat.user_deleted_ok'), "status" => true]);
}
public function subscribe_to_chat_deparment()
{
$data = $this->request->getPost();
$user_id = auth()->user()->id;
$adminExist = $this->chatDeparmentUserModel->where('chat_department_id', $data['chat_department_id'])
->where('user_id', $user_id)
->where('pedido_id', null)
->where('factura_id', null)
->where('presupuesto_id', null)->countAllResults();
if ($adminExist) {
return $this->response->setJSON(["message" => lang('Chat.subscribe_chat_wrong'), "status" => false]);
}
$chatDepartmentUserEntity = $this->chatDeparmentUserModel->where('chat_department_id', $data['chat_department_id'])->where('user_id', $user_id)->where($data['model_fk'], $data['model_id_fk']);
if ($chatDepartmentUserEntity->countAllResults() > 0) {
return $this->response->setJSON(["message" => lang('Chat.subscribe_chat_wrong'), "status" => false]);
} else {
$this->chatDeparmentUserModel->insert(["chat_department_id" => $data["chat_department_id"], "user_id" => $user_id, $data['model_fk'] => $data['model_id_fk']]);
return $this->response->setJSON(["message" => lang('Chat.subscribe_chat_ok'), "status" => true]);
}
}
public function subscribe_admin_to_department()
{
$data = $this->request->getPost();
if ($data['user_id']) {
$this->chatDeparmentUserModel
->insert(
[
"chat_department_id" => $data["chat_department_id"],
"user_id" => $data["user_id"],
]
);
return $this->response->setJSON(["message" => lang('Chat.subscribe_admin_chat_ok'), "status" => true]);
} else {
return $this->response->setStatusCode(422)->setJSON(["message" => lang('Chat.subscribe_admin_chat_wrong'), "status" => false]);
}
}
public function config_view()
{
$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' => true]
];
return view('themes/vuexy/form/configuracion/messages/configView', $this->viewData);
}
public function chat_department_edit($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],
['title' => $chatDepartment->display, 'route' => route_to("chatDepartmentEditView", $chat_department_id), 'active' => true]
];
$this->viewData["chat_department"] = $chatDepartment;
return view('themes/vuexy/form/configuracion/messages/editChatDepartmentForm', $this->viewData);
}
public function chat_department_datatable()
{
$q = $this->chatDeparmentModel->datatableQuery();
return DataTable::of($q)
->add('action', fn($r) => $r->id)
->toJson(true);
}
public function chat_department_user_datatable(int $chat_department_id)
{
$q = $this->chatDeparmentUserModel->datatableQuery($chat_department_id);
$datatable = DataTable::of($q);
if (auth()->user()->inGroup('admin')) {
$datatable->add('action', fn($r) => $r->userId);
}
return $datatable->toJson(true);
}
public function select_users_not_in_chat_department(int $chat_department_id)
{
$paramQuery = $this->request->getGet("q");
$data = $this->chatDeparmentUserModel->querySelectUsersNotInDepartment($chat_department_id, $paramQuery);
return $this->response->setJSON($data);
}
public function store_chat_department()
{
$data = $this->request->getPost();
$validated = $this->validation->run($data, 'chat_department');
if ($validated) {
$dataValidated = $this->validation->getValidated();
$dataValidated['name'] = newUUID();
$this->chatDeparmentModel->insert($dataValidated);
return $this->response->setJSON(["message" => lang('App.global_alert_save_success'), "status" => true, "data" => $dataValidated]);
} else {
return $this->response->setStatusCode(422)->setJSON(["message" => lang('App.global_alert_save_success'), "status" => false, "errors" => $this->validation->getErrors()]);
}
return $this->response->setJSON(["message" => lang('App.global_alert_save_success'), "status" => true]);
}
public function update_chat_department(int $chat_department_id)
{
$data = $this->request->getPost();
$validated = $this->validation->run($data, 'chat_department');
if ($validated) {
$dataValidated = $this->validation->getValidated();
$this->chatDeparmentModel->update($chat_department_id, $dataValidated);
return $this->response->setJSON(["message" => lang('App.global_alert_save_success'), "status" => true, "data" => $dataValidated]);
} else {
return $this->response->setStatusCode(422)->setJSON(["message" => lang('App.global_alert_save_success'), "status" => false, "errors" => $this->validation->getErrors()]);
}
}
public function delete_chat_department($chat_department_id)
{
if (auth()->user()->inGroup('admin')) {
$this->chatDeparmentModel->delete($chat_department_id);
return $this->response->setJSON(["message" => lang('App.user_alert_delete'), "status" => true]);
} else {
return $this->response->setStatusCode(403)->setJSON(["message" => lang('App.user_alert_forbidden'), "status" => false]);
}
}
}

View File

@ -250,20 +250,11 @@ class Cliente extends \App\Controllers\BaseResourceController
$start = $reqData['start'] ?? 0;
$length = $reqData['length'] ?? 5;
$search = $reqData['search']['value'];
$searchValues = get_filter_datatables_columns($reqData);
$requestedOrder = $reqData['order'] ?? [];
$requestedOrder = $reqData['order']['0']['column'] ?? 1;
$order = ClienteModel::SORTABLE[$requestedOrder > 0 ? $requestedOrder : 1];
$dir = $reqData['order']['0']['dir'] ?? 'asc';
$resourceData = $this->model->getResource($searchValues);
foreach ($requestedOrder as $order) {
$column = $order['column'] ?? 0;
$dir = $order['dir'] ?? 'asc';
$orderColumn = ClienteModel::SORTABLE[$column] ?? null;
if ($orderColumn) {
$resourceData->orderBy($orderColumn, $dir);
}
}
$resourceData = $resourceData->limit($length, $start)->get()->getResultObject();
$resourceData = $this->model->getResource($search)->orderBy($order, $dir)->limit($length, $start)->get()->getResultObject();
foreach ($resourceData as $item) :
if (isset($item->direccion) && strlen($item->direccion) > 100) :
$item->direccion = character_limiter($item->direccion, 100);
@ -282,7 +273,7 @@ class Cliente extends \App\Controllers\BaseResourceController
return $this->respond(Collection::datatable(
$resourceData,
$this->model->getResource()->countAllResults(),
$this->model->getResource($searchValues)->countAllResults()
$this->model->getResource($search)->countAllResults()
));
} else {
return $this->failUnauthorized('Invalid request', 403);
@ -384,7 +375,7 @@ class Cliente extends \App\Controllers\BaseResourceController
{
$data = ['' => lang('Basic.global.pleaseSelectA', [mb_strtolower(lang('Users.user'))])];
if (!is_null($selId)) :
$userModel = model('App\Models\Usuarios\UserModel');
$userModel = model('App\Models\UserModel');
$selOption = $userModel->where('id', $selId)->findColumn('first_name');
if (!empty($selOption)) :
@ -414,7 +405,7 @@ class Cliente extends \App\Controllers\BaseResourceController
{
$data = ['' => lang('Basic.global.pleaseSelectA', [mb_strtolower(lang('Users.user'))])];
if (!is_null($selId)) :
$userModel = model('App\Models\Usuarios\UserModel');
$userModel = model('App\Models\UserModel');
$selOption = $userModel->where('id', $selId)->findColumn('last_name');
if (!empty($selOption)) :
@ -464,7 +455,7 @@ class Cliente extends \App\Controllers\BaseResourceController
return null;
}
$modelPlantillaPreciosCliente = model('App\Models\Clientes\ClientePlantillaPreciosModel');
$plantilla = $modelPlantillaPreciosCliente->where("id", $plantilla_id)->where("deleted_at", null)->first();
$plantilla = $modelPlantillaPreciosCliente->where("id", $plantilla_id)->where("is_deleted", 0)->first();
if ($plantilla == false) {
return null;
} else {

View File

@ -1,5 +1,4 @@
<?php
namespace App\Controllers\Clientes;
<?php namespace App\Controllers\Clientes;
use App\Controllers\BaseResourceController;
@ -46,36 +45,40 @@ class ClientePrecios extends \App\Controllers\BaseResourceController
parent::initController($request, $response, $logger);
}
public function updatePlantilla()
public function update($requestedId = null)
{
if ($this->request->isAJAX()) {
if ($this->request->getPost()) :
if ($requestedId == null) :
return;
endif;
$postData = $this->request->getPost();
$cliente_id = $postData['cliente_id'] ?? -1;
$plantilla_id = $postData['plantilla_id'] ?? -1;
$postData = $this->request->getJSON();
$plantilla_id = $postData->plantilla_id ?? -1;
// Se ha actualizado un registro por lo que no es una plantilla
if ($plantilla_id == -1) {
$this->model->clean_plantilla_id($cliente_id);
} else if ($cliente_id == -1) { // actualizar todos los clientes que usan una plantilla
$this->model->update_from_plantilla($plantilla_id);
} else {
$this->model->copy_from_plantilla($cliente_id, $plantilla_id);
if($plantilla_id == -1){
$this->model->clean_plantilla_id($requestedId);
}
else if($requestedId== -1){ // actualizar todos los clientes que usan una plantilla
$this->model->update_from_plantilla($plantilla_id);
}
else{
$this->model->copy_from_plantilla($requestedId, $plantilla_id);
}
$newTokenHash = csrf_hash();
$csrfTokenName = csrf_token();
$data = [
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
} else {
return $this->failUnauthorized('Invalid request', 403);
}
endif; // ($requestMethod === 'post')
}
@ -90,113 +93,92 @@ class ClientePrecios extends \App\Controllers\BaseResourceController
}
$start = $reqData['start'] ?? 0;
$length = $reqData['length'] ?? 5;
$requestedOrder = $reqData['order'] ?? [];
$searchValues = get_filter_datatables_columns($reqData);
$requestedOrder = $reqData['order']['0']['column'] ?? 0;
$requestedOrder2 = $reqData['order']['1']['column'] ?? $requestedOrder;
$requestedOrder3 = $reqData['order']['2']['column'] ?? $requestedOrder;
$requestedOrder4 = $reqData['order']['3']['column'] ?? $requestedOrder;
$requestedOrder5 = $reqData['order']['4']['column'] ?? $requestedOrder;
$order = ClientePreciosModel::SORTABLE[$requestedOrder > 0 ? $requestedOrder : 0];
$order2 = ClientePreciosModel::SORTABLE[$requestedOrder2 >= 0 ? $requestedOrder2 : $requestedOrder];
$order3 = ClientePreciosModel::SORTABLE[$requestedOrder3 >= 0 ? $requestedOrder3 : $requestedOrder];
$order4 = ClientePreciosModel::SORTABLE[$requestedOrder4 >= 0 ? $requestedOrder4 : $requestedOrder];
$order5 = ClientePreciosModel::SORTABLE[$requestedOrder4 >= 0 ? $requestedOrder5 : $requestedOrder];
$dir = $reqData['order']['0']['dir'] ?? 'asc';
$dir2 = $reqData['order']['1']['dir'] ?? $dir;
$dir3 = $reqData['order']['2']['dir'] ?? $dir;
$dir4= $reqData['order']['3']['dir'] ?? $dir;
$dir5= $reqData['order']['4']['dir'] ?? $dir;
$cliente_id = $reqData['cliente_id'] ?? 0;
$resourceData = $this->model->getResource($searchValues, $cliente_id);
foreach ($requestedOrder as $order) {
$column = $order['column'] ?? 0;
$dir = $order['dir'] ?? 'asc';
$orderColumn = ClientePreciosModel::SORTABLE[$column] ?? null;
if ($orderColumn) {
$resourceData->orderBy($orderColumn, $dir);
}
}
$resourceData = $resourceData->limit($length, $start)->get()->getResultObject();
$resourceData = $this->model->getResource($cliente_id)
->orderBy($order, $dir)->orderBy($order2, $dir2)->orderBy($order3, $dir3)->orderBy($order4, $dir4)->orderBy($order5, $dir5)
->limit($length, $start)->get()->getResultObject();
return $this->respond(Collection::datatable(
$resourceData,
$this->model->getResource($searchValues, $cliente_id)->countAllResults(),
$this->model->getResource($searchValues, $cliente_id)->countAllResults()
$this->model->getResource($cliente_id)->countAllResults(),
$this->model->getResource($cliente_id)->countAllResults()
));
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
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, 'cliente_precios')
$response = Editor::inst( $db, 'cliente_precios' )
->fields(
Field::inst('plantilla_id'),
Field::inst('cliente_id'),
Field::inst('tipo'),
Field::inst('tipo_maquina'),
Field::inst('tipo_impresion'),
Field::inst('user_updated_id'),
Field::inst('updated_at'),
Field::inst('tiempo_min')
->getFormatter('Format::toDecimalChar')->setFormatter('Format::fromDecimalChar')
->validator(
'Validate::notEmpty',
array(
'message' => lang('ClientePrecios.validation.required')
)
Field::inst( 'plantilla_id' ),
Field::inst( 'cliente_id' ),
Field::inst( 'tipo' ),
Field::inst( 'tipo_maquina' ),
Field::inst( 'tipo_impresion' ),
Field::inst( 'user_updated_id' ),
Field::inst( 'updated_at' ),
Field::inst( 'is_deleted' ),
Field::inst( 'tiempo_min' )
->getFormatter( 'Format::toDecimalChar')->setFormatter( 'Format::fromDecimalChar')
->validator( 'Validate::notEmpty',array(
'message' => lang('ClientePrecios.validation.required'))
)
->validator(
'Validate::numeric',
array(
->validator('Validate::numeric', array(
"decimal" => ',',
'message' => lang('ClientePrecios.validation.decimal')
)
'message' => lang('ClientePrecios.validation.decimal'))
),
Field::inst('tiempo_max')
->getFormatter('Format::toDecimalChar')->setFormatter('Format::fromDecimalChar')
->validator(
'Validate::notEmpty',
array(
'message' => lang('ClientePrecios.validation.required')
)
Field::inst( 'tiempo_max' )
->getFormatter( 'Format::toDecimalChar')->setFormatter( 'Format::fromDecimalChar')
->validator( 'Validate::notEmpty',array(
'message' => lang('ClientePrecios.validation.required'))
)
->validator(
'Validate::numeric',
array(
"decimal" => ',',
'message' => lang('ClientePrecios.validation.decimal')
)
->validator('Validate::numeric', array(
"decimal" => ',',
'message' => lang('ClientePrecios.validation.decimal'))
),
Field::inst('precio_hora')
->getFormatter('Format::toDecimalChar')->setFormatter('Format::fromDecimalChar')
->validator(
'Validate::notEmpty',
array(
'message' => lang('ClientePrecios.validation.required')
)
Field::inst( 'precio_hora' )
->getFormatter( 'Format::toDecimalChar')->setFormatter( 'Format::fromDecimalChar')
->validator( 'Validate::notEmpty',array(
'message' => lang('ClientePrecios.validation.required'))
)
->validator(
'Validate::numeric',
array(
"decimal" => ',',
'message' => lang('ClientePrecios.validation.decimal')
)
->validator('Validate::numeric', array(
"decimal" => ',',
'message' => lang('ClientePrecios.validation.decimal'))
),
Field::inst('margen')
->getFormatter('Format::toDecimalChar')->setFormatter('Format::fromDecimalChar')
->validator(
'Validate::notEmpty',
array(
'message' => lang('ClientePrecios.validation.required')
)
Field::inst( 'margen' )
->getFormatter( 'Format::toDecimalChar')->setFormatter( 'Format::fromDecimalChar')
->validator( 'Validate::notEmpty',array(
'message' => lang('ClientePrecios.validation.required'))
)
->validator(
'Validate::numeric',
array(
->validator('Validate::numeric', array(
"decimal" => ',',
'message' => lang('ClientePrecios.validation.decimal')
)
'message' => lang('ClientePrecios.validation.decimal'))
),
)
@ -204,6 +186,7 @@ class ClientePrecios extends \App\Controllers\BaseResourceController
if ($action === Editor::ACTION_CREATE || $action === Editor::ACTION_EDIT) {
foreach ($data['data'] as $pkey => $values) {
// Si no se quiere borrar...
if ($data['data'][$pkey]['is_deleted'] != 1) {
$process_data['tiempo_min'] = $data['data'][$pkey]['tiempo_min'];
$process_data['tiempo_max'] = $data['data'][$pkey]['tiempo_max'];
$process_data['tipo'] = $data['data'][$pkey]['tipo'];
@ -215,23 +198,26 @@ class ClientePrecios extends \App\Controllers\BaseResourceController
if (!empty($response)) {
return $response;
}
}
}
}
})
->on('preCreate', function ($editor, &$values) {
$session = session();
$datetime = (new \CodeIgniter\I18n\Time("now"));
$editor
->field('user_updated_id')
->setValue(auth()->user()->id);
->setValue($session->id_user);
$editor
->field('updated_at')
->setValue($datetime->format('Y-m-d H:i:s'));
})
->on('preEdit', function ($editor, &$values) {
$session = session();
$datetime = (new \CodeIgniter\I18n\Time("now"));
$editor
->field('user_updated_id')
->setValue(auth()->user()->id);
->setValue($session->id_user);
$editor
->field('updated_at')
->setValue($datetime->format('Y-m-d H:i:s'));
@ -252,16 +238,4 @@ class ClientePrecios extends \App\Controllers\BaseResourceController
}
}
public function getCurrentPlantilla()
{
if ($this->request->isAJAX()) {
$cliente_id = $this->request->getGet('cliente_id');
$plantilla = $this->model->getPlantilla($cliente_id);
return $this->respond($plantilla);
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
}

View File

@ -234,10 +234,6 @@ class Clientedirecciones extends \App\Controllers\BaseResourceController
try {
$model = model('App\Models\Presupuestos\PresupuestoDireccionesModel');
$resourceData = $model->getDireccion($id);
if(count($resourceData) > 0){
$resourceData[0]->direccionId = $id;
}
$response = (object)[
'error' => false,
'data' => $resourceData

View File

@ -1,5 +1,4 @@
<?php
namespace App\Controllers\Clientes;
<?php namespace App\Controllers\Clientes;
use App\Controllers\BaseResourceController;
@ -43,7 +42,7 @@ class Clienteplantillaprecios extends \App\Controllers\BaseResourceController
// Breadcrumbs (IMN)
$this->viewData['breadcrumb'] = [
['title' => lang("App.menu_clientes"), 'route' => "javascript:void(0);", 'active' => false],
['title' => lang("App.menu_plantillas_tarifas_clientes"), 'route' => route_to("clienteplantillapreciosList"), 'active' => true]
['title' => lang("App.menu_plantillas_tarifas_clientes"), 'route' => site_url('clientes/clienteplantillaprecios'), 'active' => true]
];
parent::initController($request, $response, $logger);
@ -71,48 +70,51 @@ class Clienteplantillaprecios extends \App\Controllers\BaseResourceController
// plantilla desde la lista
public function update($requestedId = null)
{
if ($requestedId == null):
return;
endif;
$model = model('App\Models\Clientes\ClientePlantillaPreciosLineasModel');
$model->delete_values($requestedId);
$newTokenHash = csrf_hash();
$csrfTokenName = csrf_token();
$data = [
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
if ($this->request->getPost()) :
if ($requestedId == null) :
return;
endif;
$model = model('App\Models\Clientes\ClientePlantillaPreciosLineasModel');
$model->delete_values($requestedId);
$newTokenHash = csrf_hash();
$csrfTokenName = csrf_token();
$data = [
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
endif; // ($requestMethod === 'post')
}
public function add()
{
if ($this->request->getPost()):
if ($this->request->getPost()) :
$nullIfEmpty = true; // !(phpversion() >= '8.1');
$postData = $this->request->getPost();
$cliente_id = $postData['cliente_id'] ?? -1;
$from_client_data = $postData['from_client_data'] ?? 0;
$sanitizedData = $this->sanitized($postData, $nullIfEmpty);
// JJO
$sanitizedData['user_created_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)->save($sanitizedData);
} catch (\Exception $e) {
@ -124,29 +126,26 @@ class Clienteplantillaprecios extends \App\Controllers\BaseResourceController
$this->session->setFlashdata('formErrors', $this->model->errors());
endif;
if ($from_client_data == 1) {
$thenRedirect = false;
} else {
$thenRedirect = true; // Change this to false if you want your user to stay on the form after submission
}
$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 = $this->model->db->insertID();
$message = lang('Basic.global.saveSuccess', [lang('Basic.global.record')]) . '.';
if ($cliente_id != -1) {
if($cliente_id != -1){
$modelLineas = model('App\Models\Clientes\ClientePlantillaPreciosLineasModel');
$modelLineas->copy_from_cliente($cliente_id, $id);
$modelClientePrecios = model('App\Models\Clientes\ClientePreciosModel');
$modelClientePrecios->set_plantilla_id($cliente_id, $id);
return $this->respond(['status' => 'success', 'id' => $id]);
} else {
if ($thenRedirect):
if (!empty($this->indexRoute)):
return ;
}
else{
if ($thenRedirect) :
if (!empty($this->indexRoute)) :
//return redirect()->to(route_to($this->indexRoute))->with('sweet-success', $message);
return redirect()->to(site_url('/clienteplantillaprecios/edit/' . $id))->with('message', $message);
return redirect()->to(site_url('/clientes/clienteplantillaprecios/edit/' . $id))->with('message', $message);
else:
return $this->redirect2listView('sweet-success', $message);
endif;
@ -172,35 +171,35 @@ class Clienteplantillaprecios extends \App\Controllers\BaseResourceController
{
if ($requestedId == null):
if ($requestedId == null) :
return $this->redirect2listView();
endif;
$id = filter_var($requestedId, FILTER_SANITIZE_URL);
$clientePlantillaPreciosEntity = $this->model->find($id);
if ($clientePlantillaPreciosEntity == false):
if ($clientePlantillaPreciosEntity == false) :
$message = lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('Clientes.cliente')), $id]);
return $this->redirect2listView('sweet-error', $message);
endif;
if ($this->request->getPost()):
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 ($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) {
@ -217,12 +216,12 @@ class Clienteplantillaprecios extends \App\Controllers\BaseResourceController
$thenRedirect = false;
endif;
if ($noException && $successfulResult):
if ($noException && $successfulResult) :
$id = $clientePlantillaPreciosEntity->id ?? $id;
$message = lang('Basic.global.updateSuccess', [lang('Basic.global.record')]) . '.';
if ($thenRedirect):
if (!empty($this->indexRoute)):
if ($thenRedirect) :
if (!empty($this->indexRoute)) :
return redirect()->to(route_to($this->indexRoute))->with('sweet-success', $message);
else:
return $this->redirect2listView('sweet-success', $message);
@ -237,7 +236,7 @@ class Clienteplantillaprecios extends \App\Controllers\BaseResourceController
//var_dump($clientePlantillaPreciosEntity); dd();
$this->viewData['clienteplantillapreciosEntity'] = $clientePlantillaPreciosEntity;
$this->viewData['formAction'] = route_to('updateClienteplantillaprecios', $id);
$this->viewData['boxTitle'] = lang('Basic.global.edit2') . ' ' . lang('Clientes.moduleTitle') . ' ' . lang('Basic.global.edit3');
@ -247,23 +246,6 @@ class Clienteplantillaprecios extends \App\Controllers\BaseResourceController
} // end function edit(...)
public function updatePlantillaEnCliente(){
if ($this->request->isAJAX()) {
$reqData = $this->request->getPost();
$plantilla_id = $reqData['plantilla_id'] ?? -1;
$model = model('App\Models\Clientes\ClientePreciosModel');
$model->update_plantilla_id($plantilla_id);
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function datatable()
{
if ($this->request->isAJAX()) {
@ -275,16 +257,16 @@ class Clienteplantillaprecios extends \App\Controllers\BaseResourceController
}
$start = $reqData['start'] ?? 0;
$length = $reqData['length'] ?? 5;
$searchValues = get_filter_datatables_columns($reqData);
$search = $reqData['search']['value'];
$requestedOrder = $reqData['order']['0']['column'] ?? 1;
$order = ClientePlantillaPreciosModel::SORTABLE[$requestedOrder > 0 ? $requestedOrder : 0];
$dir = $reqData['order']['0']['dir'] ?? 'asc';
$resourceData = $this->model->getResource($searchValues)->orderBy($order, $dir)->limit($length, $start)->get()->getResultObject();
$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($searchValues)->countAllResults()
$this->model->getResource($search)->countAllResults()
));
} else {
return $this->failUnauthorized('Invalid request', 403);
@ -293,32 +275,34 @@ class Clienteplantillaprecios extends \App\Controllers\BaseResourceController
public function menuItems()
{
if ($this->request->isAJAX()) {
$query = $this->model->builder()->select(
[
"id",
"nombre as name"
]
)->where("deleted_at", null);
if ($this->request->getGet("q")) {
$query->groupStart()
->orLike("cliente_plantilla_precios.nombre", $this->request->getGet("q"))
->groupEnd();
$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;
try{
$menu = $this->model->getSelect2MenuItems($columns2select, $columns2select[1], $onlyActiveOnes, $searchStr, true);
$nonItem = new \stdClass;
$nonItem->id = '';
$nonItem->text = '- ' . lang('Basic.global.None') . ' -';
array_unshift($menu, $nonItem);
}
catch(Exception $e){
$menu = [];
}
$items = $query->get()->getResultObject();
// add a custom item at the beginning
$customItem = new \stdClass;
$customItem->id = 0;
$customItem->name = "Personalizado";
array_unshift($items, $customItem);
return $this->response->setJSON($items);
$newTokenHash = csrf_hash();
$csrfTokenName = csrf_token();
$data = [
'menu' => $menu,
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
}

View File

@ -93,47 +93,31 @@ class Clienteplantillaprecioslineas extends \App\Controllers\BaseResourceControl
}
$start = $reqData['start'] ?? 0;
$length = $reqData['length'] ?? 5;
$requestedOrder = $reqData['order'] ?? [];
$searchValues = get_filter_datatables_columns($reqData);
$requestedOrder = $reqData['order']['0']['column'] ?? 0;
$requestedOrder2 = $reqData['order']['1']['column'] ?? $requestedOrder;
$requestedOrder3 = $reqData['order']['2']['column'] ?? $requestedOrder;
$requestedOrder4 = $reqData['order']['3']['column'] ?? $requestedOrder;
$requestedOrder5 = $reqData['order']['4']['column'] ?? $requestedOrder;
$order = ClientePlantillaPreciosLineasModel::SORTABLE[$requestedOrder > 0 ? $requestedOrder : 0];
$order2 = ClientePlantillaPreciosLineasModel::SORTABLE[$requestedOrder2 >= 0 ? $requestedOrder2 : $requestedOrder];
$order3 = ClientePlantillaPreciosLineasModel::SORTABLE[$requestedOrder3 >= 0 ? $requestedOrder3 : $requestedOrder];
$order4 = ClientePlantillaPreciosLineasModel::SORTABLE[$requestedOrder4 >= 0 ? $requestedOrder4 : $requestedOrder];
$order5 = ClientePlantillaPreciosLineasModel::SORTABLE[$requestedOrder4 >= 0 ? $requestedOrder5 : $requestedOrder];
$dir = $reqData['order']['0']['dir'] ?? 'asc';
$dir2 = $reqData['order']['1']['dir'] ?? $dir;
$dir3 = $reqData['order']['2']['dir'] ?? $dir;
$dir4= $reqData['order']['3']['dir'] ?? $dir;
$dir5= $reqData['order']['4']['dir'] ?? $dir;
$plantilla_id = $reqData['plantilla_id'] ?? 0;
$resourceData = $this->model->getResource($searchValues, $plantilla_id);
foreach ($requestedOrder as $order) {
$column = $order['column'] ?? 0;
$dir = $order['dir'] ?? 'asc';
$orderColumn = ClientePlantillaPreciosLineasModel::SORTABLE[$column] ?? null;
if ($orderColumn) {
$resourceData->orderBy($orderColumn, $dir);
}
}
$resourceData = $resourceData->limit($length, $start)->get()->getResultObject();
$resourceData = $this->model->getResource($plantilla_id)
->orderBy($order, $dir)->orderBy($order2, $dir2)->orderBy($order3, $dir3)->orderBy($order4, $dir4)->orderBy($order5, $dir5)
->limit($length, $start)->get()->getResultObject();
return $this->respond(Collection::datatable(
$resourceData,
$this->model->getResource([], $plantilla_id)->countAllResults(),
$this->model->getResource($searchValues, $plantilla_id)->countAllResults()
));
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function getStoredRows()
{
if ($this->request->isAJAX()) {
$reqData = $this->request->getPost();
$plantilla_id = $reqData['plantilla_id'] ?? 0;
$resourceData = $this->model->getResource([], $plantilla_id);
$resourceData = $resourceData->get()->getResultObject();
return $this->respond(Collection::datatable(
$resourceData,
$this->model->getResource([], $plantilla_id)->countAllResults(),
$this->model->getResource([], $plantilla_id)->countAllResults()
$this->model->getResource($plantilla_id)->countAllResults(),
$this->model->getResource($plantilla_id)->countAllResults()
));
} else {
return $this->failUnauthorized('Invalid request', 403);
@ -154,7 +138,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')
@ -197,21 +180,42 @@ class Clienteplantillaprecioslineas extends \App\Controllers\BaseResourceControl
),
)
->validator(function ($editor, $action, $data) {
if ($action === Editor::ACTION_CREATE || $action === Editor::ACTION_EDIT) {
foreach ($data['data'] as $pkey => $values) {
// Si no se quiere borrar...
if ($data['data'][$pkey]['is_deleted'] != 1) {
$process_data['tiempo_min'] = $data['data'][$pkey]['tiempo_min'];
$process_data['tiempo_max'] = $data['data'][$pkey]['tiempo_max'];
$process_data['tipo'] = $data['data'][$pkey]['tipo'];
$process_data['tipo_maquina'] = $data['data'][$pkey]['tipo_maquina'];
$process_data['tipo_impresion'] = $data['data'][$pkey]['tipo_impresion'];
$response = $this->model->checkIntervals($process_data, $pkey, $data['data'][$pkey]['plantilla_id']);
// No se pueden duplicar valores al crear o al editar
if (!empty($response)) {
return $response;
}
}
}
}
})
->on('preCreate', function ($editor, &$values) {
$session = session();
$datetime = (new \CodeIgniter\I18n\Time("now"));
$editor
->field('user_updated_id')
->setValue(auth()->user()->id);
->setValue($session->id_user);
$editor
->field('updated_at')
->setValue($datetime->format('Y-m-d H:i:s'));
})
->on('preEdit', function ($editor, &$values) {
$session = session();
$datetime = (new \CodeIgniter\I18n\Time("now"));
$editor
->field('user_updated_id')
->setValue(auth()->user()->id);
->setValue($session->id_user);
$editor
->field('updated_at')
->setValue($datetime->format('Y-m-d H:i:s'));

View File

@ -1,5 +1,4 @@
<?php
namespace App\Controllers\Clientes;
<?php namespace App\Controllers\Clientes;
use App\Controllers\BaseResourceController;
@ -41,59 +40,6 @@ class Clienteusuarios extends \App\Controllers\BaseResourceController
parent::initController($request, $response, $logger);
}
public function removeClienteFromUser($user_id)
{
if ($this->request->isAJAX()) {
if (intval($user_id) > 0) {
$this->model->removeClienteFromUser($user_id);
return $this->respond(['status' => 'success', 'msg' => 'Usuario eliminado correctamente']);
}
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function addUserToClient(){
if ($this->request->isAJAX()) {
$user_id = $this->request->getPost("user_id");
$cliente_id = $this->request->getPost("cliente_id");
if (intval($user_id) > 0 && intval($cliente_id) > 0) {
$this->model->addUserToClient($user_id, $cliente_id);
return $this->respond(['status' => 'success', 'msg' => 'Usuario añadido correctamente']);
}
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function getAvailableUsers()
{
if ($this->request->isAJAX()) {
$query = $this->model->builder()->select(
[
"id",
"CONCAT(first_name, ' ', last_name) as name"
]
)
->where("deleted_at", null)
->where("cliente_id", null);
if ($this->request->getGet("q")) {
$column = "CONCAT(first_name, ' ', last_name)";
$value = $this->request->getGet("q");
$query->groupStart()
->where("LOWER(CONVERT($column USING utf8)) COLLATE utf8_general_ci LIKE", "%" . strtolower($value) . "%")
->groupEnd();
}
$items = $query->get()->getResultObject();
return $this->response->setJSON($items);
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function datatable()
@ -107,19 +53,14 @@ class Clienteusuarios extends \App\Controllers\BaseResourceController
}
$start = $reqData['start'] ?? 0;
$length = $reqData['length'] ?? 5;
$requestedOrder = $reqData['order'] ?? [];
$search = $reqData['search']['value'];
$requestedOrder = $reqData['order']['0']['column'] ?? 1;
$order = ClienteUsuariosModel::SORTABLE[$requestedOrder >= 0 ? $requestedOrder : 1];
$dir = $reqData['order']['0']['dir'] ?? 'asc';
$id_C = $reqData['id_cliente'] ?? -1;
$resourceData = $this->model->getResource("", $id_C);
foreach ($requestedOrder as $order) {
$column = $order['column'] ?? 0;
$dir = $order['dir'] ?? 'asc';
$orderColumn = ClienteUsuariosModel::SORTABLE[$column] ?? null;
if ($orderColumn) {
$resourceData->orderBy($orderColumn, $dir);
}
}
$resourceData = $resourceData->limit($length, $start)->get()->getResultObject();
$resourceData = $this->model->getResource("", $id_C)->orderBy($order, $dir)->limit($length, $start)->get()->getResultObject();
return $this->respond(Collection::datatable(
$resourceData,

View File

@ -50,8 +50,6 @@ class Proveedores extends \App\Controllers\BaseResourceController {
public function index() {
checkPermission('proveedores.menu');
$viewData = [
'currentModule' => static::$controllerSlug,
@ -69,7 +67,9 @@ class Proveedores extends \App\Controllers\BaseResourceController {
public function add() {
checkPermission('proveedores.create');
if ($this->request->getPost()) :
@ -138,8 +138,6 @@ class Proveedores extends \App\Controllers\BaseResourceController {
} // end function add()
public function edit($requestedId = null) {
checkPermission('proveedores.edit');
if ($requestedId == null) :
return $this->redirect2listView();

View File

@ -271,27 +271,6 @@ class Comunidadesautonomas extends \App\Controllers\BaseResourceController
}
}
public function menuItems2()
{
if ($this->request->isAJAX()) {
$query = $this->model->builder()->select(
[
"id",
"nombre as name"
]
)->orderBy("nombre", "asc");
if ($this->request->getGet("q")) {
$query->groupStart()
->orLike("lg_comunidades_autonomas.nombre", $this->request->getGet("q"))
->groupEnd();
}
return $this->response->setJSON($query->get()->getResultObject());
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
protected function getPaisListItems($selId = null)
{

View File

@ -230,19 +230,25 @@ class FormasPago extends \App\Controllers\BaseResourceController
public function menuItems()
{
if ($this->request->isAJAX()) {
$query = $this->model->builder()->select(
[
"id",
"nombre as name"
]
)->orderBy("nombre", "asc");
if ($this->request->getGet("q")) {
$query->groupStart()
->orLike("formas_pago.nombre", $this->request->getGet("q"))
->groupEnd();
}
$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);
return $this->response->setJSON($query->get()->getResultObject());
$newTokenHash = csrf_hash();
$csrfTokenName = csrf_token();
$data = [
'menu' => $menu,
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
} else {
return $this->failUnauthorized('Invalid request', 403);
}

View File

@ -28,7 +28,7 @@ class Group extends \App\Controllers\GoBaseController
// Breadcrumbs
$this->viewData['breadcrumb'] = [
['title' => "Home", 'route' => "javascript:void(0);", 'active' => false],
['title' => lang("App.menu_permission_group"), 'route' => route_to("userGroupList"), 'active' => true]
['title' => lang("App.menu_permission_group"), 'route' => site_url("configuracion/group"), 'active' => true]
];
parent::initController($request, $response, $logger);

View File

@ -1,6 +1,4 @@
<?php
namespace App\Controllers\Configuracion;
<?php namespace App\Controllers\Configuracion;
use App\Controllers\BaseResourceController;
@ -58,7 +56,7 @@ class Imposiciones extends \App\Controllers\BaseResourceController
{
if ($this->request->getPost()) :
@ -132,7 +130,7 @@ class Imposiciones extends \App\Controllers\BaseResourceController
return $this->redirect2listView('sweet-error', $message);
endif;
if ($this->request->getPost()) :
@ -281,9 +279,6 @@ class Imposiciones extends \App\Controllers\BaseResourceController
];
return $orientacionOptions;
}
public function selectImposicion()
{
$data = $this->model->querySelect($this->request->getGet('q'));
return $this->response->setJSON($data);
}
}

View File

@ -1,86 +0,0 @@
<?php
namespace App\Controllers\Configuracion;
use App\Controllers\BaseController;
use App\Models\Configuracion\MaquinaTareaModel;
use CodeIgniter\HTTP\Response;
use Hermawan\DataTables\DataTable;
use CodeIgniter\I18n\Time;
class MaquinaTarea extends BaseController
{
protected MaquinaTareaModel $maquinaTareaModel;
protected $format = 'json';
protected array $viewData = [];
protected static $viewPath = 'themes/vuexy/form/configuracion/maquina_tareas/';
protected static $controllerSlug = "maquina-tareas";
protected $indexRoute = 'viewMaquinaTarea';
protected $editRoute = 'editMaquinaTarea';
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
parent::initController($request, $response, $logger);
$this->maquinaTareaModel = model(MaquinaTareaModel::class);
}
public function index()
{
$this->viewData['breadcrumb'] = [
['title' => lang("App.menu_configuration"), 'route' => "javascript:void(0);", 'active' => false],
['title' => lang("App.menu_maquina_tareas"), 'route' => site_url('configuracion/maquina-tareas'), 'active' => true]
];
return view(static::$viewPath . $this->indexRoute, $this->viewData);
}
public function viewForm(int $maquina_tarea_id)
{
$maquinaTarea = $this->maquinaTareaModel->find($maquina_tarea_id);
$this->viewData['breadcrumb'] = [
['title' => lang("App.menu_configuration"), 'route' => "javascript:void(0);", 'active' => false],
['title' => lang("App.menu_maquina_tareas"), 'route' => site_url('configuracion/maquina-tareas'), 'active' => false],
['title' => $maquinaTarea->name, 'route' => site_url('configuracion/maquina-tareas/edit/' . $maquina_tarea_id), 'active' => true]
];
$this->viewData["model"] = $maquinaTarea;
return view(static::$viewPath . $this->editRoute, $this->viewData);
}
public function show(int $id)
{
$data = $this->maquinaTareaModel->find($id);
return $this->response->setJSON($data);
}
public function update_servicio_cliente(int $id)
{
$data = $this->request->getPost();
$status = $this->maquinaTareaModel->update($id, [
"name" => $data["name"],
"description" => $data["description"]
]);
return $this->response->setJSON(["message" => lang("App.global_alert_save_success"), "status" => $status]);
}
public function store()
{
$bodyData = $this->request->getPost();
$r = $this->maquinaTareaModel->insert($bodyData);
return $this->response->setJSON(["message" => lang("App.global_alert_save_success"), "status" => $r,"data" => $bodyData]);
}
public function delete(int $maquina_tarea_id){
$r = $this->maquinaTareaModel->delete($maquina_tarea_id);
return $this->response->setJSON(["message" => lang("App.user_alert_delete"), "status" => $r]);
}
public function datatable()
{
$query = $this->maquinaTareaModel->getQueryDatatable()->orderBy("created_at", "DESC");
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") : "")
->add("action", fn($q) => $q->id)
->toJson(true);
}
}

View File

@ -1,5 +1,4 @@
<?php
namespace App\Controllers\Configuracion;
<?php namespace App\Controllers\Configuracion;
use App\Controllers\BaseResourceController;
@ -9,8 +8,6 @@ use App\Models\Collection;
use App\Entities\Configuracion\Maquina;
use App\Models\Configuracion\MaquinaModel;
use App\Services\MaquinaService;
use CodeIgniter\Validation\Validation;
class Maquinas extends \App\Controllers\BaseResourceController
{
@ -28,25 +25,24 @@ class Maquinas extends \App\Controllers\BaseResourceController
protected static $viewPath = 'themes/vuexy/form/configuracion/maquinas/';
protected $indexRoute = 'maquinaList';
protected MaquinaService $maquinaService;
protected Validation $validation;
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
$this->viewData['pageTitle'] = lang('Maquinas.moduleTitle');
$this->viewData['usingSweetAlert'] = true;
$this->maquinaService = service('maquina');
$this->validation = service('validation');
// Se indica que este controlador trabaja con soft_delete
$this->soft_delete = true;
// Se indica el flag para los ficheros borrados
$this->delete_flag = 1;
$this->viewData = ['usingServerSideDataTable' => true]; // JJO
// Breadcrumbs (IMN)
$this->viewData['breadcrumb'] = [
['title' => lang("App.menu_configuration"), 'route' => "javascript:void(0);", 'active' => false],
['title' => lang("App.menu_maquina"), 'route' => route_to('maquinaList'), 'active' => true]
['title' => lang("App.menu_maquina"), 'route' => site_url('configuracion/maquinas'), 'active' => true]
];
parent::initController($request, $response, $logger);
@ -69,50 +65,14 @@ class Maquinas extends \App\Controllers\BaseResourceController
return view(static::$viewPath . 'viewMaquinaList', $viewData);
}
public function delete($id = null)
{
// Sanitizar el ID
$id = filter_var($id, FILTER_SANITIZE_URL);
// Validar que el ID es válido
if (empty($id) || !is_numeric($id)) {
return $this->respond(['status' => 'error', 'msg' => 'ID no válida']);
}
// Buscar la máquina en la base de datos
$maquina = $this->model->find($id);
if (!$maquina) {
$message = lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('Maquinas.maquina')), $id]);
return $this->respond(['status' => 'error', 'msg' => 'ID no válida']);
}
// Verificar que el usuario está autenticado
if (!auth()->user()) {
return $this->respond(['status' => 'error', 'msg' => 'Usuario no autenticado']);
}
// Preparar los datos para actualizar
$data = [
'id' => $id,
'is_deleted' => 1,
'deleted_at' => date('Y-m-d H:i:s'),
'user_updated_id' => auth()->user()->id,
];
// Guardar los cambios
if (!$this->model->save($data)) {
return $this->respond(['status' => 'error', 'msg' => 'Error al eliminar']);
}
// Retornar éxito
$message = lang('Basic.global.deleteSuccess', [lang('Basic.global.record')]) . '.';
return $this->respond(['status' => 'error', 'msg' => $message]);
}
public function add()
{
if ($this->request->getPost()):
if ($this->request->getPost()) :
$nullIfEmpty = true; // !(phpversion() >= '8.1');
@ -124,10 +84,10 @@ class Maquinas extends \App\Controllers\BaseResourceController
$sanitizedData['user_created_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)->save($sanitizedData);
} catch (\Exception $e) {
@ -141,14 +101,14 @@ class Maquinas extends \App\Controllers\BaseResourceController
$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 = $this->model->db->insertID();
$message = lang('Basic.global.saveSuccess', [lang('Basic.global.record')]) . '.';
if ($thenRedirect):
if (!empty($this->indexRoute)):
if ($thenRedirect) :
if (!empty($this->indexRoute)) :
//return redirect()->to(route_to($this->indexRoute))->with('sweet-success', $message);
return redirect()->to(site_url('configuracion/maquinas/edit/' . $id))->with('sweet-success', $message);
else:
@ -178,20 +138,20 @@ class Maquinas extends \App\Controllers\BaseResourceController
{
if ($requestedId == null):
if ($requestedId == null) :
return $this->redirect2listView();
endif;
$id = filter_var($requestedId, FILTER_SANITIZE_URL);
$maquina = $this->model->find($id);
if ($maquina == false):
if ($maquina == false) :
$message = lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('Maquinas.maquina')), $id]);
return $this->redirect2listView('sweet-error', $message);
endif;
if ($this->request->getPost()):
if ($this->request->getPost()) :
$nullIfEmpty = true; // !(phpversion() >= '8.1');
@ -211,19 +171,17 @@ class Maquinas extends \App\Controllers\BaseResourceController
// JJO
$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()) :
//JJO: comprobar alto y ancho impresion < alto y ancho
if ($sanitizedData['alto'] < $sanitizedData['alto_impresion']) {
$successfulResult = false;
$this->viewData['errorMessage'] = lang('Maquinas.validation.alto_menor_alto_impresion');
;
$this->viewData['errorMessage'] = lang('Maquinas.validation.alto_menor_alto_impresion');;
$this->session->setFlashdata('formErrors', $this->model->errors());
} else if ($sanitizedData['ancho'] < $sanitizedData['ancho_impresion']) {
$successfulResult = false;
$this->viewData['errorMessage'] = lang('Maquinas.validation.ancho_menor_ancho_impresion');
;
$this->viewData['errorMessage'] = lang('Maquinas.validation.ancho_menor_ancho_impresion');;
$this->session->setFlashdata('formErrors', $this->model->errors());
} else {
try {
@ -244,12 +202,12 @@ class Maquinas extends \App\Controllers\BaseResourceController
$thenRedirect = false;
endif;
if ($noException && $successfulResult):
if ($noException && $successfulResult) :
$id = $maquina->id ?? $id;
$message = lang('Basic.global.updateSuccess', [lang('Basic.global.record')]) . '.';
if ($thenRedirect):
if (!empty($this->indexRoute)):
if ($thenRedirect) :
if (!empty($this->indexRoute)) :
return redirect()->to(route_to($this->indexRoute))->with('sweet-success', $message);
else:
return $this->redirect2listView('sweet-success', $message);
@ -285,24 +243,22 @@ class Maquinas extends \App\Controllers\BaseResourceController
}
$start = $reqData['start'] ?? 0;
$length = $reqData['length'] ?? 5;
$searchValues = get_filter_datatables_columns($reqData);
$requestedOrder = $reqData['order'] ?? [];
$search = $reqData['search']['value'];
$requestedOrder = $reqData['order']['0']['column'] ?? 1;
$order = MaquinaModel::SORTABLE[$requestedOrder >= 0 ? $requestedOrder : 1];
$dir = $reqData['order']['0']['dir'] ?? 'asc';
$resourceData = $this->model->getResource($searchValues);
foreach ($requestedOrder as $order) {
$column = $order['column'] ?? 0;
$dir = $order['dir'] ?? 'asc';
$orderColumn = MaquinaModel::SORTABLE[$column] ?? null;
if ($orderColumn) {
$resourceData->orderBy($orderColumn, $dir);
}
}
$resourceData = $resourceData->limit($length, $start)->get()->getResultObject();
$resourceData = $this->model->getResource($search)->orderBy($order, $dir)->limit($length, $start)->get()->getResultObject();
foreach ($resourceData as $item) :
if (isset($item->observaciones) && strlen($item->observaciones) > 100) :
$item->observaciones = character_limiter($item->observaciones, 100);
endif;
endforeach;
return $this->respond(Collection::datatable(
$resourceData,
$this->model->getResource([])->countAllResults(),
$this->model->getResource($searchValues)->countAllResults()
$this->model->getResource()->countAllResults(),
$this->model->getResource($search)->countAllResults()
));
} else {
return $this->failUnauthorized('Invalid request', 403);
@ -341,7 +297,7 @@ class Maquinas extends \App\Controllers\BaseResourceController
$onlyActiveOnes = false;
$columns2select = [$reqId ?? 'id', $reqText ?? 'nombre'];
$onlyActiveOnes = false;
$menu = $this->model->getSelect2MenuItems($columns2select, $columns2select[1], $onlyActiveOnes, $searchStr, true);
$menu = $this->model->getSelect2MenuItems($columns2select, $columns2select[1], $onlyActiveOnes, $searchStr);
$nonItem = new \stdClass;
$nonItem->id = '';
$nonItem->text = '- ' . lang('Basic.global.None') . ' -';
@ -359,19 +315,15 @@ class Maquinas extends \App\Controllers\BaseResourceController
}
}
public function select(){
$r = $this->model->getSelectQuery($this->request->getGet("q"));
return $this->response->setJSON($r);
}
protected function getMaquinaListItems($selId = null)
{
$data = ['' => lang('Basic.global.pleaseSelectA', [mb_strtolower(lang('Maquinas.maquina'))])];
if (!empty($selId)):
if (!empty($selId)) :
$maquinaModel = model('App\Models\Configuracion\MaquinaModel');
$selOption = $maquinaModel->where('id', $selId)->findColumn('nombre');
if (!empty($selOption)):
if (!empty($selOption)) :
$data[$selId] = $selOption[0];
endif;
endif;
@ -389,23 +341,6 @@ class Maquinas extends \App\Controllers\BaseResourceController
];
return $tipoOptions;
}
public function duplicate(int $maquina_id)
{
$bodyData = $this->request->getPost();
$validated = $this->validation->run($bodyData,'maquina_duplicate');
if($validated){
$this->maquinaService->setMaquina($maquina_id);
$duplicated = $this->maquinaService->duplicate($bodyData['name']);
return $this->response->setJSON(["data" => $duplicated]);
}else{
return $this->response->setJSON(["errors" => $this->validation->getErrors()])->setStatusCode(400);
}
}
public function find_maquina(int $maquina_id){
$maquinaEntity = $this->model->find($maquina_id);
return $this->response->setJSON($maquinaEntity);
}
}

View File

@ -225,9 +225,7 @@ class Maquinaspapelesimpresion extends \App\Controllers\BaseResourceController {
];
// Se checkea que no haya otro papel con ese gramaje seleccionado y que la accion sea activar ese papel
// Esta funcionalidad esta mal: habría que comprobar también que tienen el mismo papel genérico. Se opta por
// quitar la condición el 22012025
/*if($this->model->getPapelActivo($maquina_id, $gramaje)->countAllResults() != 0 && intval($active)==1){
if($this->model->getPapelActivo($maquina_id, $gramaje)->countAllResults() != 0 && intval($active)==1){
$response['error']= lang('MaquinasPapelImpresion.gramaje_duplicado');;
$ret_vals = [
'DT_RowId' => 'row_'. $papel_id,
@ -237,9 +235,9 @@ class Maquinaspapelesimpresion extends \App\Controllers\BaseResourceController {
];
$response['data'] = $ret_vals;
}
else{*/
else{
$this->model->updateRows([$data]);
//}
}
$newTokenHash = csrf_hash();
$csrfTokenName = csrf_token();

View File

@ -1,5 +1,4 @@
<?php
namespace App\Controllers\Configuracion;
<?php namespace App\Controllers\Configuracion;
use App\Controllers\BaseResourceController;
@ -10,8 +9,6 @@ use App\Entities\Configuracion\PaisEntity;
use App\Models\Configuracion\PaisModel;
use Hermawan\DataTables\DataTable;
class Paises extends \App\Controllers\BaseResourceController
{
@ -65,17 +62,17 @@ class Paises extends \App\Controllers\BaseResourceController
public function add()
{
if ($this->request->getPost()):
if ($this->request->getPost()) :
$postData = $this->request->getPost();
$sanitizedData = $this->sanitized($postData, true);
$noException = true;
if ($successfulResult = $this->canValidate()):
if ($successfulResult = $this->canValidate()) :
if ($this->canValidate()):
if ($this->canValidate()) :
try {
$successfulResult = $this->model->skipValidation(true)->save($sanitizedData);
} catch (\Exception $e) {
@ -89,14 +86,14 @@ class Paises extends \App\Controllers\BaseResourceController
$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 = $this->model->db->insertID();
$message = lang('Basic.global.saveSuccess', [lang('Basic.global.record')]) . '.';
if ($thenRedirect):
if (!empty($this->indexRoute)):
if ($thenRedirect) :
if (!empty($this->indexRoute)) :
return redirect()->to(route_to($this->indexRoute))->with('sweet-success', $message);
else:
return $this->redirect2listView('sweet-success', $message);
@ -120,20 +117,20 @@ class Paises extends \App\Controllers\BaseResourceController
public function edit($requestedId = null)
{
if ($requestedId == null):
if ($requestedId == null) :
return $this->redirect2listView();
endif;
$id = filter_var($requestedId, FILTER_SANITIZE_URL);
$paisEntity = $this->model->find($id);
if ($paisEntity == false):
if ($paisEntity == false) :
$message = lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('Paises.pais')), $id]);
return $this->redirect2listView('sweet-error', $message);
endif;
if ($this->request->getPost()):
if ($this->request->getPost()) :
$nullIfEmpty = true; // !(phpversion() >= '8.1');
@ -146,10 +143,10 @@ class Paises extends \App\Controllers\BaseResourceController
$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) {
@ -166,12 +163,12 @@ class Paises extends \App\Controllers\BaseResourceController
$thenRedirect = false;
endif;
if ($noException && $successfulResult):
if ($noException && $successfulResult) :
$id = $paisEntity->id ?? $id;
$message = lang('Basic.global.updateSuccess', [lang('Basic.global.record')]) . '.';
if ($thenRedirect):
if (!empty($this->indexRoute)):
if ($thenRedirect) :
if (!empty($this->indexRoute)) :
return redirect()->to(route_to($this->indexRoute))->with('sweet-success', $message);
else:
return $this->redirect2listView('sweet-success', $message);
@ -196,38 +193,30 @@ class Paises extends \App\Controllers\BaseResourceController
public function datatable()
{
$q = $this->model->getDatatableQuery();
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 = PaisModel::SORTABLE[$requestedOrder > 0 ? $requestedOrder : 1];
$dir = $reqData['order']['0']['dir'] ?? 'asc';
$result = DataTable::of($q)
->edit(
"show_erp",
function ($row, $meta) {
if($row->show_erp == 1) {
return '<i class="ti ti-check"></i>';
}else{
return '';
}
}
)
->add("actionBtns", callback: function ($q) {
$actions = '';
if (auth()->user()->can('paises.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('paises.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);
$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);
}
}
public function allItemsSelect()
@ -280,25 +269,4 @@ class Paises extends \App\Controllers\BaseResourceController
}
}
public function menuItems2()
{
if ($this->request->isAJAX()) {
$query = $this->model->builder()->select(
[
"id",
"nombre as name"
]
)->orderBy("nombre", "asc");
if ($this->request->getGet("q")) {
$query->groupStart()
->orLike("lg_paises.nombre", $this->request->getGet("q"))
->groupEnd();
}
return $this->response->setJSON($query->get()->getResultObject());
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
}

View File

@ -43,7 +43,7 @@ class Papelesgenericos extends \App\Controllers\BaseResourceController
// Breadcrumbs (IMN)
$this->viewData['breadcrumb'] = [
['title' => lang("App.menu_configuration"), 'route' => "javascript:void(0);", 'active' => false],
['title' => lang("App.menu_papelgenerico"), 'route' => route_to('papelGenericoList'), 'active' => true]
['title' => lang("App.menu_papelgenerico"), 'route' => site_url('configuracion/papelesgenericos'), 'active' => true]
];
parent::initController($request, $response, $logger);
@ -72,9 +72,9 @@ class Papelesgenericos extends \App\Controllers\BaseResourceController
if ($this->request->getPost()):
if ($this->request->getPost()) :
$nullIfEmpty = true; // !(phpversion() >= '8.1');
@ -84,36 +84,36 @@ class Papelesgenericos extends \App\Controllers\BaseResourceController
$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)->save($sanitizedData);
} catch (\Exception $e) {
$noException = false;
$this->dealWithException($e);
}
else:
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):
if ($noException && $successfulResult) :
$id = $this->model->db->insertID();
$message = lang('Basic.global.saveSuccess', [lang('Basic.global.record')]) . '.';
if ($thenRedirect):
if (!empty($this->indexRoute)):
if ($thenRedirect) :
if (!empty($this->indexRoute)) :
return redirect()->to(route_to($this->indexRoute))->with('sweet-success', $message);
else:
else :
return $this->redirect2listView('sweet-success', $message);
endif;
else:
else :
$this->session->setFlashData('sweet-success', $message);
endif;
@ -133,20 +133,20 @@ class Papelesgenericos extends \App\Controllers\BaseResourceController
public function edit($requestedId = null)
{
if ($requestedId == null):
if ($requestedId == null) :
return $this->redirect2listView();
endif;
$id = filter_var($requestedId, FILTER_SANITIZE_URL);
$papelGenerico = $this->model->find($id);
if ($papelGenerico == false):
if ($papelGenerico == false) :
$message = lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('PapelGenerico.papelGenerico')), $id]);
return $this->redirect2listView('sweet-error', $message);
endif;
if ($this->request->getPost()):
if ($this->request->getPost()) :
$nullIfEmpty = true; // !(phpversion() >= '8.1');
@ -156,33 +156,22 @@ class Papelesgenericos extends \App\Controllers\BaseResourceController
if ($this->request->getPost('show_in_client') == null) {
$sanitizedData['show_in_client'] = false;
}
if ($this->request->getPost('activo') == null) {
$sanitizedData['activo'] = false;
}
if ($this->request->getPost('show_in_client_special') == null) {
$sanitizedData['show_in_client_special'] = false;
}
if ($sanitizedData['show_in_client_special']) {
$sanitizedData['show_in_client'] = true;
}
if ($sanitizedData['activo']) {
$sanitizedData['activo'] = true;
}
$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) {
$noException = false;
$this->dealWithException($e);
}
else:
else :
$this->viewData['warningMessage'] = lang('Basic.global.formErr1', [mb_strtolower(lang('PapelGenerico.papelGenerico'))]);
$this->session->setFlashdata('formErrors', $this->model->errors());
@ -192,17 +181,17 @@ class Papelesgenericos extends \App\Controllers\BaseResourceController
$thenRedirect = false;
endif;
if ($noException && $successfulResult):
if ($noException && $successfulResult) :
$id = $papelGenerico->id ?? $id;
$message = lang('Basic.global.updateSuccess', [lang('Basic.global.record')]) . '.';
$message = lang('Basic.global.updateSuccess', [lang('Basic.global.record')]).'.';
if ($thenRedirect):
if (!empty($this->indexRoute)):
if ($thenRedirect) :
if (!empty($this->indexRoute)) :
return redirect()->to(route_to($this->indexRoute))->with('sweet-success', $message);
else:
else :
return $this->redirect2listView('sweet-success', $message);
endif;
else:
else :
$this->session->setFlashData('sweet-success', $message);
endif;
@ -216,7 +205,7 @@ class Papelesgenericos extends \App\Controllers\BaseResourceController
$this->viewData['boxTitle'] = lang('Basic.global.edit2') . ' ' . lang('PapelGenerico.moduleTitle') . ' ' . lang('Basic.global.edit3');
$this->viewData['usingServerSideDataTable'] = true;
return $this->displayForm(__METHOD__, $id);
} // end function edit(...)
@ -282,7 +271,7 @@ class Papelesgenericos extends \App\Controllers\BaseResourceController
$onlyActiveOnes = false;
$columns2select = [$reqId ?? 'id', $reqText ?? 'nombre'];
$onlyActiveOnes = false;
$menu = $this->model->getSelect2MenuItems($columns2select, $columns2select[1], $onlyActiveOnes, $searchStr, true);
$menu = $this->model->getSelect2MenuItems($columns2select, $columns2select[1], $onlyActiveOnes, $searchStr);
$nonItem = new \stdClass;
$nonItem->id = '';
$nonItem->text = '- ' . lang('Basic.global.None') . ' -';
@ -299,115 +288,4 @@ class Papelesgenericos extends \App\Controllers\BaseResourceController
return $this->failUnauthorized('Invalid request', 403);
}
}
public function getPapelCliente()
{
if ($this->request->isAJAX()) {
$tirada = goSanitize($this->request->getGet('tirada'))[0] ?? null;
$POD = null;
if ($tirada != null) {
$POD_value = model('App\Models\Configuracion\ConfigVariableModel')->getVariable('POD')->value;
if (intval($tirada) <= intval($POD_value)) {
$POD = true;
} else {
$POD = false;
}
}
$tipo = goSanitize($this->request->getGet('tipo'))[0];
$selected_papel = goSanitize($this->request->getGet('papel'))[0] ?? null;
$cubierta = goSanitize($this->request->getGet('cubierta'))[0] ?? 0;
$tapa_dura = goSanitize($this->request->getGet('tapa_dura'))[0] ?? null;
$sobrecubierta = goSanitize($this->request->getGet('sobrecubierta'))[0] ?? 0;
$guardas = goSanitize($this->request->getGet('guardas'))[0] ?? 0;
$ancho = floatval($this->request->getGet('ancho') ?? 0);
$alto = floatval($this->request->getGet('alto') ?? 0);
$solapas = floatval($this->request->getGet('solapas') ?? 0);
$lomo = floatval($this->request->getGet('lomo') ?? 0);
$forSelect2 = intval($this->request->getGet('forSelect2') ?? 0);
$anchoLibro = $ancho;
if(intval($cubierta) == 1 || intval($sobrecubierta) == 1){
$anchoLibro = 2 * $ancho + 2 * $solapas + $lomo;
}
$menu = $this->model->getPapelCliente($tipo, $cubierta, $sobrecubierta, $guardas, $selected_papel, $tapa_dura, false, $POD, $anchoLibro, $alto, $tirada);
$menu2 = $this->model->getPapelCliente($tipo, $cubierta, $sobrecubierta, $guardas, $selected_papel, $tapa_dura, true, $POD, $anchoLibro, $alto, $tirada);
if ($forSelect2) {
$menu = array_map(function ($item) {
if (isset($item->id)) {
return [
'id' => $item->id,
'name' => $item->nombre
];
} else {
return [
'id' => $item->gramaje,
'name' => $item->gramaje
];
}
}, $menu);
return $this->respond($menu);
}
$newTokenHash = csrf_hash();
$csrfTokenName = csrf_token();
$data = [
'papeles' => $menu,
'papeles_especiales' => $menu2,
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function selectPapelEspecial()
{
if ($this->request->isAJAX()) {
$tirada = goSanitize($this->request->getGet('tirada'))[0] ?? null;
$POD = null;
if ($tirada != null) {
$POD_value = model('App\Models\Configuracion\ConfigVariableModel')->getVariable('POD')->value;
if (intval($tirada) <= intval($POD_value)) {
$POD = true;
} else {
$POD = false;
}
}
$tipo = goSanitize($this->request->getGet('tipo'))[0];
$cubierta = goSanitize($this->request->getGet('cubierta'))[0] ?? 0;
$sobrecubierta = goSanitize($this->request->getGet('sobrecubierta'))[0] ?? 0;
$ancho = floatval($this->request->getGet('ancho') ?? 0);
$alto = floatval($this->request->getGet('alto') ?? 0);
$solapas = floatval($this->request->getGet('solapas') ?? 0);
$lomo = floatval($this->request->getGet('lomo') ?? 0);
$tapa_dura = $this->request->getGet('tapa_dura') ?? 0;
$anchoLibro = 2 * $ancho + 2 * $solapas + $lomo;
$items = $this->model->getPapelCliente($tipo, $cubierta, $sobrecubierta, false, null, $tapa_dura, true, $POD, $anchoLibro, $alto, $tirada);
$items = array_map(function ($item) {
return [
'id' => $item->id,
'name' => $item->nombre
];
}, $items);
return $this->response->setJSON($items);
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
}

View File

@ -22,7 +22,6 @@ use
use App\Models\Collection;
use CodeIgniter\Validation\Validation;
@ -36,6 +35,7 @@ use App\Models\Configuracion\PapelImpresionTipologiaModel;
use App\Models\Configuracion\MaquinasPapelesImpresionModel;
use App\Models\Configuracion\MaquinaModel;
class Papelesimpresion extends \App\Controllers\BaseResourceController
{
@ -52,7 +52,6 @@ class Papelesimpresion extends \App\Controllers\BaseResourceController
protected static $viewPath = 'themes/vuexy/form/configuracion/papel/';
protected $indexRoute = 'papelImpresionList';
protected Validation $validation;
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
@ -67,12 +66,11 @@ class Papelesimpresion extends \App\Controllers\BaseResourceController
$this->delete_flag = 1;
$this->tpModel = new PapelImpresionTipologiaModel();
$this->validation = service("validation");
// Breadcrumbs
$this->viewData['breadcrumb'] = [
['title' => lang("App.menu_configuration"), 'route' => "javascript:void(0);", 'active' => false],
['title' => lang("App.menu_papelimpresion"), 'route' => route_to('papelImpresionList'), 'active' => true]
['title' => lang("App.menu_papelimpresion"), 'route' => site_url('configuracion/papelesimpresion'), 'active' => true]
];
parent::initController($request, $response, $logger);
@ -177,7 +175,7 @@ class Papelesimpresion extends \App\Controllers\BaseResourceController
if ($this->request->getPost()) :
$nullIfEmpty = false; // !(phpversion() >= '8.1');
$nullIfEmpty = true; // !(phpversion() >= '8.1');
$postData = $this->request->getPost();
@ -190,9 +188,6 @@ class Papelesimpresion extends \App\Controllers\BaseResourceController
if ($this->request->getPost('defecto') == null) {
$sanitizedData['defecto'] = false;
}
if ($this->request->getPost('interior') == null) {
$sanitizedData['interior'] = false;
}
if ($this->request->getPost('bn') == null) {
$sanitizedData['bn'] = false;
}
@ -202,9 +197,6 @@ class Papelesimpresion extends \App\Controllers\BaseResourceController
if ($this->request->getPost('cubierta') == null) {
$sanitizedData['cubierta'] = false;
}
if ($this->request->getPost('use_for_tapa_dura') == null) {
$sanitizedData['use_for_tapa_dura'] = false;
}
if ($this->request->getPost('sobrecubierta') == null) {
$sanitizedData['sobrecubierta'] = false;
}
@ -217,12 +209,6 @@ class Papelesimpresion extends \App\Controllers\BaseResourceController
if ($this->request->getPost('inkjet') == null) {
$sanitizedData['inkjet'] = false;
}
if ($this->request->getPost('isActivo') == null) {
$sanitizedData['isActivo'] = false;
}
if ($this->request->getPost('use_in_client') == null) {
$sanitizedData['use_in_client'] = false;
}
// Hay que asegurarse de que se quitan los consumos de tintas de rotativa
// en caso de que se haya deseleccionado la opción rotativa
@ -419,7 +405,7 @@ class Papelesimpresion extends \App\Controllers\BaseResourceController
if (!empty($selId)) :
$papelGenericoModel = model('App\Models\Configuracion\PapelGenericoModel');
$selOption = $papelGenericoModel->where('is_deleted', 0)->where('id', $selId)->findColumn('nombre');
$selOption = $papelGenericoModel->where('id', $selId)->findColumn('nombre');
if (!empty($selOption)) :
$data[$selId] = $selOption[0];
endif;
@ -445,38 +431,4 @@ class Papelesimpresion extends \App\Controllers\BaseResourceController
$ma_pa_model->updateRows($active_values);
}
}
/**
* Duplica el papel impresion y sus relaciones
*
* @param int $papel_impresion_id
* @return Response
*/
public function duplicate( int $papel_impresion_id)
{
$bodyData = $this->request->getPost();
$validated = $this->validation->run($bodyData, "papel_impresion_duplicate");
if($validated){
$papelImpresionEntity = $this->model->find($papel_impresion_id);
$papelImpresionService = service('papel_impresion');
$duplicated = $papelImpresionService
->setPapelImpresionEntity($papelImpresionEntity)
->duplicate($bodyData["name"]);
return $this->response->setJSON(["data" => $duplicated]);
}else{
return $this->response->setJSON(["errors" => $this->validation->getErrors()])->setStatusCode(400);
}
}
public function papel_impresion_select()
{
$q = $this->request->getGet('q');
$data = $this->model->querySelect($q)->get()->getResultArray();
return $this->response->setJSON($data);
}
public function papel_impresion_find(int $papel_impresion_id)
{
$piEntity = $this->model->find($papel_impresion_id);
return $this->response->setJSON($piEntity);
}
}

View File

@ -166,7 +166,7 @@ class Papelimpresionmargenes extends \App\Controllers\BaseResourceController
$id_PI = $reqData['id_PI'] ?? -1;
$resourceData = $this->model->getResource("", $id_PI)->orderBy($order, $dir)->limit($length, $start)->get()->getResultObject();
return $this->respond(Collection::datatable(
$resourceData,
$this->model->getResource()->countAllResults(),

View File

@ -271,27 +271,6 @@ class Provincias extends \App\Controllers\BaseResourceController
}
}
public function menuItems2()
{
if ($this->request->isAJAX()) {
$query = $this->model->builder()->select(
[
"id",
"nombre as name"
]
)->orderBy("nombre", "asc");
if ($this->request->getGet("q")) {
$query->groupStart()
->orLike("lg_provincias.nombre", $this->request->getGet("q"))
->groupEnd();
}
return $this->response->setJSON($query->get()->getResultObject());
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
protected function getPaisListItems($selId = null)
{

View File

@ -5,10 +5,10 @@ use App\Models\Chat\ChatDeparmentModel;
use App\Models\Chat\ChatDeparmentUserModel;
use App\Models\Usuarios\GroupModel;
use App\Models\Usuarios\UserModel;
use App\Models\UserModel;
use App\Models\Usuarios\GroupsUsersModel;
use App\Models\Collection;
use CodeIgniter\Shield\Entities\User;
use function PHPUnit\Framework\isNull;
class Users extends \App\Controllers\GoBaseController
{
@ -20,10 +20,10 @@ class Users extends \App\Controllers\GoBaseController
private ChatDeparmentUserModel $chat_department_user_model;
use \CodeIgniter\API\ResponseTrait;
protected static $primaryModelName = UserModel::class;
protected $modelName = ClientePlantillaPreciosLineasModel::class;
protected static $primaryModelName = 'App\Models\UserModel';
protected static $singularObjectNameCc = 'user';
protected static $singularObjectName = 'User';
@ -50,7 +50,7 @@ class Users extends \App\Controllers\GoBaseController
// Breadcrumbs (IMN)
$this->viewData['breadcrumb'] = [
['title' => lang("App.menu_configuration"), 'route' => "javascript:void(0);", 'active' => false],
['title' => lang("App.menu_users"), 'route' => route_to('userList'), 'active' => true]
['title' => lang("App.menu_users"), 'route' => site_url('configuracion/users'), 'active' => true]
];
parent::initController($request, $response, $logger);
@ -59,8 +59,10 @@ class Users extends \App\Controllers\GoBaseController
public function index()
{
$this->viewData['usingServerSideDataTable'] = true;
$this->viewData['usingClientSideDataTable'] = true;
$this->viewData['pageSubTitle'] = lang('Basic.global.ManageAllRecords', [lang('Users.user')]);
$this->viewData['user_model'] = $this->user_model;
$this->viewData['userList2'] = auth()->getProvider()->findAll();
parent::index();
}
@ -75,19 +77,19 @@ class Users extends \App\Controllers\GoBaseController
// Obtener contraseña nueva si se ha introducido en texto plano
if (empty($postData['new_pwd'])) {
$postData['password'] = 'Safekat2024'; // Contraseña por defecto
} else {
}else{
$postData['password'] = $postData['new_pwd'];
}
// Obtener los grupos a los que pertenece
$currentGroups = $postData['group'] ?? [];
$chatDepartments = $postData['chatDepartments'] ?? [];
unset($postData['group']);
unset($postData['chatDepartments']);
// Marcar el username como NULL
// Generar el nombre de usuario
$postData['username'] = strstr($postData['email'], '@', true);
$sanitizedData = $this->sanitized($postData, true);
$noException = true;
// Obtener proveedor de usuarios
@ -97,43 +99,33 @@ class Users extends \App\Controllers\GoBaseController
if ($this->canValidate()) :
try {
// The Email is unique
if ($this->user_model->isEmailUnique($sanitizedData['email'])) {
// Crear el usuario si pasa la validación
$user = new \CodeIgniter\Shield\Entities\User([
'username' => null, // If you don't have a username, be sure to set the value to null anyway, so that it passes CodeIgniter's empty data check
'first_name' => $sanitizedData['first_name'],
'last_name' => $sanitizedData['last_name'],
'cliente_id' => $sanitizedData['cliente_id'],
'comments' => $sanitizedData['comments'],
'email' => $sanitizedData['email'],
'password' => $sanitizedData['password'],
'status' => $sanitizedData['status'] ?? 0,
'active' => $sanitizedData['active'] ?? 0,
]);
// Add the user to the system
$users->save($user);
$successfulResult = true; // Hacked
} // Email is not unique!
else {
$this->viewData['errorMessage'] = "El correo '". $sanitizedData['email'] ."' ya está registrado en el sistema";
$this->session->setFlashdata('formErrors', $this->model->errors());
$successfulResult = false; // Hacked
}
$user = new User([
'username' => $sanitizedData['username'],
'first_name' => $sanitizedData['first_name'],
'last_name' => $sanitizedData['last_name'],
'email' => $sanitizedData['email'],
'password' => $sanitizedData['password'],
'status' => $sanitizedData['status'] ?? 0,
'active' => $sanitizedData['active'] ?? 0,
]);
$users->save($user);
$successfulResult = true; // Hacked
} catch (\Exception $e) {
$noException = false;
$this->viewData['errorMessage'] = $e->getMessage();
//$this->dealWithException($e);
if (strpos($e->getMessage(), 'correo duplicado') !== false) {
$this->viewData['errorMessage'] = "El correo electrónico ya está registrado en el sistema";
$this->session->setFlashdata('formErrors', $this->model->errors());
}
}
else:
$this->viewData['errorMessage'] = lang('Basic.global.formErr1', [mb_strtolower(lang('Users.user'))]);
$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 = $users->getInsertID();
@ -145,11 +137,12 @@ class Users extends \App\Controllers\GoBaseController
];
$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->where("user_id",$id)->delete();
foreach($chatDepartments as $chatDepartment)
{
$this->chat_department_user_model->insert([
"user_id" => $id,
"chat_department_id" => $this->chat_department_model->where("name", $chatDepartment)->first()->id
"chat_department_id" => $this->chat_department_model->where("name",$chatDepartment)->first()["id"]
]);
}
@ -206,6 +199,7 @@ class Users extends \App\Controllers\GoBaseController
unset($postData['group']);
unset($postData['chatDepartments']);
// Obtener contraseña nueva si se ha introducido en texto plano
// Obtener contraseña nueva si se ha introducido en texto plano
if (!empty($postData['new_pwd'])) {
$postData['password'] = $postData['new_pwd'];
@ -260,11 +254,12 @@ class Users extends \App\Controllers\GoBaseController
];
$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->where("user_id",$id)->delete();
foreach($chatDepartments as $chatDepartment)
{
$this->chat_department_user_model->insert([
"user_id" => $id,
"chat_department_id" => $this->chat_department_model->where("name", $chatDepartment)->first()->id
"chat_department_id" => $this->chat_department_model->where("name",$chatDepartment)->first()["id"]
]);
}
$id = $user->id ?? $id;
@ -289,7 +284,7 @@ class Users extends \App\Controllers\GoBaseController
$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['chatDepartments'] = $this->chat_department_model->select(["display", "name", "id as chatDepartmentId"])->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');
@ -312,8 +307,6 @@ class Users extends \App\Controllers\GoBaseController
return $this->redirect2listView('errorMessage', $message);
endif;
$this->chat_department_user_model->where("user_id", $id)->delete();
$users = auth()->getProvider();
$users->delete($user->id);
@ -374,49 +367,18 @@ class Users extends \App\Controllers\GoBaseController
}
}
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;
$searchValues = get_filter_datatables_columns($reqData);
$requestedOrder = $reqData['order'] ?? [];
$resourceData = $this->model->getResource($searchValues);
foreach ($requestedOrder as $order) {
$column = $order['column'] ?? 0;
$dir = $order['dir'] ?? 'asc';
$orderColumn = UserModel::SORTABLE[$column] ?? null;
if ($orderColumn) {
$resourceData->orderBy($orderColumn, $dir);
}
}
$resourceData = $resourceData->limit($length, $start)->get()->getResultObject();
return $this->respond(Collection::datatable(
$resourceData,
$this->model->getResource([])->countAllResults(),
$this->model->getResource($searchValues)->countAllResults()
));
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function getMenuComerciales()
{
if ($this->request->isAJAX()) {
$comerciales = $this->model->getComerciales();
return $this->respond($comerciales);
$newTokenHash = csrf_hash();
$csrfTokenName = csrf_token();
$data = [
'menu' => $comerciales,
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
} else {
return $this->failUnauthorized('Invalid request', 403);
}

View File

@ -6,8 +6,7 @@ use App\Models\Facturas\FacturaModel;
use App\Entities\Facturas\FacturaEntity;
use App\Models\Clientes\ClienteModel;
use App\Models\Collection;
use Hermawan\DataTables\DataTable;
use Exception;
class Facturas extends \App\Controllers\BaseResourceController
{
@ -27,9 +26,9 @@ class Facturas extends \App\Controllers\BaseResourceController
{
$this->viewData['pageTitle'] = lang('Facturas.facturas');
// Se indica que este controlador trabaja con soft_delete
$this->viewData = ['usingServerSideDataTable' => true];
// Breadcrumbs
$this->viewData['breadcrumb'] = [
['title' => lang("App.menu_facturas"), 'route' => "javascript:void(0);", 'active' => false],
@ -41,7 +40,6 @@ class Facturas extends \App\Controllers\BaseResourceController
public function index()
{
checkPermission('facturas.menu');
if (auth()->user()->inGroup('cliente-admin') || auth()->user()->inGroup('cliente-editor')) {
// Se obtiene el cliente ID a partir del usuario de la sesion
@ -49,7 +47,7 @@ class Facturas extends \App\Controllers\BaseResourceController
$user = $model_user->find(auth()->user()->id);
$clienteId = $user->cliente_id;
} else {
$clienteId = -1;
$clienteId = 0;
}
$this->viewData['cliente_id'] = $clienteId;
@ -60,11 +58,10 @@ class Facturas extends \App\Controllers\BaseResourceController
parent::index();
}
public function list()
{
checkGroups(['admin', 'cliente-admin', 'cliente-editor', 'contabilidad']);
$viewData = [
'currentModule' => static::$controllerSlug,
'pageSubTitle' => lang('Basic.global.ManageAllRecords', [lang('Facturas.facturas')]),
@ -84,39 +81,27 @@ class Facturas extends \App\Controllers\BaseResourceController
$user = $model_user->find(auth()->user()->id);
$clienteId = $user->cliente_id;
} else {
$clienteId = -1;
$clienteId = 0;
}
$viewData['cliente_id'] = $clienteId;
// Establecer el idioma (opcional, si no está configurado en app/Config/App.php)
$locale = explode('-', config('Basics')->i18n)[0]; // Or dynamically set it: \Config\Services::language()->getLocale();
// Specify the language file name (without .php)
$fileName = 'datePicker';
// Build the path to the language file
$filePath = APPPATH . "Language/{$locale}/{$fileName}.php";
// Load the entire language file as an array
$viewData['datepickerLang'] = json_encode(file_exists($filePath) ? require $filePath : []);
$viewData['datepickerLocale'] = config('Basics')->i18n;
return view(static::$viewPath . 'viewFacturasList', $viewData);
}
public function add()
{
checkPermission('facturas.create');
if ($this->request->getPost()):
if ($this->request->getPost()) :
$nullIfEmpty = true; // !(phpversion() >= '8.1');
$postData = $this->request->getPost();
$noException = true;
$allData = true;
$allData = true;
if (!isset($postData['cliente_id']) || !isset($postData['serie_id'])) {
if( !isset($postData['cliente_id']) || !isset($postData['serie_id']) ) {
$this->viewData['errorMessage'] = lang('Facturas.errors.requiredFields');
$this->session->setFlashdata('formErrors', $this->model->errors());
@ -128,8 +113,8 @@ class Facturas extends \App\Controllers\BaseResourceController
try {
$clienteModel = model('App\Models\Clientes\ClienteModel');
$datosCliente = $clienteModel->getClienteDataFacturas($postData['cliente_id']);
if (count($datosCliente) > 0) {
// add array data datosCliente to postData
if(count($datosCliente)>0){
// add array data datosCliente to postData
$postData = array_merge($postData, $datosCliente[0]);
}
} catch (\Exception $e) {
@ -137,20 +122,20 @@ class Facturas extends \App\Controllers\BaseResourceController
$this->dealWithException($e);
}
$sanitizedData = $this->sanitized($postData, $nullIfEmpty);
$sanitizedData['user_updated_id'] = auth()->user()->id;
$sanitizedData['user_created_id'] = auth()->user()->id;
if (!$sanitizedData['creditoAsegurado']) {
if(!$sanitizedData['creditoAsegurado']){
$sanitizedData['creditoAsegurado'] = 0;
}
if ($allData && $successfulResult = $this->canValidate()): // if ($successfulResult = $this->validate($this->formValidationRules) ) :
if ($allData && $successfulResult = $this->canValidate()) : // if ($successfulResult = $this->validate($this->formValidationRules) ) :
if ($this->canValidate()):
if ($this->canValidate()) :
try {
$successfulResult = $this->model->skipValidation(true)->save($sanitizedData);
} catch (\Exception $e) {
@ -163,15 +148,15 @@ class Facturas extends \App\Controllers\BaseResourceController
endif;
endif;
if ($noException && $successfulResult):
if ($noException && $successfulResult) :
$id = $this->model->db->insertID();
$message = lang('Basic.global.saveSuccess', [lang('Basic.global.record')]) . '.';
return redirect()->to(route_to('editarFactura', $id))->with('sweet-success', $message);
endif; // $noException && $successfulResult
endif; // ($requestMethod === 'post')
@ -189,7 +174,7 @@ class Facturas extends \App\Controllers\BaseResourceController
['title' => lang("App.menu_facturas"), 'route' => "javascript:void(0);", 'active' => false],
['title' => lang("Facturas.facturaList"), 'route' => route_to('facturasList'), 'active' => true]
];
$this->viewData['usingSelect2'] = true;
$validation = \Config\Services::validation();
@ -202,21 +187,19 @@ class Facturas extends \App\Controllers\BaseResourceController
} // end function add()
public function edit($id = null)
{
checkPermission('facturas.edit');
if ($id == null):
public function edit($id=null){
if ($id == null) :
return $this->redirect2listView();
endif;
$id = filter_var($id, FILTER_SANITIZE_URL);
$factura = $this->model->find($id);
if ($factura == false):
if ($factura == false) :
$message = lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('Facturas.factura')), $id]);
return $this->redirect2listView('sweet-error', $message);
endif;
$this->obtenerDatosFormulario($factura);
@ -225,15 +208,6 @@ class Facturas extends \App\Controllers\BaseResourceController
['title' => lang("Facturas.facturaList"), 'route' => route_to('facturasList'), 'active' => true]
];
$userModel = model('App\Models\Usuarios\UserModel');
$factura->created_by = $userModel->getFullName($factura->user_created_id);
$factura->updated_by = $userModel->getFullName($factura->user_updated_id);
$factura->created_at_footer = $factura->created_at ? date(' H:i d/m/Y', strtotime($factura->created_at)) : '';
$factura->updated_at_footer = $factura->updated_at ? date(' H:i d/m/Y', strtotime($factura->updated_at)) : '';
$factura->showDeleteButton = model('App\Models\Facturas\FacturaPagoModel')
->where('factura_id', $factura->id)->countAllResults() == 0;
$this->viewData['facturaEntity'] = $factura;
$this->viewData['boxTitle'] = lang('Basic.global.edit2') . ' ' . lang('Facturas.factura') . ' ' . lang('Basic.global.edit3');
@ -241,150 +215,45 @@ class Facturas extends \App\Controllers\BaseResourceController
return $this->displayForm(__METHOD__, $id);
}
public function datatable()
{
$dataForClienteForm = false;
if (auth()->user()->inGroup('cliente-admin') || auth()->user()->inGroup('cliente-editor')) {
// Se obtiene el cliente ID a partir del usuario de la sesion
$model_user = model('App\Models\Usuarios\UserModel');
$user = $model_user->find(auth()->user()->id);
$clienteId = $user->cliente_id;
} else {
$temp = $this->request->getGet('cliente_id');
$clienteId = ($temp && $temp != null && $temp != "") ? $temp : -1;
$dataForClienteForm = ($temp && $temp != null && $temp != "") ? true : false;
}
$model = model(FacturaModel::class);
$q = $model->getDatatableQuery($clienteId);
$searchValue = $this->request->getGet('fecha_factura') ?? '';
if (!empty($searchValue)) {
// Extraer las fechas del formato "YYYY-MM-DD|YYYY-MM-DD"
$dates = explode('|', $searchValue);
if (count($dates) == 2) {
$q->where('t1.fecha_factura_at >=', $dates[0] . ' 00:00:00')
->where('t1.fecha_factura_at <=', $dates[1] . ' 23:59:59');
}
}
$result = DataTable::of($q)
->edit(
"creditoAsegurado",
function ($row, $meta) {
switch ($row->creditoAsegurado) {
case "0":
return lang('Basic.global.no');
case "1":
return lang('Basic.global.yes');
default:
return '--'; // Debug
}
}
)
->edit(
"estado",
function ($row, $meta) {
switch ($row->estado) {
case "borrador":
return lang('Facturas.borrador');
case "validada":
return lang('Facturas.validada');
default:
return '--'; // Debug
}
}
)
->edit(
"estado_pago",
function ($row, $meta) {
switch ($row->estado_pago) {
case "pendiente":
return lang('Facturas.pendiente');
case "pagada":
return lang('Facturas.pagada');
case "insolvente":
return lang('Facturas.insolvente');
default:
return '--'; // Debug
}
}
)
->edit(
"forma_pago",
function ($row, $meta) {
switch ($row->forma_pago) {
case "cheque":
return lang('Facturas.cheque');
case "compensada":
return lang('Facturas.compensada');
case "confirming":
return lang('Facturas.confirming');
case "giroDomiciliado":
return lang('Facturas.giroDomiciliado');
case "pagare":
return lang('Facturas.pagare');
case "transferencia":
return lang('Facturas.transferencia');
default:
return $row->forma_pago; // Debug
}
}
)
->add("action", callback: function ($q) {
if (auth()->user()->can('facturas.edit')) {
if ($q->estado == 'borrador') {
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>
</div>
';
} else {
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>
';
}
} else
return '';
});
if ($clienteId != -1) {
$result->hide('cliente');
$result->hide('creditoAsegurado');
if (!$dataForClienteForm) {
$result->hide('estado');
$result->hide('estado_pago');
}
$result->hide('forma_pago');
$result->hide('vencimiento');
$result->hide('dias_vencimiento');
}
return $result->toJson(returnAsObject: true);
}
public function getDatosFacturacionClienteForm($cliente_id)
{
return $this->respond($this->model->getSumatoriosFacturacionCliente($cliente_id));
}
public function datatablePedidos()
{
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;
$length = $reqData['length'] ?? 5;
$search = $reqData['search']['value'];
$requestedOrder = $reqData['order']['0']['column'] ?? 0;
$order = FacturaModel::SORTABLE[$requestedOrder >= 0 ? $requestedOrder : 0];
$dir = $reqData['order']['0']['dir'] ?? 'asc';
$cliente_id = $reqData['cliente_id'] ?? -1;
$resourceData = $this->model->getResource($search, $cliente_id)->orderBy($order, $dir)->limit($length, $start)->get()->getResultObject();
return $this->respond(Collection::datatable(
$resourceData,
$this->model->getResource("", $cliente_id)->countAllResults(),
$this->model->getResource($search, $cliente_id)->countAllResults()
));
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function datatablePedidos(){
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;
@ -408,14 +277,13 @@ class Facturas extends \App\Controllers\BaseResourceController
}
}
public function update($id = null)
{
public function update($id = null){
if ($this->request->isAJAX()) {
$newTokenHash = csrf_hash();
$csrfTokenName = csrf_token();
if ($id == null):
if ($id == null) :
$data = [
'error' => 2,
$csrfTokenName => $newTokenHash
@ -425,7 +293,7 @@ class Facturas extends \App\Controllers\BaseResourceController
$id = filter_var($id, FILTER_SANITIZE_URL);
$facturaEntity = $this->model->find($id);
if ($facturaEntity == false):
if ($facturaEntity == false) :
$message = lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('Factura.factura')), $id]);
$data = [
'error' => $message,
@ -434,21 +302,21 @@ class Facturas 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);
// JJO
$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) {
@ -464,7 +332,7 @@ class Facturas extends \App\Controllers\BaseResourceController
$facturaEntity->fill($sanitizedData);
endif;
if ($noException && $successfulResult):
if ($noException && $successfulResult) :
$id = $facturaEntity->id ?? $id;
$message = lang('Basic.global.updateSuccess', [lang('Basic.global.record')]) . '.';
@ -482,54 +350,24 @@ class Facturas extends \App\Controllers\BaseResourceController
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
} else {
}
else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function delete($id = null)
{
$user_id = auth()->user()->id;
$datetime = (new \CodeIgniter\I18n\Time("now"));
$rawResult = $this->model->where('id', $id)
->set([
'deleted_at' => $datetime->format('Y-m-d H:i:s'),
'user_updated_id' => $user_id,
])
->update();
if (!$rawResult) {
return $this->failNotFound(lang('Basic.global.deleteError', [$objName]));
}
$modelLineas = model('\App\Models\Facturas\FacturaLineaModel');
$rawResult = $modelLineas->where('factura_id', $id)
->set([
'deleted_at' => $datetime->format('Y-m-d H:i:s'),
'user_updated_id' => $user_id,
])
->update();
$this->model->db->query('DELETE FROM facturas_pedidos_lineas WHERE factura_id=' . $id);
// $message = lang('Basic.global.deleteSuccess', [$objName]); IMN commented
$message = lang('Basic.global.deleteSuccess', [lang('Basic.global.record')]);
$response = $this->respondDeleted(['id' => $id, 'msg' => $message]);
return $response;
}
public function menuPedidosPendientes($cliente_id)
{
public function menuPedidosPendientes($cliente_id){
if ($this->request->isAJAX()) {
$model = model('\App\Models\Pedidos\PedidoLineaModel');
$pedidos = [];
try {
try{
$pedidos = $model->obtenerLineasPedidoSinFacturar($cliente_id);
} catch (Exception $e) {
}
catch(Exception $e){
}
$newTokenHash = csrf_hash();
@ -539,14 +377,14 @@ class Facturas extends \App\Controllers\BaseResourceController
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
} else {
}
else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function duplicate($factura_id = 0)
{
if ($this->request->isAJAX()) {
public function duplicate($factura_id = 0){
if($this->request->isAJAX()){
$factura_origen = $this->model->find($factura_id);
// se quita la key "id" del objeto
@ -569,19 +407,18 @@ class Facturas extends \App\Controllers\BaseResourceController
'id' => $id,
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
return $this->respond($data);
} else {
}else{
return $this->failUnauthorized('Invalid request', 403);
}
}
public function updateTotales($factura_id = 0)
{
if ($this->request->isAJAX()) {
public function updateTotales($factura_id = 0){
if($this->request->isAJAX()){
$postData = $this->request->getPost();
$pendiente = $postData['pendiente'] ?? 0;
$total = $postData['total'] ?? 0;
@ -591,7 +428,7 @@ class Facturas extends \App\Controllers\BaseResourceController
'pendiente' => $pendiente,
'total_pagos' => $postData['total_pagos'] ?? 0,
'user_updated_id' => auth()->user()->id,
'estado_pago' => (intval($pendiente) == 0 && intval($total) != 0) ? 'pagada' : 'pendiente',
'estado_pago' => (intval($pendiente)==0 && intval($total)!=0) ? 'pagada' : 'pendiente',
];
$newTokenHash = csrf_hash();
@ -599,23 +436,23 @@ class Facturas extends \App\Controllers\BaseResourceController
$data_ret = [
$csrfTokenName => $newTokenHash
];
if ($factura_id == 0) {
return $this->respond($data_ret);
if($factura_id == 0){
return $this->respond($data_ret);
}
$data_ret['estado_pago'] = $data['estado_pago'];
$model = model('\App\Models\Facturas\FacturaModel');
$model->update($factura_id, $data);
return $this->respond($data_ret);
} else {
return $this->respond($data_ret);
}
else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function addExcedentes($factura_id)
{
public function addExcedentes($factura_id){
if ($this->request->isAJAX()) {
$model_factura_linea = model('\App\Models\Facturas\FacturaLineaModel');
@ -630,26 +467,26 @@ class Facturas extends \App\Controllers\BaseResourceController
$pedido_linea_maquetacion_id = $postData['pedido_linea_maquetacion_id'] ?? null;
$pedido_id = $postData['pedido_id'] ?? 0;
$nuevo_precio_unidad = round($precio_unidad * (100 - floatval($descuento)) / 100, 4);
$nuevo_precio_unidad = round($precio_unidad*(100-floatval($descuento))/100, 4);
$base = round($cantidad * $nuevo_precio_unidad, 2);
$total_iva = round($base * $iva / 100, 2);
$data = (object) [
'factura_id' => $factura_id,
'pedido_linea_impresion_id' => $pedido_linea_impresion_id,
'pedido_linea_maquetacion_id' => $pedido_linea_maquetacion_id,
'descripcion' => $newString = preg_replace_callback('/Impresión de (\d+) ejemplares/', function ($matches) use ($cantidad) {
return 'Impresión de ' . $cantidad . ' ejemplares';
}, $descripcion),
'cantidad' => $cantidad,
'precio_unidad' => $nuevo_precio_unidad,
$data = (object)[
'factura_id'=>$factura_id,
'pedido_linea_impresion_id'=>$pedido_linea_impresion_id,
'pedido_linea_maquetacion_id'=>$pedido_linea_maquetacion_id,
'descripcion'=>$newString = preg_replace_callback('/Impresión de (\d+) ejemplares/', function ($matches) use ($cantidad) {
return 'Impresión de ' . $cantidad . ' ejemplares';
}, $descripcion),
'cantidad'=>$cantidad,
'precio_unidad'=> $nuevo_precio_unidad,
'iva' => $iva,
'base' => $base,
'total_iva' => $total_iva,
'total' => round($base + $total_iva, 2),
'user_updated_id' => auth()->user()->id,
];
$model_factura_linea->insert($data);
$newTokenHash = csrf_hash();
@ -657,114 +494,93 @@ class Facturas extends \App\Controllers\BaseResourceController
$data_ret = [
$csrfTokenName => $newTokenHash
];
return $this->respond($data_ret);
} else {
return $this->respond($data_ret);
}
else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function addLineaPedidoImpresion($factura_id){
public function addLineaPedidoImpresion($factura_id, $data = -1)
{
if ($this->request) {
if ($this->request->isAJAX())
if ($this->request->isAJAX()) {
$model_pedido_linea = model('\App\Models\Pedidos\PedidoLineaModel');
$model_presupuesto = model('\App\Models\Presupuestos\PresupuestoModel');
$model_factura_linea = model('\App\Models\Facturas\FacturaLineaModel');
try{
$pedido_linea_id = $this->request->getPost('lineaPedido') ?? 0;
} else {
if ($data == -1) {
return "Error: sin datos";
}
$pedido_linea_id = $data;
}
$linea = $model_pedido_linea->find($pedido_linea_id);
$model_pedido_linea = model('\App\Models\Pedidos\PedidoLineaModel');
$model_presupuesto = model('\App\Models\Presupuestos\PresupuestoModel');
$model_factura_linea = model('\App\Models\Facturas\FacturaLineaModel');
$model_factura = model('\App\Models\Facturas\FacturaModel');
$factura = $this->model->find($factura_id);
if($factura){
try {
if($linea){
$presupuesto = $model_presupuesto->find($linea->presupuesto_id);
$linea = $model_pedido_linea->find($pedido_linea_id);
if($presupuesto){
// Se añade la linea de factura
$descripcion = $model_presupuesto->generarLineaPedido($presupuesto->id, true, $linea->pedido_id);
$cantidad = intval($presupuesto->tirada) - intval($this->model->getCantidadLineaPedidoFacturada($linea->id));
$base = $cantidad * floatval($presupuesto->total_precio_unidad);
$base = round($base, 2);
$total_iva = $base * ($presupuesto->iva_reducido==1 ? 0.04 : 0.21);
// se redondea a dos decimales
$total_iva = round($total_iva, 2);
$total = $base + $total_iva;
$factura = $model_factura->find($factura_id);
if ($factura) {
if ($linea) {
$presupuesto = $model_presupuesto->find($linea->presupuesto_id);
if ($presupuesto) {
// Se añade la linea de factura
$descripcion = $model_presupuesto->generarLineaPedido($presupuesto->id, true, $linea->pedido_id);
$cantidad = intval($presupuesto->tirada) - intval($model_factura->getCantidadLineaPedidoFacturada($linea->id));
$base =
floatval($presupuesto->total_aceptado_revisado && $presupuesto->total_aceptado_revisado != 0 ?
$presupuesto->total_aceptado_revisado : $presupuesto->total_aceptado);
$base = round($base, 2);
$total_iva = $base * ($presupuesto->iva_reducido == 1 ? 0.04 : 0.21);
// se redondea a dos decimales
$total_iva = round($total_iva, 2);
$total = $base + $total_iva;
$data = (object) [
'factura_id' => $factura_id,
'pedido_linea_impresion_id' => $pedido_linea_id,
'descripcion' => $descripcion[0]->concepto,
'cantidad' => $cantidad,
'iva' => $presupuesto->iva_reducido == 1 ? 4 : 21,
'base' => $base,
'total_iva' => $total_iva,
'total' => $total,
'user_updated_id' => auth()->user()->id,
];
$model_factura_linea->insert($data);
$id = $model_factura_linea->getInsertID();
if ($id) {
$model_factura_linea->addFacturaPedidoLinea($factura_id, $linea->id, $cantidad);
$newTokenHash = csrf_hash();
$csrfTokenName = csrf_token();
$data = [
'error' => 0,
'id' => $id,
$csrfTokenName => $newTokenHash
$data = (object)[
'factura_id'=>$factura_id,
'pedido_linea_impresion_id'=>$linea->pedido_id,
'descripcion'=>$descripcion[0]->concepto,
'cantidad'=>$cantidad,
'precio_unidad'=>$presupuesto->total_precio_unidad,
'iva' => $presupuesto->iva_reducido==1 ? 4 : 21,
'base' => $base,
'total_iva' => $total_iva,
'total' => $total,
'user_updated_id' => auth()->user()->id,
];
if ($this->request) {
if ($this->request->isAJAX())
return $this->respond($data);
} else {
// remove csrf token
unset($data[$csrfTokenName]);
return $data;
$model_factura_linea->insert($data);
$id = $model_factura_linea->getInsertID();
if($id){
$model_factura_linea->addFacturaPedidoLinea($factura_id, $linea->id, $cantidad);
$newTokenHash = csrf_hash();
$csrfTokenName = csrf_token();
$data = [
'error' => 0,
'id' => $id,
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
}
}
}
}
}
} catch (Exception $e) {
catch(Exception $e){
}
$newTokenHash = csrf_hash();
$csrfTokenName = csrf_token();
$data = [
'error' => 1,
'error_text' => $e->getMessage(),
$csrfTokenName => $newTokenHash
];
if ($this->request) {
if ($this->request->isAJAX())
return $this->respond($data);
} else {
unset($data[$csrfTokenName]);
return $data;
}
return $this->respond($data);
}
else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function deleteLineaPedidoImpresion()
{
public function deleteLineaPedidoImpresion(){
if ($this->request->isAJAX()) {
@ -782,20 +598,20 @@ class Facturas extends \App\Controllers\BaseResourceController
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
} else {
}
else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function validar($factura_id){
public function validar($factura_id)
{
if ($this->request->isAJAX()) {
if($this->request->isAJAX()){
$factura = $this->model->find($factura_id);
if ($factura) {
if($factura){
$model_series = model('\App\Models\Configuracion\SeriesFacturasModel');
$numero = $model_series->getSerieNumerada($factura->serie_id);
@ -805,13 +621,13 @@ class Facturas extends \App\Controllers\BaseResourceController
'user_updated_id' => auth()->user()->id,
];
if ((strpos($numero, "REC ") === 0)) {
$data['estado_pago'] = 'pagada';
if((strpos($numero, "REC ") === 0)){
$data['estado_pago'] = 'pagada';
}
$this->model->update($factura_id, $data);
}
$newTokenHash = csrf_hash();
$csrfTokenName = csrf_token();
@ -819,30 +635,30 @@ class Facturas extends \App\Controllers\BaseResourceController
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
} else {
}
else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function updateCabecera($factura_id)
{
if ($this->request->isAJAX()) {
if ($factura_id == 0) {
public function updateCabecera($factura_id){
if($this->request->isAJAX()){
if($factura_id == 0){
return;
}
$factura = $this->model->find($factura_id);
if ($factura) {
if($factura){
$postData = $this->request->getPost();
$dataName = $postData['name'] ?? '';
$dataValue = $postData['value'] ?? '';
if ($dataName == 'factura_rectificativa_id') {
if($dataName == 'factura_rectificativa_id'){
// se actualiza la factura donde el campo 'numero' sea igual al valor de $dataValue. El campo a actualizar es 'factura_rectificada_id'
$factura_rectificada = $this->model->where('numero', $dataValue)->first();
if ($factura_rectificada) {
if($factura_rectificada){
$data2 = [
'factura_rectificada_id' => $factura->numero,
'user_updated_id' => auth()->user()->id,
@ -865,7 +681,8 @@ class Facturas extends \App\Controllers\BaseResourceController
];
return $this->respond($data);
}
} else {
}
else {
return $this->failUnauthorized('Invalid request', 403);
}
}
@ -874,13 +691,12 @@ class Facturas extends \App\Controllers\BaseResourceController
* FUNCIONES AUXILIARES
************************************/
private function obtenerDatosFormulario(&$factura)
{
if ($factura->estado == 'borrador') {
private function obtenerDatosFormulario(&$factura){
if($factura->estado == 'borrador'){
$serieModel = model('App\Models\Configuracion\SeriesFacturasModel');
$serie = $serieModel->find($factura->serie_id);
if ($serie) {
if($serie){
$factura->numero = str_replace("{numero}", $serie->next, $serie->formato);
}
}
@ -895,8 +711,9 @@ class Facturas extends \App\Controllers\BaseResourceController
$formaPagoModel = model('App\Models\Configuracion\FormaPagoModel');
$factura->formas_pago = $formaPagoModel->getMenuItems();
$factura->fecha_factura_at_text = $factura->fecha_factura_at ? date('d/m/Y', strtotime($factura->fecha_factura_at)) : '';
}
}

View File

@ -101,6 +101,15 @@ class FacturasLineas extends \App\Controllers\BaseResourceController
->validator('Validate::notEmpty', array(
'message' => lang('Facturas.validation.requerido'))
),
Field::inst( 'precio_unidad' )
->getFormatter( 'Format::toDecimalChar')->setFormatter( 'Format::fromDecimalChar')
->validator('Validate::numeric', array(
"decimal" => ',',
'message' => lang('Facturas.validation.decimal'))
)
->validator('Validate::notEmpty', array(
'message' => lang('Facturas.validation.requerido'))
),
Field::inst( 'iva' )
->validator('Validate::numeric', array(
'message' => lang('Facturas.validation.numerico'))
@ -119,7 +128,7 @@ class FacturasLineas extends \App\Controllers\BaseResourceController
$totales = $this->generate_totales(
$values['factura_id'],
$values['pedido_linea_impresion_id'],
$values['total'],
$values['precio_unidad'],
$values['iva'],
$values['cantidad'],
$values['old_cantidad']);
@ -143,7 +152,7 @@ class FacturasLineas extends \App\Controllers\BaseResourceController
$totales = $this->generate_totales(
$values['factura_id'],
$values['pedido_linea_impresion_id'],
$values['total'],
$values['precio_unidad'],
$values['iva'],
$values['cantidad'],
$values['old_cantidad']);
@ -194,7 +203,7 @@ 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, $precio_unidad, $iva, $cantidad, $old_cantidad)
{
// si es una linea que se refiere a pedido
@ -205,7 +214,6 @@ class FacturasLineas extends \App\Controllers\BaseResourceController
// 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);

View File

@ -57,7 +57,10 @@ class FacturasPagos extends \App\Controllers\BaseResourceController
->fields(
Field::inst( 'id' ),
Field::inst( 'forma_pago_id' ),
Field::inst( 'notes' ),
Field::inst( 'notes' )
->validator('Validate::notEmpty', array(
'message' => lang('Facturas.validation.requerido'))
),
Field::inst( 'fecha_pago_at' )
->validator( Validate::dateFormat( 'Y-m-d H:i:s' ) )
->getFormatter( Format::dateSqlToFormat( 'Y-m-d H:i:s' ) )

View File

@ -17,10 +17,10 @@ namespace App\Controllers;
*/
use CodeIgniter\Controller;
use CodeIgniter\Database\Query;
use App\Models\NotificationModel;
abstract class GoBaseController extends Controller
{
abstract class GoBaseController extends Controller {
/**
*
@ -102,7 +102,7 @@ abstract class GoBaseController extends Controller
* @var array
*/
public $viewData;
/**
* JJO: Variable para indicar si el controlador hace soft_delete o no
@ -139,15 +139,14 @@ 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']; //JJO
public static $queries = [];
/**
* Constructor.
*/
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger) {
// Do Not Edit This Line
parent::initController($request, $response, $logger);
@ -156,9 +155,9 @@ abstract class GoBaseController extends Controller
//--------------------------------------------------------------------
// E.g.:
$this->session = \Config\Services::session();
if ((!isset($this->viewData['pageTitle']) || empty($this->viewData['pageTitle'])) && isset(static::$pluralObjectName) && !empty(static::$pluralObjectName)) {
if ((!isset($this->viewData['pageTitle']) || empty($this->viewData['pageTitle']) ) && isset(static::$pluralObjectName) && !empty(static::$pluralObjectName)) {
$this->viewData['pageTitle'] = ucfirst(static::$pluralObjectName);
}
@ -172,7 +171,7 @@ abstract class GoBaseController extends Controller
if (empty(static::$controllerSlug)) {
$reflect = new \ReflectionClass($this);
$className = $reflect->getShortName();
$this->viewData['currentModule'] = slugify(convertToSnakeCase(str_replace('Controller', '', $className)));
$this->viewData['currentModule'] = slugify(convertToSnakeCase(str_replace('Controller','',$className)));
} else {
$this->viewData['currentModule'] = strtolower(static::$controllerSlug);
@ -186,31 +185,43 @@ abstract class GoBaseController extends Controller
$this->model = &$this->primaryModel;
}
// Preload any models, libraries, etc, here.
// Preload any models, libraries, etc, here.
// Language Validate
$language = \Config\Services::language();
$language->setLocale($this->session->lang);
// Set TimeZone
if (empty($this->session->get('settings'))) {
$time_zone = model('App\Models\Configuracion\ConfigVariableModel')->getVariable('default_timezone')->value;
date_default_timezone_set($time_zone ?? 'Europe/Madrid');
} else {
date_default_timezone_set($this->session->get('settings')['default_timezone'] ?? 'Europe/Madrid');
if(empty($this->session->get('settings'))){
$settingsModel = new SettingsModel();
$settings = $settingsModel->select('default_timezone')->first()??[];
date_default_timezone_set($this->$settings['default_timezone']??'America/Sao_Paulo');
}else{
date_default_timezone_set($this->session->get('settings')['default_timezone']??'America/Sao_Paulo');
}
// Get notification
if(!empty($this->session->get('token'))) {
$notificationModel = new NotificationModel();
$pulse = $notificationModel->where('user_recipient',$this->session->get('token'))->where('is_read',false)->countAllResults() ?? 0;
$notification = $notificationModel->select('token,title,is_read,created_at')->where('user_recipient',$this->session->get('token'))->orderBy('created_at','desc')->findAll(5) ?? [];
$this->session->set('notification', $notification);
$this->session->set('pulse', $pulse);
}else{
$this->session->set('notification', []);
$this->session->set('pulse', 0);
}
$this->viewData['currentLocale'] = $this->request->getLocale();
}
public function index()
{
public function index() {
helper('text');
if ((!isset($this->viewData['boxTitle']) || empty($this->viewData['boxTitle'])) && isset(static::$pluralObjectName) && !empty(static::$pluralObjectName)) {
if ((!isset($this->viewData['boxTitle']) || empty($this->viewData['boxTitle']) ) && isset(static::$pluralObjectName) && !empty(static::$pluralObjectName)) {
$this->viewData['boxTitle'] = ucfirst(static::$pluralObjectName);
}
@ -225,10 +236,10 @@ abstract class GoBaseController extends Controller
// if $this->currentView is assigned a view name, use it, otherwise assume the view something like 'viewSingleObjectList'
$viewFilePath = static::$viewPath . (empty($this->currentView) ? 'view' . ucfirst(static::$singularObjectNameCc) . 'List' : $this->currentView);
echo view($viewFilePath, $this->viewData);
}
/**
@ -237,13 +248,12 @@ abstract class GoBaseController extends Controller
* @param null $objId
* @return string
*/
protected function displayForm($forMethod, $objId = null)
{
protected function displayForm($forMethod, $objId = null) {
helper('form');
$this->viewData['usingSelect2'] = true;
$validation = \Config\Services::validation();
$validation = \Config\Services::validation();
$action = str_replace(static::class . '::', '', $forMethod);
$actionSuffix = ' ';
@ -260,13 +270,13 @@ abstract class GoBaseController extends Controller
}
if (!isset($this->viewData['formAction'])) {
$this->viewData['formAction'] = base_url(strtolower($this->viewData['currentModule']) . '/' . $action . '/' . $formActionSuffix);
$this->viewData['formAction'] = base_url(strtolower($this->viewData['currentModule']) . '/' . $action . '/' . $formActionSuffix);
}
if ((!isset($this->viewData['boxTitle']) || empty($this->viewData['boxTitle'])) && isset(static::$singularObjectName) && !empty(static::$singularObjectName)) {
if ((!isset($this->viewData['boxTitle']) || empty($this->viewData['boxTitle']) ) && isset(static::$singularObjectName) && !empty(static::$singularObjectName)) {
$this->viewData['boxTitle'] = ucfirst($action) . $actionSuffix . ucfirst(static::$singularObjectName);
}
$this->viewData['validation'] = $validation;
$viewFilePath = static::$viewPath . 'view' . ucfirst(static::$singularObjectNameCc) . 'Form';
@ -274,8 +284,7 @@ abstract class GoBaseController extends Controller
return view($viewFilePath, $this->viewData);
}
protected function redirect2listView($flashDataKey = null, $flashDataValue = null)
{
protected function redirect2listView($flashDataKey = null, $flashDataValue = null) {
if (!empty($this->indexRoute)) {
$uri = base_url(route_to($this->indexRoute));
@ -295,9 +304,9 @@ abstract class GoBaseController extends Controller
} else {
$getHandlingRoutes = $routes->getRoutes('get');
$indexMethod = array_search('\\App\\Controllers\\' . $className . '::index', $getHandlingRoutes);
$indexMethod = array_search('\\App\\Controllers\\'.$className.'::index', $getHandlingRoutes);
if ($indexMethod) {
$uri = route_to('App\\Controllers\\' . $className . '::index');
$uri = route_to('App\\Controllers\\'.$className.'::index');
} else {
$uri = base_url(static::$controllerSlug);
}
@ -306,7 +315,7 @@ abstract class GoBaseController extends Controller
$uri = base_url($className);
}
}
if ($flashDataKey != null && $flashDataValue != null) {
return redirect()->to($uri)->with($flashDataKey, $flashDataValue);
} else {
@ -314,11 +323,10 @@ abstract class GoBaseController extends Controller
}
}
public function delete($requestedId, bool $deletePermanently = true)
{
public function delete($requestedId, bool $deletePermanently = true) {
if (is_string($requestedId)):
if (is_numeric($requestedId)):
if (is_string($requestedId)) :
if (is_numeric($requestedId)) :
$id = filter_var($requestedId, FILTER_SANITIZE_NUMBER_INT);
else:
$onlyAlphaNumeric = true;
@ -330,66 +338,64 @@ abstract class GoBaseController extends Controller
$id = intval($requestedId);
endif;
if (empty($id) || $id === 0):
if (empty($id) || $id === 0) :
$error = 'Invalid identifier provided to delete the object.';
endif;
$rawResult = null;
if (!isset($error)):
if (!isset($error)) :
try {
if ($deletePermanently && !$this->soft_delete):
if (is_numeric($id)):
$rawResult = $this->primaryModel->delete($id);
else:
$rawResult = $this->primaryModel->where($this->primaryModel->getPrimaryKeyName(), $id)->delete();
endif;
elseif ($this->soft_delete):
$datetime = (new \CodeIgniter\I18n\Time("now"));
$rawResult = $this->primaryModel->where('id', $id)
->set([
'deleted_at' => $datetime->format('Y-m-d H:i:s'),
'is_deleted' => $this->delete_flag
])
->update();
if ($deletePermanently && !$this->soft_delete) :
if (is_numeric($id)) :
$rawResult = $this->primaryModel->delete($id);
else:
$rawResult = $this->primaryModel->update($id, ['deleted' => true]);
$rawResult = $this->primaryModel->where($this->primaryModel->getPrimaryKeyName(), $id)->delete();
endif;
elseif ($this->soft_delete):
$datetime = (new \CodeIgniter\I18n\Time("now"));
$rawResult = $this->primaryModel->where('id',$id)
->set(['deleted_at' => $datetime->format('Y-m-d H:i:s'),
'is_deleted' => $this->delete_flag])
->update();
else:
$rawResult = $this->primaryModel->update($id, ['deleted' => true]);
endif;
} catch (\Exception $e) {
log_message('error', "Exception: Error deleting object named '" . (static::$singularObjectName ?? 'unknown') . "' with $id :\r\n" . $e->getMessage());
log_message('error', "Exception: Error deleting object named '".(static::$singularObjectName ?? 'unknown')."' with $id :\r\n".$e->getMessage());
}
endif;
$ar = $this->primaryModel->db->affectedRows();
try {
$dbError = $this->primaryModel->db->error();
} catch (\Exception $e2) {
if ($e2->getMessage() != "Trying to get property 'errno' of non-object") {
log_message('error', $e2->getCode() . ' : ' . $e2->getMessage());
log_message('error', $e2->getCode() . ' : ' . $e2->getMessage()) ;
}
}
if (isset($dbError['code']) && isset($dbError['message'])) {
log_message('error', $dbError['code'] . ' ' . $dbError['message']);
log_message('error', $dbError['code'].' '.$dbError['message']);
} else {
$dbError = ['code' => '', 'message' => ''];
$dbError = ['code' => '', 'message'=>''];
}
$result = ['persisted' => $ar > 0, 'ar' => $ar, 'persistedId' => null, 'affectedRows' => $ar, 'errorCode' => $dbError['code'], 'error' => $dbError['message']];
$result = ['persisted'=>$ar>0, 'ar'=>$ar, 'persistedId'=>null, 'affectedRows'=>$ar, 'errorCode'=>$dbError['code'], 'error'=>$dbError['message']];
$nameOfDeletedObject = static::$singularObjectNameCc;
if ($ar < 1):
if ($ar < 1) :
$errorMessage = lang('Basic.global.deleteError', [$nameOfDeletedObject]); // 'No ' . static::$singularObjectName . ' was deleted now, because it probably had already been deleted.';
$fdKey = isset($this->viewData['usingSweetAlert']) && $this->viewData['usingSweetAlert'] ? 'sweet-error' : 'errorMessage';
$fdKey = isset($this->viewData['usingSweetAlert'] ) && $this->viewData['usingSweetAlert'] ? 'sweet-error' : 'errorMessage';
$errorMessage = str_replace("'", "\'", $errorMessage);
return $this->redirect2listView($fdKey, str_replace("'", '', $errorMessage));
else:
$message = lang('Basic.global.deleteSuccess', [$nameOfDeletedObject]); // 'The ' . static::$singularObjectName . ' was successfully deleted.';
$fdKey = isset($this->viewData['usingSweetAlert']) && $this->viewData['usingSweetAlert'] ? 'sweet-success' : 'successMessage';
if ($result['affectedRows'] > 1):
log_message('warning', "More than one row has been deleted in attempt to delete row for object named '" . (static::$singularObjectName ?? 'unknown') . "' with id: $id");
$fdKey = isset($this->viewData['usingSweetAlert'] ) && $this->viewData['usingSweetAlert'] ? 'sweet-success' : 'successMessage';
if ($result['affectedRows']>1) :
log_message('warning', "More than one row has been deleted in attempt to delete row for object named '".(static::$singularObjectName ?? 'unknown')."' with id: $id");
endif;
$message = str_replace("'", "\'", $message);
return $this->redirect2listView($fdKey, $message);
@ -397,7 +403,7 @@ abstract class GoBaseController extends Controller
}
/**
/**
* Convenience method to validate form submission
* @return bool
*/
@ -410,15 +416,14 @@ abstract class GoBaseController extends Controller
return true;
}
$validationErrorMessages = $this->model->validationMessages ?? $this->formValidationErrorMessagess ?? null;
;
$validationErrorMessages = $this->model->validationMessages ?? $this->formValidationErrorMessagess ?? null;;
if ($validationErrorMessages != null) {
$valid = $this->validate($validationRules, $validationErrorMessages);
} else {
$valid = $this->validate($validationRules);
}
$this->validationErrors = $valid ? '' : $this->validator->getErrors();
/*
@ -438,8 +443,7 @@ abstract class GoBaseController extends Controller
* @param array|null $postData
* @return array
*/
protected function sanitized(array $postData = null, bool $nullIfEmpty = false)
{
protected function sanitized(array $postData = null, bool $nullIfEmpty = false) {
if ($postData == null) {
$postData = $this->request->getPost();
}
@ -458,31 +462,29 @@ abstract class GoBaseController extends Controller
* Convenience method for common exception handling
* @param \Exception $e
*/
protected function dealWithException(\Exception $e)
{
protected function dealWithException(\Exception $e) {
// using another try / catch block to prevent to avoid CodeIgniter bug throwing trivial exceptions for querying DB errors
try {
$query = $this->model->db->getLastQuery();
$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):
$userFriendlyErrMsg .= PHP_EOL . lang('Basic.global.persistDuplErr', [static::$singularObjectNameCc]);
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'])):
log_message('error', $dbError['code'] . ' : ' . $dbError['message']);
log_message('error', $userFriendlyErrMsg.PHP_EOL.$e->getMessage().PHP_EOL.$queryStr);
if (isset($dbError['message']) && !empty($dbError['message'])) :
log_message('error', $dbError['code'].' : '.$dbError['message']);
endif;
$this->viewData['errorMessage'] = $userFriendlyErrMsg;
} catch (\Exception $e2) {
log_message('debug', 'You can probably safely ignore this: In attempt to check DB errors, CodeIgniter threw: ' . PHP_EOL . $e2->getMessage());
log_message('debug', 'You can probably safely ignore this: In attempt to check DB errors, CodeIgniter threw: '.PHP_EOL.$e2->getMessage());
}
}
// Collect the queries so something can be done with them later.
public static function collect(Query $query)
{
public static function collect(Query $query) {
static::$queries[] = $query;
}
@ -493,8 +495,7 @@ abstract class GoBaseController extends Controller
* @param object $sourceObject
* @return object
*/
function cast($destination, $sourceObject)
{
function cast($destination, $sourceObject) {
if (is_string($destination)) {
$destination = new $destination();
}

View File

@ -0,0 +1,518 @@
<?php
namespace App\Controllers;
use App\Models\ActivityModel;
use App\Models\PasswordRecoveryModel;
use App\Models\SettingsModel;
use App\Models\TemplateModel;
use App\Models\Usuarios\UserModel;
use App\Libraries\PasswordHash;
use CodeIgniter\HTTP\Files\FileCollection;
class Integration extends BaseController
{
private $user_model;
private $settings_model;
private $pass_recovery_model;
private $template_model;
private $activity_model;
private $id_user;
private $token_user;
function __construct()
{
$this->user_model = new UserModel();
$this->settings_model = new SettingsModel();
$this->pass_recovery_model = new PasswordRecoveryModel();
$this->template_model = new TemplateModel();
$this->activity_model = new ActivityModel();
$this->id_user = session()->get('id_user');
$this->token_user = session()->get('token');
}
public function index()
{
echo view(getenv('theme.path').'main/header');
echo view(getenv('theme.path').'form/dashboard/index');
echo view(getenv('theme.path').'main/footer');
}
public function send_email($email='',$subject='',$body='',$key='',$json=false){
if(empty($email)){
return $json ? json_encode(["return" => false]) : false;
}
$phpass = new PasswordHash(8, true);
if(!$phpass->CheckPassword(MD5($email), $key)){
return $json ? json_encode(["return" => false]) : false;
}
$user = $this->user_model->where('email',$email??null)->first();
if(!empty($user)){
foreach (keywordEmail()??[] as $item){
$field = str_replace(['[','user_',']'],'',$item);
if(str_contains($body, $field)){
$body = str_replace('['.$item.']',$user->{$field},$body);
}
}
}
if($this->sendMail($subject,unescape($body),$email)){
return $json ? json_encode(["return" => true]) : true;
}else{
return $json ? json_encode(["return" => false]) : false;
}
}
public function send_email_test($email=''){
$token = session()->get('token')??'';
if(!empty($token)){
if(empty($email)){
return $this->response->setJSON(["return" => false]);
}
$subject = "Email Test";
$body = "Email working successfully!";
if($this->sendMail($subject,unescape($body),$email)){
return $this->response->setJSON(["return" => true]);
}else{
return $this->response->setJSON(["return" => false]);
}
}else{
return $this->response->setJSON(["return" => false]);
}
}
public function reset_password(){
$session = session();
$settings = $session->get('settings');
helper('text');
if($listPost = $this->request->getPost()){
// Captcha Validation
if($settings['captcha_recovery']??false){
if($settings['captcha_gateway'] == 'recaptcha'){
if(isset($listPost['g-recaptcha-response'])){
$captcha = $listPost['g-recaptcha-response'];
$url = 'https://www.google.com/recaptcha/api/siteverify?secret='.urlencode($settings['captcha_secret_key']??'').'&response='.urlencode($captcha);
$response = file_get_contents($url);
$responseKeys = json_decode($response,true);
if(!$responseKeys["success"]) {
$session->setFlashdata('toast', ['error',lang("App.login_alert"),lang("App.login_alert_captcha_invalid")]);
return redirect()->to('/login/forgot_password');
}
}else{
$session->setFlashdata('toast', ['error',lang("App.login_alert"),lang("App.login_alert_captcha_not_found")]);
return redirect()->to('/login/forgot_password');
}
}
if($settings['captcha_gateway'] == 'hcaptcha'){
if(isset($listPost['h-captcha-response'])){
$captcha = $listPost['h-captcha-response'];
$url = 'https://hcaptcha.com/siteverify?secret='.urlencode($settings['captcha_secret_key']??'').'&response='.urlencode($captcha).'&remoteip='.$_SERVER['REMOTE_ADDR'];
$response = file_get_contents($url);
$responseKeys = json_decode($response,true);
if(!$responseKeys["success"]) {
$session->setFlashdata('toast', ['error',lang("App.login_alert"),lang("App.login_alert_captcha_invalid")]);
return redirect()->to('/login/forgot_password');
}
}else{
$session->setFlashdata('toast', ['error',lang("App.login_alert"),lang("App.login_alert_captcha_not_found")]);
return redirect()->to('/login/forgot_password');
}
}
}
$user = $this->user_model->where('email',$listPost['email']??null)->first();
if(empty($user)){
$session->setFlashdata('toast', ['error',lang("App.login_alert"),lang("App.login_alert_user_not_found")]);
return redirect()->to('/login/forgot_password');
}
$template = $this->template_model->where('id_template',1)->first();
foreach (keywordEmail()??[] as $item){
$field = str_replace(['[','user_',']'],'',$item);
$template = str_replace('['.$item.']',$user->$field ?? "",$template);
}
$token = random_string("alnum", 50);
$url = base_url().'login/recovery/'.$token;
$this->pass_recovery_model->save([
'user' => $user->token,
'token' => $token
]);
$title = $template['subject']??'';
$msg = $template['body']??'';
$msg = str_replace('[recovery_password]',$url,$msg);
$email = $user->email;
$this->setLog('recovery','recovery-password',$user->token);
$send = $this->sendMail($title,$msg,$email);
if($send){
$session->setFlashdata('toast', ['success',lang("App.login_alert_send"),lang("App.login_alert_send_pass")]);
return redirect()->to('/login/forgot_password');
}else{
$session->setFlashdata('toast', ['error',lang("App.login_alert"),lang("App.login_alert_error_email")]);
return redirect()->to('/login/forgot_password');
}
}else{
$session->setFlashdata('toast', ['error',lang("App.login_alert"),lang("App.login_alert_error_pass")]);
return redirect()->to('/login/forgot_password');
}
}
public function setLog($level,$event,$user='')
{
$request = \Config\Services::request();
$ip = $request->getIPAddress();
$agent = $request->getUserAgent();
if ($agent->isBrowser())
{
$currentAgent = $agent->getBrowser().' '.$agent->getVersion();
}
elseif ($agent->isRobot())
{
$currentAgent = $this->agent->robot();
}
elseif ($agent->isMobile())
{
$currentAgent = $agent->getMobile();
}
else
{
$currentAgent = 'Unidentified User Agent';
}
$this->activity_model->save([
'user' => $this->token_user??$user,
'level' => $level,
'event' => $event,
'ip' => $ip,
'os' => $agent->getPlatform(),
'browser' => $currentAgent,
'detail' => $agent
]);
}
private function sendMail($subject,$body,$recipient)
{
$config = $this->settings_model->first();
$gateway = $config['email_gateway'];
$body = html_entity_decode($body);
if($gateway == 'smtp'){
try {
//https://codeigniter.com/user_guide/libraries/email.html
$email = \Config\Services::email();
$config['protocol'] = $config['email_gateway'];
$config['SMTPHost'] = $config['email_smtp'];
$config['SMTPUser'] = $config['email_address'];
$config['SMTPPass'] = $config['email_pass'];
$config['SMTPPort'] = $config['email_port'];
$config['SMTPCrypto'] = $config['email_cert']=='none'?'':$config['email_cert'];
$config['SMTPTimeout'] = 15;
$config['mailType'] = 'html';
$config['wordWrap'] = true;
$email->initialize($config);
$email->setFrom($config['email_address'], $config['email_name']);
$email->setTo($recipient);
$email->setSubject($subject);
$email->setMessage($body);
if (!$email->send())
{
return false;
}else{
return true;
}
} catch (\Exception $ex) {
return false;
}
}
return false;
}
public function saveStorage($file=null,$path='',$allow=[]){
$config = $this->settings_model->first();
$gateway = $config['storage_gateway'];
switch ($gateway) {
case "local":
try {
$ext = $file ? $file->getExtension() : '';
if (in_array(strtolower($ext), $allow)) {
if(strtolower(PHP_OS) == 'linux'){
$pathServer = $path;
}else{
$pathServer = str_replace('/','\\',$path);
}
if ($file->isValid()) {
$name = $file->getName();
$rename = $file->getRandomName();
$file->move($pathServer,$rename);
return $path.$rename;
}
}
return null;
} catch (\Exception $ex) {
return null;
}
case "aws":
case "minio":
$aws_endpoint = $config['aws_endpoint'];
$aws_key = $config['aws_key'];
$aws_secret = $config['aws_secret'];
$aws_region = $config['aws_region'];
$aws_bucket = $config['aws_bucket'];
try {
$ext = $file ? $file->getExtension() : '';
if (in_array(strtolower($ext), $allow)) {
if($gateway=="minio"){
$s3Client = new \Aws\S3\S3Client([
'version' => 'latest',
'region' => $aws_region,
'endpoint' => $aws_endpoint,
'use_path_style_endpoint' => true,
'credentials' => [
'key' => $aws_key,
'secret' => $aws_secret
]
]);
}else{
$s3Client = new \Aws\S3\S3Client([
'version' => 'latest',
'region' => $aws_region,
'credentials' => [
'key' => $aws_key,
'secret' => $aws_secret
]
]);
}
try {
$rename = $file->getRandomName();
$file->move(WRITEPATH.'uploads',$rename);
if(strtolower(PHP_OS) == 'linux'){
$file_Path = WRITEPATH.'uploads/'. $rename;
}else{
$file_Path = WRITEPATH.'uploads\\'. $rename;
}
$result = $s3Client->putObject([
'Bucket' => $aws_bucket,
'Key' => $rename,
'Body' => fopen($file_Path, 'r')
]);
unlink($file_Path);
if($result['@metadata']['statusCode'] == 200){
return $result['@metadata']['effectiveUri'];
}else{
return null;
}
} catch (\Aws\S3\Exception\S3Exception $e) {
return null;
}
}
return null;
} catch (\Exception $ex) {
return null;
}
default:
return null;
}
}
public function saveStorageBackup($file=null,$name=null){
$config = $this->settings_model->first();
$gateway = $config['backup_storage'];
switch ($gateway) {
case "local":
try {
return $file;
} catch (\Exception $ex) {
return null;
}
case "aws":
case "minio":
$aws_endpoint = $config['aws_endpoint'];
$aws_key = $config['aws_key'];
$aws_secret = $config['aws_secret'];
$aws_region = $config['aws_region'];
$aws_bucket = $config['aws_bucket'];
try {
if($gateway=="minio"){
$s3Client = new \Aws\S3\S3Client([
'version' => 'latest',
'region' => $aws_region,
'endpoint' => $aws_endpoint,
'use_path_style_endpoint' => true,
'credentials' => [
'key' => $aws_key,
'secret' => $aws_secret
]
]);
}else{
$s3Client = new \Aws\S3\S3Client([
'version' => 'latest',
'region' => $aws_region,
'credentials' => [
'key' => $aws_key,
'secret' => $aws_secret
]
]);
}
try {
$result = $s3Client->putObject([
'Bucket' => $aws_bucket,
'Key' => $name,
'Body' => fopen($file, 'r')
]);
unlink($file);
if($result['@metadata']['statusCode'] == 200){
return $result['@metadata']['effectiveUri'];
}else{
return null;
}
} catch (\Aws\S3\Exception\S3Exception $e) {
return null;
}
} catch (\Exception $ex) {
return null;
}
default:
return null;
}
}
public function create_backup($download=false)
{
//Demo Mode
if(env('demo.mode')??false){
if($download==true){
session()->setFlashdata('sweet', ['warning',lang("App.general_demo_mode")]);
return redirect()->to('/settings');
}else{
die();
}
}
$settings = $this->settings_model->first()??[];
if($settings['backup_automatic']){
helper('text');
$db = db_connect('default');
try {
$all = false;
$tables = explode(',',$settings['backup_table']??'');
foreach ($tables as $item){
if ($item == 'all'){
$all = true;
}
}
$token = random_string("alnum", 10);
$name ='mysql_'.$token.'_'.date("YmdHis").'.sql';
if(strtolower(PHP_OS) == 'linux'){
$file_Path = WRITEPATH.'uploads/'.$name;
}else{
$file_Path = WRITEPATH.'uploads\\'.$name;
}
if($all){
\Spatie\DbDumper\Databases\MySql::create()
->setHost(getenv('database.default.hostname'))
->setDbName(getenv('database.default.database'))
->setUserName(getenv('database.default.username'))
->setPassword(getenv('database.default.password'))
->setDumpBinaryPath(getenv('database.default.dump'))
->dumpToFile($file_Path);
}else{
\Spatie\DbDumper\Databases\MySql::create()
->setHost(getenv('database.default.hostname'))
->setDbName(getenv('database.default.database'))
->setUserName(getenv('database.default.username'))
->setPassword(getenv('database.default.password'))
->setDumpBinaryPath(getenv('database.default.dump'))
->includeTables($tables)
->dumpToFile($file_Path);
}
$file = $this->saveStorageBackup($file_Path,$name);
$db->query("INSERT INTO backup VALUES (NULL,'".$file."','',NOW(),NOW())");
if($settings['backup_notification_email']){
$send = $this->send_email($settings['backup_email'],$settings['title']." (BACKUP)",lang("App.crontab_backup_success").date("Y-m-d H:i:s"));
if(!$send){
$db->query("INSERT INTO backup VALUES (NULL,'','".lang("App.crontab_email_error")."',NOW(),NOW())");
}
}
if($download){
$this->download_backup($file,$name);
}
} catch (\Spatie\DbDumper\Exceptions\DumpFailed $e) {
$error = str_replace("'","\'",$e->getMessage());
$db->query("INSERT INTO backup VALUES (NULL,'','".$error."',NOW(),NOW())");
if($settings['backup_notification_email']){
$send = $this->send_email($settings['backup_email'],$settings['title']." (BACKUP ERROR)",'Error: '.$e->getMessage());
if(!$send){
$db->query("INSERT INTO backup VALUES (NULL,'','".lang("App.crontab_email_error")."',NOW(),NOW())");
}
}
if($download){
session()->setFlashdata('sweet', ['error',lang("App.crontab_backup_error")]);
return redirect()->to('/settings');
}
}
}
}
private function download_backup($path=null,$name=null)
{
if (!empty(session()->get('token')??'')){
set_time_limit(0);
if(!empty($path) && !empty($name) && file_exists($path)){
header('Content-Description: File Transfer');
header('Content-Disposition: attachment; filename="'.$name.'"');
header('Content-Type: application/octet-stream');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($path));
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Expires: 0');
readfile($path);
}
}else{
return redirect()->to('/settings');
}
}
public function download_postman()
{
if(!empty(session()->get('token')??'')){
set_time_limit(0);
$path = WRITEPATH.'postman_collection.json';
if(file_exists($path)){
header('Content-Description: File Transfer');
header('Content-Disposition: attachment; filename="WebGuard ApiRest - postman_collection.json"');
header('Content-Type: application/octet-stream');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($path));
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Expires: 0');
readfile($path);
}
}else{
return redirect()->to('/settings');
}
}
}

View File

@ -14,10 +14,10 @@ class Js_loader extends BaseController
function comparadorPresupuestoAdmin_js()
function comparadorCosidoTapaBlanda_js()
{
$this->response->setHeader('Content-Type', 'text/javascript');
return view('themes/vuexy/form/presupuestos/admin/comparador.js');
return view('themes/vuexy/form/presupuestos/cosidotapablanda/comparador.js');
}
@ -33,46 +33,53 @@ class Js_loader extends BaseController
}
function datosLibro_js()
{
$this->response->setHeader('Content-Type', 'text/javascript');
return view('themes/vuexy/form/presupuestos/cosidotapablanda/_datosLibroItems.js');
}
function previsualizador_js()
{
$this->response->setHeader('Content-Type', 'text/javascript');
return view('themes/vuexy/form/presupuestos/admin/previews.js');
return view('themes/vuexy/form/presupuestos/cosidotapablanda/previews.js');
}
function lineasPresupuesto_js()
{
$this->response->setHeader('Content-Type', 'text/javascript');
return view('themes/vuexy/form/presupuestos/admin/_lineasPresupuestoItems.js');
return view('themes/vuexy/form/presupuestos/cosidotapablanda/_lineasPresupuestoItems.js');
}
function tiradasAlternativas_js()
{
$this->response->setHeader('Content-Type', 'text/javascript');
return view('themes/vuexy/form/presupuestos/admin/_tiradasAlternativasItems.js');
return view('themes/vuexy/form/presupuestos/cosidotapablanda/_tiradasAlternativasItems.js');
}
function datosServicios_js()
{
$this->response->setHeader('Content-Type', 'text/javascript');
return view('themes/vuexy/form/presupuestos/admin/_datosServiciosItems.js');
return view('themes/vuexy/form/presupuestos/cosidotapablanda/_datosServiciosItems.js');
}
function datosEnvios_js()
{
$this->response->setHeader('Content-Type', 'text/javascript');
return view('themes/vuexy/form/presupuestos/admin/_datosEnvios.js');
return view('themes/vuexy/form/presupuestos/cosidotapablanda/_datosEnvios.js');
}
function resumenPresupuestos_js()
{
$this->response->setHeader('Content-Type', 'text/javascript');
return view('themes/vuexy/form/presupuestos/admin/_resumenPresupuestos.js');
return view('themes/vuexy/form/presupuestos/cosidotapablanda/_resumenPresupuestos.js');
}
function presupuestos_js()
{
$this->response->setHeader('Content-Type', 'text/javascript');
return view('themes/vuexy/form/presupuestos/admin/_presupuestos.js');
return view('themes/vuexy/form/presupuestos/cosidotapablanda/_presupuestos.js');
}
function presupuestoCliente_js()

View File

@ -21,22 +21,9 @@ class Language extends BaseController
public function getTranslation()
{
$translationFile = $this->request->getPost('translationFile');
$data = [];
if(is_array($translationFile)){
foreach($translationFile as $file){
$locale = $this->request->getPost('locale');
$path = "Language/{$locale}/$file.php";
$lang = require APPPATH.$path;
$data[$file] = $lang;
}
return json_encode($data);
}
else{
$locale = $this->request->getPost('locale');
$path = "Language/{$locale}/$translationFile.php";
$lang = require APPPATH.$path;
return json_encode($lang);
}
$locale = $this->request->getPost('locale');
$path = "Language/{$locale}/$translationFile.php";
$lang = require APPPATH.$path;
return json_encode($lang);
}
}

View File

@ -1,31 +0,0 @@
<?php
namespace App\Controllers\Logistica;
use App\Controllers\BaseController;
use App\Services\ImpresoraEtiquetaService;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;
class LogisticaController extends BaseController
{
protected ImpresoraEtiquetaService $impresoraEtiquetaService;
protected string $locale;
protected array $viewData;
public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
{
$this->impresoraEtiquetaService = service('impresora_etiqueta');
$this->locale = session()->get('lang');
parent::initController($request, $response, $logger);
}
public function print_test_label()
{
$etiquetaData = $this->impresoraEtiquetaService->test();
$responseMessage = $etiquetaData["status"] ? "OK" : "ERROR";
return $this->response->setJSON(["message" => $responseMessage, "data" => $etiquetaData, "status" => $etiquetaData["status"]]);
}
}

26
ci4/app/Controllers/My.php Executable file
View File

@ -0,0 +1,26 @@
<?php
namespace App\Controllers;
use App\Models\NotificationModel;
use App\Models\Usuarios\UserModel;
class My extends BaseController
{
private $user_model;
private $notification_model;
function __construct()
{
$this->user_model = new UserModel();
$this->notification_model = new NotificationModel();
}
public function index()
{
return redirect()->to('profile');
}
}

View File

@ -21,8 +21,6 @@ class PrintPresupuestos extends BaseController
$data['lp_Color'] = $lineasPresupuestoModel->getResourceColorForPdf($id_presupuesto)->get()->getRow();
$data['lp_Cubierta'] = $lineasPresupuestoModel->getResourceCubiertaForPdf($id_presupuesto)->get()->getRow();
$data['lp_Sobrecubierta'] = $lineasPresupuestoModel->getResourceSobrecubiertaForPdf($id_presupuesto)->get()->getRow();
$data['lp_Guardas'] = $lineasPresupuestoModel->getResourceGuardasForPdf($id_presupuesto)->get()->getRow();
$data['lp_Faja'] = $lineasPresupuestoModel->getResourceFajaForPdf($id_presupuesto)->get()->getRow();
$data['acabado_cubierta'] = $presupuestoAcabadosModel->getAcabadoCubiertaForPdf($id_presupuesto)->get()->getRow();
$data['acabado_sobrecubierta'] = $presupuestoAcabadosModel->getAcabadoSobrecubiertaForPdf($id_presupuesto)->get()->getRow();
$data['acabado_reserva_uvi'] = $presupuestoAcabadosModel->getAcabadoReservaUviForPdf($id_presupuesto)->get()->getRow();
@ -46,8 +44,6 @@ class PrintPresupuestos extends BaseController
$data['lp_Color'] = $lineasPresupuestoModel->getResourceColorForPdf($presupuesto_id)->get()->getRow();
$data['lp_Cubierta'] = $lineasPresupuestoModel->getResourceCubiertaForPdf($presupuesto_id)->get()->getRow();
$data['lp_Sobrecubierta'] = $lineasPresupuestoModel->getResourceSobrecubiertaForPdf($presupuesto_id)->get()->getRow();
$data['lp_Guardas'] = $lineasPresupuestoModel->getResourceGuardasForPdf($presupuesto_id)->get()->getRow();
$data['lp_Faja'] = $lineasPresupuestoModel->getResourceFajaForPdf($presupuesto_id)->get()->getRow();
$data['acabado_cubierta'] = $presupuestoAcabadosModel->getAcabadoCubiertaForPdf($presupuesto_id)->get()->getRow();
$data['acabado_sobrecubierta'] = $presupuestoAcabadosModel->getAcabadoSobrecubiertaForPdf($presupuesto_id)->get()->getRow();
$data['acabado_reserva_uvi'] = $presupuestoAcabadosModel->getAcabadoReservaUviForPdf($presupuesto_id)->get()->getRow();
@ -60,13 +56,8 @@ class PrintPresupuestos extends BaseController
$options->set('isRemoteEnabled', true);
$dompdf = new \Dompdf\Dompdf($options);
// Metodo que funciona en el docker
$css = file_get_contents(getenv('theme.path'). 'css/pdf.presupuesto.css');
$html = view(getenv('theme.path') . 'pdfs/presupuesto', $data);
$html = "<style>$css</style>" . $html;
$dompdf->loadHtml($html);
//$dompdf->loadHtml(view(getenv('theme.path') . 'pdfs/presupuesto', $data));
// Contenido HTML del documento
$dompdf->loadHtml(view(getenv('theme.path').'pdfs/presupuesto', $data));
// Establecer el tamaño del papel
$dompdf->setPaper('A4', 'portrait');

View File

@ -2,14 +2,10 @@
namespace App\Controllers\Pedidos;
use App\Controllers\BaseController;
use App\Controllers\Facturacion\Facturas;
use App\Entities\Pedidos\PedidoEntity;
use App\Models\Collection;
use App\Models\Pedidos\PedidoModel;
use App\Services\PedidoXMLService;
use App\Services\ProductionService;
use Hermawan\DataTables\DataTable;
use CodeIgniter\I18n\Time;
class Pedido extends \App\Controllers\BaseResourceController
{
@ -36,7 +32,6 @@ class Pedido extends \App\Controllers\BaseResourceController
$this->viewData['breadcrumb'] = [
['title' => lang("App.menu_pedidos"), 'route' => "javascript:void(0);", 'active' => false],
];
helper("time");
parent::initController($request, $response, $logger);
@ -71,7 +66,7 @@ class Pedido extends \App\Controllers\BaseResourceController
'pedidoEntity' => new PedidoEntity(),
'usingServerSideDataTable' => true,
'pageTitle' => lang('Pedidos.Pedidos'),
'estadoPedidos' => 'produccion',
'estadoPedidos' => 'activo',
['title' => lang("App.menu_pedidos"), 'route' => site_url('pedidos/todos'), 'active' => true]
];
@ -115,32 +110,6 @@ class Pedido extends \App\Controllers\BaseResourceController
return view(static::$viewPath . 'viewPedidosList', $viewData);
}
public function validacion()
{
$viewData = [
'currentModule' => static::$controllerSlug,
'pageSubTitle' => lang('Basic.global.ManageAllRecords', [lang('Pedidos.pedido')]),
'pedidoEntity' => new PedidoEntity(),
'usingServerSideDataTable' => true,
'pageTitle' => lang('Pedidos.Pedidos'),
'estadoPedidos' => 'validacion',
['title' => lang("App.menu_pedidos"), 'route' => site_url('pedidos/todos'), 'active' => true]
];
if (auth()->user()->inGroup('cliente-admin') || auth()->user()->inGroup('cliente-editor')) {
// Se obtiene el cliente ID a partir del usuario de la sesion
$model_user = model('App\Models\Usuarios\UserModel');
$user = $model_user->find(auth()->user()->id);
$clienteId = $user->cliente_id;
} else {
$clienteId = -1;
}
$viewData['cliente_id'] = $clienteId;
return view(static::$viewPath . 'viewPedidosList', $viewData);
}
public function cancelados()
{
$viewData = [
@ -211,8 +180,6 @@ class Pedido extends \App\Controllers\BaseResourceController
public function update($id = null){
$data = [];
if ($this->request->isAJAX()) {
$newTokenHash = csrf_hash();
$csrfTokenName = csrf_token();
@ -244,14 +211,6 @@ class Pedido extends \App\Controllers\BaseResourceController
$sanitizedData = $this->sanitized($postData, $nullIfEmpty);
foreach(array_keys($sanitizedData) as $key){
if(str_starts_with($key, "fecha_")){
$sanitizedData[$key . "_change_user_id"] =
auth()->user()->id;
$data[$key . "_change_user"] =
model('App\Models\Usuarios\UserModel')->getFullName(auth()->user()->id);
}
}
// JJO
$sanitizedData['user_updated_id'] = auth()->user()->id;
@ -278,9 +237,10 @@ class Pedido extends \App\Controllers\BaseResourceController
$id = $pedidoEntity->id ?? $id;
$message = lang('Basic.global.updateSuccess', [lang('Basic.global.record')]) . '.';
$data['error'] = 0;
$data[$csrfTokenName] = $newTokenHash;
$data = [
'error' => 0,
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
endif; // $noException && $successfulResult
@ -312,33 +272,11 @@ class Pedido extends \App\Controllers\BaseResourceController
$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):"";
$this->viewData['pedidoEntity'] = $pedidoEntity;
if($pedidoEntity->estado == 'validacion'){
$clienteModel = model('App\Models\Clientes\ClienteModel');
$pendiente = $clienteModel->getPendienteCobro($pedidoEntity->cliente_id);
$pendiente = $pendiente[0] + $pendiente[1];
$this->viewData['importePendiente'] = $pendiente;
}
$modelOrden = new \App\Models\OrdenTrabajo\OrdenTrabajoModel();
$orden = $modelOrden->where('pedido_id', $pedidoEntity->id)->first();
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);
}
@ -370,118 +308,29 @@ class Pedido extends \App\Controllers\BaseResourceController
$resourceData = $model_linea->getResource($searchValues, $estado, $cliente_id)->orderBy($order, $dir)->limit($length, $start)->get()->getResultObject();
$totalTirada = $model_linea->getSumOfTirada($searchValues, $estado, $cliente_id, $start, $length);
$total = $model_linea->getSumOfTotalAceptado($searchValues, $estado, $cliente_id, $start, $length);
$extra_data['total_tirada'] = $totalTirada;
$extra_data['total'] = $total;
$total2 = 0;
if($showTotal){
$total2 = $model_linea->getTotalOfTotalAceptado($estado);
$tirada2 = $model_linea->getTotalTirada($estado);
$extra_data['total2'] = $total2;
$extra_data['total_tirada2'] = $tirada2;
$total2 = $model_linea->getTotalOfTotalAceptado();
}
if($total2 != 0){
$total = "" . $total . " \n(" . $total2 . ")";
}
return $this->respond(Collection::datatable(
$resourceData,
$model_linea->getResource("", $estado)->countAllResults(),
$model_linea->getResource($searchValues, $estado)->countAllResults(),
"",
$extra_data
[
'total_tirada' => $totalTirada,
'total' => $total
]
));
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function tablaClienteForm()
{
$clienteId = $this->request->getGet('cliente_id') ?? -1;
$q = $this->model->getPedidosClienteForm($clienteId);
$searchValue = $this->request->getGet('fecha') ?? '';
if (!empty($searchValue)) {
// Extraer las fechas del formato "YYYY-MM-DD|YYYY-MM-DD"
$dates = explode('|', $searchValue);
if (count($dates) == 2) {
$q->where('p.created_at >=', $dates[0] . ' 00:00:00')
->where('p.created_at <=', $dates[1] . ' 23:59:59');
}
}
$searchValue = $this->request->getGet('fecha_entrega') ?? '';
if (!empty($searchValue)) {
// Extraer las fechas del formato "YYYY-MM-DD|YYYY-MM-DD"
$dates = explode('|', $searchValue);
if (count($dates) == 2) {
$q->where('p.fecha_entrega_real >=', $dates[0] . ' 00:00:00')
->where('p.fecha_entrega_real <=', $dates[1] . ' 23:59:59');
}
}
$result = DataTable::of($q)
->edit(
'fecha',
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"):""
)
->edit(
"estado",
function ($row, $meta) {
switch ($row->estado) {
case "validacion":
return lang('Pedidos.validacion');
case "produccion":
return lang('Pedidos.produccion');
case "finalizado":
return lang('Pedidos.finalizado');
case "enviado":
return lang('Pedidos.enviado');
case "cancelado":
return lang('Pedidos.cancelado');
default:
return '--'; // Debug
}
}
)
->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 obtenerTotalPedidosCliente($cliente_id){
$error = false;
$result = [
'total_impresion' => 0,
'total_maquetacion' => 0,
];
$data = $this->model
->where('presupuestos.cliente_id', $cliente_id)->whereNotIn('pedidos.estado', ['cancelado'])
->select('SUM(pedidos.total_precio) as total')
->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){
$result['total_impresion'] = round(floatval($data[0]->total), 2);
}
else{
$error = true;
}
$result['total'] = $result['total_impresion'] + $result['total_maquetacion'];
return $this->respond(['status' => $error?'error':'success', 'totales' => $result]);
}
public function obtenerPedidosForFacturas(){
if ($this->request->isAJAX()) {
@ -516,74 +365,6 @@ class Pedido extends \App\Controllers\BaseResourceController
}
}
public function addFactura(){
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){
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,
'estado' => 'borrador',
'estado_pago' => 'pendiente',
'fecha_factura_at' => date('Y-m-d'),
'cliente_nombre' => $datosFactura->cliente_nombre,
'cliente_cif' => $datosFactura->cliente_cif,
'cliente_pais' => $datosFactura->cliente_pais,
'cliente_address' => $datosFactura->cliente_direccion,
'cliente_cp' => $datosFactura->cliente_cp,
'cliente_cuidad' => $datosFactura->cliente_ciudad,
'cliente_provincia' => $datosFactura->cliente_provincia,
'user_created_id' => auth()->user()->id,
'user_updated_id' => auth()->user()->id
]);
$factura_id = $modelFactura->getInsertID();
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){
// 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([
'base' => $linea_added->base,
'total' => $linea_added->total,
'pendiente' => $linea_added->total,
])->where('id', $factura_id)->update();
return $this->respond(['status' => 'success', 'id' => $factura_id, 'message' => lang('Basic.global.success')]);
}else{
return $this->respond(['status' => 'error', 'message' => 'Error insertando lineas de factura']);
}
}
return $this->respond(['status' => 'error', 'message' => 'Error insertando factura']);
}else{
return $this->failUnauthorized('Invalid request', 403);
}
}
private function obtenerDatosFormulario(&$pedidoEntity){
$datos = $this->model->obtenerDatosForm($pedidoEntity->id);
@ -600,12 +381,6 @@ class Pedido extends \App\Controllers\BaseResourceController
$pedidoEntity->fecha_impresion_text = $pedidoEntity->fecha_impresion ? date('d/m/Y', strtotime($pedidoEntity->fecha_impresion)) : '';
$pedidoEntity->fecha_encuadernado_text = $pedidoEntity->fecha_encuadernado ? date('d/m/Y', strtotime($pedidoEntity->fecha_encuadernado)) : '';
$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_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)) : '';
}
public function get_xml_pedido($pedido_id)
{
@ -613,21 +388,5 @@ 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);
$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"]);
}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"]);
}
}
}

View File

@ -52,7 +52,7 @@ class Buscador extends \App\Controllers\BaseResourceController
// Breadcrumbs (IMN)
$this->viewData['breadcrumb'] = [
['title' => lang("App.menu_presupuestos"), 'route' => "javascript:void(0);", 'active' => false],
['title' => lang("App.menu_presupuesto_buscador"), 'route' => route_to("buscadorPresupuestosList"), 'active' => true]
['title' => lang("App.menu_presupuesto_buscador"), 'route' => site_url('presupuestos/buscador'), 'active' => true]
];
parent::initController($request, $response, $logger);
@ -62,8 +62,6 @@ class Buscador extends \App\Controllers\BaseResourceController
public function index()
{
checkPermission('presupuesto.menu');
$viewData = [
'currentModule' => static::$controllerSlug,
'pageSubTitle' => lang('Basic.global.ManageAllRecords', [lang('Presupuestos.presupuesto')]),

File diff suppressed because it is too large Load Diff

View File

@ -1,607 +0,0 @@
<?php
namespace App\Controllers\Presupuestos;
use App\Models\Presupuestos\ImportadorModel;
use App\Models\Clientes\ClienteModel;
use stdClass;
class Importadorpresupuestos extends \App\Controllers\BaseResourceController
{
protected $modelName = "ImportadorModel";
protected $format = 'json';
protected static $singularObjectName = 'Importadorpresupuesto';
protected static $singularObjectNameCc = 'Importadorpresupuesto';
protected static $pluralObjectName = 'ImportadorPresupuestos';
protected static $pluralObjectNameCc = 'Importadorpresupuestos';
protected static $controllerSlug = 'importadorpresupuestos';
protected static $viewPath = 'themes/vuexy/form/presupuestos/importador/';
protected $indexRoute = 'listaPresupuestos';
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
$this->viewData['usingSweetAlert'] = true;
$this->viewData = ['usingServerSideDataTable' => true]; // JJO
// Breadcrumbs
$this->viewData['breadcrumb'] = [
['title' => 'Importador de presupuestos', 'route' => "javascript:void(0);", 'active' => false]
];
$this->messageService = service('messages');
parent::initController($request, $response, $logger);
$this->model = new ImportadorModel();
}
public function index()
{
$viewData = [
'currentModule' => static::$controllerSlug,
'pageSubTitle' => lang('Basic.global.ManageAllRecords', [lang('Presupuestos.moduleName')]),
];
$this->viewData['serviciosAutomaticos'] = [
'ferro' => model('App\Models\Configuracion\ConfigVariableModel')->getVariable('id_servicio_ferro')->value,
'prototipo' => model('App\Models\Configuracion\ConfigVariableModel')->getVariable('id_servicio_prototipo')->value,
'ferro_digital' => model('App\Models\Configuracion\ConfigVariableModel')->getVariable('id_servicio_ferro_digital')->value,
];
$viewData = array_merge($this->viewData, $viewData); // merge any possible values from the parent controller class
return view(static::$viewPath . 'viewImportadorPresupuestos', $viewData);
}
public function getClientList()
{
$search = "";
if ($this->request->getGet("q")) {
$search = $this->request->getGet("q");
}
$dataOld = (new ImportadorModel())->getClientList();
$dataNew = (new ClienteModel())->getIdName($search);
$newKeys = array_map(fn($item) => $item->id . '_' . $item->name, $dataNew);
// Filtrar $dataOld para obtener solo los elementos comunes
$commonData = array_filter($dataOld, fn($item) => in_array($item->id . '_' . $item->name, $newKeys));
return $this->response->setJSON(array_values($commonData));
}
public function getPresupuestosList()
{
$search = "";
if ($this->request->getGet("q")) {
$search = $this->request->getGet("q");
}
$clienteId = $this->request->getGet("clienteId");
$data = (new ImportadorModel())->getPresupuestosList($clienteId, $search);
return $this->response->setJSON($data);
}
public function getEncuadernacionList()
{
$search = "";
if ($this->request->getGet("q")) {
$search = $this->request->getGet("q");
}
$model = model('App\Models\Configuracion\TipoPresupuestoModel');
$data = $model->getLibros($search);
return $this->response->setJSON($data);
}
public function getPresupuesto()
{
if ($this->request->isAJAX()) {
$id = $this->request->getGet("id") ?? 0;
if ($id == 0) {
return $this->failUnauthorized('Invalid request', 403);
}
$data = (new ImportadorModel())->getPresupuestoForImport($id);
$model_papel_formato = model('App\Models\Configuracion\PapelFormatoModel');
$papel_formato = $model_papel_formato->where('is_deleted', 0)->where('ancho>', 0)->findAll();
$papel_formato_id = null;
$papel_formato_texto = null;
foreach ($papel_formato as $formato) {
if ($data['datosGenerales']->papel_formato_personalizado) {
if ($formato->ancho == $data['datosGenerales']->papel_formato_personalizado_ancho && $formato->alto == $data['datosGenerales']->papel_formato_personalizado_alto) {
$papel_formato_id = $formato->id;
$papel_formato_texto = $formato->ancho . 'x' . $formato->alto;
break;
}
} else {
if ($formato->ancho == $data['datosGenerales']->papel_formato_ancho && $formato->alto == $data['datosGenerales']->papel_formato_alto) {
$papel_formato_id = $formato->id;
$papel_formato_texto = $formato->ancho . 'x' . $formato->alto;
break;
}
}
}
$datosGenerales = new \stdClass();
$datosGenerales->tirada = $data['datosGenerales']->tirada;
$datosGenerales->paginas = $data['datosGenerales']->paginas;
if ($papel_formato_id != null) {
$datosGenerales->papel_formato_personalizado = 0;
$datosGenerales->papel_formato_id = $papel_formato_id;
$datosGenerales->papel_formato_texto = $papel_formato_texto;
} else {
$datosGenerales->papel_formato_personalizado = 1;
if ($data['datosGenerales']->papel_formato_personalizado) {
$datosGenerales->papel_formato_ancho = $data['datosGenerales']->papel_formato_personalizado_ancho;
$datosGenerales->papel_formato_alto = $data['datosGenerales']->papel_formato_personalizado_alto;
} else {
$datosGenerales->papel_formato_ancho = $data['datosGenerales']->papel_formato_ancho;
$datosGenerales->papel_formato_alto = $data['datosGenerales']->papel_formato_alto;
}
}
$data['manipulados'] = array_map(fn($item) => $item->nombre, $data['manipulados']);
$data['acabados'] = array_map(fn($item) => $item->nombre, $data['acabados']);
$encuadernacion = $this->getEncuadernacion($data['manipulados']);
$lineas = $this->getLineasPresupuesto($data['lineas']);
$acabados = $this->getAcabados($data['acabados']);
$returnData = [
'success' => true,
'data' => [
'datosGenerales' => $datosGenerales,
'encuadernacion' => $encuadernacion,
'lineas' => $lineas,
'acabados' => $acabados,
'servicios' => [
'ferro' => $data['datosGenerales']->ferro,
'ferroDigital' => $data['datosGenerales']->ferro_digital,
'marcapaginas' => $data['datosGenerales']->marcapaginas,
'prototipo' => $data['datosGenerales']->prototipo
]
]
];
return $this->response->setJSON($returnData);
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
private function getEncuadernacion($manipulados)
{
$encuadernacion_values = [
'libroFresadoTapaDura' => 'Tapa Dura al Cromo Fresada',
'libroFresadoTapaBlanda' => 'Rústica Fresada',
'libroCosidoTapaDura' => 'Tapa Dura al Cromo Cosida Hilo',
'libroCosidoTapaBlanda' => 'Rústica Cosido Hilo vegetal',
'libroEspiralTapaDura' => 'Espiral',
'libroGrapado' => 'Cosido a caballete 2 grapas'
];
$encuadernacionOld = "";
$encuadernacion = new stdClass();
foreach ($manipulados as $manipulado) {
// check if manipulado is like strlower encuadernacion_values values
foreach ($encuadernacion_values as $valor) {
if (strpos(strtolower($manipulado), strtolower($valor)) !== false) {
$encuadernacionOld = $manipulado;
$key = array_search(strtolower($valor), array_map('strtolower', $encuadernacion_values));
$model = model('App\Models\Configuracion\TipoPresupuestoModel');
$encuadernacion = $model->select('id, codigo, encuadernacion')->where('codigo', $key)->first();
break;
}
}
}
return [
'encuadernacion' => $encuadernacion,
'encuadernacionOld' => $encuadernacionOld
];
}
private function getLineasPresupuesto($lineas)
{
$isHq = false;
foreach ($lineas as $linea) {
if ($linea->tipo == 'bn' || $linea->tipo == 'color' || $linea->tipo == 'rotativa') {
if ($linea->hq == 1) {
$isHq = true;
break;
}
}
}
$model_papelGenerico = model('App\Models\Configuracion\PapelGenericoModel');
$bn = new stdClass();
$color = new stdClass();
$cubierta = new stdClass();
$sobrecubierta = new stdClass();
foreach ($lineas as $linea) {
$newPapel = $model_papelGenerico->where('code', $linea->papel_code)->where('deleted_at', NULL)->first();
if ($linea->tipo == 'bn') {
$bn->papel_id = $linea->papel_id;
$bn->papel_nombre = $linea->papel_nombre;
$bn->papel_code = $linea->papel_code;
$bn->gramaje = $linea->gramaje;
$bn->paginas = $linea->paginas;
$bn->new_papel_id = $newPapel->id;
$bn->new_papel_nombre = $newPapel->nombre;
}
else if ($linea->tipo == 'color') {
$color->papel_id = $linea->papel_id;
$color->papel_nombre = $linea->papel_nombre;
$color->papel_code = $linea->papel_code;
$color->gramaje = $linea->gramaje;
$color->paginas = $linea->paginas;
$color->new_papel_id = $newPapel->id;
$color->new_papel_nombre = $newPapel->nombre;
}
else if ($linea->tipo == 'portada') {
$cubierta->papel_id = $linea->papel_id;
$cubierta->papel_nombre = $linea->papel_nombre;
$cubierta->papel_code = $linea->papel_code;
$cubierta->gramaje = $linea->gramaje;
$cubierta->paginas = $linea->paginas;
$cubierta->new_papel_id = $newPapel->id;
$cubierta->new_papel_nombre = $newPapel->nombre;
$cubierta->solapas = $linea->solapas_ancho;
}
else if ($linea->tipo == 'cubierta') {
$sobrecubierta->papel_id = $linea->papel_id;
$sobrecubierta->papel_nombre = $linea->papel_nombre;
$sobrecubierta->papel_code = $linea->papel_code;
$sobrecubierta->gramaje = $linea->gramaje;
$sobrecubierta->paginas = $linea->paginas;
$sobrecubierta->new_papel_id = $newPapel->id;
$sobrecubierta->new_papel_nombre = $newPapel->nombre;
$sobrecubierta->solapas = $linea->solapas_ancho;
}
else if ($linea->tipo == 'rotativa') {
if ($linea->rotativa_impresion == 'negro') {
$bn->papel_id = $linea->papel_id;
$bn->papel_nombre = $linea->papel_nombre;
$bn->papel_code = $linea->papel_code;
$bn->gramaje = $linea->gramaje;
$bn->paginas = $linea->paginas;
$bn->new_papel_id = $newPapel->id;
$bn->new_papel_nombre = $newPapel->nombre;
} else {
if ($linea->paginas == $linea->rotativa_pag_color) {
$color->papel_id = $linea->papel_id;
$color->papel_nombre = $linea->papel_nombre;
$color->papel_code = $linea->papel_code;
$color->gramaje = $linea->gramaje;
$color->paginas = $linea->paginas;
$color->new_papel_id = $newPapel->id;
$color->new_papel_nombre = $newPapel->nombre;
} else {
$bn->papel_id = $color->papel_id = $linea->papel_id;
$bn->papel_nombre = $color->papel_nombre = $linea->papel_nombre;
$bn->papel_code = $color->papel_code = $linea->papel_code;
$bn->gramaje = $color->gramaje = $linea->gramaje;
$color->paginas = $linea->rotativa_pag_color;
$bn->paginas = intval($linea->paginas) - intval($linea->rotativa_pag_color);
$bn->new_papel_id = $color->new_papel_id = $newPapel->id;
$bn->new_papel_nombre = $color->new_papel_nombre = $newPapel->nombre;
}
}
}
}
return [
'bn' => $bn,
'color' => $color,
'cubierta' => $cubierta,
'sobrecubierta' => $sobrecubierta,
'isHq' => $isHq
];
}
private function getAcabados($acabados){
$acabadoCubierta = "";
$reservaUVICubierta = false;
$acabadoSobrecubierta = "";
$reservaUVISobrecubierta = false;
$acabadoCubiertaOld = "";
$acabadoSobrecubiertaOld = "";
// por defecto, si pone portada o no pone ni portada ni cubierta, se asigna a la cubierta (portada en el antiguo)
foreach ($acabados as $acabado) {
if (strpos(strtolower($acabado), 'portada') !== false ||
(strpos(strtolower($acabado), 'portada') === false &&
strpos(strtolower($acabado), 'sobre cubierta') === false)) {
// palabras clave: brillo, mate, gofrado, antirayado, antirrayado, sandy, uvi para buscar en acabado
if(strpos(strtolower($acabado), 'brillo') !== false){
$acabadoCubierta = 1;
$acabadoCubiertaOld = strlen($acabadoCubiertaOld)==0? $acabado: $acabadoCubiertaOld . ', ' . $acabado;
} else if(strpos(strtolower($acabado), 'gofrado') !== false){
$acabadoCubierta = 6;
$acabadoCubiertaOld = strlen($acabadoCubiertaOld)==0? $acabado: $acabadoCubiertaOld . ', ' . $acabado;
} else if(strpos(strtolower($acabado), 'antirayado') !== false || strpos(strtolower($acabado), 'antirrayado') !== false){
$acabadoCubierta = 8;
$acabadoCubiertaOld = strlen($acabadoCubiertaOld)==0? $acabado: $acabadoCubiertaOld . ', ' . $acabado;
} else if(strpos(strtolower($acabado), 'sandy') !== false){
$acabadoCubierta = 9;
$acabadoCubiertaOld = strlen($acabadoCubiertaOld)==0? $acabado: $acabadoCubiertaOld . ', ' . $acabado;
} else if(strpos(strtolower($acabado), 'uvi') !== false){
$reservaUVICubierta = true;
$acabadoCubiertaOld = strlen($acabadoCubiertaOld)==0? $acabado: $acabadoCubiertaOld . ', ' . $acabado;
} else if(strpos(strtolower($acabado), 'mate') !== false){
$acabadoCubierta = 5;
$acabadoCubiertaOld = strlen($acabadoCubiertaOld)==0? $acabado: $acabadoCubiertaOld . ', ' . $acabado;
}
}
else if (strpos(strtolower($acabado), 'sobre cubierta') !== false) {
// palabras clave: brillo, mate, gofrado, antirayado, antirrayado, sandy, uvi para buscar en acabado
if(strpos(strtolower($acabado), 'brillo') !== false){
$acabadoSobrecubierta = 1;
$acabadoSobrecubiertaOld = strlen($acabadoSobrecubiertaOld)==0? $acabado: $acabadoSobrecubiertaOld . ', ' . $acabado;
} else if(strpos(strtolower($acabado), 'gofrado') !== false){
$acabadoSobrecubierta = 6;
$acabadoSobrecubiertaOld = strlen($acabadoSobrecubiertaOld)==0? $acabado: $acabadoSobrecubiertaOld . ', ' . $acabado;
} else if(strpos(strtolower($acabado), 'antirayado') !== false || strpos(strtolower($acabado), 'antirrayado') !== false){
$acabadoSobrecubierta = 8;
$acabadoSobrecubiertaOld = strlen($acabadoSobrecubiertaOld)==0? $acabado: $acabadoSobrecubiertaOld . ', ' . $acabado;
} else if(strpos(strtolower($acabado), 'sandy') !== false){
$acabadoSobrecubierta = 9;
$acabadoSobrecubiertaOld = strlen($acabadoSobrecubiertaOld)==0? $acabado: $acabadoSobrecubiertaOld . ', ' . $acabado;
} else if(strpos(strtolower($acabado), 'uvi') !== false){
$reservaUVISobrecubierta = true;
$acabadoSobrecubiertaOld = strlen($acabadoSobrecubiertaOld)==0? $acabado: $acabadoSobrecubiertaOld . ', ' . $acabado;
} else if(strpos(strtolower($acabado), 'mate') !== false){
$acabadoSobrecubierta = 5;
$acabadoSobrecubiertaOld = strlen($acabadoSobrecubiertaOld)==0? $acabado: $acabadoSobrecubiertaOld . ', ' . $acabado;
}
}
}
// Si es mate y lleva UVI, se cambia al servicio correspondiente
if($acabadoCubierta == 5 && $reservaUVICubierta){
$acabadoCubierta = 2;
}
if($acabadoSobrecubierta == 5 && $reservaUVISobrecubierta){
$acabadoSobrecubierta = 2;
}
$model = model('App\Models\Tarifas\Acabados\ServicioAcabadoModel');
$cubierta = new stdClass();
$cubierta->acabadoOld = $acabadoCubiertaOld;
$cubierta->acabado = $model->select('id as id, nombre as name')->where('id', $acabadoCubierta)->first();
$sobrecubierta = new stdClass();
$sobrecubierta->acabadoOld = $acabadoSobrecubiertaOld;
$sobrecubierta->acabado = $model->select('id as id, nombre as name')->where('id', $acabadoSobrecubierta)->first();
return [
'cubierta' => $cubierta,
'sobrecubierta' => $sobrecubierta,
];
}
public function importarPresupuesto(){
if($this->request->isAJAX()){
$presupuesto_id = $this->request->getPost('id');
$tipo_presupuesto_id = intval($this->request->getPost('encuadernacion') ?? 0);
$papel_formato_id = $this->request->getPost('papel_formato_id');
$papel_formato_personalizado = intval($this->request->getPost('papel_formato_personalizado') ?? 0);
$papel_formato_ancho = intval($this->request->getPost('papel_formato_ancho') ?? 0);
$papel_formato_alto = intval($this->request->getPost('papel_formato_alto') ?? 0);
if($papel_formato_personalizado){
$tamanio = array(
"ancho" => $papel_formato_ancho,
"alto" => $papel_formato_alto
);
}
else{
$medidas = model('App\Models\Configuracion\PapelFormatoModel')->select('ancho, alto')->where('id', $papel_formato_id)->first();
$tamanio = array(
"ancho" => $medidas->ancho,
"alto" => $medidas->alto
);
}
$isHq = intval($this->request->getPost('isHq') ?? 0);
$paginas_bn = intval($this->request->getPost('paginas_bn') ?? 0);
$paginas_color = intval($this->request->getPost('paginas_color') ?? 0);
$gramaje_bn = intval($this->request->getPost('gramaje_bn') ?? 0);
$gramaje_color = intval($this->request->getPost('gramaje_color') ?? 0);
$papel_bn = intval($this->request->getPost('papel_bn') ?? 0);
$papel_color = intval($this->request->getPost('papel_color') ?? 0);
$papel_interior_diferente = false;
if($papel_bn != $papel_color && $papel_bn != 0 && $papel_color != 0){
$papel_interior_diferente = true;
$papel_interior = array(
"negro" => $papel_bn,
"color" => $papel_color
);
$gramaje_interior = array(
"negro" => $gramaje_bn,
"color" => $gramaje_color
);
}
else{
$papel_interior = $papel_bn == 0 ? $papel_color : $papel_bn;
$gramaje_interior = $gramaje_bn == 0 ? $gramaje_color : $gramaje_bn;
}
$interior = array(
"papelInterior" => $papel_interior,
"gramajeInterior" => $gramaje_interior
);
$isColor = false;
if(intval($paginas_color)>0){
$isColor = true;
}
$tapaCubierta = model('App\Models\Configuracion\TipoPresupuestoModel')->
select("is_tapa_dura")->where('id', $tipo_presupuesto_id)->first();
$tapaCubierta = $tapaCubierta->is_tapa_dura == 0 ? "tapaBlanda" : "tapaDura";
$cubierta = array(
"carasImpresion" => intval($this->request->getPost('paginas_cubierta') ?? 0),
"tipoCubierta" => $tapaCubierta,
"papelCubierta" => intval($this->request->getPost('papel_cubierta') ?? 0),
"gramajeCubierta" => intval($this->request->getPost('gramaje_cubierta') ?? 0),
"acabado" => intval($this->request->getPost('acabado_cubierta') ?? 0),
);
$solapas_cubierta = intval($this->request->getPost('solapas_cubierta') ?? 0);
if($solapas_cubierta>0){
$cubierta["solapas"] = 1;
$cubierta["tamanioSolapas"] = $solapas_cubierta;
}
else{
$cubierta["solapas"] = 0;
}
$sobrecubierta = intval($this->request->getPost('sobrecubierta') ?? 0);
if($sobrecubierta>0){
$sobrecubierta = array(
"papel" => intval($this->request->getPost('papel_sobrecubierta') ?? 0),
"gramaje" => intval($this->request->getPost('gramaje_sobrecubierta') ?? 0),
"solapas" => intval($this->request->getPost('solapas_sobrecubierta') ?? 0),
"acabado" => intval($this->request->getPost('acabado_sobrecubierta') ?? 0),
);
// para corregir el fallo de un presupuesto sin solapas en sobrecubierta
if($sobrecubierta["solapas"] == 0){
$sobrecubierta["solapas"] = 80;
}
}
else{
$sobrecubierta = false;
}
$datosSave = model('App\Models\Presupuestos\ImportadorModel')->getDatosGuardar($presupuesto_id);
$direcciones = model('App\Models\Presupuestos\ImportadorModel')->getDirecciones($presupuesto_id);
$direcciones = (array) $direcciones;
$direcciones = array_map(fn($item) => (array) $item, $direcciones);
$direccionesToSend = [];
foreach($direcciones as $direccion){
$direccion['pais_id'] =
model('App\Models\Configuracion\PaisModel')->select('id')->like('nombre', $direccion['pais'])->first()->id;
$tempData = [];
$tempData['direccion'] = $direccion;
$tempData['entregaPalets'] = 0;
$tempData['unidades'] = $direccion['unidades'];
array_push($direccionesToSend, $tempData);
}
$datos = array(
"tirada" => array(intval($this->request->getPost('tirada') ?? 0)),
"selectedTirada" => intval($this->request->getPost('tirada') ?? 0),
"paginas" => intval($this->request->getPost('paginas') ?? 0),
"tamanio" => $tamanio,
"tipo_presupuesto_id" => $tipo_presupuesto_id,
"clienteId" => intval($this->request->getPost('cliente_id') ?? 0),
"isColor" => $isColor,
"isHq" => $isHq,
"papelInteriorDiferente" => $papel_interior_diferente,
"paginasColor" => $paginas_color,
"paginasCuadernillo" => 32,
"interior" => $interior,
"cubierta" => $cubierta,
"sobrecubierta" => $sobrecubierta,
"guardas" => false,
"faja" => 0,
"servicios" => $this->request->getPost('servicios') ?? [],
"datosCabecera" => [
"titulo" => $datosSave->titulo ?? "",
"autor" => $datosSave->autor ?? "",
"coleccion" => $datosSave->coleccion ?? "",
"isbn" => $datosSave->isbn ?? "",
"referenciaCliente" => $datosSave->referenciaCliente ?? ""
],
'entrega_taller' => $datosSave->entrega_taller,
'direcciones' => $direccionesToSend
);
$value = (new Presupuestocliente())->guardar($datos);
if(isset($value['sk_id'])){
$texto_comments = '[PRESUPUESTO IMPORTADO ' . $presupuesto_id . ' - ERP ANTIGUO]' . PHP_EOL .
'------------------------------------------------------------------------------------------' . PHP_EOL;
$presupuesto_model = model('App\Models\Presupuestos\PresupuestoModel');
$presupuesto_model->update($value['sk_id'], [
'comentarios_cliente' => strlen($datosSave->comentarios_cliente)>0?$texto_comments . $datosSave->comentarios_cliente:"",
'comentarios_safekat' => strlen($datosSave->comentarios_safekat)>0? $texto_comments . $datosSave->comentarios_safekat:"",
]);
$returnData = [
'success' => true,
'id' => $value['sk_id']
];
}
else{
$returnData = [
'success' =>false,
];
}
return $this->response->setJSON($returnData);
}
else{
return $this->failUnauthorized('Invalid request', 403);
}
}
}

View File

@ -1,5 +1,4 @@
<?php
namespace App\Controllers\Presupuestos;
<?php namespace App\Controllers\Presupuestos;
use App\Controllers\BaseResourceController;
@ -10,7 +9,7 @@ use App\Models\Collection;
use App\Models\Presupuestos\PresupuestoAcabadosModel;
class Presupuestoacabados extends \App\Controllers\BaseResourceController
{
@ -38,18 +37,19 @@ class Presupuestoacabados extends \App\Controllers\BaseResourceController
public function edit($requestedId = null)
{
if ($requestedId == null):
if ($requestedId == null) :
return;
endif;
$postData = $this->request->getJSON();
if (count($postData->datos) > 0) {
if(count($postData->datos)>0){
$this->model->deleteServiciosNotInArray($requestedId, $postData->datos);
} else {
}
else{
$this->model->deleteAllServicios($requestedId);
}
if (count($postData->datos) > 0) {
if(count($postData->datos)>0){
$this->model->updateTarifas($requestedId, $postData->datos);
}
@ -58,74 +58,41 @@ class Presupuestoacabados extends \App\Controllers\BaseResourceController
$data = [
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
}
public function update($requestedId = null)
{
if ($requestedId == null):
if ($requestedId == null) :
return;
endif;
$postData = $this->request->getPost();
$datos_tarifas = $postData['datos'] ?? [];
$tirada = $postData['tirada'] ?? 0;
$POD = model('App\Models\Configuracion\ConfigVariableModel')->getVariable('POD')->value;
$result = $this->getServiciosAcabados($datos_tarifas, $tirada, $POD);
$postData = $this->request->getJSON();
$tarifas = array_column($postData->datos, 'tarifa_id');
$tirada = $postData->tirada ?? 0;
$POD = $postData->POD ?? 0;
$result = [];
if(count($tarifas)>0){
foreach ($tarifas as $tarifa){
$values = $this->model->getPrecioTarifa($tarifa, $tirada, $POD);
array_push($result, $values);
}
}
$newTokenHash = csrf_hash();
$csrfTokenName = csrf_token();
$data = [
'lineas' => $result,
'lines' => $result,
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
}
public function getServiciosAcabados($datos_tarifas, $tirada, $POD)
{
$model = model('App\Models\Presupuestos\PresupuestoAcabadosModel');
$result = [];
if (count($datos_tarifas) > 0) {
foreach ($datos_tarifas as $tarifa) {
$proveedor = $tarifa['proveedor_id'] == '' ? -1 : $tarifa['proveedor_id'];
$values = $model->getPrecioTarifa($tarifa['tarifa_id'], $tirada, $proveedor, $POD);
$values[0]->cubierta = $tarifa['cubierta'] ?? 0;
$values[0]->sobrecubierta = $tarifa['sobrecubierta'] ?? 0;
$values[0]->faja = $tarifa['faja'] ?? 0;
array_push($result, $values[0]);
}
}
return $result;
}
public function cargar()
{
if ($this->request->isAJAX()) {
$presupuesto_id = $this->request->getGet('presupuesto_id') ?? null;
$rows = $this->model->getResource($presupuesto_id)->get()->getResultObject();
$newTokenHash = csrf_hash();
$csrfTokenName = csrf_token();
$data = [
'rows' => $rows,
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function getRowValues()
public function datatable()
{
if ($this->request->isAJAX()) {
$reqData = $this->request->getPost();
@ -133,37 +100,15 @@ class Presupuestoacabados extends \App\Controllers\BaseResourceController
$tarifa_acabado_id = $reqData['tarifa_acabado_id'] ?? 0;
$tirada = $reqData['tirada'] ?? 0;
$proveedor_id = $reqData['proveedor_id'] ?? -1;
$POD = model('App\Models\Configuracion\ConfigVariableModel')->getVariable('POD')->value;
$isTarifa = $reqData['isTarifa'] ?? 0;
$POD = $reqData['POD'] ?? 0;
$newTokenHash = csrf_hash();
$csrfTokenName = csrf_token();
$data = [];
if ($isTarifa == 1) {
$values = $this->model->getPrecioTarifa($tarifa_acabado_id, $tirada, $proveedor_id, $POD);
$values[0]->tarifa_id = $tarifa_acabado_id;
array_push($data, $values[0]);
}
else {
$model = model('App\Models\Tarifas\Acabados\TarifasAcabadoServiciosAcabadoModel');
$tarifas = $model->getTarifasForServicio($tarifa_acabado_id);
foreach ($tarifas as $tarifa) {
$values = $this->model->getPrecioTarifa($tarifa, $tirada, $proveedor_id, $POD);
$values[0]->tarifa_id = $tarifa;
array_push($data, $values[0]);
}
}
//$values = $this->model->getPrecioTarifa($tarifa_acabado_id, $tirada, $proveedor_id, $POD);
$values = $this->model->getPrecioTarifa($tarifa_acabado_id, $tirada, $proveedor_id, $POD);
$data = [
'values' => $data,
'values' => $values,
$csrfTokenName => $newTokenHash
];
@ -174,63 +119,17 @@ class Presupuestoacabados extends \App\Controllers\BaseResourceController
}
}
public function getAcabados()
{
if ($this->request->isAJAX()) {
$cubierta = $this->request->getGet("cubierta") ?? 0;
$sobrecubierta = $this->request->getGet("sobrecubierta") ?? 0;
$cliente = $this->request->getGet("cliente") ?? 0;
$model = model('App\Models\Tarifas\Acabados\ServicioAcabadoModel');
$query = $model->builder()->select(
[
"id",
"nombre as name"
]
)
->where("servicios_acabado.deleted_at", null);
if ($cubierta == 1) {
$query->where("servicios_acabado.acabado_cubierta", 1);
} else if ($sobrecubierta == 1) {
$query->where("servicios_acabado.acabado_sobrecubierta", 1);
}
if ($cliente == 1) {
$query->where("servicios_acabado.mostrar_en_presupuesto_cliente", 1);
}
if ($this->request->getGet("q")) {
$query->groupStart()
->orLike("servicios_acabado.nombre", $this->request->getGet("q"))
->groupEnd();
}
$items = $query->get()->getResultObject();
// add a custom item at the beginning
$customItem = new \stdClass;
$customItem->id = 0;
$customItem->name = "Ninguno";
array_unshift($items, $customItem);
return $this->response->setJSON($items);
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function menuItems()
{
if ($this->request->isAJAX()) {
$reqData = $this->request->getPost();
try {
try{
$tarifa_id = $reqData['tarifa_id'] ?? -1;
$tirada = $reqData['tirada'] ?? 0;
$newTokenHash = csrf_hash();
$csrfTokenName = csrf_token();
@ -241,19 +140,19 @@ class Presupuestoacabados extends \App\Controllers\BaseResourceController
$csrfTokenName => $newTokenHash
];
} catch (Exception $e) {
}
catch(Exception $e){
$data = [
'error' => $e,
$csrfTokenName => $newTokenHash
];
} finally {
}
finally{
return $this->respond($data);
}
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -44,7 +44,7 @@ class Presupuestodirecciones extends \App\Controllers\BaseResourceController
$att = $reqData['att'] ?? "";
$email = $reqData['email'] ?? "";
$direccion = $reqData['direccion'] ?? "";
$pais_id = $reqData['pais_id'] ?? -1;
$pais_id = $reqData['paisId'] ?? -1;
$provincia = $reqData['provincia'] ?? "";
$municipio = $reqData['municipio'] ?? "";
$cp = $reqData['cp'] ?? "";
@ -145,7 +145,6 @@ class Presupuestodirecciones extends \App\Controllers\BaseResourceController
$reqData = $this->request->getJSON();
if($reqData->tipo=='get_tarifa'){
$peso = $reqData->peso ?? 0;
$paisId = $reqData->paisId ?? 0;
$cp = $reqData->cp ?? 0;

View File

@ -1,5 +1,4 @@
<?php
namespace App\Controllers\Presupuestos;
<?php namespace App\Controllers\Presupuestos;
use App\Controllers\BaseResourceController;
@ -10,7 +9,7 @@ use App\Models\Presupuestos\PresupuestoEncuadernacionesModel;
use DataTables\Editor;
use DataTables\Editor\Field;
use DataTables\Editor\Validate;
class Presupuestoencuadernaciones extends \App\Controllers\BaseResourceController
{
@ -26,7 +25,7 @@ class Presupuestoencuadernaciones extends \App\Controllers\BaseResourceControlle
protected static $viewPath = 'themes/vuexy/form/presupuestos/';
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
parent::initController($request, $response, $logger);
@ -36,19 +35,20 @@ class Presupuestoencuadernaciones extends \App\Controllers\BaseResourceControlle
public function edit($requestedId = null)
{
if ($requestedId == null):
if ($requestedId == null) :
return;
endif;
$postData = $this->request->getJSON();
$tarifas = array_column($postData->datos, 'tarifa_id');
if (count($tarifas) > 0) {
if(count($tarifas)>0){
$this->model->deleteServiciosNotInArray($requestedId, $tarifas);
} else {
}
else{
$this->model->deleteAllServicios($requestedId);
}
if (count($tarifas) > 0) {
if(count($tarifas)>0){
$this->model->updateTarifas($requestedId, $postData->datos);
}
@ -57,7 +57,7 @@ class Presupuestoencuadernaciones extends \App\Controllers\BaseResourceControlle
$data = [
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
}
@ -65,48 +65,38 @@ class Presupuestoencuadernaciones extends \App\Controllers\BaseResourceControlle
{
$tarifaModel = model('App\Models\Tarifas\TarifaEncuadernacionModel');
if ($requestedId == null):
if ($requestedId == null) :
return;
endif;
$postData = $this->request->getPost();
$datos_tarifas = $postData['datos'] ?? [];
$tirada = $postData['tirada'] ?? 0;
$paginas = $postData['paginas'] ?? 0;
$POD = model('App\Models\Configuracion\ConfigVariableModel')->getVariable('POD')->value;
$ancho = $postData['ancho'] ?? 0;
$alto = $postData['alto'] ?? 0;
$result = $this->getServiciosEncuadernacion($datos_tarifas, $tirada, $paginas, $ancho, $alto, $POD);
$postData = $this->request->getJSON();
$tarifas = array_column($postData->datos, 'tarifa_id');
$tirada = $postData->tirada ?? 0;
$paginas = $postData->paginas ?? 0;
$POD = $postData->POD ?? 0;
$ancho = $postData->ancho ?? 0;
$alto = $postData->alto ?? 0;
$result = [];
if(count($tarifas)>0){
foreach ($tarifas as $tarifa){
if($tarifaModel->isTarifaPorHoras($tarifa)){
$values = $this->model->getPrecioTarifaHoras($tarifa, $paginas, $tirada, -1, $POD);
}else{
$values = $this->model->getPrecioTarifa($tarifa, $paginas, $tirada, $ancho, $alto, -1, $POD);
}
array_push($result, $values);
}
}
$newTokenHash = csrf_hash();
$csrfTokenName = csrf_token();
$data = [
'lineas' => $result,
'lines' => $result,
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
}
public function getServiciosEncuadernacion($datos_tarifas, $tirada, $paginas, $ancho, $alto, $POD)
{
$result = [];
$tarifaModel = model('App\Models\Tarifas\TarifaEncuadernacionModel');
$model = model('App\Models\Presupuestos\PresupuestoEncuadernacionesModel');
if (count($datos_tarifas) > 0) {
foreach ($datos_tarifas as $tarifa) {
if ($tarifaModel->isTarifaPorHoras($tarifa['tarifa_id'])) {
$values = $model->getPrecioTarifaHoras($tarifa['tarifa_id'], $paginas, $tirada, -1, $POD);
} else {
$values = $model->getPrecioTarifa($tarifa['tarifa_id'], $paginas, $tirada, $ancho, $alto, -1, $POD);
}
array_push($result, $values[0]);
}
}
return $result;
return $this->respond($data);
}
@ -115,127 +105,96 @@ class Presupuestoencuadernaciones extends \App\Controllers\BaseResourceControlle
if ($this->request->isAJAX()) {
$reqData = $this->request->getPost();
$tipo = $reqData['tipo'] ?? null;
if (is_null($tipo) || $tipo == 'tarifa') {
if(is_null($tipo) || $tipo=='tarifa'){
$tarifa_encuadernacion_id = $reqData['tarifa_encuadernacion_id'] ?? 0;
$proveedor_id = $reqData['proveedor_id'] ?? 0;
} else {
}
else{
$solapas = $reqData['solapas'] ?? 0;
}
$paginas = $reqData['paginas'] ?? 0;
$tirada = $reqData['tirada'] ?? 0;
$ancho = $reqData['ancho'] ?? 0;
$alto = $reqData['alto'] ?? 0;
$POD = $reqData['POD'] ?? 0;
$paginas_cuadernillo = $reqData['paginas_por_cuadernillo'] ?? null;
$newTokenHash = csrf_hash();
$csrfTokenName = csrf_token();
$tarifaModel = model('App\Models\Tarifas\TarifaEncuadernacionModel');
if (is_null($tipo)) {
if ($tarifaModel->isTarifaPorHoras($tarifa_encuadernacion_id)) {
if(is_null($tipo)){
if($tarifaModel->isTarifaPorHoras($tarifa_encuadernacion_id)){
$values = $this->model->getPrecioTarifaHoras($tarifa_encuadernacion_id, $paginas, $tirada, $proveedor_id, $POD, $paginas_cuadernillo);
} else {
}else{
$values = $this->model->getPrecioTarifa($tarifa_encuadernacion_id, $paginas, $tirada, $ancho, $alto, $proveedor_id, $POD);
}
} else if ($tipo == 'tarifa') {
if ($tarifaModel->isTarifaPorHoras($tarifa_encuadernacion_id)) {
}
else if($tipo=='tarifa'){
if($tarifaModel->isTarifaPorHoras($tarifa_encuadernacion_id)){
$values = $this->model->getPrecioTarifaHoras($tarifa_encuadernacion_id, $paginas, $tirada, -1, $POD);
} else {
}
else{
$values = $this->model->getPrecioTarifa($tarifa_encuadernacion_id, $paginas, $tirada, $ancho, $alto, -1, $POD);
}
} else {
}
else{
$tipo_impresion_id = $reqData['tipo_impresion_id'] ?? 4;
$values = $this->model->initPresupuesto($tipo_impresion_id, $solapas, $tirada, $paginas, $ancho, $alto, $POD);
}
$data = [
'values' => $values,
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function getRowValues()
{
if ($this->request->isAJAX()) {
$tarifaModel = model('App\Models\Tarifas\TarifaEncuadernacionModel');
$reqData = $this->request->getPost();
$tarifa_enc_id = $reqData['tarifa_enc_id'] ?? 0;
$tirada = $reqData['tirada'] ?? 0;
$paginas = $reqData['paginas'] ?? 0;
$ancho = $reqData['ancho'] ?? 0;
$alto = $reqData['alto'] ?? 0;
$proveedor_id = $reqData['proveedor_id'] ?? -1;
$paginas_cuadernillo = $reqData['paginas_por_cuadernillo'] ?? 32;
$POD = model('App\Models\Configuracion\ConfigVariableModel')->getVariable('POD')->value;
$newTokenHash = csrf_hash();
$csrfTokenName = csrf_token();
if ($tarifaModel->isTarifaPorHoras($tarifa_enc_id)) {
$values = $this->model->getPrecioTarifaHoras($tarifa_enc_id, $paginas, $tirada, $proveedor_id, $POD, $paginas_cuadernillo);
} else {
$values = $this->model->getPrecioTarifa($tarifa_enc_id, $paginas, $tirada, $ancho, $alto, $proveedor_id, $POD);
}
$data = [
'values' => $values,
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function menuItems()
{
if ($this->request->isAJAX()) {
$reqData = $this->request->getPost();
try {
try{
$tarifa_id = $reqData['tarifa_id'] ?? -1;
$paginas = $reqData['paginas'] ?? 0;
$tirada = $reqData['tirada'] ?? 0;
$ancho = $reqData['ancho'] ?? 0;
$alto = $reqData['alto'] ?? 0;
$paginas_cuadernillo = $reqData['paginas_por_cuadernillo'] ?? 32;
//$searchStr = goSanitize($this->request->getPost('searchTerm'))[0];
$newTokenHash = csrf_hash();
$csrfTokenName = csrf_token();
$menu = $this->model->getProveedoresForSelector($tarifa_id, $paginas, $tirada, $ancho, $alto, $paginas_cuadernillo);
$menu = $this->model->getProveedoresForSelector($tarifa_id, $paginas, $tirada, $ancho, $alto);
$data = [
'menu' => $menu,
$csrfTokenName => $newTokenHash
];
} catch (Exception $e) {
}
catch(Exception $e){
$data = [
'error' => $e,
$csrfTokenName => $newTokenHash
];
} finally {
}
finally{
return $this->respond($data);
}
} else {
return $this->failUnauthorized('Invalid request', 403);
}

View File

@ -63,27 +63,6 @@ class Presupuestomanipulados extends \App\Controllers\BaseResourceController
return $this->respond($data);
}
public function getServicioSolapas(){
if($this->request->isAJAX()){
$servicio = model('App\Models\Configuracion\ConfigVariableModel')->getVariable('servicio_solapas')->value;
$newTokenHash = csrf_hash();
$csrfTokenName = csrf_token();
$data = [
'service' => $servicio,
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
}
else{
return $this->failUnauthorized('Invalid request', 403);
}
}
public function update($requestedId = null)
{
@ -91,51 +70,28 @@ class Presupuestomanipulados extends \App\Controllers\BaseResourceController
return;
endif;
$postData = $this->request->getPost();
$tarifas = $postData['datos'] ?? [];
$tirada = $postData['tirada'] ?? 0;
$POD = model('App\Models\Configuracion\ConfigVariableModel')->getVariable('POD')->value;
$result = $this->getServiciosManipulado($tarifas, $tirada, $POD);
$postData = $this->request->getJSON();
$tarifas = array_column($postData->datos, 'tarifa_id');
$tirada = $postData->tirada ?? 0;
$POD = $postData->POD ?? 0;
$result = [];
if(count($tarifas)>0){
foreach ($tarifas as $tarifa){
$values = $this->model->getPrecioTarifa($tarifa, $tirada, $POD);
array_push($result, $values);
}
}
$newTokenHash = csrf_hash();
$csrfTokenName = csrf_token();
$data = [
'lineas' => $result,
'lines' => $result,
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
}
public function getServiciosManipulado($datos_tarifas, $tirada, $POD)
{
$result = [];
$model = model('App\Models\Presupuestos\PresupuestoManipuladosModel');
if (count($datos_tarifas) > 0) {
foreach ($datos_tarifas as $tarifa) {
$tarifa_id = 0;
if(is_array($tarifa)){
//check if $tarifa['tarifa_manipulado_id'] exists
if(array_key_exists('tarifa_manipulado_id', $tarifa)){
$tarifa_id = $tarifa['tarifa_manipulado_id'];
}
else if(array_key_exists('tarifa_id', $tarifa)){
$tarifa_id = $tarifa['tarifa_id'];
}
}
else{
$tarifa_id = $tarifa;
}
$values = $model->getPrecioTarifa($tarifa_id, $tirada, $POD);
$values[0]->cubierta = $tarifa['cubierta'] ?? 0;
$values[0]->sobrecubierta = $tarifa['sobrecubierta'] ?? 0;
array_push($result, $values[0]);
}
}
return $result;
}
public function datatable()
@ -145,7 +101,7 @@ class Presupuestomanipulados extends \App\Controllers\BaseResourceController
$tarifa_manipulado_id = $reqData['tarifa_manipulado_id'] ?? 0;
$tirada = $reqData['tirada'] ?? 0;
$POD = model('App\Models\Configuracion\ConfigVariableModel')->getVariable('POD')->value;
$POD = $reqData['POD'] ?? 0;
$tipo = $reqData['tipo'] ?? null;
@ -173,29 +129,4 @@ class Presupuestomanipulados extends \App\Controllers\BaseResourceController
}
}
public function getRowValues()
{
if ($this->request->isAJAX()) {
$reqData = $this->request->getPost();
$tarifa_manipulado_id = $reqData['tarifa_manipulado_id'] ?? 0;
$tirada = $reqData['tirada'] ?? 0;
$POD = model('App\Models\Configuracion\ConfigVariableModel')->getVariable('POD')->value;
$newTokenHash = csrf_hash();
$csrfTokenName = csrf_token();
$values = $this->model->getPrecioTarifa($tarifa_manipulado_id, $tirada, $POD);
$data = [
'values' => $values,
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
}

View File

@ -86,21 +86,6 @@ class Presupuestopreimpresiones extends \App\Controllers\BaseResourceController
return $this->respond($data);
}
public function getServiciosPreimpresion($datos_tarifas)
{
$result = [];
$model = model('App\Models\Presupuestos\Presupuestopreimpresiones');
if (count($datos_tarifas) > 0) {
foreach ($datos_tarifas as $tarifa) {
$values = $model->getPrecioTarifa($tarifa);
array_push($result, $values[0]);
}
}
return $result;
}
public function datatable()
{
if ($this->request->isAJAX()) {
@ -125,47 +110,4 @@ class Presupuestopreimpresiones extends \App\Controllers\BaseResourceController
}
}
public function getRowValues()
{
if ($this->request->isAJAX()) {
$reqData = $this->request->getPost();
$tarifa_preimpresion_id = $reqData['tarifa_preimpresion_id'] ?? 0;
$newTokenHash = csrf_hash();
$csrfTokenName = csrf_token();
$values = $this->model->getPrecioTarifa($tarifa_preimpresion_id);
$data = [
'values' => $values,
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function cargar()
{
if($this->request->isAJAX()) {
$presupuesto_id = $this->request->getGet('presupuesto_id') ?? null;
$rows = $this->model->getResource($presupuesto_id)->get()->getResultObject();
$newTokenHash = csrf_hash();
$csrfTokenName = csrf_token();
$data = [
'rows' => $rows,
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
}

View File

@ -86,20 +86,6 @@ class Presupuestoserviciosextra extends \App\Controllers\BaseResourceController
return $this->respond($data);
}
public function getServiciosExtra($datos_tarifas)
{
$result = [];
$model = model('App\Models\Presupuestos\PresupuestoServiciosExtraModel');
if (count($datos_tarifas) > 0) {
foreach ($datos_tarifas as $tarifa) {
$values = $model->getPrecioTarifa($tarifa);
array_push($result, $values[0]);
}
}
return $result;
}
public function datatable()
{
if ($this->request->isAJAX()) {
@ -124,28 +110,4 @@ class Presupuestoserviciosextra extends \App\Controllers\BaseResourceController
}
}
public function getRowValues()
{
if ($this->request->isAJAX()) {
$reqData = $this->request->getPost();
$tarifa_extra_id = $reqData['tarifa_extra_id'] ?? 0;
$newTokenHash = csrf_hash();
$csrfTokenName = csrf_token();
$values = $this->model->getPrecioTarifa($tarifa_extra_id);
$data = [
'values' => $values,
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
}

View File

@ -82,23 +82,11 @@ class Presupuestotiradasalternativas extends \App\Controllers\BaseResourceContro
$newTokenHash = csrf_hash();
$csrfTokenName = csrf_token();
$id = $reqData['id'] ?? 0;
$json_data = $reqData['json_tiradas'] ?? null;
$json_data_acabados = $reqData['json_acabados'] ?? null;
$json_data_encuadernacion = $reqData['json_encuadernaciones'] ?? null;
$json_data_manipulado = $reqData['json_manipulado'] ?? null;
$json_data_preimpresion = $reqData['json_preimpresion'] ?? null;
$json_data_extra = $reqData['json_extra'] ?? null;
$cliente_id = $reqData['cliente_id'] ?? 0;
$faja_alto = $reqData['faja_alto'] ?? 0;
$solapas_faja = $reqData['solapas_faja'] ?? 0;
$tipo_impresion_id = $reqData['tipo_impresion_id'] ?? 4;
$tirada = $reqData['tirada'] ?? 0;
$values = [];
if ($json_data) {
@ -107,7 +95,7 @@ class Presupuestotiradasalternativas extends \App\Controllers\BaseResourceContro
foreach ($data as $linea) {
// Se obtienen los valores de cada linea para el calculo del precio
$datosPedido = (object) array(
$datosPedido = (object)array(
'paginas' => intval($linea['paginas']) ?? 0,
'tirada' => intval($reqData['tirada']) ?? 0,
'merma' => intval($reqData['merma']) ?? 0,
@ -127,29 +115,14 @@ class Presupuestotiradasalternativas extends \App\Controllers\BaseResourceContro
} else if ($tipo_impresion_id == 5 || $tipo_impresion_id == 7) {
$datosPedido->isCosido = false;
}
} else if ($linea['row_id'] == 'lp_sobrecubierta' || $linea['row_id'] == 'lp_cubierta' || $linea['row_id'] == 'lp_faja') {
$datosPedido->solapas = $reqData['solapas_cubierta'];
if ($linea['row_id'] == 'lp_faja') {
$datosPedido->solapas = 1;
$datosPedido->alto = $faja_alto;
} else if ($linea['row_id'] == 'lp_sobrecubierta') {
$datosPedido->solapas = $reqData['solapas_sobrecubierta'];
}
$datosPedido->solapas_ancho = $reqData['solapas_cubierta_ancho'];
if ($linea['row_id'] == 'lp_faja') {
$datosPedido->solapas_ancho = $solapas_faja;
} else if ($linea['row_id'] == 'lp_sobrecubierta') {
$datosPedido->solapas_ancho = $reqData['solapas_sobrecubierta_ancho'];
}
} else if ($linea['row_id'] == 'lp_sobrecubierta' || $linea['row_id'] == 'lp_cubierta') {
$datosPedido->solapas =
$linea['row_id'] == 'lp_cubierta' ? $reqData['solapas_cubierta'] : $reqData['solapas_sobrecubierta'];
$datosPedido->solapas_ancho =
$linea['row_id'] == 'lp_cubierta' ? $reqData['solapas_cubierta_ancho'] : $reqData['solapas_sobrecubierta_ancho'];
$datosPedido->lomo = $reqData['lomo'];
$type = 'lp_cubierta';
if ($linea['row_id'] == 'lp_sobrecubierta') {
$type = 'lp_sobrecubierta';
} else if ($linea['row_id'] == 'lp_faja') {
$type = 'lp_faja';
}
$type = $linea['row_id'] == 'lp_cubierta' ? 'cubierta' : 'sobrecubierta';
$datosPedido->anchoExteriores = PresupuestoService::getAnchoTotalExteriores($type, $tipo_impresion_id, $datosPedido);
$datosPedido->altoExteriores = PresupuestoService::getAltoTotalExteriores($type, $tipo_impresion_id, $datosPedido);
@ -171,24 +144,24 @@ class Presupuestotiradasalternativas extends \App\Controllers\BaseResourceContro
$uso = 'interior';
$tipo = strpos($linea['row_id'], "_bn") !== false ? 'negro' : 'color';
$paginas_negro = isset($linea['numPagColor']) ? intval($datosPedido->paginas) - intval($linea['numPagColor']) : 0;
$paginas_color = $linea['numPagColor'] ?? 0;
$paginas = (object) array(
$paginas_color = $linea['numPagColor'] ?? 0;
$paginas = (object)array(
'negro' => $paginas_negro,
'color' => $paginas_color,
);
$parametrosRotativa = (object) array(
$parametrosRotativa = (object)array(
'a_favor_fibra' => $datosPedido->a_favor_fibra,
'bnPages' => $paginas->negro,
'colorPages' => $paginas->color,
'bnPages' => $paginas->negro,
'colorPages' => $paginas->color,
'rotativa_gota_negro' => 0,
'rotativa_gota_color' => 0,
);
$parametrosRotativa->rotativa_gota_negro = floatval($linea['gotaNegro'] ?? 0);
$parametrosRotativa->rotativa_gota_color = floatval($linea['gotaColor'] ?? 0);
$parametrosRotativa->rotativa_negro = floatval($linea['cobNegro'] ?? 0);
$parametrosRotativa->rotativa_cyan = floatval($linea['cobCyan'] ?? 0);
$parametrosRotativa->rotativa_magenta = floatval($linea['cobMagenta'] ?? 0);
$parametrosRotativa->rotativa_amarillo = floatval($linea['cobAmarillo'] ?? 0);
$parametrosRotativa->rotativa_gota_negro = floatval($linea['gotaNegro']?? 0);
$parametrosRotativa->rotativa_gota_color = floatval($linea['gotaColor']?? 0);
$parametrosRotativa->rotativa_negro = floatval($linea['cobNegro'] ?? 0);
$parametrosRotativa->rotativa_cyan = floatval($linea['cobCyan'] ?? 0);
$parametrosRotativa->rotativa_magenta = floatval($linea['cobMagenta']?? 0);
$parametrosRotativa->rotativa_amarillo = floatval($linea['cobAmarillo']?? 0);
break;
case 'lp_cubierta':
$uso = 'cubierta';
@ -196,9 +169,6 @@ class Presupuestotiradasalternativas extends \App\Controllers\BaseResourceContro
case 'lp_sobrecubierta':
$uso = 'sobrecubierta';
break;
case 'lp_faja':
$uso = 'faja';
break;
case 'lp_guardas':
$uso = 'guardas';
break;
@ -210,7 +180,7 @@ class Presupuestotiradasalternativas extends \App\Controllers\BaseResourceContro
break;
}
if ($uso == 'cubierta' || $uso == 'sobrecubierta' || $uso == 'faja' || $uso == 'guardas') {
if ($uso == 'cubierta' || $uso == 'sobrecubierta' || $uso == 'guardas') {
$isColor = true;
$isHq = true;
$tipo = 'colorhq';
@ -224,14 +194,14 @@ class Presupuestotiradasalternativas extends \App\Controllers\BaseResourceContro
$datosTipolog = $linea['gotaNegro'] ?? null;
if (!is_null($datosTipolog)) {
$datosTipolog = [];
$data_temp = (object) array(
$data_temp = (object)array(
'negro' => floatval($linea['cobNegro'] ?? 0),
'cyan' => floatval($linea['cobCyan'] ?? 0),
'magenta' => floatval($linea['cobMagenta'] ?? 0),
'amarillo' => floatval($linea['cobAmarillo'] ?? 0),
'magenta' => floatval($linea['cobMagenta']?? 0),
'amarillo' => floatval($linea['cobAmarillo']?? 0),
'cg' => floatval($linea['cobCG'] ?? 0),
'gota_negro' => floatval($linea['gotaNegro'] ?? 0),
'gota_color' => floatval($linea['gotaColor'] ?? 0),
'gota_negro' => floatval($linea['gotaNegro']?? 0),
'gota_color' => floatval($linea['gotaColor']?? 0),
);
array_push($datosTipolog, $data_temp);
}
@ -243,13 +213,13 @@ class Presupuestotiradasalternativas extends \App\Controllers\BaseResourceContro
$datosLinea['datosPedido'] = $datosPedido;
$datosLinea['cliente_id'] = $cliente_id;
$datosLinea['papel'] = $papel;
if (isset($isColor))
$datosLinea['isColor'] = $isColor;
if (isset($opciones_papel))
if(isset($isColor))
$datosLinea['isColor'] = $isColor;
if(isset($opciones_papel))
$datosLinea['opciones_papel'] = $opciones_papel;
if (isset($parametrosRotativa))
if(isset($parametrosRotativa))
$datosLinea['parametrosRotativa'] = $parametrosRotativa;
if (isset($paginas))
if(isset($paginas))
$datosLinea['paginas'] = $paginas;
$datosLinea['maquina'] = $maquina;
$datosLinea['papel_generico'] = $papel_generico;
@ -287,149 +257,19 @@ class Presupuestotiradasalternativas extends \App\Controllers\BaseResourceContro
$linea_coste['total_coste'] +=
$linea_coste['fields']['precio_tinta'];
if (strpos($linea['row_id'], 'lp_rot') === 0) {
$linea_coste['total_coste'] +=
$linea_coste['fields']['total_corte'];
}
$linea_coste['total_coste'] +=
$linea_coste['fields']['total_corte'];
}
}
$linea_coste['total_margen'] = $linea_coste['fields']['margen_papel_pedido'] +
$linea_coste['fields']['margen_impresion_horas'] +
$linea_coste['fields']['margen_click_pedido'];
unset($linea_coste['fields']);
array_push($values, $linea_coste);
}
// Calculo de los servicios (presimpresion y extra no dependen de nada)
$servicios = (object) (['coste' => 0.0, 'margen' => 0.0]);
if ($json_data_acabados) {
$json_data_acabados = json_decode($json_data_acabados, true);
if (count($json_data_acabados) > 0) {
$acabados = new Presupuestoacabados();
$POD = (new \App\Models\Configuracion\ConfigVariableModel())->getVariable('POD')->value;
$result = $acabados->getServiciosAcabados($json_data_acabados, $reqData['tirada'], $POD);
if (count($result) > 0) {
foreach ($result as $servicio) {
$servicios->coste += round(floatval($servicio->total), 2);
$base = round(floatval($servicio->total / (1 + $servicio->margen / 100.0)), 2);
$base = round(floatval($base / $datosPedido->tirada) , 2)* $datosPedido->tirada;
$servicios->margen += round(floatval($servicio->total - $base), 2);
}
}
}
}
if ($json_data_encuadernacion) {
$json_data_encuadernacion = json_decode($json_data_encuadernacion, true);
if (count($json_data_encuadernacion) > 0) {
$encuadernacion = new Presupuestoencuadernaciones();
$POD = (new \App\Models\Configuracion\ConfigVariableModel())->getVariable('POD')->value;
$result = $encuadernacion->getServiciosEncuadernacion($json_data_encuadernacion, $reqData['tirada'], $reqData['paginas'], $reqData['ancho'], $reqData['alto'], $POD);
if (count($result) > 0) {
foreach ($result as $servicio) {
$servicios->coste += round(floatval($servicio->total), 2);
$base = round(floatval($servicio->total / (1 + $servicio->margen / 100.0)), 2);
$base = round(floatval($base / $datosPedido->tirada) , 2)* $datosPedido->tirada;
$servicios->margen += round(floatval($servicio->total - $base), 2);
}
}
}
}
if ($json_data_manipulado) {
$json_data_manipulado = json_decode($json_data_manipulado, true);
if (count($json_data_manipulado) > 0) {
$manipulados = new Presupuestomanipulados();
$POD = (new \App\Models\Configuracion\ConfigVariableModel())->getVariable('POD')->value;
$result = $manipulados->getServiciosManipulado($json_data_manipulado, $reqData['tirada'], $POD);
if (count($result) > 0) {
foreach ($result as $servicio) {
$servicios->coste += round(floatval($servicio->total), 2);
$base = round(floatval($servicio->total / (1 + $servicio->margen / 100.0)), 2);
$base = round(floatval($base / $datosPedido->tirada) , 2)* $datosPedido->tirada;
$servicios->margen += round(floatval($servicio->total - $base), 2);
}
}
}
}
if($json_data_preimpresion){
$json_data_preimpresion = json_decode($json_data_preimpresion, true);
if (count($json_data_preimpresion) > 0) {
$preimpresion = new Presupuestopreimpresiones();
$POD = (new \App\Models\Configuracion\ConfigVariableModel())->getVariable('POD')->value;
$result = $preimpresion->getServiciosPreimpresion($json_data_preimpresion);
if (count($result) > 0) {
foreach ($result as $servicio) {
$servicios->coste += round(floatval($servicio->total), 2);
$base = round(floatval($servicio->total / (1 + $servicio->margen / 100.0)), 2);
$base = round(floatval($base / $datosPedido->tirada) , 2)* $datosPedido->tirada;
$servicios->margen += round(floatval($servicio->total - $base), 2);
}
}
}
}
if($json_data_extra){
$json_data_extra = json_decode($json_data_extra, true);
if (count($json_data_extra) > 0) {
$extra = new Presupuestoserviciosextra();
$json_data_extra = array_map(function($item) {
return $item['tarifa_id'];
}, $json_data_extra);
$result = $extra->getServiciosExtra($json_data_extra);
if (count($result) > 0) {
foreach ($result as $servicio) {
$servicios->coste += round(floatval($servicio->precio), 2);
$base = round(floatval($servicio->precio / (1 + floatval($servicio->margen) / 100.0)), 2);
$base = round(floatval($base / $datosPedido->tirada) , 2)* $datosPedido->tirada;
$servicios->margen += round(floatval($servicio->precio - $base), 2);
}
}
}
}
$json_envios = $reqData['json_envios'] ?? null;
$coste_envio = 0.0;
$margen_envio = 0.0;
$tirada_base = floatval($reqData['tirada_base']);
$peso_libro = floatval($reqData['peso_libro']);
// el primer envio con la tirada base
$model = model('App\Models\Tarifas\TarifaEnvioModel');
$envios = $model->getTarifaEnvio(1, 18000, $tirada_base * $peso_libro / 1000.0, "cajas");
$resultado = $this->calcular_envio($envios, $tirada_base * $peso_libro / 1000.0);
$coste_envio += $resultado->coste;
$margen_envio += $resultado->margen;
if ($json_envios) {
$json_envios = json_decode($json_envios, true);
if (count($json_envios) > 0) {
//la primera linea es el envio base
for ($i = 1; $i < count($json_envios); $i++) {
$porcentaje = ($json_envios[$i]['cantidad']) / $tirada_base * 100.0;
$cantidad = floor($reqData['tirada'] * $porcentaje / 100.0);
$peso_envio = $cantidad * $peso_libro / 1000.0;
$paisId = $json_envios[$i]['pais_id'];
$cp = $json_envios[$i]['cp'];
$tipo_envio = $json_envios[$i]['entregaPieCalle'] == 1 ? 'palets' : 'cajas';
$model = model('App\Models\Tarifas\TarifaEnvioModel');
$envios = $model->getTarifaEnvio($paisId, $cp, $peso_envio, $tipo_envio);
$resultado = $this->calcular_envio($envios, $peso_envio);
$coste_envio += $resultado->coste;
$margen_envio += $resultado->margen;
}
}
}
} else {
$values = [];
}
@ -439,36 +279,8 @@ class Presupuestotiradasalternativas extends \App\Controllers\BaseResourceContro
$response[$csrfTokenName] = $newTokenHash;
$response['lineas'] = $values;
$response['servicios'] = $servicios;
$response['envios'] = (object) (['coste' => $coste_envio, 'margen' => $margen_envio]);
return $this->respond($response);
}
private function calcular_envio($envio, $peso_envio)
{
$coste_envio = 0.0;
$margen_envio = 0.0;
if (count(value: $envio) > 0) {
$envio = $envio[0];
if ($envio->id != null) {
if ($peso_envio > $envio->peso_max || floatval($envio->precio_max) == 0) {
$coste_envio += number_format(floatval($envio->precio_min) + ($peso_envio - floatval($envio->peso_min)) * floatval($envio->precio_adicional), 2);
}
// si no se calcula linealmente
else {
$m = (($envio->precio_max - $envio->precio_min) / ($envio->peso_max - $envio->peso_min));
$b = $envio->precio_max - $m * $envio->peso_max;
$coste_envio = number_format($m * $peso_envio + $b, 2);
}
$margen_envio += $coste_envio * $envio->margen / 100.0;
}
}
return (object) (['coste' => $coste_envio, 'margen' => $margen_envio]);
}
}

View File

@ -1,439 +1,50 @@
<?php
namespace App\Controllers\Produccion;
use App\Controllers\BaseController;
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\ProductionService;
use CodeIgniter\Files\File;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\I18n\Time;
use CodeIgniter\Validation\Validation;
use Config\LogoImpresion;
use Exception;
use Hermawan\DataTables\DataTable;
use Psr\Log\LoggerInterface;
class Ordentrabajo extends BaseController
{
protected $format = 'json';
protected array $viewData = [];
protected ProductionService $produccionService;
protected OrdenTrabajoModel $otModel;
protected OrdenTrabajoUser $otUserModel;
protected OrdenTrabajoTarea $otTarea;
protected UserModel $userModel;
protected Validation $validation;
protected static $viewPath = 'themes/vuexy/form/produccion/';
protected static $controllerSlug = "orden-trabajo";
protected $indexRoute = 'viewOrdenTrabajoList';
protected $indexRoutePlanning = 'ot/viewPlanningRotativa';
protected $editRoute = 'viewOrdenTrabajoEdit';
public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
{
$this->otModel = model(OrdenTrabajoModel::class);
$this->userModel = model(UserModel::class);
$this->produccionService = new ProductionService();
$this->otTarea = model(OrdenTrabajoTarea::class);
$this->validation = service("validation");
helper("time");
parent::initController($request, $response, $logger);
{
function __construct()
{
}
public function index()
{
// Breadcrumbs
$this->viewData['breadcrumb'] = [
['title' => lang("Produccion.ot"), 'route' => "javascript:void(0);", 'active' => false],
['title' => lang("Produccion.ots"), 'route' => site_url('produccion/ordentrabajo'), 'active' => true]
];
return view(static::$viewPath . $this->indexRoute, $this->viewData);
}
public function index_planning_rotativa()
{
// Breadcrumbs
$this->viewData['breadcrumb'] = [
['title' => lang("Produccion.ots"), 'route' => "javascript:void(0);", 'active' => false],
['title' => lang("Produccion.ots"), 'route' => site_url('produccion/ordentrabajo/planning/rotativa'), 'active' => true]
];
return view(static::$viewPath . $this->indexRoutePlanning, $this->viewData);
echo 'Orden trabajo';
}
public function get_orden_trabajo_summary($orden_trabajo_id)
{
try {
//code...
$summary = $this->produccionService->init($orden_trabajo_id)->getSummary();
return $this->response->setJSON($summary);
} catch (\Throwable $th) {
return $this->response->setStatusCode(500)->setJSON(["message" => $th->getMessage(), "error" => $th]);
}
}
public function add() {}
/**========================================================================
* UPDATES
*========================================================================**/
public function update_orden_trabajo()
{
$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"])->updateOrdenTrabajo($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);
}
}
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) {
$r = $this->produccionService->updateOrdenTrabajoTarea($bodyData["orden_trabajo_tarea_id"], $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);
}
}
public function update_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) {
$r = $this->produccionService->init($bodyData["orden_trabajo_id"])->updateOrdenTrabajoDate($bodyData);
return $this->response->setJSON(["message" => lang("App.global_alert_save_success"), "status" => $r["status"], "user" => $r["user"], "data" => $bodyData]);
} else {
return $this->response->setJSON(["errors" => $this->validation->getErrors()])->setStatusCode(400);
}
}
public function update_orden_trabajo_pedido_date()
{
try {
$bodyData = $this->request->getPost();
$r = $this->produccionService->init($bodyData["orden_trabajo_id"])->updateOrdenTrabajoPedidoDate($bodyData);
return $this->response->setJSON(["message" => lang("App.global_alert_save_success"), "status" => $r["status"], "user" => $r["user"], "data" => $bodyData]);
} catch (\Throwable $th) {
return $this->response->setJSON(["errors" => $th->getMessage(), "status" => false])->setStatusCode(500);
}
}
public function update_orden_trabajo_pedido()
{
try {
$bodyData = $this->request->getPost();
$r = $this->produccionService->init($bodyData["orden_trabajo_id"])->updateOrdenTrabajoPedido($bodyData);
return $this->response->setJSON(["message" => lang("App.global_alert_save_success"), "status" => $r, "data" => $bodyData]);
} catch (\Throwable $th) {
return $this->response->setJSON(["errors" => $th->getMessage(), "status" => false])->setStatusCode(500);
}
}
public function edit($orden_trabajo_id)
{
// Breadcrumbs
$this->viewData['breadcrumb'] = [
['title' => lang("Produccion.ot"), 'route' => site_url('produccion/ordentrabajo'), 'active' => false],
['title' => $this->otModel->find($orden_trabajo_id)->pedido()->presupuesto()->titulo, 'route' => site_url('produccion/ordentrabajo/edit/' . $orden_trabajo_id), 'active' => true]
];
$this->viewData["modelId"] = $orden_trabajo_id;
$this->produccionService->init($orden_trabajo_id);
$this->viewData["presupuesto"] = $this->produccionService->getPresupuesto();
$this->viewData["cliente"] = $this->produccionService->getCliente();
$this->viewData["ot"] = $this->produccionService->getOrdenTrabajo();
$this->viewData["user_dates"] = $this->produccionService->userDates();
$this->viewData["pedido_user_dates"] = $this->produccionService->pedidoUserDates();
return view(static::$viewPath . $this->editRoute, $this->viewData);
}
public function datatable()
{
$logo = config(LogoImpresion::class);
$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()])
->edit(
"fecha_encuadernado_at",
fn($q) => $q->fecha_encuadernado_at ? Time::createFromFormat("Y-m-d", $q->fecha_encuadernado_at)->format("d/m/Y") : ""
)
->add("action", 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());
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", $q->fecha_encuadernado_at)->format("d/m/Y") : ""
)
->add("action", fn($q) => $q->id)
->toJson(true);
}
public function datatable_ferro_pendiente()
{
$logo = config(LogoImpresion::class);
$q = $this->otModel->getDatatableQuery()->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()])
->edit(
"fecha_encuadernado_at",
fn($q) => $q->fecha_encuadernado_at ? Time::createFromFormat("Y-m-d", $q->fecha_encuadernado_at)->format("d/m/Y") : ""
)
->add("action", 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);
// 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()])
->edit(
"fecha_encuadernado_at",
fn($q) => $q->fecha_encuadernado_at ? Time::createFromFormat("Y-m-d", $q->fecha_encuadernado_at)->format("d/m/Y") : ""
)
->add("action", fn($q) => $q->id)
->toJson(true);
}
public function papel_gramaje_datatable()
public function delete()
{
$q = $this->produccionService->papelGramajeDatatableQuery();
return DataTable::of($q)
->edit("tiempoReal", fn($q) => $q->tiempoReal)
->add("action", fn($q) => ["title" => lang('Produccion.datatable.filter_by_paper'), 'data' => $q])
->toJson(true);
}
public function papel_pliego_datatable()
public function add()
{
$q = $this->produccionService->papelPliegoDatatableQuery();
return DataTable::of($q)
->edit("tiempoReal", fn($q) => $q->tiempoReal)
->add("action", fn($q) => ["title" => lang('Produccion.datatable.filter_by_paper'), 'data' => $q])
->toJson(true);
}
public function reset_tareas(int $orden_trabajo_id)
{
$r = $this->produccionService->init($orden_trabajo_id)->resetAllTareas();
return $this->response->setJSON(["message" => "Tareas reseteadas", "status" => $r]);
}
public function delete_tarea(int $orden_trabajo_tarea_id)
{
$r = $this->otTarea->delete($orden_trabajo_tarea_id);
return $this->response->setJSON(["message" => "Tarea eliminada", "states" => $r]);
}
public function tareas_datatable(int $orden_trabajo_id)
{
$q = $this->produccionService->init($orden_trabajo_id)->taskDatatableQuery($orden_trabajo_id);
// return $this->response->setJSON($q->get()->getResultArray());
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))
->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);
}
public function get_pdf($orden_trabajo_id)
{
return $this->produccionService->init($orden_trabajo_id)->getPdf();
}
public function upload_orden_trabajo_portada()
{
try {
$file = $this->request->getFile("portada_file");
$bodyData = $this->request->getPost();
$id = $bodyData["orden_trabajo_id"];
$r = null;
$fullpath = null;
if ($file->isValid() && !$file->hasMoved()) {
$fullpath = $file->store('ordenes_trabajo_portadas');
$otEntity = $this->otModel->find($id);
if ($otEntity->portada_path) {
if (file_exists($otEntity->full_path)) {
unlink($otEntity->full_path);
}
}
$r = $this->otModel->update($id, ["portada_path" => $fullpath]);
}
return $this->response->setJSON(["message" => "Portada subida", "data" => $r]);
} catch (\Throwable $th) {
if ($fullpath) {
delete_files($fullpath);
}
return $this->response->setJSON(["message" => "Portada error", "error" => $th->getMessage()])->setStatusCode(500);
}
}
public function delete_orden_trabajo_portada($orden_trabajo_id)
{
try {
helper('filesystem');
$otEntity = $this->otModel->find($orden_trabajo_id);
$pathActualFile = $otEntity->portada_path;
$fullPath = WRITEPATH . 'uploads/' . $pathActualFile;
if (file_exists($fullPath)) {
delete_files($fullPath);
}
$r = $this->otModel->update($otEntity->id, ["portada_path" => null]);
return $this->response->setJSON(["message" => "Portada eliminada", "data" => $r]);
} catch (\Throwable $th) {
return $this->response->setStatusCode(500)->setJSON(["message" => "Portada error", "error" => $th->getMessage()]);
}
}
public function get_portada_img($orden_trabajo_id)
{
try {
$ot = $this->otModel->find($orden_trabajo_id);
if ($ot->portada_path) {
$filePath = $ot->full_path;
if (file_exists($filePath)) {
$mimeType = mime_content_type($filePath);
return $this->response
->setHeader('Content-Type', $mimeType)
->setHeader('Content-Length', filesize($filePath))
->setBody(file_get_contents($filePath));
} else {
throw new Exception('File' . $ot->portada_path . ' does not exist');
}
} else {
return $this->response->setJSON(["message" => "Portada error", "error" => "No hay portada"])->setStatusCode(400);
}
} catch (\Throwable $th) {
return $this->response->setJSON(["message" => "Portada error", "error" => $th->getMessage()])->setStatusCode(500);
}
}
public function planning_rotativa_datatable()
public function edit()
{
$query = $this->produccionService->planningRotativaQueryDatatable();
return DataTable::of($query)
->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("metros_check", fn($q) => $q->otId)
->add("corte", fn($q) => ["otId" => $q->otId, "tipo_corte" => $this->produccionService->ordenTrabajoTareaCorte($q->otId)])
->add("action", fn($q) => ["data" => $q])
->toJson(true);
}
public function planning_plana_datatable()
public function cien()
{
$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 ])
->toJson(true);
echo 'Orden trabajo 100%';
}
public function select_maquina_planning_rot()
public function finalizado()
{
$q = $this->request->getGet('q');
$result = $this->produccionService->querySelectMaquinaPlanningRotativa($q);
return $this->response->setJSON($result);
echo 'Orden trabajo finalizado';
}
public function select_papel_planning_rot()
public function pendiente()
{
$q = $this->request->getGet('q');
$result = $this->produccionService->querySelectPapelPlanningRot($q);
return $this->response->setJSON($result);
}
public function select_maquina_planning_plana()
{
$q = $this->request->getGet('q');
$result = $this->produccionService->querySelectMaquinaPlanningPlana($q);
return $this->response->setJSON($result);
}
public function select_maquina_padre_planning_plana()
{
$q = $this->request->getGet('q');
$result = $this->produccionService->querySelectMaquinaPadrePlanningPlana($q);
return $this->response->setJSON($result);
}
public function select_papel_planning_plana()
{
$q = $this->request->getGet('q');
$result = $this->produccionService->querySelectPapelPlanningPlana($q);
return $this->response->setJSON($result);
}
public function tarea_toggle_corte($orden_trabajo_id)
{
$status = $this->produccionService->tareaUpdateMaquinaCorte($orden_trabajo_id);
return $this->response->setJSON(["message" => lang("App.global_alert_save_success"), "status" => $status]);
}
public function get_files()
{
$bodyData = $this->request->getPost();
$files = $this->produccionService->init($bodyData["orden_trabajo_id"])->getOtFiles();
$response = [];
foreach ($files as $key => $file) {
$file_ci4 = new File($file->file_path);
$response[] = [
"name" => $file->name,
"size" => $file_ci4->getSize(),
"hash" => $file->hash()
];
}
return json_encode($response);
}
public function upload_files()
{
try {
//code...
$otFiles = [];
$bodyData = $this->request->getPost();
$files = $this->request->getFileMultiple('file');
$ps = $this->produccionService->init($bodyData["orden_trabajo_id"]);
$existingFiles = json_decode($bodyData["oldFiles"]);
$ps->deleteOtFiles($existingFiles);
if ($files) {
$response = $ps->storeOtFiles($files);
} else {
$response = null;
}
return $this->response->setJSON([
"message" => lang("App.global_alert_save_success"),
"data" => $response,
"status" => true
]);
} catch (\Throwable $th) {
return $this->response->setJSON(
[
"message" => lang("App.global_alert_save_error"),
"data" => $th,
"error" => $th->getMessage(),
"status" => false
]
);
}
}
public function get_orden_trabajo_color_status(int $orden_trabajo_id)
{
$color = $this->produccionService->init($orden_trabajo_id)->getOtColorStatus();
return $this->response->setJSON(["color" => $color]);
echo 'Orden trabajo pendiente';
}
}

View File

@ -3,7 +3,7 @@
namespace App\Controllers;
use App\Models\Usuarios\UserModel;
use App\Models\UserModel;
class Profile extends BaseController
{

View File

@ -35,7 +35,6 @@ class Actividad extends BaseResourceController
public function index()
{
checkPermission('actividad.menu');
$viewData = [

View File

@ -0,0 +1,110 @@
<?php namespace App\Controllers\Sistema;
use App\Controllers\BaseResourceController;
use App\Models\Sistema\SettingsModel;
class Ajustes extends BaseResourceController
{
protected $modelName = SettingsModel::class;
protected $format = 'json';
protected static $controllerSlug = 'settings';
protected static $viewPath = 'themes/vuexy/form/settings/';
protected static string $formViewName = 'settingsForm';
protected static $singularObjectName = 'settings';
protected static $singularObjectNameCc = 'settings';
protected $indexRoute = 'ajustesList';
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
$this->viewData['pageTitle'] = lang('Provincias.moduleTitle');
$this->viewData['usingSweetAlert'] = true;
// Breadcrumbs (IMN)
$this->viewData['breadcrumb'] = [
['title' => lang("App.menu_configuration"), 'route' => "javascript:void(0);", 'active' => false],
['title' => lang("App.menu_settings"), 'route' => route_to('ajustesList'), 'active' => true]
];
parent::initController($request, $response, $logger);
}
public function settings()
{
$id = 1;
$settingsEntity = $this->model->find($id);
if (!$settingsEntity) :
$message = lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('Provincias.provincia')), $id]);
return $this->redirect2listView('sweet-error', $message);
endif;
if ($this->request->is('post')) :
$postData = $this->request->getPost();
$sanitizedData = $this->sanitized($postData, true);
$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('Provincias.provincia'))]);
$this->session->setFlashdata('formErrors', $this->model->errors());
endif;
$settingsEntity->fill($sanitizedData);
$thenRedirect = false;
endif;
if ($noException && $successfulResult) :
$id = $settingsEntity->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['settingsEntity'] = $settingsEntity;
$this->viewData['formAction'] = route_to('settingsEdit');
$this->viewData['tables'] = db_connect()->listTables();
return $this->displayForm(__METHOD__, $id);
} // end function settings(...)
}

View File

@ -32,51 +32,4 @@ class Intranet extends Controller
}
function tickets($resource_name)
{
helper('file');
$resource_path = WRITEPATH . 'uploads/tickets/' . $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 orden_trabajo($ot_id,$resource_name)
{
helper('file');
$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();
}
}
}

View File

@ -1,398 +0,0 @@
<?php
namespace App\Controllers\Soporte;
use App\Models\Soporte\TicketModel;
use App\Models\CategoriaModel;
use App\Models\EstadoModel;
use CodeIgniter\Controller;
use App\Entities\Soporte\TicketEntity;
use App\Models\Soporte\ticketFileModel;
use App\Models\Collection;
class Ticketcontroller extends \App\Controllers\BaseResourceController
{
protected $modelName = TicketModel::class;
protected $format = 'json';
protected static $singularObjectNameCc = 'ticket';
protected static $singularObjectName = 'Ticket';
protected static $pluralObjectName = 'Tickets';
protected static $controllerSlug = 'ticket';
protected static $viewPath = 'themes/vuexy/form/soporte/';
protected $indexRoute = 'TicketIndex';
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
$this->viewData['pageTitle'] = lang('Tickets.moduleTitle');
// Breadcrumbs
$this->viewData['breadcrumb'] = [
['title' => lang("App.menu_soporte"), 'route' => "javascript:void(0);", 'active' => false],
['title' => lang("App.menu_soporte_ticket_list"), 'route' => route_to('TicketIndex'), 'active' => true]
];
parent::initController($request, $response, $logger);
}
public function index()
{
checkPermission('tickets.menu');
$viewData = [
'currentModule' => static::$controllerSlug,
'pageSubTitle' => lang('Basic.global.ManageAllRecords', [lang('Tickets.tickets')]),
'usingServerSideDataTable' => true,
'userType' => auth()->user()->can('tickets.edit') ? 1 : 0,
];
$viewData = array_merge($this->viewData, $viewData); // merge any possible values from the parent controller class
return view(static::$viewPath . 'viewTicketList', $viewData);
}
private function sendMail($subject, $body, $recipient)
{
// Funcion wrapper para el servicio de envio de correos dentro de la fucionalidad previa
$emailService = service('emailService');
return $emailService->send($subject, $body, $recipient);
}
public function add()
{
checkPermission('tickets.create');
if ($this->request->getPost()):
$nullIfEmpty = false; // !(phpversion() >= '8.1');
$postData = $this->request->getPost();
// get user id
$postData['usuario_id'] = auth()->user()->id;
$postData['user_soporte_id'] = model('App\Models\Configuracion\ConfigVariableModel')->getVariable('default_soporte_user_id')->value;
$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();
$this->saveImages($id, $this->request->getFiles());
$message = lang('Basic.global.saveSuccess', [lang('Basic.global.record')]) . '.';
$userModel = new \App\Models\Usuarios\UserModel();
$this->sendMail(lang('Tickets.newTicket'), lang('Tickets.newTicketBody') . base_url(route_to('editTicket', $id)), $userModel->find($sanitizedData['user_soporte_id'])->email);
if ($thenRedirect):
if (!empty($this->indexRoute)):
return redirect()->to(route_to($this->indexRoute))->with('successMessage', $message);
else:
return $this->redirect2listView('successMessage', $message);
endif;
else:
$this->session->setFlashData('sweet-success', $message);
endif;
endif; // $noException && $successfulResult
endif; // ($requestMethod === 'post')
$this->viewData['ticket'] = isset($sanitizedData) ? new TicketEntity($sanitizedData) : new TicketEntity();
$this->viewData['formAction'] = route_to('NewTicket');
$this->viewData['categorias'] = $this->model->getCategorias();
$this->viewData['estados'] = $this->model->getEstados();
$this->viewData['secciones'] = $this->model->getSecciones();
$this->viewData['supportUsers'] = $this->getSupportUsers();
$this->viewData['boxTitle'] = lang('Basic.global.addNew') . ' ' . lang('Tickets.ticket') . ' ' . lang('Basic.global.addNewSuffix');
return $this->displayForm(__METHOD__);
} // end function add()
public function edit($requestedId = null)
{
checkPermission('tickets.edit');
$modelRespuesta = new \App\Models\Soporte\TicketRespuestaModel();
if ($requestedId == null):
return $this->redirect2listView();
endif;
$id = filter_var($requestedId, FILTER_SANITIZE_URL);
$ticket = $this->model->find($id);
if ($ticket == false):
$message = lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('Tickets.ticket')), $id]);
return $this->redirect2listView('errorMessage', $message);
endif;
if (!auth()->user()->can('Tickets.edit') && auth()->user()->id != $ticket->usuario_id) {
return redirect()->to(route_to('TicketIndex'))->with('errorMessage', lang('Basic.global.noPermission'));
}
if ($this->request->getPost()):
$oldUserSupport = $ticket->user_soporte_id;
$oldState = $ticket->estado_id;
$postData = $this->request->getPost();
$sanitizedData = $this->sanitized($postData, false);
$noException = true;
if ($successfulResult = $this->canValidate()): // if ($successfulResult = $this->validate($this->formValidationRules) ) :
if ($this->canValidate()):
try {
$successfulResult = $this->model->skipValidation(true)->update($id, $sanitizedData);
$this->saveImages($id, $this->request->getFiles());
if (auth()->user()->can('Tickets.edit')) {
$respuesta = $modelRespuesta->where('ticket_id', $id)->first();
if ($respuesta == null) {
$modelRespuesta->insert([
'ticket_id' => $id,
'usuario_id' => auth()->user()->id,
'mensaje' => $sanitizedData['respuesta_mensaje']
]);
} else {
$modelRespuesta->update($respuesta->id, [
'mensaje' => $sanitizedData['respuesta_mensaje'],
'usuario_id' => auth()->user()->id,
]);
}
// envio de correos
$userModel = new \App\Models\Usuarios\UserModel();
if ($oldUserSupport != $sanitizedData['user_soporte_id']) {
$this->sendMail(lang('Tickets.asgignToChanged'), lang('Tickets.asgignToChangedBody') . base_url(route_to('editTicket', $id)), $userModel->find($sanitizedData['user_soporte_id'])->email);
}
if ($oldState != $sanitizedData['estado_id']) {
$this->sendMail(lang('Tickets.stateChange'), lang('Tickets.stateChangeBody') . base_url(route_to('editTicket', $id)), $userModel->find($ticket->usuario_id)->email);
}
}
} catch (\Exception $e) {
$noException = false;
$this->dealWithException($e);
}
else:
$this->viewData['warningMessage'] = lang('Basic.global.formErr1', [mb_strtolower(lang('Tickets.ticket'))]);
$this->session->setFlashdata('formErrors', $this->model->errors());
endif;
$ticket->fill($sanitizedData);
$thenRedirect = false;
endif;
if ($noException && $successfulResult):
$id = $ticket->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('successMessage', $message);
else:
return $this->redirect2listView('successMessage', $message);
endif;
else:
return redirect()->to(route_to("editTicket", $id))->with('successMessage', $message);
//$this->session->setFlashData('sweet-success', $message);
endif;
endif; // $noException && $successfulResult
endif; // ($requestMethod === 'post')
$this->viewData['ticket'] = $ticket;
$this->viewData['respuesta'] = $modelRespuesta->where('ticket_id', $id)->first();
$this->viewData['formAction'] = route_to('updateTicket', $id);
$this->viewData['categorias'] = $this->model->getCategorias();
$this->viewData['estados'] = $this->model->getEstados();
$this->viewData['secciones'] = $this->model->getSecciones();
$this->viewData['supportUsers'] = $this->getSupportUsers();
$this->viewData['imagesTicket'] = $this->getImages('ticket', $id);
$this->viewData['imagesRespuesta'] = $this->getImages('respuesta', $id);
$this->viewData['boxTitle'] = lang('Basic.global.edit2') . ' ' . lang('Tickets.ticket') . ' ' . lang('Basic.global.edit3');
return $this->displayForm(__METHOD__, $id);
} // end function edit(...)
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;
$requestedOrder = $reqData['order'] ?? [];
$searchValues = get_filter_datatables_columns($reqData);
if (auth()->user()->can('tickets.edit')) {
$user_id = null;
} else {
$user_id = auth()->user()->id;
}
$resourceData = $this->model->getResource($searchValues, $user_id);
foreach ($requestedOrder as $order) {
$column = $order['column'] ?? 0;
$dir = $order['dir'] ?? 'asc';
$orderColumn = $this->model::SORTABLE[$column] ?? null;
if ($orderColumn) {
$resourceData->orderBy($orderColumn, $dir);
}
}
$resourceData = $resourceData->limit($length, $start)->get()->getResultObject();
return $this->respond(Collection::datatable(
$resourceData,
$this->model->getResource($searchValues)->countAllResults(),
$this->model->getResource($searchValues)->countAllResults()
));
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function image($imageName)
{
$filePath = WRITEPATH . "uploads/tickets/" . $imageName;
if (!file_exists($filePath)) {
return $this->response->setStatusCode(404, 'Imagen no encontrada');
}
$mimeType = mime_content_type($filePath);
return $this->response
->setHeader('Content-Type', $mimeType)
->setBody(file_get_contents($filePath));
}
private function saveImages($ticket_id, $files = [])
{
$uploadPath = WRITEPATH . 'uploads/tickets/';
$fileModel = new ticketFileModel();
if ($files && isset($files['files'])) {
foreach ($files['files'] as $file) {
if ($file->isValid() && !$file->hasMoved()) {
$originalName = $file->getClientName();
$fileExt = $file->getExtension();
// Generar hash SHA-256 basado en el contenido del archivo
$fileHash = hash_file("sha256", $file->getTempName());
$newFileName = $fileHash . '.' . $fileExt;
// Mover el archivo con el nombre basado en el hash
$file->move($uploadPath, $newFileName);
// Guardar en la base de datos
$fileModel->insert([
'nombre' => $originalName,
'ticket_id' => $ticket_id,
'hash' => $fileHash,
'path' => 'uploads/tickets/' . $newFileName
]);
}
}
}
}
private function getImages($tipo = 'ticket', $id = null)
{
$images = [];
$model = new ticketFileModel();
if ($tipo == 'ticket') {
$files = $model->where('ticket_id', $id)->findAll();
foreach ($files as $file) {
$ext = pathinfo($file['nombre'], PATHINFO_EXTENSION);
array_push($images, array(
"path" => '/soporte/image/' . $file['hash'] . "." . $ext,
"name" => $file['nombre']
));
}
} else {
$files = $model->where('respuesta_id', $id)->findAll();
foreach ($files as $file) {
$ext = pathinfo($file['nombre'], PATHINFO_EXTENSION);
array_push($images, array(
"path" => '/soporte/image/' . $file['hash'] . "." . $ext,
"name" => $file['nombre']
));
}
}
return $images;
}
private function getSupportUsers()
{
$defatulSoporteUserId = model('App\Models\Configuracion\ConfigVariableModel')->getVariable('default_soporte_user_id')->value;
$supportUsers = array(
array(
'id' => $defatulSoporteUserId,
'name' => model('App\Models\Usuarios\UserModel')->getFullName($defatulSoporteUserId)
),
array(
'id' => 2,
'name' => model('App\Models\Usuarios\UserModel')->getFullName(2)
),
array(
'id' => 1,
'name' => model('App\Models\Usuarios\UserModel')->getFullName(1)
),
);
return $supportUsers;
}
}

View File

@ -1,325 +0,0 @@
<?php
namespace App\Controllers\Tarifas\Acabados;
use App\Controllers\BaseResourceController;
use App\Entities\Tarifas\Acabados\ServicioAcabadoEntity;
use App\Models\Tarifas\Acabados\ServicioAcabadoModel;
use CodeIgniter\I18n\Time;
use Hermawan\DataTables\DataTable;
class ServiciosAcabado extends BaseResourceController
{
protected $modelName = ServicioAcabadoModel::class;
protected $format = 'json';
protected static $singularObjectName = 'Servicio Acabado';
protected static $singularObjectNameCc = 'serviciosAcabado';
protected static $pluralObjectName = 'Servicios Acabado';
protected static $pluralObjectNameCc = 'serviciosAcabado';
protected static $controllerSlug = 'serviciosacabado';
protected static $viewPath = 'themes/vuexy/form/tarifas/acabado/';
protected $indexRoute = 'serviciosAcabadoList';
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
$this->viewData['pageTitle'] = lang('Servicioacabado.moduleTitle');
$this->viewData['usingSweetAlert'] = true;
$this->viewData = ['usingServerSideDataTable' => true];
// Breadcrumbs
$this->viewData['breadcrumb'] = [
['title' => lang("App.menu_tarifas"), 'route' => "javascript:void(0);", 'active' => false],
['title' => lang("App.menu_servicioAcabado"), 'route' => route_to('serviciosAcabadoList'), 'active' => true]
];
helper("time");
parent::initController($request, $response, $logger);
}
public function index()
{
checkPermission('tarifa-acabado.menu');
$viewData = [
'currentModule' => static::$controllerSlug,
'pageSubTitle' => lang('Basic.global.ManageAllRecords', [lang('Servicioacabado.serviciosacabado')]),
'servicioacabadoEntity' => new ServicioAcabadoEntity(),
'usingServerSideDataTable' => true,
];
$viewData = array_merge($this->viewData, $viewData); // merge any possible values from the parent controller class
return view(static::$viewPath . 'viewServiciosAcabadoList', $viewData);
}
public function add()
{
checkPermission('tarifa-acabado.create', $this->indexRoute);
if ($this->request->getPost()) :
$nullIfEmpty = true; // !(phpversion() >= '8.1');
$postData = $this->request->getPost();
$tarifasSeleccionadas = $postData['tarifasAcabado'] ?? [];
unset($postData['tarifasAcabado']);
$sanitizedData = $this->sanitized($postData, $nullIfEmpty);
$sanitizedData['user_updated_id'] = auth()->user()->id;
if ($this->request->getPost('mostrar_en_presupuesto_cliente') == null) {
$sanitizedData['mostrar_en_presupuesto'] = false;
}
if ($this->request->getPost('acabado_cubierta') == null) {
$sanitizedData['acabado_cubierta'] = false;
}
if ($this->request->getPost('acabado_sobrecubierta') == null) {
$sanitizedData['acabado_sobrecubierta'] = false;
}
$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')]) . '.';
$modelTable = model("App\Models\Tarifas\Acabados\TarifasAcabadoServiciosAcabadoModel");
foreach ($tarifasSeleccionadas as $tarifaId) {
$modelTable->insert(['servicio_id' => $id, 'tarifa_id' => $tarifaId, 'user_updated_id' => auth()->user()->id]);
}
if ($thenRedirect) :
if (!empty($this->indexRoute)) :
return redirect()->to(site_url('/serviciosacabado/edit/' . $id))->with('message', $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['tarifasSeleccionadas'] = [];
$this->viewData['servicio'] = isset($sanitizedData) ? new ServicioAcabadoEntity($sanitizedData) : new ServicioAcabadoEntity();
$this->viewData['formAction'] = route_to('createServicioAcabado');
$this->viewData['boxTitle'] = lang('Basic.global.addNew') . ' ' . lang('ServicioAcabado.moduleTitle') . ' ' . lang('Basic.global.addNewSuffix');
return $this->displayForm(__METHOD__);
}
public function edit($requestedId = null)
{
if ($requestedId == null):
return $this->redirect2listView();
endif;
$id = filter_var($requestedId, FILTER_SANITIZE_URL);
$servicio = $this->model->find($id);
if ($servicio == false):
$message = lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('ServicioAcabado.servicioacabado')), $id]);
return $this->redirect2listView('sweet-error', $message);
endif;
if ($this->request->getPost()):
$nullIfEmpty = true; // !(phpversion() >= '8.1');
$postData = $this->request->getPost();
$tarifasSeleccionadas = $postData['tarifasAcabado'] ?? [];
unset($postData['tarifasAcabado']);
$sanitizedData = $this->sanitized($postData, $nullIfEmpty);
$sanitizedData['user_updated_id'] = auth()->user()->id;
if ($this->request->getPost('mostrar_en_presupuesto_cliente') == null) {
$sanitizedData['mostrar_en_presupuesto'] = false;
}
if ($this->request->getPost('acabado_cubierta') == null) {
$sanitizedData['acabado_cubierta'] = false;
}
if ($this->request->getPost('acabado_sobrecubierta') == null) {
$sanitizedData['acabado_sobrecubierta'] = false;
}
$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('ServicioAcabado.servicioacabado'))]);
$this->session->setFlashdata('formErrors', $this->model->errors());
endif;
$servicio->fill($sanitizedData);
$modelTable = model("App\Models\Tarifas\Acabados\TarifasAcabadoServiciosAcabadoModel");
$modelTable->where('servicio_id',$id)->delete();
foreach ($tarifasSeleccionadas as $tarifaId) {
$modelTable->insert(['servicio_id' => $id, 'tarifa_id' => $tarifaId, 'user_updated_id' => auth()->user()->id]);
}
$thenRedirect = false;
endif;
if ($noException && $successfulResult):
$id = $servicio->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['servicio'] = $servicio;
$this->viewData['tarifasSeleccionadas'] = $this->getTarifasSeleccionadasForView($id);
$this->viewData['formAction'] = route_to('updateServicioAcabado', $id);
$this->viewData['boxTitle'] = lang('Basic.global.edit2') . ' ' . lang('ServicioAcabado.moduleTitle') . ' ' . lang('Basic.global.edit3');
return $this->displayForm(__METHOD__, $id);
} // end function edit(...)
public function datatable()
{
$model = model(ServicioAcabadoModel::class);
$q = $model->getDatatableQuery();
//return $this->response->setJSON($q->get());
return DataTable::of($q)
->add("action", callback: function ($q) {
return '<span class="edit"><a href="javascript:void(0);"><i class="ti ti-pencil ti-sm btn-edit mx-2" data-id="' . $q->id . '"></i></a></span>'
. (auth()->user()->can("servicio-acabado.delete") ?
'<span class="delete"><a href="javascript:void(0);"><i class="ti ti-trash ti-sm btn-delete mx-2" data-id="' . $q->id . '"></i></a></span>'
: '');
})
->edit(
"updated_at",
fn($q) => Time::createFromFormat("Y-m-d H:i:s", $q->updated_at)->format("d/m/Y")
)
->toJson(returnAsObject: true);
}
public function getTarifasSeleccionadasForView($servicioId){
$model = model("App\Models\Tarifas\Acabados\TarifasAcabadoServiciosAcabadoModel");
$ids = $model->getTarifasForServicio($servicioId);
return $ids;
}
public function getTarifasSeleccionadas()
{
$model = model("App\Models\Tarifas\Acabados\TarifaAcabadoModel");
$ids = $this->request->getGet('ids');
if (empty($ids)) {
return $this->response->setJSON([]);
}
$query = $model->select('lg_tarifa_acabado.id, lg_tarifa_acabado.nombre')->whereIn('lg_tarifa_acabado.id', $ids);
$query->where('lg_tarifa_acabado.deleted_at', null);
$tarifas = $query->findAll();
return $this->response->setJSON($tarifas);
}
public function getTarifas()
{
$model = model("App\Models\Tarifas\Acabados\TarifaAcabadoModel");
$search = $this->request->getGet('search'); // Obtiene el parámetro de búsqueda
$acabado_cubierta = $this->request->getGet('acabado_cubierta');
$acabado_sobrecubierta = $this->request->getGet('acabado_sobrecubierta');
$query = $model->select('lg_tarifa_acabado.id, lg_tarifa_acabado.nombre');
if (!empty($search)) {
$query->like('lg_tarifa_acabado.nombre', $search);
}
if($acabado_cubierta){
$query->where('lg_tarifa_acabado.acabado_cubierta', $acabado_cubierta);
}
if($acabado_sobrecubierta){
$query->where('lg_tarifa_acabado.acabado_sobrecubierta', $acabado_sobrecubierta);
}
$query->where('lg_tarifa_acabado.deleted_at', null);
$tarifas = $query->findAll();
return $this->response->setJSON($tarifas);
}
}

View File

@ -1,6 +1,4 @@
<?php
namespace App\Controllers\Tarifas\Acabados;
<?php namespace App\Controllers\Tarifas\Acabados;
use App\Controllers\BaseResourceController;
use App\Entities\Tarifas\Acabados\TarifaAcabadoEntity;
@ -24,7 +22,7 @@ class TarifaAcabados extends BaseResourceController
protected static $controllerSlug = 'tarifasacabado';
protected static $viewPath = 'themes/vuexy/form/tarifas/acabado/';
protected static $viewPath = 'themes/vuexy/form/tarifas/acabado/';
protected $indexRoute = 'tarifaAcabadoList';
@ -135,7 +133,7 @@ class TarifaAcabados extends BaseResourceController
endif; // ($requestMethod === 'post')
$this->viewData['proveedores'] = $this->getProveedores();
$this->viewData['proveedores'] = $this->getProveedores();
$this->viewData['tarifaacabadoEntity'] = isset($sanitizedData) ? new TarifaAcabadoEntity($sanitizedData) : new TarifaAcabadoEntity();
$this->viewData['formAction'] = route_to('tarifaAcabadoAdd');
@ -171,7 +169,7 @@ class TarifaAcabados extends BaseResourceController
// JJO
$sanitizedData['user_updated_id'] = auth()->user()->id;
if ($this->request->getPost('mostrar_en_presupuesto') == null) {
$sanitizedData['mostrar_en_presupuesto'] = false;
}
@ -183,7 +181,7 @@ class TarifaAcabados extends BaseResourceController
if ($this->request->getPost('acabado_sobrecubierta') == null) {
$sanitizedData['acabado_sobrecubierta'] = false;
}
$noException = true;
if ($successfulResult = $this->canValidate()) : // if ($successfulResult = $this->validate($this->formValidationRules) ) :
@ -209,7 +207,7 @@ class TarifaAcabados extends BaseResourceController
if ($noException && $successfulResult) :
$id = $tarifaacabadoEntity->id ?? $id;
$message = lang('Basic.global.updateSuccess', [lang('Basic.global.record')]) . '.';
$message = lang('Basic.global.updateSuccess', [lang('Basic.global.record')]) .'.';
if ($thenRedirect) :
if (!empty($this->indexRoute)) :
@ -314,47 +312,12 @@ class TarifaAcabados extends BaseResourceController
}
}
private function getProveedores()
{
private function getProveedores(){
$provTipoModel = new ProveedorTipoModel();
$provModel = new ProveedorModel();
$tipoId = $provTipoModel->getTipoId("Acabados");
return $provModel->getProvList($tipoId);
}
public function show_select()
{
$query = $this->model->builder()
->select(
["id", "nombre as name", "code as description"]
)
->where("deleted_at",null);
if ($this->request->getGet("q")) {
$query->groupStart()
->orLike("nombre", $this->request->getGet("q"))
->groupEnd();
}
return $this->response->setJSON($query->get()->getResultObject());
}
public function getSelect2()
{
if ($this->request->isAJAX()) {
$query = $this->model->builder()->select(
[
"id",
"nombre as name"
]
)->where("deleted_at", null);
if ($this->request->getGet("q")) {
$query->groupStart()
->orLike("lg_tarifa_acabado.nombre", $this->request->getGet("q"))
->groupEnd();
}
return $this->response->setJSON($query->get()->getResultObject());
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
}

View File

@ -216,7 +216,7 @@ class TarifaAcabadosLineas extends \App\Controllers\BaseResourceController
$searchValues = get_filter_datatables_columns($reqData);
$resourceData = $this->model->getResource($searchValues, $id_TA)->orderBy($order, $dir)->limit($length, $start)->get()->getResultObject();
return $this->respond(Collection::datatable(
$resourceData,
$this->model->getResource()->countAllResults(),

View File

@ -1,205 +0,0 @@
<?php
namespace App\Controllers\Tarifas\Maquinas;
use App\Controllers\BaseController;
use App\Models\Configuracion\MaquinaModel;
use App\Models\Configuracion\MaquinaTareaModel;
use App\Models\Tarifas\Maquinas\TarifaAcabadoMaquinaModel;
use App\Models\Tarifas\Maquinas\TarifaManipuladoMaquinaModel;
use App\Models\Tarifas\Maquinas\TarifaEncuadernacionMaquinaModel;
use App\Models\Tarifas\Maquinas\TarifaPreimpresionMaquinaModel;
use App\Models\Tarifas\Maquinas\TarifaExtraMaquinaModel;
use App\Services\TarifaMaquinaService;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Validation\Validation;
use Hermawan\DataTables\DataTable;
use Psr\Log\LoggerInterface;
class TarifaMaquinas extends BaseController
{
protected $format = 'json';
protected array $viewData = [];
protected MaquinaModel $maquinaModel;
protected MaquinaTareaModel $maquinaTareaModel;
protected TarifaMaquinaService $tarifaMaquinaService;
protected Validation $validation;
protected static $controllerSlug = "tarifa-maquinas";
public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
{
$this->maquinaModel = model(MaquinaModel::class);
$this->maquinaTareaModel = model(MaquinaTareaModel::class);
$this->tarifaMaquinaService = service("tarifa_maquina");
$this->validation = service("validation");
parent::initController($request, $response, $logger);
}
/**========================================================================
* CREATE
*========================================================================**/
public function add_tarifa_acabado_maquina_with_tarea()
{
$bodyData = $this->request->getPost();
$validated = $this->validation->run($bodyData, "tarifa_maquina_acabado");
if ($validated) {
$r = $this->tarifaMaquinaService->attachAcabadoToMaquina(...$bodyData);
return $this->response->setJSON(["message" => lang("App.global_alert_save_success"), "status" => true, "data" => $r]);
} else {
return $this->response->setJSON($this->validation->getErrors())->setStatusCode(400);
}
}
public function add_tarifa_manipulado_maquina_with_tarea()
{
$bodyData = $this->request->getPost();
$validated = $this->validation->run($bodyData, "tarifa_maquina_manipulado");
if ($validated) {
$r = $this->tarifaMaquinaService->attachManipuladoToMaquina(...$bodyData);
return $this->response->setJSON(["message" => lang("App.global_alert_save_success"), "status" => true, "data" => $r]);
} else {
return $this->response->setJSON(["errors" => $this->validation->getErrors()])->setStatusCode(400);
}
}
public function add_tarifa_preimpresion_maquina_with_tarea()
{
$bodyData = $this->request->getPost();
$validated = $this->validation->run($bodyData, "tarifa_maquina_preimpresion");
if ($validated) {
$r = $this->tarifaMaquinaService->attachPreimpresionToMaquina(...$bodyData);
return $this->response->setJSON(["message" => lang("App.global_alert_save_success"), "status" => true, "data" => $r]);
} else {
return $this->response->setJSON(["errors" => $this->validation->getErrors()])->setStatusCode(400);
}
}
public function add_tarifa_encuadernacion_maquina_with_tarea()
{
$bodyData = $this->request->getPost();
$validated = $this->validation->run($bodyData, "tarifa_maquina_encuadernacion");
if ($validated) {
$r = $this->tarifaMaquinaService->attachEncuadernacionToMaquina(...$bodyData);
return $this->response->setJSON(["message" => lang("App.global_alert_save_success"), "status" => true, "data" => $r]);
} else {
return $this->response->setJSON(["errors" => $this->validation->getErrors()])->setStatusCode(400);
}
}
public function add_tarifa_extra_maquina_with_tarea()
{
$bodyData = $this->request->getPost();
$validated = $this->validation->run($bodyData, "tarifa_maquina_encuadernacion");
if ($validated) {
$r = $this->tarifaMaquinaService->attachExtraToMaquina(...$bodyData);
return $this->response->setJSON(["message" => lang("App.global_alert_save_success"), "status" => true, "data" => $r]);
} else {
return $this->response->setJSON(["errors" => $this->validation->getErrors()])->setStatusCode(400);
}
}
/**========================================================================
* DELETES
*========================================================================**/
public function delete_tarifa_acabado_maquina_with_tarea($tarifa_acabado_maquina_id)
{
$m = model(TarifaAcabadoMaquinaModel::class);
$r = $m->delete($tarifa_acabado_maquina_id);
return $this->response->setJSON(["message" => lang("App.user_alert_delete"), "status" => true, "data" => $r]);
}
public function delete_tarifa_manipulado_maquina_with_tarea($tarifa_manipulado_maquina_id)
{
$m = model(TarifaManipuladoMaquinaModel::class);
$r = $m->delete($tarifa_manipulado_maquina_id);
return $this->response->setJSON(["message" => lang("App.user_alert_delete"), "status" => true, "data" => $r]);
}
public function delete_tarifa_encuadernacion_maquina_with_tarea($tarifa_encuadernacion_maquina_id)
{
$m = model(TarifaEncuadernacionMaquinaModel::class);
$r = $m->delete($tarifa_encuadernacion_maquina_id);
return $this->response->setJSON(["message" => lang("App.user_alert_delete"), "status" => true, "data" => $r]);
}
public function delete_tarifa_preimpresion_maquina_with_tarea($tarifa_preimpresion_maquina_id)
{
$m = model(TarifaPreimpresionMaquinaModel::class);
$r = $m->delete($tarifa_preimpresion_maquina_id);
return $this->response->setJSON(["message" => lang("App.user_alert_delete"), "status" => true, "data" => $r]);
}
public function delete_tarifa_extra_maquina_with_tarea($tarifa_extra_maquina_id)
{
$m = model(TarifaExtraMaquinaModel::class);
$r = $m->delete($tarifa_extra_maquina_id);
return $this->response->setJSON(["message" => lang("App.user_alert_delete"), "status" => true, "data" => $r]);
}
/**========================================================================
* SELECTS
*========================================================================**/
public function get_select_maquina_acabado()
{
$r = $this->maquinaModel->getSelectQuery(q: $this->request->getGet("q"), type: 'acabado');
return $this->response->setJSON($r);
}
public function get_select_maquina_impresion()
{
$r = $this->maquinaModel->getSelectQuery(q: $this->request->getGet("q"), type: 'impresion');
return $this->response->setJSON($r);
}
public function get_select_maquina_manipulado()
{
$r = $this->maquinaModel->getSelectQuery(q: $this->request->getGet("q"), type: 'manipulado');
return $this->response->setJSON($r);
}
public function get_select_maquina_tareas()
{
$r = $this->maquinaTareaModel->getSelectQuery(q: $this->request->getGet("q"));
return $this->response->setJSON($r);
}
/**========================================================================
* DATATABLES
*========================================================================**/
public function get_datatable_tarifa_acabado_maquina(int $tarifa_acabado_id)
{
$m = model(TarifaAcabadoMaquinaModel::class);
$q = $m->queryDatatable($tarifa_acabado_id);
return DataTable::of($q)
->add("action", fn($q) => $q->id)
->toJson(true);
}
public function get_datatable_tarifa_manipulado_maquina(int $tarifa_manipulado_id)
{
$m = model(TarifaManipuladoMaquinaModel::class);
$q = $m->queryDatatable($tarifa_manipulado_id);
return DataTable::of($q)
->add("action", fn($q) => $q->id)
->toJson(true);
}
public function get_datatable_tarifa_preimpresion_maquina(int $tarifa_preimpresion_id)
{
$m = model(TarifaPreimpresionMaquinaModel::class);
$q = $m->queryDatatable($tarifa_preimpresion_id);
return DataTable::of($q)
->add("action", fn($q) => $q->id)
->toJson(true);
}
public function get_datatable_tarifa_encuadernacion_maquina(int $tarifa_encuadernacion_id)
{
$m = model(TarifaEncuadernacionMaquinaModel::class);
$q = $m->queryDatatable($tarifa_encuadernacion_id);
return DataTable::of($q)
->add("action", fn($q) => $q->id)
->toJson(true);
}
public function get_datatable_tarifa_extra_maquina(int $tarifa_extra_id)
{
$m = model(TarifaExtraMaquinaModel::class);
$q = $m->queryDatatable($tarifa_extra_id);
return DataTable::of($q)
->add("action", fn($q) => $q->id)
->toJson(true);
}
}

View File

@ -1,5 +1,4 @@
<?php
namespace App\Controllers\Tarifas;
@ -12,15 +11,15 @@ use App\Entities\Tarifas\TarifaEncuadernacionLinea;
use App\Models\Tarifas\TarifaEncuadernacionLineaModel;
use
DataTables\Editor,
DataTables\Database,
DataTables\Editor\Field,
DataTables\Editor\Format,
DataTables\Editor\Mjoin,
DataTables\Editor\Options,
DataTables\Editor\Upload,
DataTables\Editor\Validate,
DataTables\Editor\ValidateOptions;
DataTables\Editor,
DataTables\Database,
DataTables\Editor\Field,
DataTables\Editor\Format,
DataTables\Editor\Mjoin,
DataTables\Editor\Options,
DataTables\Editor\Upload,
DataTables\Editor\Validate,
DataTables\Editor\ValidateOptions;
class Tarifaencuadernacionlineas extends \App\Controllers\BaseResourceController
@ -358,6 +357,7 @@ class Tarifaencuadernacionlineas extends \App\Controllers\BaseResourceController
$response[$csrfTokenName] = $newTokenHash;
echo json_encode($response);
} else {
return $this->failUnauthorized('Invalid request', 403);
}
@ -384,6 +384,7 @@ class Tarifaencuadernacionlineas extends \App\Controllers\BaseResourceController
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
} else {
if (!isset($reqData['draw']) || !isset($reqData['columns'])) {
@ -411,8 +412,9 @@ class Tarifaencuadernacionlineas extends \App\Controllers\BaseResourceController
$id_TE = $reqData['tirada_id'] ?? -1;
$resourceData = $this->model->getResource("", $id_TE)->orderBy($order1, $dir1)->orderBy($order2, $dir2)->orderBy($order3, $dir3)->limit($length, $start)->get()->getResultObject();
$resourceData = $this->model->getResource("", $id_TE)->
orderBy($order1, $dir1)->orderBy($order2, $dir2)->orderBy($order3, $dir3)->limit($length, $start)->get()->getResultObject();
return $this->respond(Collection::datatable(
$resourceData,
$this->model->getResource()->countAllResults(),
@ -473,4 +475,5 @@ class Tarifaencuadernacionlineas extends \App\Controllers\BaseResourceController
return $this->failUnauthorized('Invalid request', 403);
}
}
}

View File

@ -223,6 +223,7 @@ class Tarifaencuadernaciontiradas extends \App\Controllers\BaseResourceControlle
$resourceData = $model->getResource("", $id_TM)->
orderBy($order0, $dir0)->orderBy($order1, $dir1)->orderBy($order2, $dir2)->
limit($length, $start)->get()->getResultObject();
return $this->respond(Collection::datatable(
$resourceData,
$model->getResource()->countAllResults(),

View File

@ -65,9 +65,7 @@ class Tarifaextra extends \App\Controllers\GoBaseController
if ($this->request->getPost('mostrar_en_presupuesto') == null) {
$sanitizedData['mostrar_en_presupuesto'] = false;
}
if ($this->request->getPost('mostrar_en_presupuesto_cliente') == null) {
$sanitizedData['mostrar_en_presupuesto_cliente'] = false;
}
$noException = true;
if ($successfulResult = $this->canValidate()) : // if ($successfulResult = $this->validate($this->formValidationRules) ) :
@ -144,9 +142,7 @@ class Tarifaextra extends \App\Controllers\GoBaseController
if ($this->request->getPost('mostrar_en_presupuesto') == null) {
$sanitizedData['mostrar_en_presupuesto'] = false;
}
if ($this->request->getPost('mostrar_en_presupuesto_cliente') == null) {
$sanitizedData['mostrar_en_presupuesto_cliente'] = false;
}
$noException = true;
if ($successfulResult = $this->canValidate()) : // if ($successfulResult = $this->validate($this->formValidationRules) ) :
if ($this->canValidate()) :
@ -243,25 +239,4 @@ class Tarifaextra extends \App\Controllers\GoBaseController
}
}
public function getSelect2()
{
if ($this->request->isAJAX()) {
$query = $this->model->builder()->select(
[
"id",
"nombre as name"
]
)->where("deleted_at", null)
->where("mostrar_en_presupuesto", 1);
if ($this->request->getGet("q")) {
$query->groupStart()
->orLike("tarifa_extra.nombre", $this->request->getGet("q"))
->groupEnd();
}
return $this->response->setJSON($query->get()->getResultObject());
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
}

View File

@ -63,9 +63,7 @@ class Tarifapreimpresion extends \App\Controllers\GoBaseController
if ($this->request->getPost('mostrar_en_presupuesto') == null) {
$sanitizedData['mostrar_en_presupuesto'] = false;
}
if ($this->request->getPost('mostrar_en_presupuesto_cliente') == null) {
$sanitizedData['mostrar_en_presupuesto_cliente'] = false;
}
$noException = true;
if ($successfulResult = $this->canValidate()) : // if ($successfulResult = $this->validate($this->formValidationRules) ) :
@ -146,9 +144,7 @@ class Tarifapreimpresion extends \App\Controllers\GoBaseController
if ($this->request->getPost('mostrar_en_presupuesto') == null) {
$sanitizedData['mostrar_en_presupuesto'] = false;
}
if ($this->request->getPost('mostrar_en_presupuesto_cliente') == null) {
$sanitizedData['mostrar_en_presupuesto_cliente'] = false;
}
$noException = true;
if ($successfulResult = $this->canValidate()) : // if ($successfulResult = $this->validate($this->formValidationRules) ) :
if ($this->canValidate()) :
@ -246,25 +242,4 @@ class Tarifapreimpresion extends \App\Controllers\GoBaseController
}
}
public function getSelect2()
{
if ($this->request->isAJAX()) {
$query = $this->model->builder()->select(
[
"id",
"nombre as name"
]
)->where("deleted_at", null)
->where("mostrar_en_presupuesto", 1);
if ($this->request->getGet("q")) {
$query->groupStart()
->orLike("lg_tarifa_preimpresion.nombre", $this->request->getGet("q"))
->groupEnd();
}
return $this->response->setJSON($query->get()->getResultObject());
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
}

View File

@ -356,26 +356,4 @@ class Tarifasencuadernacion extends \App\Controllers\BaseResourceController
}
return $dimensiones;
}
public function getSelect2()
{
if ($this->request->isAJAX()) {
$query = $this->model->builder()->select(
[
"id",
"nombre as name"
]
)->where("deleted_at", null)
->where("mostrar_en_presupuesto", 1);
if ($this->request->getGet("q")) {
$query->groupStart()
->orLike("tarifa_encuadernacion.nombre", $this->request->getGet("q"))
->groupEnd();
}
return $this->response->setJSON($query->get()->getResultObject());
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
}

Some files were not shown because too many files have changed in this diff Show More