From 4cf4e3fcfdfcd347bd7014923a1264d345f6a948 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jaime=20Jim=C3=A9nez?= Date: Fri, 29 Nov 2024 17:06:23 +0100 Subject: [PATCH 01/18] trabajando --- .../assets/js/safekat/pages/cliente/cliente.js | 5 +++++ .../js/safekat/pages/cliente/tarifasCliente.js | 14 ++++++++++++++ 2 files changed, 19 insertions(+) create mode 100644 httpdocs/assets/js/safekat/pages/cliente/tarifasCliente.js diff --git a/httpdocs/assets/js/safekat/pages/cliente/cliente.js b/httpdocs/assets/js/safekat/pages/cliente/cliente.js index fabbe83f..286be4ec 100644 --- a/httpdocs/assets/js/safekat/pages/cliente/cliente.js +++ b/httpdocs/assets/js/safekat/pages/cliente/cliente.js @@ -1,4 +1,5 @@ import ClassSelect from '../../components/select2.js'; +import tarifasClienteView from './tarifasCliente.js'; class Cliente { @@ -7,6 +8,8 @@ class Cliente { this.csrf_token = this.getToken(); this.csrf_hash = $('#clienteForm').find('input[name="' + this.csrf_token + '"]').val(); + this.tarifas = new tarifasClienteView(); + this.pais = new ClassSelect($("#paisId"), '/paises/menuitems2', "Seleccione un país", {[this.csrf_token]: this.csrf_hash}); this.soporte = new ClassSelect($("#soporteId"), '/users/getMenuComerciales', "Seleccione un usuario", {[this.csrf_token]: this.csrf_hash}); this.comercial = new ClassSelect($("#comercialId"), '/users/getMenuComerciales', "Seleccione un usuario", {[this.csrf_token]: this.csrf_hash}); @@ -30,6 +33,8 @@ class Cliente { this.formaPago.init(); this.provincia.init(); this.comunidadAutonoma.init(); + + this.tarifas.init(); $(document).keypress(function (e) { var key = e.which; diff --git a/httpdocs/assets/js/safekat/pages/cliente/tarifasCliente.js b/httpdocs/assets/js/safekat/pages/cliente/tarifasCliente.js new file mode 100644 index 00000000..d6d7a423 --- /dev/null +++ b/httpdocs/assets/js/safekat/pages/cliente/tarifasCliente.js @@ -0,0 +1,14 @@ +import { getToken } from "../../utils/common"; + +class tarifasClienteView{ + + constructor(domItem) { + this.csrf_token = document.querySelector('meta[name="csrf-token"]').content; + this.csrf_hash = document.querySelector('meta[name="csrf-hash"]').content; + this.token = getToken(); + } + + init() { + + } +} \ No newline at end of file From d870fca64d7e9668531f58c79c1e319250d24ca0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jaime=20Jim=C3=A9nez?= Date: Sat, 30 Nov 2024 13:59:05 +0100 Subject: [PATCH 02/18] trabajando en el datatable --- ci4/app/Controllers/Language.php | 21 ++++- .../clientes/cliente/_clienteFormItems.php | 8 +- .../js/safekat/pages/cliente/cliente.js | 32 +++---- .../safekat/pages/cliente/tarifasCliente.js | 91 +++++++++++++++++-- 4 files changed, 122 insertions(+), 30 deletions(-) diff --git a/ci4/app/Controllers/Language.php b/ci4/app/Controllers/Language.php index 437f18eb..f9c32e5d 100755 --- a/ci4/app/Controllers/Language.php +++ b/ci4/app/Controllers/Language.php @@ -21,9 +21,22 @@ class Language extends BaseController public function getTranslation() { $translationFile = $this->request->getPost('translationFile'); - $locale = $this->request->getPost('locale'); - $path = "Language/{$locale}/$translationFile.php"; - $lang = require APPPATH.$path; - return json_encode($lang); + $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); + } + } } diff --git a/ci4/app/Views/themes/vuexy/form/clientes/cliente/_clienteFormItems.php b/ci4/app/Views/themes/vuexy/form/clientes/cliente/_clienteFormItems.php index 3a741867..f66999c1 100644 --- a/ci4/app/Views/themes/vuexy/form/clientes/cliente/_clienteFormItems.php +++ b/ci4/app/Views/themes/vuexy/form/clientes/cliente/_clienteFormItems.php @@ -1046,6 +1046,8 @@ $(document).on('click', '.btn-remove', function(e) { }) }) +/* + var theTablePrecios = $('#tableOfPrecios').DataTable( { serverSide: true, processing: true, @@ -1143,7 +1145,7 @@ $(document).on('click', '.btn-remove', function(e) { } } ] } ); - +*/ const initPrecioTemplate = ; if(initPrecioTemplate != null){ @@ -1151,7 +1153,7 @@ $(document).on('click', '.btn-remove', function(e) { $('#plantillas').append(newOption); } - + /* // Activate an inline edit on click of a table cell $('#tableOfPrecios').on( 'click', 'tbody span.edit', function (e) { editorPrecios.inline( @@ -1165,7 +1167,7 @@ $(document).on('click', '.btn-remove', function(e) { } ); } ); - +*/ // Delete row $(document).on('click', '.btn-delete', function(e) { diff --git a/httpdocs/assets/js/safekat/pages/cliente/cliente.js b/httpdocs/assets/js/safekat/pages/cliente/cliente.js index 286be4ec..0bd83277 100644 --- a/httpdocs/assets/js/safekat/pages/cliente/cliente.js +++ b/httpdocs/assets/js/safekat/pages/cliente/cliente.js @@ -1,14 +1,12 @@ import ClassSelect from '../../components/select2.js'; import tarifasClienteView from './tarifasCliente.js'; +import Ajax from '../../components/ajax.js'; class Cliente { constructor() { - this.csrf_token = this.getToken(); - this.csrf_hash = $('#clienteForm').find('input[name="' + this.csrf_token + '"]').val(); - - this.tarifas = new tarifasClienteView(); + this.tarifas = new tarifasClienteView($('#tarifascliente')); this.pais = new ClassSelect($("#paisId"), '/paises/menuitems2', "Seleccione un país", {[this.csrf_token]: this.csrf_hash}); this.soporte = new ClassSelect($("#soporteId"), '/users/getMenuComerciales', "Seleccione un usuario", {[this.csrf_token]: this.csrf_hash}); @@ -17,7 +15,6 @@ class Cliente { this.provincia = new ClassSelect($("#provinciaId"), '/provincias/menuitems2', "Seleccione una provincia", {[this.csrf_token]: this.csrf_hash}); this.comunidadAutonoma = new ClassSelect($("#comunidadAutonomaId"), '/comunidades-autonomas/menuitems2', "Seleccione una comunidad autónoma", {[this.csrf_token]: this.csrf_hash}); - this.init(); } init() { @@ -54,18 +51,21 @@ class Cliente { }); } - - getToken(){ - - const scriptUrl = new URL(import.meta.url); - const params = new URLSearchParams(scriptUrl.search); - - const paramsObject = Object.fromEntries(params.entries()); - return paramsObject.token; - } } document.addEventListener('DOMContentLoaded', function () { - new Cliente().init(); -}); \ No newline at end of file + + const locale = document.querySelector('meta[name="locale"]').getAttribute('content'); + + new Ajax('/translate/getTranslation', { locale: locale, translationFile: ['ClienteContactos', 'ClientePrecios'] }, {}, + function(translations) { + window.language = JSON.parse(translations); + new Cliente().init(); + }, + function (error) { + console.log("Error getting translations:", error); + } + ).post(); +}); + diff --git a/httpdocs/assets/js/safekat/pages/cliente/tarifasCliente.js b/httpdocs/assets/js/safekat/pages/cliente/tarifasCliente.js index d6d7a423..55d61ad0 100644 --- a/httpdocs/assets/js/safekat/pages/cliente/tarifasCliente.js +++ b/httpdocs/assets/js/safekat/pages/cliente/tarifasCliente.js @@ -1,14 +1,91 @@ -import { getToken } from "../../utils/common"; +import Table from '../../components/table.js'; +import { getToken } from '../../common/common.js'; -class tarifasClienteView{ +class tarifasClienteView { constructor(domItem) { - this.csrf_token = document.querySelector('meta[name="csrf-token"]').content; - this.csrf_hash = document.querySelector('meta[name="csrf-hash"]').content; - this.token = getToken(); + + this.domItem = domItem; + + this.csrf_token = getToken(); + this.csrf_hash = $('#mainContainer').find('input[name="' + this.csrf_token + '"]').val(); + + this.clienteId = window.location.href.split("/").pop(); + this.actions = ['edit', 'delete']; } init() { - + + const self = this; + + const columns = [ + { + 'data': 'tipo', + 'render': function (data, type, row, meta) { + if (data == 'interior') + return window.language.ClientePrecios.interior; + else if (data == 'cubierta') + return window.language.ClientePrecios.cubierta; + else if (data == 'sobrecubierta') + return window.language.ClientePrecios.sobrecubierta; + } + }, + { + 'data': 'tipo_maquina', + 'render': function (data, type, row, meta) { + if (data == 'toner') + return window.language.ClientePrecios.toner; + else if (data == 'inkjet') + return window.language.ClientePrecios.inkjet; + } + }, + { + 'data': 'tipo_impresion', + 'render': function (data, type, row, meta) { + if (data == 'negro') + return window.language.ClientePrecios.negro; + else if (data == 'negrohq') + return window.language.ClientePrecios.negrohq; + else if (data == 'color') + return window.language.ClientePrecios.color; + else if (data == 'colorhq') + return window.language.ClientePrecios.colorhq; + } + }, + { 'data': 'tiempo_min' }, + { 'data': 'tiempo_max' }, + { 'data': 'precio_hora' }, + { 'data': 'margen' }, + { 'data': 'user_updated' }, + { 'data': 'updated_at' }, + { 'data': 'plantilla_id' }, + + ]; + this.tableTarifas = new Table( + $('#tableOfPrecios'), + 'tarifasCliente', + '/clienteprecios/datatable', + columns, + [ + { name: 'cliente_id', value: window.location.href.split("/").pop() }, + { name: this.csrf_token, value: this.csrf_hash }, + ] + ); + + this.tableTarifas.init({ + actions: ['edit', 'delete'], + buttonsNewEditor: true, + + }); + + $('button[data-bs-target="#tarifascliente"]').on('shown.bs.tab', function(event) { + setTimeout(() => { + self.tableTarifas.table.columns.adjust().draw(); + }, 100); // Usamos setTimeout para asegurar que se dibuje después del renderizado + }); } -} \ No newline at end of file + + +} + +export default tarifasClienteView; \ No newline at end of file From 510e33b5fa01b864fe1af9756f2f7859fc26c412 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jaime=20Jim=C3=A9nez?= Date: Sun, 1 Dec 2024 20:44:15 +0100 Subject: [PATCH 03/18] trabajando en el editor --- .../Controllers/Clientes/ClientePrecios.php | 8 +- .../Models/Clientes/ClientePreciosModel.php | 17 +- .../clientes/cliente/_clienteFormItems.php | 12 +- .../form/clientes/cliente/viewClienteForm.php | 3 + .../assets/js/safekat/components/table.js | 175 ++++++++++++ .../js/safekat/components/tableEditor.js | 32 +++ .../js/safekat/pages/cliente/cliente.js | 2 + .../safekat/pages/cliente/tarifasCliente.js | 249 +++++++++++++++++- 8 files changed, 481 insertions(+), 17 deletions(-) create mode 100644 httpdocs/assets/js/safekat/components/table.js create mode 100644 httpdocs/assets/js/safekat/components/tableEditor.js diff --git a/ci4/app/Controllers/Clientes/ClientePrecios.php b/ci4/app/Controllers/Clientes/ClientePrecios.php index 2a73ba78..bc258921 100755 --- a/ci4/app/Controllers/Clientes/ClientePrecios.php +++ b/ci4/app/Controllers/Clientes/ClientePrecios.php @@ -108,16 +108,18 @@ class ClientePrecios extends \App\Controllers\BaseResourceController $dir3 = $reqData['order']['2']['dir'] ?? $dir; $dir4= $reqData['order']['3']['dir'] ?? $dir; $dir5= $reqData['order']['4']['dir'] ?? $dir; + + $searchValues = get_filter_datatables_columns($reqData); $cliente_id = $reqData['cliente_id'] ?? 0; - $resourceData = $this->model->getResource($cliente_id) + $resourceData = $this->model->getResource($searchValues, $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($cliente_id)->countAllResults(), - $this->model->getResource($cliente_id)->countAllResults() + $this->model->getResource($searchValues, $cliente_id)->countAllResults(), + $this->model->getResource($searchValues, $cliente_id)->countAllResults() )); } else { return $this->failUnauthorized('Invalid request', 403); diff --git a/ci4/app/Models/Clientes/ClientePreciosModel.php b/ci4/app/Models/Clientes/ClientePreciosModel.php index a52893c8..3bfbdb1d 100755 --- a/ci4/app/Models/Clientes/ClientePreciosModel.php +++ b/ci4/app/Models/Clientes/ClientePreciosModel.php @@ -256,7 +256,7 @@ class ClientePreciosModel extends \App\Models\BaseModel * * @return \CodeIgniter\Database\BaseBuilder */ - public function getResource($cliente_id = -1) + public function getResource($search = [], $cliente_id = -1) { $builder = $this->db ->table($this->table . " t1") @@ -271,9 +271,20 @@ class ClientePreciosModel extends \App\Models\BaseModel $builder->where('t1.is_deleted', 0); $builder->where('t1.cliente_id', $cliente_id); - - return $builder; + if (empty($search)) + return $builder; + else { + $builder->groupStart(); + foreach ($search as $col_search) { + if ($col_search[0] > 2) + $builder->like(self::SORTABLE[$col_search[0]], $col_search[2]); + else + $builder->where(self::SORTABLE[$col_search[0]], $col_search[2]); + } + $builder->groupEnd(); + return $builder; + } } diff --git a/ci4/app/Views/themes/vuexy/form/clientes/cliente/_clienteFormItems.php b/ci4/app/Views/themes/vuexy/form/clientes/cliente/_clienteFormItems.php index f66999c1..dc3e7967 100644 --- a/ci4/app/Views/themes/vuexy/form/clientes/cliente/_clienteFormItems.php +++ b/ci4/app/Views/themes/vuexy/form/clientes/cliente/_clienteFormItems.php @@ -591,10 +591,10 @@ - - - plantilla_id - + + + plantilla_id + @@ -924,7 +924,7 @@ $(document).on('click', '.btn-remove', function(e) { `; }; - +/* const tipo_linea = [ {label:'', value:'interior'}, {label:'', value: 'cubierta'}, @@ -1045,7 +1045,7 @@ $(document).on('click', '.btn-remove', function(e) { } }) }) - +*/ /* var theTablePrecios = $('#tableOfPrecios').DataTable( { diff --git a/ci4/app/Views/themes/vuexy/form/clientes/cliente/viewClienteForm.php b/ci4/app/Views/themes/vuexy/form/clientes/cliente/viewClienteForm.php index 9c3eb039..a149252e 100644 --- a/ci4/app/Views/themes/vuexy/form/clientes/cliente/viewClienteForm.php +++ b/ci4/app/Views/themes/vuexy/form/clientes/cliente/viewClienteForm.php @@ -43,5 +43,8 @@ section("additionalExternalJs") ?> + + + endSection() ?> \ No newline at end of file diff --git a/httpdocs/assets/js/safekat/components/table.js b/httpdocs/assets/js/safekat/components/table.js new file mode 100644 index 00000000..83ea0bee --- /dev/null +++ b/httpdocs/assets/js/safekat/components/table.js @@ -0,0 +1,175 @@ +let Table = function ( + domItem, + alias, + url, + columns, + data, + language = "es-ES") { + + this.domItem = domItem; + this.alias = alias; + this.url = url; + this.columns = columns; + this.data = data; + this.language = language; + + this.table = null; + this.actions = []; // Declaración inicial de actions como propiedad + this.deleteModal = null; + + const self = this; + + this.init = function ({ + dom = '<"mt-4"><"float-end"B><"float-start"l><"mt-4 mb-3"p>', + actions = ['view', 'edit', 'delete', 'cancel'], + order = [[0, 'asc']], + deleteModal = null, + buttonsExport = true, + buttonNewWithEditor = false, + editor = null, + booleanColumns = [], + } = {}) { + + this.actions = actions; // Guardar actions como propiedad de la instancia + this.deleteModal = deleteModal; + + const lastColNr = this.domItem.find("tr:first th").length - 1; + + let columnDefs = []; + if (actions.length > 0) { + columnDefs = [ + { + orderable: false, + searchable: false, + targets: [lastColNr] + } + ]; + columns.push( + { + 'data': self.actionBtns.bind(self), // Vincular correctamente el contexto + 'className': 'row-edit dt-center', + } + ); + } + + let buttons = []; + if (buttonsExport) { + buttons = [ + { + extend: 'colvis', + columns: ':not(.noVis)', + + }, + 'copy', 'csv', 'excel', 'print', { + extend: 'pdfHtml5', + orientation: 'landscape', + pageSize: 'A4' + } + ]; + } + if (buttonNewWithEditor) { + buttons.push( + { + className: 'btn btn-primary me-sm-3 me-1', + extend: "createInline", + editor: editor, + formOptions: { + submitTrigger: -1, + submitHtml: '' + } + } + ); + } + + // Inicialización de DataTable + this.table = this.domItem.DataTable({ + processing: true, + serverSide: true, + autoWidth: true, + responsive: true, + scrollX: true, + stateSave: false, + lengthMenu: [5, 10, 25, 50, 75, 100, 250, 500, 1000, 2500], + order: order, + orderCellsTop: true, + fixedHeader: true, + dom: dom, + ajax: $.fn.dataTable.pipeline({ + url: this.url, + method: 'POST', + headers: { 'X-Requested-With': 'XMLHttpRequest' }, + data: function (d) { + $.each(self.data, function (key, val) { + d[val.name] = val.value; + }); + }, + async: true, + }), + buttons: buttons, + columns: this.columns, + language: { + url: "/themes/vuexy/vendor/libs/datatables-sk/plugins/i18n/" + this.language + ".json" + }, + columnDefs: columnDefs, + }); + + if (Array.isArray(booleanColumns) && booleanColumns.length > 0) { + this.table.on('draw.dt', function () { + for (let coln of booleanColumns) { + self.table.column(coln, { page: 'current' }).nodes().each(function (cell) { + cell.innerHTML = cell.innerHTML == '1' ? '' : ''; + }); + } + }); + } + }; + + this.setData = function (data) { + this.data = data; + } + + this.setPageLength = function (length) { + this.table.page.len(length).draw(); + } + + this.setEditCallback = function (callback) { + this.domItem.on('click', '.btn-edit-' + this.alias, function () { + let id = $(this).data('id'); + callback(id); + }); + } + + this.setDeleteCallback = function (callback) { + this.domItem.on('click', '.btn-delete-' + this.alias, function () { + let id = $(this).data('id'); + callback(id); + }); + } + + this.setViewCallback = function (callback) { + this.domItem.on('click', '.btn-view-' + this.alias, function () { + let id = $(this).data('id'); + callback(id); + }); + } + + this.actionBtns = function (data) { + let btns = ``; + if (this.actions.includes('view')) { + btns += ``; + } + if (this.actions.includes('edit')) { + btns += ``; + } + if (this.actions.includes('delete')) { + btns += ``; + } + if (this.actions.includes('cancel')) { + btns += ``; + } + return btns; + }; + +} + +export default Table; diff --git a/httpdocs/assets/js/safekat/components/tableEditor.js b/httpdocs/assets/js/safekat/components/tableEditor.js new file mode 100644 index 00000000..89b12369 --- /dev/null +++ b/httpdocs/assets/js/safekat/components/tableEditor.js @@ -0,0 +1,32 @@ +let TableEditor = function ( + table, + url, + headers, + idSrc, + fields) { + + + this.table = table; + this.url = url; + this.headers = headers; + this.idSrc = idSrc; + this.fields = fields; + + this.editor = null; + + this.init = function () { + + this.editor = new $.fn.dataTable.Editor( { + ajax: { + url: url, + headers: headers, + }, + table : table, + idSrc: idSrc, + fields: fields + }); + }; +} + +export default TableEditor; + diff --git a/httpdocs/assets/js/safekat/pages/cliente/cliente.js b/httpdocs/assets/js/safekat/pages/cliente/cliente.js index 0bd83277..0ef85e60 100644 --- a/httpdocs/assets/js/safekat/pages/cliente/cliente.js +++ b/httpdocs/assets/js/safekat/pages/cliente/cliente.js @@ -57,6 +57,8 @@ class Cliente { document.addEventListener('DOMContentLoaded', function () { const locale = document.querySelector('meta[name="locale"]').getAttribute('content'); + + new Ajax('/translate/getTranslation', { locale: locale, translationFile: ['ClienteContactos', 'ClientePrecios'] }, {}, function(translations) { diff --git a/httpdocs/assets/js/safekat/pages/cliente/tarifasCliente.js b/httpdocs/assets/js/safekat/pages/cliente/tarifasCliente.js index 55d61ad0..5e6ad756 100644 --- a/httpdocs/assets/js/safekat/pages/cliente/tarifasCliente.js +++ b/httpdocs/assets/js/safekat/pages/cliente/tarifasCliente.js @@ -1,6 +1,8 @@ import Table from '../../components/table.js'; +import TableEditor from '../../components/tableEditor.js'; import { getToken } from '../../common/common.js'; + class tarifasClienteView { constructor(domItem) { @@ -12,12 +14,148 @@ class tarifasClienteView { this.clienteId = window.location.href.split("/").pop(); this.actions = ['edit', 'delete']; + + this.headerSearcher(); + + this.tableTarifas = null; + this.editorTarifas = null; } init() { const self = this; + const tipo_linea = [ + { label: window.language.ClientePrecios.interior, value: 'interior' }, + { label: window.language.ClientePrecios.cubierta, value: 'cubierta' }, + { label: window.language.ClientePrecios.sobrecubierta, value: 'sobrecubierta' } + ]; + + const tipo_maquina = [ + { label: window.language.ClientePrecios.toner, value: 'toner' }, + { label: window.language.ClientePrecios.inkjet, value: 'inkjet' }, + ]; + + const tipo_impresion = [ + { label: window.language.ClientePrecios.negro, value: 'negro' }, + { label: window.language.ClientePrecios.negrohq, value: 'negrohq' }, + { label: window.language.ClientePrecios.color, value: 'color' }, + { label: window.language.ClientePrecios.colorhq, value: 'colorhq' }, + ]; + + const editorFields = [{ + name: "tipo", + type: "select", + options: tipo_linea + }, { + name: "tipo_maquina", + type: "select", + options: tipo_maquina + }, { + name: "tipo_impresion", + type: "select", + options: tipo_impresion + }, { + name: "tiempo_min" + }, { + name: "tiempo_max" + }, { + name: "precio_hora" + }, { + name: "margen" + }, { + name: "user_updated_id", + type: 'hidden', + + }, { + name: "updated_at", + type: 'hidden', + + }, { + "name": "plantilla_id", + "type": "hidden" + }, { + "name": "cliente_id", + "type": "hidden" + }, { + "name": "deleted_at", + "type": "hidden" + }, { + "name": "is_deleted", + "type": "hidden" + }, + ]; + this.editorTarifas = new TableEditor( + $('#tableOfPrecios'), + '/clienteprecios/datatable_editor', + { [this.csrf_token]: this.csrf_hash }, + editorFields); + + this.editorTarifas.init(); + + this.editorTarifas.editor.on('preSubmit', function (e, d, type) { + if (type === 'create') { + d.data[0]['cliente_id'] = this.clienteId; + } + else if (type === 'edit') { + for (v in d.data) { + d.data[v]['cliente_id'] = this.clienteId; + } + } + }); + + this.editorTarifas.editor.on('submitSuccess', function (e, json, data, action) { + + this.tableTarifas.table.clearPipeline(); + this.tableTarifas.table.draw(); + }); + + this.editorTarifas.editor.on('postEdit', function (e, json, data, action) { + /*const domain = window.location.origin + fetch(domain + "/clientes/clienteprecios/update/" + id, { + method: "POST", + body: JSON.stringify({ + : v + }), + headers: { + "Content-type": "application/json; charset=UTF-8" + } + })*/ + }) + + this.editorTarifas.editor.on('postCreate', function (e, json, data, action) { + const domain = window.location.origin + /*fetch(domain + "/clientes/clienteprecios/update/" + id, { + method: "POST", + body: JSON.stringify({ + : v + }), + headers: { + "Content-type": "application/json; charset=UTF-8" + } + })*/ + }) + this.#initTable(); + + this.tableTarifas.table.on( 'click', 'tbody span.edit', function (e) { + self.editorTarifas.editor.inline( + self.tableTarifas.table.cells(this.parentNode.parentNode, '*').nodes(), + { + cancelHtml: '', + cancelTrigger: 'span.cancel', + submitHtml: '', + submitTrigger: 'span.edit', + submit: 'allIfChanged' + } + ); + } ); + } + + + #initTable() { + + const self = this; + const columns = [ { 'data': 'tipo', @@ -58,9 +196,14 @@ class tarifasClienteView { { 'data': 'margen' }, { 'data': 'user_updated' }, { 'data': 'updated_at' }, - { 'data': 'plantilla_id' }, + { + 'data': 'plantilla_id', + 'searchable': false, + 'visible': false, + }, ]; + this.tableTarifas = new Table( $('#tableOfPrecios'), 'tarifasCliente', @@ -72,20 +215,116 @@ class tarifasClienteView { ] ); + this.tableTarifas.init({ actions: ['edit', 'delete'], - buttonsNewEditor: true, - + buttonNewWithEditor: true, + buttonsExport: true, + editor: this.editorTarifas.editor, }); - $('button[data-bs-target="#tarifascliente"]').on('shown.bs.tab', function(event) { + + this.tableTarifas.table.on('init.dt', function () { + self.tableTarifas.table.page.len(50).draw(); + }); + + $('button[data-bs-target="#tarifascliente"]').on('shown.bs.tab', function (event) { setTimeout(() => { self.tableTarifas.table.columns.adjust().draw(); - }, 100); // Usamos setTimeout para asegurar que se dibuje después del renderizado + }, 1000); // Usamos setTimeout para asegurar que se dibuje después del renderizado }); + } + headerSearcher() { + const self = this; + + $('#tableOfPrecios thead tr').clone(false).appendTo('#tableOfPrecios thead'); + $('#tableOfPrecios thead tr:eq(1) th').each(function (i) { + + if (!$(this).hasClass("noFilter")) { + + if (i == 0) { + + // Agregar un selector en la segunda columna + $(this).html(''); + + // Agregar opciones al selector + var selector = $('select', this); + selector.append(''); // Opción vacía + selector.append(''); + selector.append(''); + selector.append(''); + + selector.on('change', function () { + var val = $.fn.dataTable.util.escapeRegex( + $(this).val() + ); + self.tableTarifas.table.column(i).search(val).draw(); + }); + + } + + else if (i == 1) { + // Agregar un selector en la tercera columna + $(this).html(''); + + // Agregar opciones al selector + var selector = $('select', this); + selector.append(''); // Opción vacía + selector.append(''); + selector.append(''); + + selector.on('change', function () { + var val = $.fn.dataTable.util.escapeRegex( + $(this).val() + ); + self.tableTarifas.table.column(i).search(val).draw(); + }); + } + + else if (i == 2) { + // Agregar un selector en la cuarta columna + $(this).html(''); + + // Agregar opciones al selector + var selector = $('select', this); + selector.append(''); // Opción vacía + selector.append(''); + selector.append(''); + selector.append(''); + selector.append(''); + + selector.on('change', function () { + var val = $.fn.dataTable.util.escapeRegex( + $(this).val() + ); + self.tableTarifas.table.column(i).search(val).draw(); + }); + } + else { + $(this).html(''); + + $('input', this).on('change clear', function () { + if (self.tableTarifas.table.column(i).search() !== this.value) { + self.tableTarifas.table + .column(i) + .search(this.value) + .draw(); + } + }); + } + } + else { + $(this).html(''); + } + }); + + + } } + + export default tarifasClienteView; \ No newline at end of file From 9bec8f7adb3ae1ad2df53fc7600af8b5a6def32b Mon Sep 17 00:00:00 2001 From: Jaime Jimenez Date: Mon, 2 Dec 2024 15:10:26 +0100 Subject: [PATCH 04/18] haciendo el borrar! --- .../Models/Clientes/ClientePreciosModel.php | 22 +- .../clientes/cliente/_clienteFormItems.php | 1 + .../form/clientes/cliente/viewClienteForm.php | 1 + .../safekat/components/ConfirmDeleteModal.js | 51 +++++ .../assets/js/safekat/components/table.js | 10 +- .../js/safekat/components/tableEditor.js | 2 +- .../safekat/pages/cliente/tarifasCliente.js | 196 ++++++++++-------- 7 files changed, 182 insertions(+), 101 deletions(-) create mode 100644 httpdocs/assets/js/safekat/components/ConfirmDeleteModal.js diff --git a/ci4/app/Models/Clientes/ClientePreciosModel.php b/ci4/app/Models/Clientes/ClientePreciosModel.php index 3bfbdb1d..eb76141d 100755 --- a/ci4/app/Models/Clientes/ClientePreciosModel.php +++ b/ci4/app/Models/Clientes/ClientePreciosModel.php @@ -14,14 +14,14 @@ class ClientePreciosModel extends \App\Models\BaseModel protected $useAutoIncrement = true; const SORTABLE = [ - 0 => "t1.tipo", - 1 => "t1.tipo_maquina", - 2 => "t1.tipo_impresion", - 3 => "t1.tiempo_min", - 4 => "t1.tiempo_max", - 5 => "t1.precio_hora", - 6 => "t1.margen", - + 0 => "t1.id", + 1 => "t1.tipo", + 2 => "t1.tipo_maquina", + 3 => "t1.tipo_impresion", + 4 => "t1.tiempo_min", + 5 => "t1.tiempo_max", + 6 => "t1.precio_hora", + 7 => "t1.margen", ]; protected $allowedFields = [ @@ -277,10 +277,10 @@ class ClientePreciosModel extends \App\Models\BaseModel else { $builder->groupStart(); foreach ($search as $col_search) { - if ($col_search[0] > 2) - $builder->like(self::SORTABLE[$col_search[0]], $col_search[2]); - else + if ($col_search[0] > 0 && $col_search[0] < 4) $builder->where(self::SORTABLE[$col_search[0]], $col_search[2]); + else + $builder->like(self::SORTABLE[$col_search[0]], $col_search[2]); } $builder->groupEnd(); return $builder; diff --git a/ci4/app/Views/themes/vuexy/form/clientes/cliente/_clienteFormItems.php b/ci4/app/Views/themes/vuexy/form/clientes/cliente/_clienteFormItems.php index dc3e7967..92c184d8 100644 --- a/ci4/app/Views/themes/vuexy/form/clientes/cliente/_clienteFormItems.php +++ b/ci4/app/Views/themes/vuexy/form/clientes/cliente/_clienteFormItems.php @@ -584,6 +584,7 @@ + diff --git a/ci4/app/Views/themes/vuexy/form/clientes/cliente/viewClienteForm.php b/ci4/app/Views/themes/vuexy/form/clientes/cliente/viewClienteForm.php index a149252e..84a2ea39 100644 --- a/ci4/app/Views/themes/vuexy/form/clientes/cliente/viewClienteForm.php +++ b/ci4/app/Views/themes/vuexy/form/clientes/cliente/viewClienteForm.php @@ -1,6 +1,7 @@ include("themes/_commonPartialsBs/datatables") ?> include("themes/_commonPartialsBs/select2bs5") ?> include("themes/_commonPartialsBs/sweetalert") ?> +include('themes/_commonPartialsBs/_confirm2delete') ?> extend('themes/vuexy/main/defaultlayout') ?> section("content") ?> diff --git a/httpdocs/assets/js/safekat/components/ConfirmDeleteModal.js b/httpdocs/assets/js/safekat/components/ConfirmDeleteModal.js new file mode 100644 index 00000000..a874abf7 --- /dev/null +++ b/httpdocs/assets/js/safekat/components/ConfirmDeleteModal.js @@ -0,0 +1,51 @@ +class ConfirmDeleteModal { + constructor(alias = "") { + this.modalId = 'confirm2delete'; + + const removeClass = alias !== "" ? `btn-remove-${alias}` : 'btn-remove'; + + this.modalHtml = ` + + `; + } + + // Método para mostrar el modal + show(callback) { + // Insertar el modal en el body del documento si no existe + if (!document.getElementById(this.modalId)) { + document.body.insertAdjacentHTML('beforeend', this.modalHtml); + } + + // Mostrar el modal usando Bootstrap + const modal = new bootstrap.Modal(document.getElementById(this.modalId)); + modal.show(); + + // Configurar el evento de confirmación de eliminación + document.getElementById('confirmDelete').addEventListener('click', () => { + callback(); // Llamar al callback que el usuario haya proporcionado + modal.hide(); // Cerrar el modal + }); + } + + // Método para ocultar el modal si es necesario + hide() { + const modal = new bootstrap.Modal(document.getElementById(this.modalId)); + modal.hide(); + } +} diff --git a/httpdocs/assets/js/safekat/components/table.js b/httpdocs/assets/js/safekat/components/table.js index 83ea0bee..2f3c8eb3 100644 --- a/httpdocs/assets/js/safekat/components/table.js +++ b/httpdocs/assets/js/safekat/components/table.js @@ -156,19 +156,21 @@ let Table = function ( this.actionBtns = function (data) { let btns = ``; if (this.actions.includes('view')) { - btns += ``; + btns += ``; } if (this.actions.includes('edit')) { btns += ``; } - if (this.actions.includes('delete')) { - btns += ``; - } if (this.actions.includes('cancel')) { btns += ``; } + if (this.actions.includes('delete')) { + btns += ``; + } + return btns; }; + } diff --git a/httpdocs/assets/js/safekat/components/tableEditor.js b/httpdocs/assets/js/safekat/components/tableEditor.js index 89b12369..c0a5c370 100644 --- a/httpdocs/assets/js/safekat/components/tableEditor.js +++ b/httpdocs/assets/js/safekat/components/tableEditor.js @@ -23,7 +23,7 @@ let TableEditor = function ( }, table : table, idSrc: idSrc, - fields: fields + fields: fields, }); }; } diff --git a/httpdocs/assets/js/safekat/pages/cliente/tarifasCliente.js b/httpdocs/assets/js/safekat/pages/cliente/tarifasCliente.js index 5e6ad756..be539820 100644 --- a/httpdocs/assets/js/safekat/pages/cliente/tarifasCliente.js +++ b/httpdocs/assets/js/safekat/pages/cliente/tarifasCliente.js @@ -1,5 +1,6 @@ import Table from '../../components/table.js'; import TableEditor from '../../components/tableEditor.js'; +import Confirm2Delete from '../../components/confirm2delete.js'; import { getToken } from '../../common/common.js'; @@ -13,18 +14,51 @@ class tarifasClienteView { this.csrf_hash = $('#mainContainer').find('input[name="' + this.csrf_token + '"]').val(); this.clienteId = window.location.href.split("/").pop(); - this.actions = ['edit', 'delete']; + this.actions = ['edit', 'delete', 'cancel']; this.headerSearcher(); this.tableTarifas = null; this.editorTarifas = null; + this.confirmDeleteModal = null; } init() { const self = this; + this.#initEditor(); + + this.#initTable(); + + + // Editar en linea la fila + this.tableTarifas.table.on('click', 'tbody span.edit', function (e) { + + const row = $(this).closest('tr'); + + // Iniciar la edición en línea para todas las celdas de la fila + self.editorTarifas.editor.inline( + self.tableTarifas.table.cells(row, '*').nodes(), + { + cancelHtml: '', + submitHtml: '', + cancelTrigger: row.find('span.cancel')[0], + submitTrigger: row.find('span.edit')[0], + submit: 'allIfChanged' + } + ); + }); + + + + } + + + #initEditor() { + + const self = this; + const tipo_linea = [ { label: window.language.ClientePrecios.interior, value: 'interior' }, { label: window.language.ClientePrecios.cubierta, value: 'cubierta' }, @@ -43,120 +77,111 @@ class tarifasClienteView { { label: window.language.ClientePrecios.colorhq, value: 'colorhq' }, ]; - const editorFields = [{ - name: "tipo", - type: "select", - options: tipo_linea - }, { - name: "tipo_maquina", - type: "select", - options: tipo_maquina - }, { - name: "tipo_impresion", - type: "select", - options: tipo_impresion - }, { - name: "tiempo_min" - }, { - name: "tiempo_max" - }, { - name: "precio_hora" - }, { - name: "margen" - }, { - name: "user_updated_id", - type: 'hidden', + const editorFields = [ + { + name: "id", + type: "readonly" + }, { + name: "tipo", + type: "select", + options: tipo_linea + }, { + name: "tipo_maquina", + type: "select", + options: tipo_maquina + }, { + name: "tipo_impresion", + type: "select", + options: tipo_impresion + }, { + name: "tiempo_min" + }, { + name: "tiempo_max" + }, { + name: "precio_hora" + }, { + name: "margen" + }, { + name: "user_updated_id", + type: 'hidden', - }, { - name: "updated_at", - type: 'hidden', + }, { + name: "updated_at", + type: 'hidden', - }, { - "name": "plantilla_id", - "type": "hidden" - }, { - "name": "cliente_id", - "type": "hidden" - }, { - "name": "deleted_at", - "type": "hidden" - }, { - "name": "is_deleted", - "type": "hidden" - }, + }, { + name: "plantilla_id", + type: "hidden" + }, { + name: "cliente_id", + type: "hidden" + }, { + name: "deleted_at", + type: "hidden" + }, { + name: "is_deleted", + type: "hidden" + }, ]; this.editorTarifas = new TableEditor( $('#tableOfPrecios'), '/clienteprecios/datatable_editor', { [this.csrf_token]: this.csrf_hash }, + 'id', editorFields); this.editorTarifas.init(); this.editorTarifas.editor.on('preSubmit', function (e, d, type) { if (type === 'create') { - d.data[0]['cliente_id'] = this.clienteId; - } - else if (type === 'edit') { - for (v in d.data) { - d.data[v]['cliente_id'] = this.clienteId; - } + d.data[0]['cliente_id'] = self.clienteId; } }); this.editorTarifas.editor.on('submitSuccess', function (e, json, data, action) { - this.tableTarifas.table.clearPipeline(); - this.tableTarifas.table.draw(); + self.tableTarifas.table.clearPipeline(); + self.tableTarifas.table.draw(); }); + this.editorTarifas.editor.on('postEdit', function (e, json, data, action) { - /*const domain = window.location.origin - fetch(domain + "/clientes/clienteprecios/update/" + id, { - method: "POST", - body: JSON.stringify({ - : v - }), - headers: { - "Content-type": "application/json; charset=UTF-8" - } - })*/ + self.#borrarPlantillaTarifa(self.clienteId); }) this.editorTarifas.editor.on('postCreate', function (e, json, data, action) { - const domain = window.location.origin - /*fetch(domain + "/clientes/clienteprecios/update/" + id, { - method: "POST", - body: JSON.stringify({ - : v - }), - headers: { - "Content-type": "application/json; charset=UTF-8" - } - })*/ + self.#borrarPlantillaTarifa(self.clienteId); }) - this.#initTable(); - this.tableTarifas.table.on( 'click', 'tbody span.edit', function (e) { - self.editorTarifas.editor.inline( - self.tableTarifas.table.cells(this.parentNode.parentNode, '*').nodes(), - { - cancelHtml: '', - cancelTrigger: 'span.cancel', - submitHtml: '', - submitTrigger: 'span.edit', - submit: 'allIfChanged' - } - ); - } ); + this.editorTarifas.editor.on('postCancel', function (e, json, data) { + // Restaurar botones de acción por fila + self.tableTarifas.table.rows().nodes().each(function (node) { + $(node).find('span.edit').removeClass('d-none'); + $(node).find('span.cancel, span.submit').addClass('d-none'); + }); + }); } + #borrarPlantillaTarifa(id) { + + const domain = window.location.origin + fetch(domain + "/clientes/clienteprecios/update/" + id, { + method: "POST", + body: JSON.stringify({ + [self.csrf_token]: self.csrf_hash + }), + headers: { + "Content-type": "application/json; charset=UTF-8" + } + }) + } #initTable() { const self = this; const columns = [ + { 'data': 'id' }, { 'data': 'tipo', 'render': function (data, type, row, meta) { @@ -217,10 +242,11 @@ class tarifasClienteView { this.tableTarifas.init({ - actions: ['edit', 'delete'], + actions: self.actions, buttonNewWithEditor: true, buttonsExport: true, editor: this.editorTarifas.editor, + deleteModal: '#confirm2delete' }); @@ -245,7 +271,7 @@ class tarifasClienteView { if (!$(this).hasClass("noFilter")) { - if (i == 0) { + if (i == 1) { // Agregar un selector en la segunda columna $(this).html(''); @@ -266,7 +292,7 @@ class tarifasClienteView { } - else if (i == 1) { + else if (i == 2) { // Agregar un selector en la tercera columna $(this).html(''); @@ -284,7 +310,7 @@ class tarifasClienteView { }); } - else if (i == 2) { + else if (i == 3) { // Agregar un selector en la cuarta columna $(this).html(''); From 6eb4446affe3edad2cb0a7f5844511ec267c169f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jaime=20Jim=C3=A9nez?= Date: Mon, 2 Dec 2024 18:22:26 +0100 Subject: [PATCH 05/18] solucionado problema --- .../Services/PresupuestoClienteService.php | 5 ++++ ci4/app/Services/PresupuestoService.php | 30 +++++++++---------- 2 files changed, 20 insertions(+), 15 deletions(-) diff --git a/ci4/app/Services/PresupuestoClienteService.php b/ci4/app/Services/PresupuestoClienteService.php index 000a27e3..d066937d 100644 --- a/ci4/app/Services/PresupuestoClienteService.php +++ b/ci4/app/Services/PresupuestoClienteService.php @@ -523,6 +523,11 @@ class PresupuestoClienteService extends BaseService $linea_rotativa = array_merge($linea_rotativa, $lineas); } } + + $linea_rotativa = array_filter($linea_rotativa, function($item) { + return count($item['fields']['num_formas']) > 1; + }); + if (count($linea_rotativa) > 0) { usort( diff --git a/ci4/app/Services/PresupuestoService.php b/ci4/app/Services/PresupuestoService.php index 1aba14fd..a9495780 100755 --- a/ci4/app/Services/PresupuestoService.php +++ b/ci4/app/Services/PresupuestoService.php @@ -639,11 +639,11 @@ class PresupuestoService extends BaseService $calles = (new \App\Models\Configuracion\MaquinasCallesModel())->getCallesForMaquina($maquina->maquina_id, $h1_temp); // Si son mas de 2 formas if (count($calles) > 0) - $h1 = ($h1_temp * $anchoForCalculo + 2 * $calles[0]->externas + ($h1_temp - 1) * $calles[0]->internas < ($maquina->ancho)) ? $h1_temp : $h1_temp - 1; + $h1 = ($h1_temp * $anchoForCalculo + 2 * $calles[0]->externas + ($h1_temp - 1) * $calles[0]->internas < (floatval($maquina->ancho))) ? $h1_temp : $h1_temp - 1; else $h1 = $h1_temp; - $v1 = floor($maquina->alto_click / $altoForCalculo); + $v1 = floor(floatval($maquina->alto_click) / $altoForCalculo); $formas_h = $h1 * $v1; //p1 } // verticales @@ -651,10 +651,10 @@ class PresupuestoService extends BaseService $calles = (new \App\Models\Configuracion\MaquinasCallesModel())->getCallesForMaquina($maquina->maquina_id, $h2_temp); if (count($calles) > 0) - $h2 = ($h2_temp * $altoForCalculo + 2 * $calles[0]->externas + ($h2_temp - 1) * $calles[0]->internas < ($maquina->ancho)) ? $h2_temp : $h2_temp - 1; + $h2 = ($h2_temp * $altoForCalculo + 2 * $calles[0]->externas + ($h2_temp - 1) * $calles[0]->internas < (floatval($maquina->ancho))) ? $h2_temp : $h2_temp - 1; else $h2 = $h2_temp; - $v2 = floor($maquina->alto_click / $anchoForCalculo); + $v2 = floor(floatval($maquina->alto_click) / $anchoForCalculo); $formas_v = $h2 * $v2; //p2 } @@ -1061,16 +1061,16 @@ class PresupuestoService extends BaseService ), 'cliente_id' => ($input_data['presupuesto'])->cliente_id, 'datosTipolog' => [ - (object) array( - 'negro' => $linea->rotativa_negro, - 'cyan' => $linea->rotativa_cyan, - 'magenta' => $linea->rotativa_magenta, - 'amarillo' => $linea->rotativa_amarillo, - 'cg' => $linea->rotativa_cg, - 'gota_negro' => $linea->rotativa_gota_negro, - 'gota_color' => $linea->rotativa_gota_color, - ) - ] + (object) array( + 'negro' => $linea->rotativa_negro, + 'cyan' => $linea->rotativa_cyan, + 'magenta' => $linea->rotativa_magenta, + 'amarillo' => $linea->rotativa_amarillo, + 'cg' => $linea->rotativa_cg, + 'gota_negro' => $linea->rotativa_gota_negro, + 'gota_color' => $linea->rotativa_gota_color, + ) + ] ]; $comp_data = PresupuestoService::obtenerComparadorRotativa($datos); @@ -1816,7 +1816,7 @@ class PresupuestoService extends BaseService } if ($uso == 'cubierta' || $uso == 'sobrecubierta') { - + $linea['fields']['dimension_desarrollo']['ancho'] = $datosPedido->anchoExteriores; $linea['fields']['dimension_desarrollo']['alto'] = $datosPedido->altoExteriores; } From 310b4e7a43f78a8aef9cd23d1b9003d91672bf8a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jaime=20Jim=C3=A9nez?= Date: Mon, 2 Dec 2024 19:01:21 +0100 Subject: [PATCH 06/18] =?UTF-8?q?a=C3=B1adido=20que=20si=20no=20es=20pod?= =?UTF-8?q?=20busca=20papel=20rotativa=20para=20color=20y=20negro?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Configuracion/Papelesgenericos.php | 28 +++++++++++++++++-- .../Configuracion/PapelGenericoModel.php | 9 +++++- .../presupuestoCliente/datosGenerales.js | 2 ++ .../presupuestoCliente/disenioInterior.js | 15 ++++------ 4 files changed, 41 insertions(+), 13 deletions(-) diff --git a/ci4/app/Controllers/Configuracion/Papelesgenericos.php b/ci4/app/Controllers/Configuracion/Papelesgenericos.php index 628be5c4..861131df 100755 --- a/ci4/app/Controllers/Configuracion/Papelesgenericos.php +++ b/ci4/app/Controllers/Configuracion/Papelesgenericos.php @@ -298,13 +298,24 @@ class Papelesgenericos extends \App\Controllers\BaseResourceController { if ($this->request->isAJAX()) { + $tirada = goSanitize($this->request->getGet('tirada'))[0] ?? null; + $POD = null; + if($tirada != null){ + $POD_value = model('App\Models\Configuracion\ConfiguracionSistemaModel')->getPOD(); + 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; - $menu = $this->model->getPapelCliente($tipo, $cubierta, $selected_papel, $tapa_dura, false); - $menu2 = $this->model->getPapelCliente($tipo, $cubierta, $selected_papel, $tapa_dura, true); + $menu = $this->model->getPapelCliente($tipo, $cubierta, $selected_papel, $tapa_dura, false, $POD); + $menu2 = $this->model->getPapelCliente($tipo, $cubierta, $selected_papel, $tapa_dura, true, $POD); $newTokenHash = csrf_hash(); $csrfTokenName = csrf_token(); @@ -325,10 +336,21 @@ class Papelesgenericos extends \App\Controllers\BaseResourceController if ($this->request->isAJAX()) { + $tirada = goSanitize($this->request->getGet('tirada'))[0] ?? null; + $POD = null; + if($tirada != null){ + $POD_value = model('App\Models\Configuracion\ConfiguracionSistemaModel')->getPOD(); + 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; - $items = $this->model->getPapelCliente($tipo, $cubierta, null, true); + $items = $this->model->getPapelCliente($tipo, $cubierta, null, true, $POD); $items = array_map(function ($item) { return [ 'id' => $item->id, diff --git a/ci4/app/Models/Configuracion/PapelGenericoModel.php b/ci4/app/Models/Configuracion/PapelGenericoModel.php index 63f0403e..2012b392 100755 --- a/ci4/app/Models/Configuracion/PapelGenericoModel.php +++ b/ci4/app/Models/Configuracion/PapelGenericoModel.php @@ -313,7 +313,7 @@ class PapelGenericoModel extends \App\Models\BaseModel } - public function getPapelCliente($tipo, $is_cubierta = false, $selected_papel_id = null, $tapa_dura = null, $papel_especial = false) + public function getPapelCliente($tipo, $is_cubierta = false, $selected_papel_id = null, $tapa_dura = null, $papel_especial = false, $POD = null) { /* 1.-> Tipo impresion @@ -404,6 +404,13 @@ class PapelGenericoModel extends \App\Models\BaseModel if ($tipo == 'colorhq' || $tipo == 'negrohq') { $builder->where("t2.rotativa", 0); } + else{ + if($POD == false){ + if(($tipo == 'color' || $tipo == 'negro')){ + $builder->where("t2.rotativa", 1); + } + } + } if ($selected_papel_id != null) diff --git a/httpdocs/assets/js/safekat/pages/presupuestoCliente/datosGenerales.js b/httpdocs/assets/js/safekat/pages/presupuestoCliente/datosGenerales.js index ce8f2226..7821b5bd 100644 --- a/httpdocs/assets/js/safekat/pages/presupuestoCliente/datosGenerales.js +++ b/httpdocs/assets/js/safekat/pages/presupuestoCliente/datosGenerales.js @@ -727,6 +727,8 @@ class DatosGenerales { } // Para recalcular el presupuesto + $('#divGramajeInterior').empty(); + $('#divGramajeInteriorColor').empty(); element.trigger('change'); } diff --git a/httpdocs/assets/js/safekat/pages/presupuestoCliente/disenioInterior.js b/httpdocs/assets/js/safekat/pages/presupuestoCliente/disenioInterior.js index 02669b39..61c0a0cb 100644 --- a/httpdocs/assets/js/safekat/pages/presupuestoCliente/disenioInterior.js +++ b/httpdocs/assets/js/safekat/pages/presupuestoCliente/disenioInterior.js @@ -42,15 +42,6 @@ class DisenioInterior { this.colorPremium_color = this.domItem.find("#colorPremiumColor"); this.gramaje_color = this.domItem.find(".check-interior-color-gramaje"); - this.gramaje70_color = this.domItem.find("#interiorGramaje70Color"); - this.gramaje80_color = this.domItem.find("#interiorGramaje80Color"); - this.gramaje90_color = this.domItem.find("#interiorGramaje90Color"); - this.gramaje100_color = this.domItem.find("#interiorGramaje100Color"); - this.gramaje115_color = this.domItem.find("#interiorGramaje115Color"); - this.gramaje120_color = this.domItem.find("#interiorGramaje120Color"); - this.gramaje135_color = this.domItem.find("#interiorGramaje135Color"); - this.gramaje150_color = this.domItem.find("#interiorGramaje150Color"); - this.gramaje170_color = this.domItem.find("#interiorGramaje170Color"); this.checksGramaje = $('.gramaje-interior'); @@ -121,6 +112,7 @@ class DisenioInterior { new Ajax('/papelesgenericos/getpapelcliente', { [this.csrf_token]: this.csrf_hash, + tirada: $('#tirada').val(), tipo: this.getTipoImpresion(), cubierta: 0, }, @@ -135,6 +127,7 @@ class DisenioInterior { new Ajax('/papelesgenericos/getpapelcliente', { [this.csrf_token]: this.csrf_hash, + tirada: $('#tirada').val(), tipo: this.getTipoImpresion(), cubierta: 0, }, @@ -859,6 +852,7 @@ class DisenioInterior { new Ajax('/papelesgenericos/getpapelcliente', { [this.csrf_token]: this.csrf_hash, + tirada: $('#tirada').val(), papel: papel, tipo: tipo, cubierta: 0, @@ -886,6 +880,7 @@ class DisenioInterior { new Ajax('/papelesgenericos/getpapelcliente', { [this.csrf_token]: this.csrf_hash, + tirada: $('#tirada').val(), papel: this.papelInterior, tipo: tipo, cubierta: 0, @@ -931,6 +926,7 @@ class DisenioInterior { new Ajax('/papelesgenericos/getpapelcliente', { [this.csrf_token]: this.csrf_hash, + tirada: $('#tirada').val(), papel: papel, tipo: tipo, cubierta: 0, @@ -954,6 +950,7 @@ class DisenioInterior { new Ajax('/papelesgenericos/getpapelcliente', { [this.csrf_token]: this.csrf_hash, + tirada: $('#tirada').val(), papel: this.papelInterior, tipo: tipo, cubierta: 0, From 3c8d99c873ca5de4bb8b971e84900c70a600c6dc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jaime=20Jim=C3=A9nez?= Date: Mon, 2 Dec 2024 19:05:57 +0100 Subject: [PATCH 07/18] corregido para POD --- ci4/app/Models/Configuracion/PapelGenericoModel.php | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/ci4/app/Models/Configuracion/PapelGenericoModel.php b/ci4/app/Models/Configuracion/PapelGenericoModel.php index 2012b392..8ee13720 100755 --- a/ci4/app/Models/Configuracion/PapelGenericoModel.php +++ b/ci4/app/Models/Configuracion/PapelGenericoModel.php @@ -405,10 +405,12 @@ class PapelGenericoModel extends \App\Models\BaseModel $builder->where("t2.rotativa", 0); } else{ - if($POD == false){ - if(($tipo == 'color' || $tipo == 'negro')){ - $builder->where("t2.rotativa", 1); - } + if($POD == false){ + $builder->where("t2.rotativa", 1); + + } + else if ($POD == true){ + $builder->where("t2.rotativa", 0); } } From af131b6658a1772f04fecef7de60cc29ec9e0147 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jaime=20Jim=C3=A9nez?= Date: Mon, 2 Dec 2024 19:23:13 +0100 Subject: [PATCH 08/18] POD siempre en hq --- ci4/app/Models/Configuracion/PapelGenericoModel.php | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/ci4/app/Models/Configuracion/PapelGenericoModel.php b/ci4/app/Models/Configuracion/PapelGenericoModel.php index 8ee13720..70c0447c 100755 --- a/ci4/app/Models/Configuracion/PapelGenericoModel.php +++ b/ci4/app/Models/Configuracion/PapelGenericoModel.php @@ -322,6 +322,13 @@ class PapelGenericoModel extends \App\Models\BaseModel 4.-> papeles genericos que aparecen en esos papeles impresion */ + if ($POD == true && ($tipo == 'color' || $tipo == 'negro')) { + if($tipo == 'color') + $tipo = 'colorhq'; + else if($tipo == 'negro') + $tipo = 'negrohq'; + } + if ($selected_papel_id != null) { $builder = $this->db ->table($this->table . " t1") @@ -407,7 +414,6 @@ class PapelGenericoModel extends \App\Models\BaseModel else{ if($POD == false){ $builder->where("t2.rotativa", 1); - } else if ($POD == true){ $builder->where("t2.rotativa", 0); From 515d275c7eec9f0fb1e6216c9f01cf2ef2a9f5e3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jaime=20Jim=C3=A9nez?= Date: Mon, 2 Dec 2024 19:44:23 +0100 Subject: [PATCH 09/18] para POD siempre es HQ --- .../Controllers/Presupuestos/Presupuestocliente.php | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/ci4/app/Controllers/Presupuestos/Presupuestocliente.php b/ci4/app/Controllers/Presupuestos/Presupuestocliente.php index f0ae65af..a7f3d0be 100755 --- a/ci4/app/Controllers/Presupuestos/Presupuestocliente.php +++ b/ci4/app/Controllers/Presupuestos/Presupuestocliente.php @@ -522,6 +522,11 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController 'a_favor_fibra' => 1, ); + // Para POD siempre es HQ + if ($tirada[0] <= $POD) { + $isHq = true; + } + $input_data = array( 'uso' => 'interior', 'tipo_impresion_id' => $tipo_impresion_id, @@ -1509,6 +1514,11 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController $info['merma'] = $datosPedido->merma; } + // Para POD siempre es HQ + if ($tirada[$t] <= $POD) { + $isHq = true; + } + $input_data = array( 'uso' => 'interior', 'tipo_impresion_id' => $tipo_impresion_id, From 2c3b8cb581b29ea193b9f5d2c70bfaf73948d873 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jaime=20Jim=C3=A9nez?= Date: Mon, 2 Dec 2024 20:50:11 +0100 Subject: [PATCH 10/18] resuelto direcciones en nuevo presupuesto cliente y quitar check papeles distintos --- .../presupuestos/cliente/items/_datosGenerales.php | 2 +- .../safekat/pages/presupuestoCliente/datosGenerales.js | 10 +++++----- .../pages/presupuestoCliente/presupuestoCliente.js | 2 +- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/ci4/app/Views/themes/vuexy/form/presupuestos/cliente/items/_datosGenerales.php b/ci4/app/Views/themes/vuexy/form/presupuestos/cliente/items/_datosGenerales.php index 3f9997af..2456bd2a 100644 --- a/ci4/app/Views/themes/vuexy/form/presupuestos/cliente/items/_datosGenerales.php +++ b/ci4/app/Views/themes/vuexy/form/presupuestos/cliente/items/_datosGenerales.php @@ -63,7 +63,7 @@ -
">
user()->inGroup('cliente-admin') || auth()->user()->inGroup('cliente-editor')) ? " hidden" : "" ?> class=" calcular-solapas calcular-presupuesto form-check-input" type="checkbox" id="excluirRotativa" diff --git a/httpdocs/assets/js/safekat/pages/presupuestoCliente/datosGenerales.js b/httpdocs/assets/js/safekat/pages/presupuestoCliente/datosGenerales.js index 7821b5bd..5cb58bd9 100644 --- a/httpdocs/assets/js/safekat/pages/presupuestoCliente/datosGenerales.js +++ b/httpdocs/assets/js/safekat/pages/presupuestoCliente/datosGenerales.js @@ -572,8 +572,8 @@ class DatosGenerales { this.pagColorConsecutivas.prop('checked', datos.paginasColorConsecutivas); if (datos.paginasColorConsecutivas) { - this.divPapelDiferente.removeClass('d-none'); - this.papelDiferente.prop('checked', datos.papelInteriorDiferente).trigger('change'); + //this.divPapelDiferente.removeClass('d-none'); + //this.papelDiferente.prop('checked', datos.papelInteriorDiferente).trigger('change'); } this.posPaginasColor.val(datos.posPaginasColor); @@ -794,11 +794,11 @@ class DatosGenerales { #handPaginasConsecutivas() { if (this.pagColorConsecutivas.is(':checked')) { - this.divPapelDiferente.removeClass('d-none'); + //this.divPapelDiferente.removeClass('d-none'); } else { - this.divPapelDiferente.addClass('d-none'); - this.papelDiferente.prop('checked', false); + /*this.divPapelDiferente.addClass('d-none'); + this.papelDiferente.prop('checked', false);*/ } } diff --git a/httpdocs/assets/js/safekat/pages/presupuestoCliente/presupuestoCliente.js b/httpdocs/assets/js/safekat/pages/presupuestoCliente/presupuestoCliente.js index 431b1d76..5ce4fa4a 100644 --- a/httpdocs/assets/js/safekat/pages/presupuestoCliente/presupuestoCliente.js +++ b/httpdocs/assets/js/safekat/pages/presupuestoCliente/presupuestoCliente.js @@ -78,7 +78,7 @@ class PresupuestoCliente { } - if (this.datosGenerales.excluirRotativa.length == 0) { + if ($('#divExcluirRotativa').hasClass('d-none')) { this.direcciones.direccionesCliente.setParams({ 'cliente_id': $("#clienteId").val() }) } From aa22b81c965f337748b9ea784ed1b076337dbd1a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jaime=20Jim=C3=A9nez?= Date: Tue, 3 Dec 2024 17:51:03 +0100 Subject: [PATCH 11/18] =?UTF-8?q?terminada=20pesta=C3=B1a=20cliente=20tari?= =?UTF-8?q?fas?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Controllers/Clientes/ClientePrecios.php | 6 +-- .../safekat/components/ConfirmDeleteModal.js | 42 ++++++++++++++++--- .../assets/js/safekat/components/table.js | 10 +++-- .../safekat/pages/cliente/tarifasCliente.js | 24 ++++++++++- 4 files changed, 66 insertions(+), 16 deletions(-) diff --git a/ci4/app/Controllers/Clientes/ClientePrecios.php b/ci4/app/Controllers/Clientes/ClientePrecios.php index bc258921..105d085a 100755 --- a/ci4/app/Controllers/Clientes/ClientePrecios.php +++ b/ci4/app/Controllers/Clientes/ClientePrecios.php @@ -205,21 +205,19 @@ class ClientePrecios extends \App\Controllers\BaseResourceController } }) ->on('preCreate', function ($editor, &$values) { - $session = session(); $datetime = (new \CodeIgniter\I18n\Time("now")); $editor ->field('user_updated_id') - ->setValue($session->id_user); + ->setValue(auth()->user()->id); $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($session->id_user); + ->setValue(auth()->user()->id); $editor ->field('updated_at') ->setValue($datetime->format('Y-m-d H:i:s')); diff --git a/httpdocs/assets/js/safekat/components/ConfirmDeleteModal.js b/httpdocs/assets/js/safekat/components/ConfirmDeleteModal.js index a874abf7..161c593f 100644 --- a/httpdocs/assets/js/safekat/components/ConfirmDeleteModal.js +++ b/httpdocs/assets/js/safekat/components/ConfirmDeleteModal.js @@ -1,9 +1,16 @@ class ConfirmDeleteModal { + constructor(alias = "") { - this.modalId = 'confirm2delete'; + + this.modalId = alias !== "" ? `confirm2delete-${alias}`: 'confirm2delete'; const removeClass = alias !== "" ? `btn-remove-${alias}` : 'btn-remove'; + this.btnCancelId = alias !== "" ? `btnCancelDelete-${alias}` : 'btnCancelDelete'; + this.btnDeleteId = alias !== "" ? `btnConfirmDelete-${alias}` : 'btnConfirmDelete'; + + this.data = null; + this.modalHtml = `
@@ -25,19 +32,39 @@ class ConfirmDeleteModal { `; } - // Método para mostrar el modal - show(callback) { + init() { + // Insertar el modal en el body del documento si no existe if (!document.getElementById(this.modalId)) { document.body.insertAdjacentHTML('beforeend', this.modalHtml); } + document.getElementById(this.btnCancelId).addEventListener('click', () => { + const modal = new bootstrap.Modal(document.getElementById(this.modalId)); + modal.hide(); + }); + } + + getModalId() { + return '#' + this.modalId; + } + + setData(data) { + this.data = data; + } + + getData() { + return this.data; + } + + // Método para mostrar el modal + show(callback) { // Mostrar el modal usando Bootstrap const modal = new bootstrap.Modal(document.getElementById(this.modalId)); modal.show(); // Configurar el evento de confirmación de eliminación - document.getElementById('confirmDelete').addEventListener('click', () => { + document.getElementById(this.btnDeleteId).addEventListener('click', () => { callback(); // Llamar al callback que el usuario haya proporcionado modal.hide(); // Cerrar el modal }); @@ -49,3 +76,6 @@ class ConfirmDeleteModal { modal.hide(); } } + + +export default ConfirmDeleteModal; \ No newline at end of file diff --git a/httpdocs/assets/js/safekat/components/table.js b/httpdocs/assets/js/safekat/components/table.js index 2f3c8eb3..84f94c7b 100644 --- a/httpdocs/assets/js/safekat/components/table.js +++ b/httpdocs/assets/js/safekat/components/table.js @@ -23,15 +23,13 @@ let Table = function ( dom = '<"mt-4"><"float-end"B><"float-start"l><"mt-4 mb-3"p>', actions = ['view', 'edit', 'delete', 'cancel'], order = [[0, 'asc']], - deleteModal = null, buttonsExport = true, buttonNewWithEditor = false, editor = null, booleanColumns = [], } = {}) { - this.actions = actions; // Guardar actions como propiedad de la instancia - this.deleteModal = deleteModal; + this.actions = actions; const lastColNr = this.domItem.find("tr:first th").length - 1; @@ -124,6 +122,10 @@ let Table = function ( } }; + this.getAlias = function () { + return this.alias; + } + this.setData = function (data) { this.data = data; } @@ -165,7 +167,7 @@ let Table = function ( btns += ``; } if (this.actions.includes('delete')) { - btns += ``; + btns += ``; } return btns; diff --git a/httpdocs/assets/js/safekat/pages/cliente/tarifasCliente.js b/httpdocs/assets/js/safekat/pages/cliente/tarifasCliente.js index be539820..0ed7c8ea 100644 --- a/httpdocs/assets/js/safekat/pages/cliente/tarifasCliente.js +++ b/httpdocs/assets/js/safekat/pages/cliente/tarifasCliente.js @@ -1,6 +1,6 @@ import Table from '../../components/table.js'; import TableEditor from '../../components/tableEditor.js'; -import Confirm2Delete from '../../components/confirm2delete.js'; +import ConfirmDeleteModal from '../../components/ConfirmDeleteModal.js'; import { getToken } from '../../common/common.js'; @@ -21,12 +21,16 @@ class tarifasClienteView { this.tableTarifas = null; this.editorTarifas = null; this.confirmDeleteModal = null; + this.deleteModal = null; } init() { const self = this; + this.deleteModal = new ConfirmDeleteModal('tarifascliente'); + this.deleteModal.init(); + this.#initEditor(); this.#initTable(); @@ -51,6 +55,21 @@ class tarifasClienteView { }); + this.tableTarifas.table.on('click', '.btn-delete-' + this.tableTarifas.getAlias(), function (e) { + const row = $(this).closest('tr')[0]._DT_RowIndex; + self.deleteModal.setData($(this).attr('data-id')); + self.deleteModal.show(() =>{ + if ($.isNumeric(self.deleteModal.getData())) { + self.editorTarifas.editor + .create( false ) + .edit( self.tableTarifas.table.rows(row), false) + .set( 'deleted_at', new Date().toISOString().slice(0, 19).replace('T', ' ') ) + .set( 'is_deleted', 1 ) + .submit(); + self.deleteModal.hide(); + } + }); + }); } @@ -246,7 +265,6 @@ class tarifasClienteView { buttonNewWithEditor: true, buttonsExport: true, editor: this.editorTarifas.editor, - deleteModal: '#confirm2delete' }); @@ -262,6 +280,8 @@ class tarifasClienteView { } + + headerSearcher() { const self = this; From 3fb37af0f8746ca9f4352ca3149f71bafce71a87 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jaime=20Jim=C3=A9nez?= Date: Tue, 3 Dec 2024 22:59:57 +0100 Subject: [PATCH 12/18] terminadas tarifas cliente --- ci4/app/Config/Routes.php | 4 +- .../Controllers/Clientes/ClientePrecios.php | 168 ++++++----- .../Clientes/Clienteplantillaprecios.php | 109 +++---- .../ClientePlantillaPreciosLineasModel.php | 5 +- .../Models/Clientes/ClientePreciosModel.php | 21 ++ .../clientes/cliente/_clienteFormItems.php | 276 +----------------- .../cliente/convert2templateModal.php | 65 ----- .../assets/js/safekat/components/select2.js | 4 + .../pages/cliente/modalConvert2Template.js | 83 ++++++ .../safekat/pages/cliente/tarifasCliente.js | 129 ++++++-- .../presupuestoCliente/presupuestoCliente.js | 5 +- 11 files changed, 384 insertions(+), 485 deletions(-) delete mode 100644 ci4/app/Views/themes/vuexy/form/clientes/cliente/convert2templateModal.php create mode 100644 httpdocs/assets/js/safekat/pages/cliente/modalConvert2Template.js diff --git a/ci4/app/Config/Routes.php b/ci4/app/Config/Routes.php index a8339e44..167056f8 100644 --- a/ci4/app/Config/Routes.php +++ b/ci4/app/Config/Routes.php @@ -394,6 +394,8 @@ $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->resource('clienteprecios', ['namespace' => 'App\Controllers\Clientes', 'controller' => 'ClientePrecios', 'except' => 'show,new,create,update']); @@ -405,7 +407,7 @@ $routes->group('clienteplantillaprecios', ['namespace' => 'App\Controllers\Clien $routes->post('edit/(:num)', 'Clienteplantillaprecios::edit/$1', ['as' => 'updateClienteplantillaprecios']); $routes->get('delete/(:num)', 'Clienteplantillaprecios::delete/$1', ['as' => 'deleteClienteplantillaprecios']); $routes->post('datatable', 'Clienteplantillaprecios::datatable', ['as' => 'dataTableOfClientesplantillaprecios']); - $routes->post('menuitems', 'Clienteplantillaprecios::menuItems', ['as' => 'menuItemsOfClienteplantillaprecios']); + $routes->get('menuitems', 'Clienteplantillaprecios::menuItems', ['as' => 'menuItemsOfClienteplantillaprecios']); }); $routes->resource('clienteplantillaprecios', ['namespace' => 'App\Controllers\Clientes', 'controller' => 'Clienteplantillaprecios', 'except' => 'show,new,create,update']); diff --git a/ci4/app/Controllers/Clientes/ClientePrecios.php b/ci4/app/Controllers/Clientes/ClientePrecios.php index 105d085a..fe37272c 100755 --- a/ci4/app/Controllers/Clientes/ClientePrecios.php +++ b/ci4/app/Controllers/Clientes/ClientePrecios.php @@ -1,4 +1,5 @@ -request->getPost()) : - - if ($requestedId == null) : - return; - endif; + if ($this->request->isAJAX()) { - $postData = $this->request->getJSON(); + $postData = $this->request->getPost(); + + $cliente_id = $postData['cliente_id'] ?? -1; + $plantilla_id = $postData['plantilla_id'] ?? -1; - $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($requestedId); - } - else if($requestedId== -1){ // actualizar todos los clientes que usan 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); } - else{ - $this->model->copy_from_plantilla($requestedId, $plantilla_id); - } - + $newTokenHash = csrf_hash(); $csrfTokenName = csrf_token(); $data = [ $csrfTokenName => $newTokenHash ]; - + return $this->respond($data); - endif; // ($requestMethod === 'post') + } else { + return $this->failUnauthorized('Invalid request', 403); + } } @@ -106,11 +103,11 @@ class ClientePrecios extends \App\Controllers\BaseResourceController $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; + $dir4 = $reqData['order']['3']['dir'] ?? $dir; + $dir5 = $reqData['order']['4']['dir'] ?? $dir; $searchValues = get_filter_datatables_columns($reqData); - + $cliente_id = $reqData['cliente_id'] ?? 0; $resourceData = $this->model->getResource($searchValues, $cliente_id) @@ -126,61 +123,86 @@ class ClientePrecios extends \App\Controllers\BaseResourceController } } - public function datatable_editor() { + public function datatable_editor() + { if ($this->request->isAJAX()) { include(APPPATH . "ThirdParty/DatatablesEditor/DataTables.php"); // Build our Editor instance and process the data coming from _POST - $response = Editor::inst( $db, '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( 'is_deleted' ), - 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')) - ), - - 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')) - ), - - 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') + ) + ), + + 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') + ) + ), + + Field::inst('margen') + ->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') + ) ), ) @@ -238,4 +260,16 @@ 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); + } + } + } diff --git a/ci4/app/Controllers/Clientes/Clienteplantillaprecios.php b/ci4/app/Controllers/Clientes/Clienteplantillaprecios.php index f2edea93..d528339f 100755 --- a/ci4/app/Controllers/Clientes/Clienteplantillaprecios.php +++ b/ci4/app/Controllers/Clientes/Clienteplantillaprecios.php @@ -1,4 +1,5 @@ -request->getPost()) : - - if ($requestedId == null) : + + 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') @@ -95,26 +96,27 @@ class Clienteplantillaprecios extends \App\Controllers\BaseResourceController 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) { @@ -126,24 +128,27 @@ class Clienteplantillaprecios extends \App\Controllers\BaseResourceController $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 + 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 + } 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 ; - } - else{ - if ($thenRedirect) : - if (!empty($this->indexRoute)) : + return $this->respond(['status' => 'success', 'id' => $id]); + } else { + if ($thenRedirect): + if (!empty($this->indexRoute)): //return redirect()->to(route_to($this->indexRoute))->with('sweet-success', $message); return redirect()->to(site_url('/clientes/clienteplantillaprecios/edit/' . $id))->with('message', $message); else: @@ -171,35 +176,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) { @@ -216,12 +221,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); @@ -236,7 +241,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'); @@ -275,34 +280,32 @@ class Clienteplantillaprecios extends \App\Controllers\BaseResourceController public function menuItems() { + if ($this->request->isAJAX()) { - $searchStr = goSanitize($this->request->getPost('searchTerm'))[0]; - $reqId = goSanitize($this->request->getPost('id'))[0]; - $reqText = goSanitize($this->request->getPost('text'))[0]; - $onlyActiveOnes = false; - $columns2select = [$reqId ?? 'id', $reqText ?? 'nombre']; - $onlyActiveOnes = false; - 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 = []; + $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(); } - $newTokenHash = csrf_hash(); - $csrfTokenName = csrf_token(); - $data = [ - 'menu' => $menu, - $csrfTokenName => $newTokenHash - ]; - return $this->respond($data); + $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); } else { return $this->failUnauthorized('Invalid request', 403); } + } } diff --git a/ci4/app/Models/Clientes/ClientePlantillaPreciosLineasModel.php b/ci4/app/Models/Clientes/ClientePlantillaPreciosLineasModel.php index 9b3072d4..29351dd3 100755 --- a/ci4/app/Models/Clientes/ClientePlantillaPreciosLineasModel.php +++ b/ci4/app/Models/Clientes/ClientePlantillaPreciosLineasModel.php @@ -183,14 +183,13 @@ class ClientePlantillaPreciosLineasModel extends \App\Models\BaseModel function copy_from_cliente($cliente_id = 0, $plantilla_id = 0){ - $session = session(); $datetime = (new \CodeIgniter\I18n\Time("now")); $date_value = $datetime->format('Y-m-d H:i:s'); // Se cargan los valores en la plantilla $clientePreciosModel = model('App\Models\Clientes\ClientePreciosModel'); - $values = $clientePreciosModel->getResource($cliente_id)->get()->getResultObject(); + $values = $clientePreciosModel->getResource([], $cliente_id)->get()->getResultObject(); foreach ($values as $value) { $this->db ->table($this->table . " t1") @@ -201,7 +200,7 @@ class ClientePlantillaPreciosLineasModel extends \App\Models\BaseModel ->set('tiempo_min', $value->tiempo_min) ->set('tiempo_max', $value->tiempo_max) ->set('margen', $value->margen) - ->set('user_updated_id', $session->id_user) + ->set('user_updated_id', auth()->user()->id) ->set('updated_at', $date_value) ->insert(); } diff --git a/ci4/app/Models/Clientes/ClientePreciosModel.php b/ci4/app/Models/Clientes/ClientePreciosModel.php index eb76141d..adeef70b 100755 --- a/ci4/app/Models/Clientes/ClientePreciosModel.php +++ b/ci4/app/Models/Clientes/ClientePreciosModel.php @@ -287,6 +287,27 @@ class ClientePreciosModel extends \App\Models\BaseModel } } + public function getPlantilla($cliente_id = -1){ + $builder = $this->db + ->table($this->table . " t1") + ->select( + "t1.plantilla_id AS id, t2.nombre AS nombre" + ); + + $builder->where('t1.is_deleted', 0); + $builder->where('t1.cliente_id', $cliente_id); + $builder->join("cliente_plantilla_precios t2", "t1.plantilla_id = t2.id", "left"); + $builder->limit(1); + + $values = $builder->get()->getResultArray(); + if(count($values)>0){ + return $values[0]; + } + + return []; + } + + public function checkIntervals($data = [], $id_linea = null, $cliente_id = null){ diff --git a/ci4/app/Views/themes/vuexy/form/clientes/cliente/_clienteFormItems.php b/ci4/app/Views/themes/vuexy/form/clientes/cliente/_clienteFormItems.php index 92c184d8..52a869f9 100644 --- a/ci4/app/Views/themes/vuexy/form/clientes/cliente/_clienteFormItems.php +++ b/ci4/app/Views/themes/vuexy/form/clientes/cliente/_clienteFormItems.php @@ -561,7 +561,6 @@
-
@@ -885,7 +884,7 @@ $(document).on('click', '.btn-remove', function(e) { /************************************** Tarifas cliente ***************************************/ - +/* $('#plantillas').select2({ allowClear: false, ajax: { @@ -915,280 +914,7 @@ $(document).on('click', '.btn-remove', function(e) { } }); - const lastColNr_lineas = $('#tableOfPrecios').find("tr:first th").length - 1; - const actionBtns_lineas = function(data) { - return ` - - - - `; - }; - -/* - const tipo_linea = [ - {label:'', value:'interior'}, - {label:'', value: 'cubierta'}, - {label:'', value: 'sobrecubierta'} - ]; - - const tipo_maquina = [ - {label: '', value:'toner'}, - {label: '', value:'inkjet'}, - ]; - - const tipo_impresion = [ - {label: '', value:'negro'}, - {label: '', value:'negrohq'}, - {label: '', value:'color'}, - {label: '', value:'colorhq'}, - ]; - - var editorPrecios = new $.fn.dataTable.Editor( { - ajax: { - url: "", - headers: { - : v, - }, - }, - table : "#tableOfPrecios", - idSrc: 'id', - fields: [ { - name: "tipo", - type: "select", - options: tipo_linea - }, { - name: "tipo_maquina", - type: "select", - options: tipo_maquina - }, { - name: "tipo_impresion", - type: "select", - options: tipo_impresion - }, { - name: "tiempo_min" - }, { - name: "tiempo_max" - }, { - name: "precio_hora" - }, { - name: "margen" - }, { - name: "user_updated_id", - type:'hidden', - - }, { - name: "updated_at", - type:'hidden', - - }, { - "name": "plantilla_id", - "type": "hidden" - },{ - "name": "cliente_id", - "type": "hidden" - },{ - "name": "deleted_at", - "type": "hidden" - },{ - "name": "is_deleted", - "type": "hidden" - }, - ] - } ); - - editorPrecios.on( 'preSubmit', function ( e, d, type ) { - if ( type === 'create'){ - d.data[0]['cliente_id'] = id; - } - else if(type === 'edit' ) { - for (v in d.data){ - d.data[v]['cliente_id'] = id; - } - } - }); - - - editorPrecios.on( 'postSubmit', function ( e, json, data, action ) { - - yeniden(json.); - - }); - - editorPrecios.on( 'submitSuccess', function ( e, json, data, action ) { - - theTablePrecios.clearPipeline(); - theTablePrecios.draw(); - }); - - editorPrecios.on ('postEdit', function ( e, json, data, action ) { - const domain = window.location.origin - fetch(domain + "/clientes/clienteprecios/update/" + id , { - method: "POST", - body: JSON.stringify({ - : v - }), - headers: { - "Content-type": "application/json; charset=UTF-8" - } - }) - }) - - editorPrecios.on ('postCreate', function ( e, json, data, action ) { - const domain = window.location.origin - fetch(domain + "/clientes/clienteprecios/update/" + id , { - method: "POST", - body: JSON.stringify({ - : v - }), - headers: { - "Content-type": "application/json; charset=UTF-8" - } - }) - }) -*/ -/* - - var theTablePrecios = $('#tableOfPrecios').DataTable( { - serverSide: true, - processing: true, - autoWidth: true, - responsive: true, - lengthMenu: [ 10, 25, 50, 100], - order: [[ 0, "asc" ], [ 1, "asc" ], [ 2, "asc" ], [ 3, "asc" ]], - pageLength: 50, - lengthChange: true, - searching: false, - paging: true, - info: false, - dom: '<"mt-4"><"float-end"B><"float-start"l><"mt-4 mb-3"p>', - ajax : $.fn.dataTable.pipeline( { - url: '', - data: { - cliente_id: id, - }, - method: 'POST', - headers: {'X-Requested-With': 'XMLHttpRequest'}, - async: true, - }), - columns: [ - { 'data': 'tipo' , - 'render': function ( data, type, row, meta ) { - if(data=='interior') - return ''; - else if(data=='cubierta') - return ''; - else if(data=='sobrecubierta') - return ''; - } - }, - { 'data': 'tipo_maquina', - 'render': function ( data, type, row, meta ) { - if(data=='toner') - return ''; - else if(data=='inkjet') - return ''; - } - }, - { 'data': 'tipo_impresion', - 'render': function ( data, type, row, meta ) { - if(data=='negro') - return ''; - else if(data=='negrohq') - return ''; - else if(data=='color') - return ''; - else if(data=='colorhq') - return ''; - } - }, - { 'data': 'tiempo_min' }, - { 'data': 'tiempo_max' }, - { 'data': 'precio_hora' }, - { 'data': 'margen' }, - { 'data': 'user_updated_id', - 'render': function ( data, type, row, meta ) { - return row.user_updated - } - }, - { 'data': 'updated_at' }, - { 'data': 'plantilla_id' }, - { - data: actionBtns_lineas, - className: 'row-edit dt-center' - } - ], - columnDefs: [ - { - target: 9, - orderable: false, - visible: false, - searchable: false - }, - { - orderable: false, - searchable: false, - targets: [lastColNr_lineas] - }, - {"orderData": [ 0, 1 ], "targets": 0 }, - - ], - language: { - url: "/themes/vuexy/vendor/libs/datatables-sk/plugins/i18n/es-ES.json" - }, - buttons: [ { - className: 'btn btn-primary me-sm-3 me-1', - extend: "createInline", - editor: editorPrecios, - formOptions: { - submitTrigger: -1, - submitHtml: '' - } - } ] - } ); -*/ - - const initPrecioTemplate = ; - if(initPrecioTemplate != null){ - var newOption = new Option(initPrecioTemplate.label, initPrecioTemplate.value, false, false); - $('#plantillas').append(newOption); - } - - /* - // Activate an inline edit on click of a table cell - $('#tableOfPrecios').on( 'click', 'tbody span.edit', function (e) { - editorPrecios.inline( - theTablePrecios.cells(this.parentNode.parentNode, '*').nodes(), - { - cancelHtml: '', - cancelTrigger: 'span.cancel', - submitHtml: '', - submitTrigger: 'span.edit', - submit: 'allIfChanged' - } - ); - } ); -*/ - - // Delete row - $(document).on('click', '.btn-delete', function(e) { - $(".btn-remove").attr('data-id', $(this).attr('data-id')); - $(".btn-remove").attr('table-id', '#tableOfPrecios'); - $(".btn-remove").attr('row', $(this).closest('tr')[0]._DT_RowIndex); - }); - - function delete_precio(dataId, row){ - if ($.isNumeric(dataId)) { - editorPrecios - .create( false ) - .edit( theTablePrecios.rows(row), false) - .set( 'deleted_at', new Date().toISOString().slice(0, 19).replace('T', ' ') ) - .set( 'is_deleted', 1 ) - .submit(); - $('#confirm2delete').modal('toggle'); - } - } - $('#plantillas').on('change.select2', function(){ const data = $('#plantillas').select2('data'); diff --git a/ci4/app/Views/themes/vuexy/form/clientes/cliente/convert2templateModal.php b/ci4/app/Views/themes/vuexy/form/clientes/cliente/convert2templateModal.php deleted file mode 100644 index 709f32a0..00000000 --- a/ci4/app/Views/themes/vuexy/form/clientes/cliente/convert2templateModal.php +++ /dev/null @@ -1,65 +0,0 @@ - - - -section("additionalInlineJs") ?> -$('#saveTemplate').on('click', function(){ - if($('#nombre_plantilla').val().length == 0){ - popErrorAlert('', 'error-nombre') - } - else{ - data = new FormData(); - data.append('cliente_id', id) - data.append('nombre', $('#nombre_plantilla').val()) - data.append('', v) - fetch('' , { - method: "POST", - body: data, - }) - .then(data => { - $('#convert2Template').modal("hide"); - var newOption = new Option($('#nombre_plantilla').val(), "", false, false); - $('#plantillas').append(newOption); - $('#nombre_plantilla').val(""); - }) - } -}) - - -$('#cancelTemplate').on('click', function(){ - $('#convert2Template').modal("hide"); -}) -endSection() ?> \ No newline at end of file diff --git a/httpdocs/assets/js/safekat/components/select2.js b/httpdocs/assets/js/safekat/components/select2.js index 1d987376..febfa86c 100644 --- a/httpdocs/assets/js/safekat/components/select2.js +++ b/httpdocs/assets/js/safekat/components/select2.js @@ -84,6 +84,10 @@ let ClassSelect = function (domItem, url, placeholder, allowClear = false, param this.onChange = function(callback) { this.item.on('change', callback); }; + this.offChange = function() { + this.item.off('change'); + }; + }; export default ClassSelect; diff --git a/httpdocs/assets/js/safekat/pages/cliente/modalConvert2Template.js b/httpdocs/assets/js/safekat/pages/cliente/modalConvert2Template.js new file mode 100644 index 00000000..772647f2 --- /dev/null +++ b/httpdocs/assets/js/safekat/pages/cliente/modalConvert2Template.js @@ -0,0 +1,83 @@ +class ModalConvert2Template { + + constructor() { + + this.modalId = 'modalConvert2Template'; + this.modalHtml = ` + + `; + + this.modalInstance = null; + } + + init() { + + const self = this; + + // Insertar el modal en el body del documento si no existe + if (!document.getElementById(this.modalId)) { + document.body.insertAdjacentHTML('beforeend', this.modalHtml); + } + + this.modalInstance = new bootstrap.Modal(document.getElementById(this.modalId)); + + // Configurar el evento del botón de cancelar + document.getElementById('cancelTemplate').addEventListener('click', () => { + this.modalInstance.hide(); + }); + } + + // Método para mostrar el modal + show(callback) { + + // Mostrar el modal usando Bootstrap + this.modalInstance.show(); + + // Configurar el evento de confirmación de eliminación + document.getElementById('saveTemplate').addEventListener('click', () => { + callback(); // Llamar al callback que el usuario haya proporcionado + this.modalInstance.hide(); + }); + } + + hide() { + document.getElementById('nombre_plantilla').value = ""; + const modal = new bootstrap.Modal(document.getElementById(this.modalId)); + modal.hide(); + } + + getNombrePlantilla() { + return document.getElementById('nombre_plantilla').value; + } +} + +export default ModalConvert2Template; \ No newline at end of file diff --git a/httpdocs/assets/js/safekat/pages/cliente/tarifasCliente.js b/httpdocs/assets/js/safekat/pages/cliente/tarifasCliente.js index 0ed7c8ea..22c82e02 100644 --- a/httpdocs/assets/js/safekat/pages/cliente/tarifasCliente.js +++ b/httpdocs/assets/js/safekat/pages/cliente/tarifasCliente.js @@ -1,6 +1,9 @@ import Table from '../../components/table.js'; import TableEditor from '../../components/tableEditor.js'; import ConfirmDeleteModal from '../../components/ConfirmDeleteModal.js'; +import ConvertToTemplate from './modalConvert2Template.js'; +import ClassSelect from '../../components/select2.js'; +import Ajax from '../../components/ajax.js'; import { getToken } from '../../common/common.js'; @@ -21,7 +24,14 @@ class tarifasClienteView { this.tableTarifas = null; this.editorTarifas = null; this.confirmDeleteModal = null; + this.deleteModal = null; + this.convertToTemplate = null; + + this.plantillas = $(this.domItem.find('#plantillas')); + this.selectorPlantilla = new ClassSelect(this.plantillas, '/clienteplantillaprecios/menuitems', ''); + + this.convertToTemplateBtn = $('#convert2template'); } init() { @@ -31,24 +41,35 @@ class tarifasClienteView { this.deleteModal = new ConfirmDeleteModal('tarifascliente'); this.deleteModal.init(); + this.convertToTemplate = new ConvertToTemplate(); + this.convertToTemplate.init(); + this.#initEditor(); this.#initTable(); + this.selectorPlantilla.init(); + + this.#getPlantillaPrecios(); + + this.convertToTemplateBtn.on('click', function () { + self.convertToTemplate.show(self.#convertir2plantilla.bind(self)); + }) + // Editar en linea la fila this.tableTarifas.table.on('click', 'tbody span.edit', function (e) { const row = $(this).closest('tr'); - + // Iniciar la edición en línea para todas las celdas de la fila self.editorTarifas.editor.inline( self.tableTarifas.table.cells(row, '*').nodes(), { cancelHtml: '', submitHtml: '', - cancelTrigger: row.find('span.cancel')[0], - submitTrigger: row.find('span.edit')[0], + cancelTrigger: row.find('span.cancel')[0], + submitTrigger: row.find('span.edit')[0], submit: 'allIfChanged' } ); @@ -58,19 +79,19 @@ class tarifasClienteView { this.tableTarifas.table.on('click', '.btn-delete-' + this.tableTarifas.getAlias(), function (e) { const row = $(this).closest('tr')[0]._DT_RowIndex; self.deleteModal.setData($(this).attr('data-id')); - self.deleteModal.show(() =>{ + self.deleteModal.show(() => { if ($.isNumeric(self.deleteModal.getData())) { self.editorTarifas.editor - .create( false ) - .edit( self.tableTarifas.table.rows(row), false) - .set( 'deleted_at', new Date().toISOString().slice(0, 19).replace('T', ' ') ) - .set( 'is_deleted', 1 ) + .create(false) + .edit(self.tableTarifas.table.rows(row), false) + .set('deleted_at', new Date().toISOString().slice(0, 19).replace('T', ' ')) + .set('is_deleted', 1) .submit(); self.deleteModal.hide(); } }); }); - + } @@ -166,10 +187,16 @@ class tarifasClienteView { this.editorTarifas.editor.on('postEdit', function (e, json, data, action) { self.#borrarPlantillaTarifa(self.clienteId); + self.selectorPlantilla.offChange(); + self.selectorPlantilla.setOption(0, 'Personalizado'); + self.selectorPlantilla.onChange(self.#changePlantilla.bind(this)); }) this.editorTarifas.editor.on('postCreate', function (e, json, data, action) { self.#borrarPlantillaTarifa(self.clienteId); + self.selectorPlantilla.offChange(); + self.selectorPlantilla.setOption(0, 'Personalizado'); + self.selectorPlantilla.onChange(self.#changePlantilla.bind(this)); }) this.editorTarifas.editor.on('postCancel', function (e, json, data) { @@ -181,18 +208,82 @@ class tarifasClienteView { }); } + #convertir2plantilla() { + if (this.convertToTemplate.getNombrePlantilla().length == 0) { + popErrorAlert(window.language.ClientePrecios.errors.error_nombre_template, 'error-nombre') + } + else { + new Ajax('/clientes/clienteplantillaprecios/add', + { + 'from_client_data': 1, + 'cliente_id': this.clienteId, + 'nombre': this.convertToTemplate.getNombrePlantilla(), + [this.csrf_token]: this.csrf_hash + }, + {}, + (response) => { + if (response.id) { + + this.selectorPlantilla.offChange(); + this.selectorPlantilla.setOption(response.id, this.convertToTemplate.getNombrePlantilla()); + this.selectorPlantilla.onChange(this.#changePlantilla.bind(this)); + } + }, + (error) => { + console.log(error); + } + ).post(); + } + } + + #getPlantillaPrecios() { + + new Ajax( + '/clienteprecios/getplantilla', + { + 'cliente_id': this.clienteId, + [this.csrf_token]: this.csrf_hash + }, + {}, + (data) => { + if (data !== null && typeof data === 'object') { + if (data.hasOwnProperty('id') && data.id != null) + this.selectorPlantilla.setOption(data.id, data.nombre); + else { + this.selectorPlantilla.setOption(0, 'Personalizado'); + } + } + else { + this.selectorPlantilla.setOption(0, 'Personalizado'); + } + this.selectorPlantilla.onChange(this.#changePlantilla.bind(this)); + }, + (data) => { + this.selectorPlantilla.onChange(this.#changePlantilla.bind(this)); + console.log(data); + } + ).get(); + } + + #changePlantilla() { + + + } + #borrarPlantillaTarifa(id) { - const domain = window.location.origin - fetch(domain + "/clientes/clienteprecios/update/" + id, { - method: "POST", - body: JSON.stringify({ - [self.csrf_token]: self.csrf_hash - }), - headers: { - "Content-type": "application/json; charset=UTF-8" + new Ajax( + '/clienteprecios/changeplantilla', + { + 'cliente_id': id, + [this.csrf_token]: this.csrf_hash + }, + {}, + () => { }, + (data) => { + console.log(data); } - }) + ).post(); } #initTable() { @@ -280,7 +371,7 @@ class tarifasClienteView { } - + headerSearcher() { diff --git a/httpdocs/assets/js/safekat/pages/presupuestoCliente/presupuestoCliente.js b/httpdocs/assets/js/safekat/pages/presupuestoCliente/presupuestoCliente.js index 5ce4fa4a..32505ce0 100644 --- a/httpdocs/assets/js/safekat/pages/presupuestoCliente/presupuestoCliente.js +++ b/httpdocs/assets/js/safekat/pages/presupuestoCliente/presupuestoCliente.js @@ -44,7 +44,8 @@ class PresupuestoCliente { this.datos = {}; this.ajax_calcular = new Ajax('/presupuestocliente/calcular', - {}, this.datos, + this.datos, + {}, this.#procesarPresupuesto.bind(this), () => { $('#loader').modal('hide'); }); @@ -78,7 +79,7 @@ class PresupuestoCliente { } - if ($('#divExcluirRotativa').hasClass('d-none')) { + if (this.datosGenerales.excluirRotativa.length == 0) { this.direcciones.direccionesCliente.setParams({ 'cliente_id': $("#clienteId").val() }) } From a7cda851f0b3c501c5d2ac3912441a09e6b9a831 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jaime=20Jim=C3=A9nez?= Date: Wed, 4 Dec 2024 12:34:10 +0100 Subject: [PATCH 13/18] trabajando en editar plantillas --- ci4/app/Config/Routes.php | 4 +- .../Controllers/Clientes/ClientePrecios.php | 31 +- .../Clientes/Clienteplantillaprecios.php | 32 +- .../Clienteplantillaprecioslineas.php | 38 +- .../ClientePlantillaPreciosLineasModel.php | 48 +- .../Clientes/ClientePlantillaPreciosModel.php | 24 +- .../clientes/cliente/_clienteFormItems.php | 68 --- .../viewClienteplantillapreciosForm.php | 523 +++++++++--------- .../viewClienteplantillapreciosList.php | 104 +--- .../themes/vuexy/form/user/_userFormItems.php | 8 +- .../assets/js/safekat/components/table.js | 17 +- .../js/safekat/components/tableEditor.js | 31 +- .../safekat/pages/cliente/tarifasCliente.js | 30 +- .../pages/plantillasTarifasCliente/edit.js | 433 +++++++++++++++ .../pages/plantillasTarifasCliente/list.js | 153 +++++ 15 files changed, 1024 insertions(+), 520 deletions(-) create mode 100644 httpdocs/assets/js/safekat/pages/plantillasTarifasCliente/edit.js create mode 100644 httpdocs/assets/js/safekat/pages/plantillasTarifasCliente/list.js diff --git a/ci4/app/Config/Routes.php b/ci4/app/Config/Routes.php index 167056f8..8bf72145 100644 --- a/ci4/app/Config/Routes.php +++ b/ci4/app/Config/Routes.php @@ -405,11 +405,13 @@ $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->resource('clienteplantillaprecios', ['namespace' => 'App\Controllers\Clientes', 'controller' => 'Clienteplantillaprecios', 'except' => 'show,new,create,update']); +$routes->resource('clienteplantillaprecios', ['namespace' => 'App\Controllers\Clientes', 'controller' => 'Clienteplantillaprecios', 'except' => 'show,new,create']); $routes->group('clienteplantillaprecioslineas', ['namespace' => 'App\Controllers\Clientes'], function ($routes) { diff --git a/ci4/app/Controllers/Clientes/ClientePrecios.php b/ci4/app/Controllers/Clientes/ClientePrecios.php index fe37272c..61cfb986 100755 --- a/ci4/app/Controllers/Clientes/ClientePrecios.php +++ b/ci4/app/Controllers/Clientes/ClientePrecios.php @@ -90,29 +90,24 @@ class ClientePrecios extends \App\Controllers\BaseResourceController } $start = $reqData['start'] ?? 0; $length = $reqData['length'] ?? 5; - $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; + + $requestedOrder = $reqData['order'] ?? []; $searchValues = get_filter_datatables_columns($reqData); $cliente_id = $reqData['cliente_id'] ?? 0; - $resourceData = $this->model->getResource($searchValues, $cliente_id) - ->orderBy($order, $dir)->orderBy($order2, $dir2)->orderBy($order3, $dir3)->orderBy($order4, $dir4)->orderBy($order5, $dir5) - ->limit($length, $start)->get()->getResultObject(); + $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(); + return $this->respond(Collection::datatable( $resourceData, $this->model->getResource($searchValues, $cliente_id)->countAllResults(), diff --git a/ci4/app/Controllers/Clientes/Clienteplantillaprecios.php b/ci4/app/Controllers/Clientes/Clienteplantillaprecios.php index d528339f..0c65fc90 100755 --- a/ci4/app/Controllers/Clientes/Clienteplantillaprecios.php +++ b/ci4/app/Controllers/Clientes/Clienteplantillaprecios.php @@ -72,24 +72,20 @@ class Clienteplantillaprecios extends \App\Controllers\BaseResourceController public function update($requestedId = null) { + if ($requestedId == null): + return; + endif; + $model = model('App\Models\Clientes\ClientePlantillaPreciosLineasModel'); + $model->delete_values($requestedId); - if ($this->request->getPost()): + $newTokenHash = csrf_hash(); + $csrfTokenName = csrf_token(); + $data = [ + $csrfTokenName => $newTokenHash + ]; - if ($requestedId == null): - return; - endif; - $model = model('App\Models\Clientes\ClientePlantillaPreciosLineasModel'); - $model->delete_values($requestedId); + return $this->respond($data); - $newTokenHash = csrf_hash(); - $csrfTokenName = csrf_token(); - $data = [ - $csrfTokenName => $newTokenHash - ]; - - return $this->respond($data); - - endif; // ($requestMethod === 'post') } @@ -262,16 +258,16 @@ class Clienteplantillaprecios 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']['0']['column'] ?? 1; $order = ClientePlantillaPreciosModel::SORTABLE[$requestedOrder > 0 ? $requestedOrder : 0]; $dir = $reqData['order']['0']['dir'] ?? 'asc'; - $resourceData = $this->model->getResource($search)->orderBy($order, $dir)->limit($length, $start)->get()->getResultObject(); + $resourceData = $this->model->getResource($searchValues)->orderBy($order, $dir)->limit($length, $start)->get()->getResultObject(); return $this->respond(Collection::datatable( $resourceData, $this->model->getResource()->countAllResults(), - $this->model->getResource($search)->countAllResults() + $this->model->getResource($searchValues)->countAllResults() )); } else { return $this->failUnauthorized('Invalid request', 403); diff --git a/ci4/app/Controllers/Clientes/Clienteplantillaprecioslineas.php b/ci4/app/Controllers/Clientes/Clienteplantillaprecioslineas.php index a2378aec..83cfd625 100755 --- a/ci4/app/Controllers/Clientes/Clienteplantillaprecioslineas.php +++ b/ci4/app/Controllers/Clientes/Clienteplantillaprecioslineas.php @@ -93,31 +93,27 @@ class Clienteplantillaprecioslineas extends \App\Controllers\BaseResourceControl } $start = $reqData['start'] ?? 0; $length = $reqData['length'] ?? 5; - $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; - + + $requestedOrder = $reqData['order'] ?? []; + $searchValues = get_filter_datatables_columns($reqData); + $plantilla_id = $reqData['plantilla_id'] ?? 0; - $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(); + $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(); + 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($searchValues, $plantilla_id)->countAllResults() )); } else { return $this->failUnauthorized('Invalid request', 403); diff --git a/ci4/app/Models/Clientes/ClientePlantillaPreciosLineasModel.php b/ci4/app/Models/Clientes/ClientePlantillaPreciosLineasModel.php index 29351dd3..9e1b6852 100755 --- a/ci4/app/Models/Clientes/ClientePlantillaPreciosLineasModel.php +++ b/ci4/app/Models/Clientes/ClientePlantillaPreciosLineasModel.php @@ -7,14 +7,16 @@ class ClientePlantillaPreciosLineasModel extends \App\Models\BaseModel protected $table = "cliente_plantilla_precios_lineas"; const SORTABLE = [ - 0 => "t1.tipo", - 1 => "t1.tipo_maquina", - 2 => "t1.tipo_impresion", - 3 => "t1.tiempo_min", - 4 => "t1.tiempo_max", - 5 => "t1.precio_hora", - 6 => "t1.margen", - + 0 => "t1.id", + 1 => "t1.tipo", + 2 => "t1.tipo_maquina", + 3 => "t1.tipo_impresion", + 4 => "t1.tiempo_min", + 5 => "t1.tiempo_max", + 6 => "t1.precio_hora", + 7 => "t1.margen", + 8 => "CONCAT(t2.first_name, ' ', t2.last_name)", + 9 => "t1.updated_at", ]; /** @@ -113,10 +115,20 @@ class ClientePlantillaPreciosLineasModel extends \App\Models\BaseModel function delete_values($plantilla_id = 0){ + $datetime = (new \CodeIgniter\I18n\Time("now")); + $date_value = $datetime->format('Y-m-d H:i:s'); + $this->db ->table($this->table . " t1") ->where('t1.plantilla_id', $plantilla_id) ->set('is_deleted', 1) + ->set('deleted_at', $date_value) + ->update(); + + $this->db + ->table('cliente_precios' . " t1") + ->where('t1.plantilla_id', $plantilla_id) + ->set('plantilla_id', null) ->update(); } @@ -127,14 +139,15 @@ class ClientePlantillaPreciosLineasModel extends \App\Models\BaseModel * * @return \CodeIgniter\Database\BaseBuilder */ - public function getResource($plantilla_id = -1) + public function getResource($search = [], $plantilla_id = -1) { $builder = $this->db ->table($this->table . " t1") ->select( "t1.id as id, t1.tipo AS tipo, t1.tipo_maquina AS tipo_maquina, t1.tipo_impresion AS tipo_impresion, t1.tiempo_min AS tiempo_min, t1.tiempo_max AS tiempo_max, t1.precio_hora AS precio_hora, t1.margen AS margen, - t1.user_updated_id AS user_updated_id, t1.updated_at AS updated_at, CONCAT(t2.first_name, ' ', t2.last_name) AS user_updated" + t1.user_updated_id AS user_updated_id, t1.updated_at AS updated_at, CONCAT(t2.first_name, ' ', t2.last_name) AS user_updated, + t1.id AS DT_RowId" ); $builder->join("users t2", "t1.user_updated_id = t2.id", "left"); @@ -142,8 +155,19 @@ class ClientePlantillaPreciosLineasModel extends \App\Models\BaseModel $builder->where('t1.is_deleted', 0); $builder->where('t1.plantilla_id', $plantilla_id); - - return $builder; + if (empty($search)) + return $builder; + else { + $builder->groupStart(); + foreach ($search as $col_search) { + if ($col_search[0] > 0 && $col_search[0] < 4) + $builder->where(self::SORTABLE[$col_search[0]], $col_search[2]); + else + $builder->like(self::SORTABLE[$col_search[0]], $col_search[2]); + } + $builder->groupEnd(); + return $builder; + } } public function checkIntervals($data = [], $id_linea = null, $plantilla_id = null){ diff --git a/ci4/app/Models/Clientes/ClientePlantillaPreciosModel.php b/ci4/app/Models/Clientes/ClientePlantillaPreciosModel.php index 2ec9978d..c3f55da2 100755 --- a/ci4/app/Models/Clientes/ClientePlantillaPreciosModel.php +++ b/ci4/app/Models/Clientes/ClientePlantillaPreciosModel.php @@ -7,7 +7,8 @@ class ClientePlantillaPreciosModel extends \App\Models\BaseModel protected $table = "cliente_plantilla_precios"; const SORTABLE = [ - 0 => "t1.nombre", + 0 => "t1.id", + 1 => "t1.nombre", ]; /** @@ -48,11 +49,11 @@ class ClientePlantillaPreciosModel extends \App\Models\BaseModel /** * Get resource data. * - * @param string $search + * @param array $search * * @return \CodeIgniter\Database\BaseBuilder */ - public function getResource(string $search = "", $cliente_id = -1) + public function getResource($search = []) { $builder = $this->db ->table($this->table . " t1") @@ -61,14 +62,17 @@ class ClientePlantillaPreciosModel extends \App\Models\BaseModel ); $builder->where('t1.is_deleted', 0); - - return empty($search) - ? $builder - : $builder - ->groupStart() - ->like("t1.nombre", $search) - ->groupEnd(); + if (empty($search)) + return $builder; + else { + $builder->groupStart(); + foreach ($search as $col_search) { + $builder->like(self::SORTABLE[$col_search[0]], $col_search[2]); + } + $builder->groupEnd(); + return $builder; + } } } diff --git a/ci4/app/Views/themes/vuexy/form/clientes/cliente/_clienteFormItems.php b/ci4/app/Views/themes/vuexy/form/clientes/cliente/_clienteFormItems.php index 52a869f9..5766a61f 100644 --- a/ci4/app/Views/themes/vuexy/form/clientes/cliente/_clienteFormItems.php +++ b/ci4/app/Views/themes/vuexy/form/clientes/cliente/_clienteFormItems.php @@ -880,74 +880,6 @@ $(document).on('click', '.btn-remove', function(e) { endSection() ?> -section("additionalInlineJs") ?> -/************************************** - Tarifas cliente -***************************************/ -/* - $('#plantillas').select2({ - allowClear: false, - ajax: { - url: '', - type: 'post', - dataType: 'json', - - data: function (params) { - return { - id: 'id', - text: 'nombre', - searchTerm: params.term, - : v - }; - }, - delay: 60, - processResults: function (response) { - - yeniden(response.); - - return { - results: response.menu - }; - }, - - cache: true - } - }); - - - - $('#plantillas').on('change.select2', function(){ - const data = $('#plantillas').select2('data'); - if(data.length>0){ - const domain = window.location.origin - fetch(domain + "/clientes/clienteprecios/update/" + id , { - method: "POST", - body: JSON.stringify({ - plantilla_id: data[0].id, - : v - }), - headers: { - "Content-type": "application/json; charset=UTF-8" - } - }).then(function(){ - theTablePrecios.clearPipeline(); - theTablePrecios.draw(); - }) - - } - - }); - - - $('#convert2template').on('click', function(){ - var newAddDialog = $('#convert2Template') - newAddDialog.modal("show"); - - }) - -endSection() ?> - - section("additionalInlineJs") ?> /**************************************** Direcciones cliente diff --git a/ci4/app/Views/themes/vuexy/form/clientes/plantillaprecios/viewClienteplantillapreciosForm.php b/ci4/app/Views/themes/vuexy/form/clientes/plantillaprecios/viewClienteplantillapreciosForm.php index d2c26e2f..17d94304 100644 --- a/ci4/app/Views/themes/vuexy/form/clientes/plantillaprecios/viewClienteplantillapreciosForm.php +++ b/ci4/app/Views/themes/vuexy/form/clientes/plantillaprecios/viewClienteplantillapreciosForm.php @@ -16,12 +16,8 @@ getErrors()) ? $validation->listErrors("bootstrap_style") : "" ?>
- " - /> + " /> "btn btn-secondary"]) ?>
@@ -31,22 +27,28 @@
- - + +
+

-

- + +
ID
+ @@ -55,308 +57,327 @@ - - + + - + -
ID +
+ - - + + endSection() ?> - -section('additionalInlineJs') ?> - + + section('additionalInlineJs') ?> + /* const lastColNr_lineas = $('#tableOfPlantillasPreciosLineas').find("tr:first th").length - 1; - + const url = window.location.href; const url_parts = url.split('/'); let id = -1; if(url_parts[url_parts.length-2] == 'edit'){ - id = url_parts[url_parts.length-1]; + id = url_parts[url_parts.length-1]; } const actionBtns_lineas = function(data) { - return ` - - - - `; + return ` + + + + `; }; const tipo_linea = [ - {label:'', value:'interior'}, - {label:'', value: 'cubierta'}, - {label:'', value: 'sobrecubierta'} + {label:'', value:'interior'}, + {label:'', value: 'cubierta'}, + {label:'', value: 'sobrecubierta'} ]; const tipo_maquina = [ - {label: '', value:'toner'}, - {label: '', value:'inkjet'}, + {label: '', value:'toner'}, + {label: '', value:'inkjet'}, ]; const tipo_impresion = [ - {label: '', value:'negro'}, - {label: '', value:'negrohq'}, - {label: '', value:'color'}, - {label: '', value:'colorhq'}, + {label: '', value:'negro'}, + {label: '', value:'negrohq'}, + {label: '', value:'color'}, + {label: '', value:'colorhq'}, ]; - var editor = new $.fn.dataTable.Editor( { - ajax: { - url: "", - headers: { - : v, - }, - }, - table : "#tableOfPlantillasPreciosLineas", - idSrc: 'id', - fields: [ { - name: "tipo", - type: "select", - options: tipo_linea - }, { - name: "tipo_maquina", - type: "select", - options: tipo_maquina - }, { - name: "tipo_impresion", - type: "select", - options: tipo_impresion - }, { - name: "tiempo_min" - }, { - name: "tiempo_max" - }, { - name: "precio_hora" - }, { - name: "margen" - }, { - name: "user_updated_id", - type:'hidden', - - }, { - name: "updated_at", - type:'hidden', - - }, { - "name": "plantilla_id", - "type": "hidden" - },{ - "name": "deleted_at", - "type": "hidden" - },{ - "name": "is_deleted", - "type": "hidden" - }, - ] + var editor = new $.fn.dataTable.Editor( { + ajax: { + url: "", + headers: { + : v, + }, + }, + table : "#tableOfPlantillasPreciosLineas", + idSrc: 'id', + fields: [ { + name: "tipo", + type: "select", + options: tipo_linea + }, { + name: "tipo_maquina", + type: "select", + options: tipo_maquina + }, { + name: "tipo_impresion", + type: "select", + options: tipo_impresion + }, { + name: "tiempo_min" + }, { + name: "tiempo_max" + }, { + name: "precio_hora" + }, { + name: "margen" + }, { + name: "user_updated_id", + type:'hidden', + + }, { + name: "updated_at", + type:'hidden', + + }, { + "name": "plantilla_id", + "type": "hidden" + },{ + "name": "deleted_at", + "type": "hidden" + },{ + "name": "is_deleted", + "type": "hidden" + }, + ] } ); editor.on( 'preSubmit', function ( e, d, type ) { - if ( type === 'create'){ - d.data[0]['plantilla_id'] = id; - } - else if(type === 'edit' ) { - for (v in d.data){ - d.data[v]['plantilla_id'] = id; - } - } + if ( type === 'create'){ + d.data[0]['plantilla_id'] = id; + } + else if(type === 'edit' ) { + for (v in d.data){ + d.data[v]['plantilla_id'] = id; + } + } }); - - - editor.on( 'postSubmit', function ( e, json, data, action ) { - - yeniden(json.); - const domain = window.location.origin - fetch(domain + "/clientes/clienteprecios/update/" + -1 , { - method: "POST", - body: JSON.stringify({ - plantilla_id: id, - : v - }), - headers: { - "Content-type": "application/json; charset=UTF-8" - } - }) + + editor.on( 'postSubmit', function ( e, json, data, action ) { + + yeniden(json.); + + const domain = window.location.origin + fetch(domain + "/clientes/clienteprecios/update/" + -1 , { + method: "POST", + body: JSON.stringify({ + plantilla_id: id, + : v + }), + headers: { + "Content-type": "application/json; charset=UTF-8" + } + }) }); editor.on( 'submitSuccess', function ( e, json, data, action ) { - - theTable.clearPipeline(); - theTable.draw(); + + theTable.clearPipeline(); + theTable.draw(); }); - var theTable = $('#tableOfPlantillasPreciosLineas').DataTable( { - serverSide: true, - processing: true, - autoWidth: true, - responsive: true, - lengthMenu: [ 10, 25, 50, 100], - order: [[ 0, "asc" ], [ 1, "asc" ], [ 2, "asc" ], [ 3, "asc" ]], - pageLength: 50, - lengthChange: true, - searching: false, - paging: true, - info: false, - dom: '<"mt-4"><"float-end"B><"float-start"l><"mt-4 mb-3"p>', - ajax : $.fn.dataTable.pipeline( { - url: '', - data: { - plantilla_id: id, - }, - method: 'POST', - headers: {'X-Requested-With': 'XMLHttpRequest'}, - async: true, - }), - columns: [ - { 'data': 'tipo' , - 'render': function ( data, type, row, meta ) { - if(data=='interior') + var theTable = $('#tableOfPlantillasPreciosLineas').DataTable( { + serverSide: true, + processing: true, + autoWidth: true, + responsive: true, + lengthMenu: [ 10, 25, 50, 100], + order: [[ 0, "asc" ], [ 1, "asc" ], [ 2, "asc" ], [ 3, "asc" ]], + pageLength: 50, + lengthChange: true, + searching: false, + paging: true, + info: false, + dom: '<"mt-4"><"float-end"B><"float-start"l> + <"mt-4 mb-3"p>', + ajax : $.fn.dataTable.pipeline( { + url: '', + data: { + plantilla_id: id, + }, + method: 'POST', + headers: {'X-Requested-With': 'XMLHttpRequest'}, + async: true, + }), + columns: [ + { 'data': 'tipo' , + 'render': function ( data, type, row, meta ) { + if(data=='interior') return ''; - else if(data=='cubierta') + else if(data=='cubierta') return ''; - else if(data=='sobrecubierta') + else if(data=='sobrecubierta') return ''; - } - }, - { 'data': 'tipo_maquina', - 'render': function ( data, type, row, meta ) { - if(data=='toner') + } + }, + { 'data': 'tipo_maquina', + 'render': function ( data, type, row, meta ) { + if(data=='toner') return ''; - else if(data=='inkjet') + else if(data=='inkjet') return ''; - } - }, - { 'data': 'tipo_impresion', - 'render': function ( data, type, row, meta ) { - if(data=='negro') + } + }, + { 'data': 'tipo_impresion', + 'render': function ( data, type, row, meta ) { + if(data=='negro') return ''; - else if(data=='negrohq') + else if(data=='negrohq') return ''; - else if(data=='color') + else if(data=='color') return ''; - else if(data=='colorhq') + else if(data=='colorhq') return ''; - } - }, - { 'data': 'tiempo_min' }, - { 'data': 'tiempo_max' }, - { 'data': 'precio_hora' }, - { 'data': 'margen' }, - { 'data': 'user_updated_id', - 'render': function ( data, type, row, meta ) { - return row.user_updated - } - }, - { 'data': 'updated_at' }, - { - data: actionBtns_lineas, - className: 'row-edit dt-center' - } - ], - columnDefs: [ - { - orderable: false, - searchable: false, - targets: [lastColNr_lineas] - }, - {"orderData": [ 0, 1 ], "targets": 0 }, + } + }, + { 'data': 'tiempo_min' }, + { 'data': 'tiempo_max' }, + { 'data': 'precio_hora' }, + { 'data': 'margen' }, + { 'data': 'user_updated_id', + 'render': function ( data, type, row, meta ) { + return row.user_updated + } + }, + { 'data': 'updated_at' }, + { + data: actionBtns_lineas, + className: 'row-edit dt-center' + } + ], + columnDefs: [ + { + orderable: false, + searchable: false, + targets: [lastColNr_lineas] + }, + {"orderData": [ 0, 1 ], "targets": 0 }, - ], - language: { - url: "/themes/vuexy/vendor/libs/datatables-sk/plugins/i18n/es-ES.json" - }, - buttons: [ - { - extend: 'collection', - text: 'Exportar', - buttons:[ - 'copy', 'csv', 'excel', 'print', { + ], + language: { + url: "/themes/vuexy/vendor/libs/datatables-sk/plugins/i18n/es-ES.json" + }, + buttons: [ + { + extend: 'collection', + text: 'Exportar', + buttons:[ + 'copy', 'csv', 'excel', 'print', { extend: 'pdfHtml5', orientation: 'landscape', pageSize: 'A4' - } - ] - }, - { - className: 'btn btn-primary me-sm-3 me-1', - extend: "createInline", - editor: editor, - formOptions: { - submitTrigger: -1, - submitHtml: '' - } - } ] - } ); + } + ] + }, + { + className: 'btn btn-primary me-sm-3 me-1', + extend: "createInline", + editor: editor, + formOptions: { + submitTrigger: -1, + submitHtml: '' + } + } ] + } ); - - - // Activate an inline edit on click of a table cell - $('#tableOfPlantillasPreciosLineas').on( 'click', 'tbody span.edit', function (e) { - editor.inline( - theTable.cells(this.parentNode.parentNode, '*').nodes(), - { - cancelHtml: '', - cancelTrigger: 'span.cancel', - submitHtml: '', - submitTrigger: 'span.edit', - submit: 'allIfChanged' - } - ); - } ); - - // Delete row - $(document).on('click', '.btn-delete', function(e) { - $(".btn-remove").attr('data-id', $(this).attr('data-id')); - }); - $(document).on('click', '.btn-remove', function(e) { - const dataId = $(this).attr('data-id'); - const row = $(this).closest('tr'); - if ($.isNumeric(dataId)) { - $.ajax({ - url: `/clientes/clienteplantillaprecioslineas/delete/${dataId}`, - method: 'GET', - }).done((data, textStatus, jqXHR) => { - $('#confirm2delete').modal('toggle'); - theTable.clearPipeline(); - theTable.row($(row)).invalidate().draw(); - popSuccessAlert(data.msg ?? jqXHR.statusText); - }).fail((jqXHR, textStatus, errorThrown) => { - popErrorAlert(jqXHR.responseJSON.messages.error) - }) - } - }); -endSection() ?> + // Activate an inline edit on click of a table cell + $('#tableOfPlantillasPreciosLineas').on( 'click', 'tbody span.edit', function (e) { + editor.inline( + theTable.cells(this.parentNode.parentNode, '*').nodes(), + { + cancelHtml: '', + cancelTrigger: 'span.cancel', + submitHtml: '', + submitTrigger: 'span.edit', + submit: 'allIfChanged' + } + ); + } ); + + + // Delete row + $(document).on('click', '.btn-delete', function(e) { + $(".btn-remove").attr('data-id', $(this).attr('data-id')); + }); + + $(document).on('click', '.btn-remove', function(e) { + const dataId = $(this).attr('data-id'); + const row = $(this).closest('tr'); + if ($.isNumeric(dataId)) { + $.ajax({ + url: `/clientes/clienteplantillaprecioslineas/delete/${dataId}`, + method: 'GET', + }).done((data, textStatus, jqXHR) => { + $('#confirm2delete').modal('toggle'); + theTable.clearPipeline(); + theTable.row($(row)).invalidate().draw(); + popSuccessAlert(data.msg ?? jqXHR.statusText); + }).fail((jqXHR, textStatus, errorThrown) => { + popErrorAlert(jqXHR.responseJSON.messages.error) + }) + } + }); + */ +endSection() ?> -section('css') ?> - - "> -endSection() ?> +section('css') ?> + + "> +endSection() ?> section('additionalExternalJs') ?> - - - - - - - - -endSection() ?> - + + + + + + + + + + + +endSection() ?> \ No newline at end of file diff --git a/ci4/app/Views/themes/vuexy/form/clientes/plantillaprecios/viewClienteplantillapreciosList.php b/ci4/app/Views/themes/vuexy/form/clientes/plantillaprecios/viewClienteplantillapreciosList.php index cadb02aa..ff910539 100644 --- a/ci4/app/Views/themes/vuexy/form/clientes/plantillaprecios/viewClienteplantillapreciosList.php +++ b/ci4/app/Views/themes/vuexy/form/clientes/plantillaprecios/viewClienteplantillapreciosList.php @@ -10,14 +10,16 @@

'btn btn-primary float-end']); ?> -
+ +
+ - + @@ -50,100 +52,6 @@ + + endSection() ?> - -section('additionalInlineJs') ?> - - const lastColNr2 = $(".using-exportable-data-table").find("tr:first th").length - 1; - const actionBtns2 = function(data) { - return ` - - - - `; - }; - - - $(document).on('click', '.btn-edit', function(e) { - window.location.href = `/clientes/clienteplantillaprecios/edit/${$(this).attr('data-id')}`; - }); - - - // Delete row - $(document).on('click', '.btn-delete', function(e) { - $(".btn-remove").attr('data-id', $(this).attr('data-id')); - }); - - $(document).on('click', '.btn-remove', function(e) { - const dataId = $(this).attr('data-id'); - const row = $(this).closest('tr'); - if ($.isNumeric(dataId)) { - - $.ajax({ - url: `/clientes/clienteplantillaprecios/delete/${dataId}`, - method: 'GET', - }).done((data, textStatus, jqXHR) => { - $('#confirm2delete').modal('toggle'); - tablePLantillaPrecios.clearPipeline(); - tablePLantillaPrecios.row($(row)).invalidate().draw(); - - // Se borran las lineas asociadas - const domain = window.location.origin - fetch(domain + "/clientes/clienteplantillaprecios/update/" + dataId , { - method: "POST", - body: JSON.stringify({ - : v - }), - headers: { - "Content-type": "application/json; charset=UTF-8" - } - }) - - popSuccessAlert(data.msg ?? jqXHR.statusText); - }).fail((jqXHR, textStatus, errorThrown) => { - popErrorAlert(jqXHR.responseJSON.messages.error) - }); - } - }); - - - var tablePLantillaPrecios = $('#tableOfClienteplantillaprecios').DataTable( { - serverSide: true, - processing: true, - autoWidth: true, - responsive: true, - lengthMenu: [ 5, 10, 25, 50, 75, 100, 250], - order: [[ 0, "asc" ]], - pageLength: 25, - lengthChange: true, - searching: true, - paging: true, - info: true, - stateSave: true, - dom: "lftp", - ajax : $.fn.dataTable.pipeline( { - url: '', - method: 'POST', - headers: {'X-Requested-With': 'XMLHttpRequest'}, - async: true, - }), - columns: [ - { data: 'nombre'}, - { data: actionBtns2, - className: 'row-edit dt-center'} - ], - columnDefs: [ - { - orderable: false, - targets: [lastColNr2] - }, - { - searchable: false, - targets: [lastColNr2] - } - ], - language: { - url: "/themes/vuexy/vendor/libs/datatables-sk/plugins/i18n/es-ES.json" - } - } ); -endSection() ?> \ No newline at end of file diff --git a/ci4/app/Views/themes/vuexy/form/user/_userFormItems.php b/ci4/app/Views/themes/vuexy/form/user/_userFormItems.php index 3e75ae63..e7e5b32a 100644 --- a/ci4/app/Views/themes/vuexy/form/user/_userFormItems.php +++ b/ci4/app/Views/themes/vuexy/form/user/_userFormItems.php @@ -61,11 +61,11 @@ $selectedChatDepartments = isset($chatDepartmentUser) && is_array($chatDepartmentUser) ? $chatDepartmentUser : []; $selectedKeywords = array_map(fn($chatDepartment) => $chatDepartment->name, $selectedChatDepartments); foreach ($chatDepartments as $item) : - $isSelected = in_array($item["name"], $selectedKeywords) ? 'selected' : ''; + $isSelected = in_array($item->name, $selectedKeywords) ? 'selected' : ''; ?> - diff --git a/httpdocs/assets/js/safekat/components/table.js b/httpdocs/assets/js/safekat/components/table.js index 84f94c7b..af794fe0 100644 --- a/httpdocs/assets/js/safekat/components/table.js +++ b/httpdocs/assets/js/safekat/components/table.js @@ -4,6 +4,8 @@ let Table = function ( url, columns, data, + row_id = "DT_RowId", + language = "es-ES") { this.domItem = domItem; @@ -11,6 +13,7 @@ let Table = function ( this.url = url; this.columns = columns; this.data = data; + this.row_id = row_id; this.language = language; this.table = null; @@ -24,6 +27,7 @@ let Table = function ( actions = ['view', 'edit', 'delete', 'cancel'], order = [[0, 'asc']], buttonsExport = true, + colVisibility = true, buttonNewWithEditor = false, editor = null, booleanColumns = [], @@ -53,11 +57,6 @@ let Table = function ( let buttons = []; if (buttonsExport) { buttons = [ - { - extend: 'colvis', - columns: ':not(.noVis)', - - }, 'copy', 'csv', 'excel', 'print', { extend: 'pdfHtml5', orientation: 'landscape', @@ -65,6 +64,13 @@ let Table = function ( } ]; } + if(colVisibility){ + buttons.unshift({ + extend: 'colvis', + columns: ':not(.noVis)', + + }) + } if (buttonNewWithEditor) { buttons.push( { @@ -91,6 +97,7 @@ let Table = function ( order: order, orderCellsTop: true, fixedHeader: true, + rowId: row_id, dom: dom, ajax: $.fn.dataTable.pipeline({ url: this.url, diff --git a/httpdocs/assets/js/safekat/components/tableEditor.js b/httpdocs/assets/js/safekat/components/tableEditor.js index c0a5c370..9b650765 100644 --- a/httpdocs/assets/js/safekat/components/tableEditor.js +++ b/httpdocs/assets/js/safekat/components/tableEditor.js @@ -1,6 +1,6 @@ let TableEditor = function ( table, - url, + url = "", headers, idSrc, fields) { @@ -16,15 +16,26 @@ let TableEditor = function ( this.init = function () { - this.editor = new $.fn.dataTable.Editor( { - ajax: { - url: url, - headers: headers, - }, - table : table, - idSrc: idSrc, - fields: fields, - }); + if (url == "") { + this.editor = new $.fn.dataTable.Editor({ + table: table, + idSrc: idSrc, + fields: fields, + }); + } + + else { + this.editor = new $.fn.dataTable.Editor({ + ajax: { + url: url, + headers: headers, + }, + table: table, + idSrc: idSrc, + fields: fields, + }); + } + }; } diff --git a/httpdocs/assets/js/safekat/pages/cliente/tarifasCliente.js b/httpdocs/assets/js/safekat/pages/cliente/tarifasCliente.js index 22c82e02..d973be42 100644 --- a/httpdocs/assets/js/safekat/pages/cliente/tarifasCliente.js +++ b/httpdocs/assets/js/safekat/pages/cliente/tarifasCliente.js @@ -213,14 +213,14 @@ class tarifasClienteView { popErrorAlert(window.language.ClientePrecios.errors.error_nombre_template, 'error-nombre') } else { - new Ajax('/clientes/clienteplantillaprecios/add', + new Ajax('/clientes/clienteplantillaprecios/add', { 'from_client_data': 1, 'cliente_id': this.clienteId, 'nombre': this.convertToTemplate.getNombrePlantilla(), [this.csrf_token]: this.csrf_hash - }, - {}, + }, + {}, (response) => { if (response.id) { @@ -228,7 +228,7 @@ class tarifasClienteView { this.selectorPlantilla.setOption(response.id, this.convertToTemplate.getNombrePlantilla()); this.selectorPlantilla.onChange(this.#changePlantilla.bind(this)); } - }, + }, (error) => { console.log(error); } @@ -267,6 +267,28 @@ class tarifasClienteView { #changePlantilla() { + self = this; + const data = $('#plantillas').select2('data'); + if (data.length > 0) { + const id = data[0].id; + new Ajax( + '/clienteprecios/changeplantilla', + { + 'cliente_id': self.clienteId, + 'plantilla_id': id, + [this.csrf_token]: this.csrf_hash + }, + {}, + () => { + self.tableTarifas.table.clearPipeline(); + self.tableTarifas.table.draw(); + }, + (error) => { + console.log(error); + } + ).post(); + } + } diff --git a/httpdocs/assets/js/safekat/pages/plantillasTarifasCliente/edit.js b/httpdocs/assets/js/safekat/pages/plantillasTarifasCliente/edit.js new file mode 100644 index 00000000..03156c92 --- /dev/null +++ b/httpdocs/assets/js/safekat/pages/plantillasTarifasCliente/edit.js @@ -0,0 +1,433 @@ +import Table from '../../components/table.js'; +import TableEditor from '../../components/tableEditor.js'; +import ConfirmDeleteModal from '../../components/ConfirmDeleteModal.js'; +import Ajax from '../../components/ajax.js'; +import { getToken } from '../../common/common.js'; + +class PlantillasTarifasClienteForm { + + constructor() { + + this.domItem = $('.card-body'); + + this.plantillaId = window.location.href.split("/").pop(); + + this.csrf_token = getToken(); + this.csrf_hash = $('#mainContainer').find('input[name="' + this.csrf_token + '"]').val(); + + this.tablePlantilla = null; + this.deleteModal = null; + + this.localEditor = null; + this.ajaxEditor = null; + + this.changedRows = []; + } + + init() { + + const self = this; + + this.headerSearcher(); + + this.deleteModal = new ConfirmDeleteModal('plantillasTarifasCliente'); + this.deleteModal.init(); + + this.#initTable(); + + this.#initEditor(); + + // Editar en linea la fila + this.tablePlantilla.table.on('click', 'tbody span.edit', function (e) { + + const row = $(this).closest('tr'); + + // Iniciar la edición en línea para todas las celdas de la fila + self.localEditor.editor.inline( + self.tablePlantilla.table.cells(row, '*').nodes(), + { + cancelHtml: '', + submitHtml: '', + cancelTrigger: row.find('span.cancel')[0], + submitTrigger: row.find('span.edit')[0], + submit: 'allIfChanged' + } + ); + }); + } + + + #initEditor() { + + const self = this; + + const tipo_linea = [ + { label: window.language.ClientePrecios.interior, value: 'interior' }, + { label: window.language.ClientePrecios.cubierta, value: 'cubierta' }, + { label: window.language.ClientePrecios.sobrecubierta, value: 'sobrecubierta' } + ]; + + const tipo_maquina = [ + { label: window.language.ClientePrecios.toner, value: 'toner' }, + { label: window.language.ClientePrecios.inkjet, value: 'inkjet' }, + ]; + + const tipo_impresion = [ + { label: window.language.ClientePrecios.negro, value: 'negro' }, + { label: window.language.ClientePrecios.negrohq, value: 'negrohq' }, + { label: window.language.ClientePrecios.color, value: 'color' }, + { label: window.language.ClientePrecios.colorhq, value: 'colorhq' }, + ]; + + const editorFields = [ + { + name: "id", + type: "readonly" + }, { + name: "tipo", + type: "select", + options: tipo_linea + }, { + name: "tipo_maquina", + type: "select", + options: tipo_maquina + }, { + name: "tipo_impresion", + type: "select", + options: tipo_impresion + }, { + name: "tiempo_min" + }, { + name: "tiempo_max" + }, { + name: "precio_hora" + }, { + name: "margen" + }, + ]; + this.localEditor = new TableEditor( + $('#tableOfPlantillasPreciosLineas'), + '', + {}, + 'id', + editorFields); + + this.localEditor.init(); + + this.ajaxEditor = new TableEditor( + $('#tableOfPlantillasPreciosLineas'), + '/clienteplantillaprecioslineas/datatable_editor', + { [this.csrf_token]: this.csrf_hash }, + 'id', + editorFields); + + this.ajaxEditor.init(); + + + this.localEditor.editor.on('postEdit', function (e, json, data) { + + /*console.log(self.tablePlantilla.table.row(0).data()); + self.tablePlantilla.table.rows().every( function ( rowIdx ) { + var rowData = this.data(); + if(rowData.id == data.id){ + self.tablePlantilla.table.row(rowIdx).data({ + id: data.id, + tipo: 'interior', // 'interior', 'cubierta', etc. + tipo_maquina: 'toner', // 'toner', 'inkjet' + tipo_impresion: 'negro', // 'negro', 'color', etc. + tiempo_min: 0, + tiempo_max: 1, + precio_hora: 1, + margen: 100, + user_updated: 'yo', + updated_at: '200000' + }).draw(false); + } + }) + //self.tablePlantilla.table.row(0).data(data2).draw(false); + + /*self.tablePlantilla.table.row(0).data({ + id: 1, + tipo: 'interior', // 'interior', 'cubierta', etc. + tipo_maquina: 'toner', // 'toner', 'inkjet' + tipo_impresion: 'negro', // 'negro', 'color', etc. + tiempo_min: 0, + tiempo_max: 1, + precio_hora: 1, + margen: 100, + user_updated: 'yo', + updated_at: '200000' + }).draw(false);*/ + let row = self.tablePlantilla.table.row('#' + data.id); + if (row.length) { + console.log('Data:', data) + let rowData = row.data(); + console.log('Datos de la fila:', rowData); + + // Actualizar los datos de la fila + self.tablePlantilla.table.row('#' + data.id).data({ + id: data.id, + tipo: data.tipo, + tipo_maquina: data.tipo_maquina, + tipo_impresion: data.tipo_impresion, + tiempo_min: data.tiempo_min, + tiempo_max: data.tiempo_max, + precio_hora: data.precio_hora, + margen: "150", + user_updated_id: data.user_updated_id, + user_updated: data.user_updated, + updated_at: data.updated_at + }).draw(true); // Usar invalidate() si es necesario + rowData = row.data(); + console.log('Datos de la fila actualizados:', rowData); + } else { + console.warn('No se encontró la fila con ID row_' + data.id); + } + /* + if (row.length > 0) { + self.tablePlantilla.table.row(row[0]).data({ + id: data.id, + tipo: data.tipo, // 'interior', 'cubierta', etc. + tipo_maquina: data.tipo_maquina, // 'toner', 'inkjet' + tipo_impresion: data.tipo_impresion, // 'negro', 'color', etc. + tiempo_min: data.tiempo_min, + tiempo_max: data.tiempo_max, + precio_hora: data.precio_hora, + margen: data.margen, + user_updated: data.user_updated, + updated_at: data.updated_at + }).invalidate().draw(false); + + console.log('---'); + console.log(self.tablePlantilla.table.row(row[0]).data()) + }*/ + + + + // check if this id exists + if (!self.changedRows.includes(data.id)) + self.changedRows.push(data.id); + + + }); + + /* + this.editorTarifas.editor.on('preSubmit', function (e, d, type) { + if (type === 'create') { + d.data[0]['cliente_id'] = self.clienteId; + } + }); + + this.editorTarifas.editor.on('submitSuccess', function (e, json, data, action) { + + self.tablePlantilla.table.clearPipeline(); + self.tablePlantilla.table.draw(); + }); + + + this.editorTarifas.editor.on('postEdit', function (e, json, data, action) { + self.#borrarPlantillaTarifa(self.clienteId); + self.selectorPlantilla.offChange(); + self.selectorPlantilla.setOption(0, 'Personalizado'); + self.selectorPlantilla.onChange(self.#changePlantilla.bind(this)); + }) + + this.editorTarifas.editor.on('postCreate', function (e, json, data, action) { + self.#borrarPlantillaTarifa(self.clienteId); + self.selectorPlantilla.offChange(); + self.selectorPlantilla.setOption(0, 'Personalizado'); + self.selectorPlantilla.onChange(self.#changePlantilla.bind(this)); + }) + + this.editorTarifas.editor.on('postCancel', function (e, json, data) { + // Restaurar botones de acción por fila + self.tablePlantilla.table.rows().nodes().each(function (node) { + $(node).find('span.edit').removeClass('d-none'); + $(node).find('span.cancel, span.submit').addClass('d-none'); + }); + });*/ + } + + + #initTable() { + + const self = this; + + const columns = + [ + { 'data': 'id' }, + { + 'data': 'tipo', + 'render': function (data, type, row, meta) { + if (data == 'interior') + return window.language.ClientePrecios.interior; + else if (data == 'cubierta') + return window.language.ClientePrecios.cubierta; + else if (data == 'sobrecubierta') + return window.language.ClientePrecios.sobrecubierta; + } + }, + { + 'data': 'tipo_maquina', + 'render': function (data, type, row, meta) { + if (data == 'toner') + return window.language.ClientePrecios.toner; + else if (data == 'inkjet') + return window.language.ClientePrecios.inkjet; + } + }, + { + 'data': 'tipo_impresion', + 'render': function (data, type, row, meta) { + if (data == 'negro') + return window.language.ClientePrecios.negro; + else if (data == 'negrohq') + return window.language.ClientePrecios.negrohq; + else if (data == 'color') + return window.language.ClientePrecios.color; + else if (data == 'colorhq') + return window.language.ClientePrecios.colorhq; + } + }, + { 'data': 'tiempo_min' }, + { 'data': 'tiempo_max' }, + { 'data': 'precio_hora' }, + { 'data': 'margen' }, + { 'data': 'user_updated' }, + { 'data': 'updated_at' }, + + ]; + + const actions = ['edit', 'delete', 'cancel']; + + this.tablePlantilla = new Table( + $('#tableOfPlantillasPreciosLineas'), + 'plantillaTarifasCliente', + '/clienteplantillaprecioslineas/datatable', + columns, + [ + { name: 'plantilla_id', value: this.plantillaId } + ],'id' + ); + + + this.tablePlantilla.init({ + actions: actions, + colVisibility: false, + buttonsExport: true, + }); + + + this.tablePlantilla.table.on('init.dt', function () { + self.tablePlantilla.table.page.len(50).draw(); + }); + + } + + headerSearcher() { + + const self = this; + + $('#tableOfPlantillasPreciosLineas thead tr').clone(false).appendTo('#tableOfPlantillasPreciosLineas thead'); + $('#tableOfPlantillasPreciosLineas thead tr:eq(1) th').each(function (i) { + + if (!$(this).hasClass("noFilter")) { + + if (i == 1) { + + // Agregar un selector en la segunda columna + $(this).html(''); + + // Agregar opciones al selector + var selector = $('select', this); + selector.append(''); // Opción vacía + selector.append(''); + selector.append(''); + selector.append(''); + + selector.on('change', function () { + var val = $.fn.dataTable.util.escapeRegex( + $(this).val() + ); + self.tablePlantilla.table.column(i).search(val).draw(); + }); + + } + + else if (i == 2) { + // Agregar un selector en la tercera columna + $(this).html(''); + + // Agregar opciones al selector + var selector = $('select', this); + selector.append(''); // Opción vacía + selector.append(''); + selector.append(''); + + selector.on('change', function () { + var val = $.fn.dataTable.util.escapeRegex( + $(this).val() + ); + self.tablePlantilla.table.column(i).search(val).draw(); + }); + } + + else if (i == 3) { + // Agregar un selector en la cuarta columna + $(this).html(''); + + // Agregar opciones al selector + var selector = $('select', this); + selector.append(''); // Opción vacía + selector.append(''); + selector.append(''); + selector.append(''); + selector.append(''); + + selector.on('change', function () { + var val = $.fn.dataTable.util.escapeRegex( + $(this).val() + ); + self.tablePlantilla.table.column(i).search(val).draw(); + }); + } + else { + $(this).html(''); + + $('input', this).on('change clear', function () { + if (self.tablePlantilla.table.column(i).search() !== this.value) { + self.tablePlantilla.table + .column(i) + .search(this.value) + .draw(); + } + }); + } + } + else { + $(this).html(''); + } + }); + + + } + +} + +document.addEventListener('DOMContentLoaded', function () { + + const locale = document.querySelector('meta[name="locale"]').getAttribute('content'); + + + + new Ajax('/translate/getTranslation', { locale: locale, translationFile: ['ClientePrecios'] }, {}, + function (translations) { + window.language = JSON.parse(translations); + new PlantillasTarifasClienteForm().init(); + }, + function (error) { + console.log("Error getting translations:", error); + } + ).post(); + +}); \ No newline at end of file diff --git a/httpdocs/assets/js/safekat/pages/plantillasTarifasCliente/list.js b/httpdocs/assets/js/safekat/pages/plantillasTarifasCliente/list.js new file mode 100644 index 00000000..f0d78bcf --- /dev/null +++ b/httpdocs/assets/js/safekat/pages/plantillasTarifasCliente/list.js @@ -0,0 +1,153 @@ +import Table from '../../components/table.js'; +import ConfirmDeleteModal from '../../components/ConfirmDeleteModal.js'; +import Ajax from '../../components/ajax.js'; +import { getToken } from '../../common/common.js'; + +class PlantillasTarifasClienteList { + + constructor() { + + this.domItem = $('.card-body'); + + this.csrf_token = getToken(); + this.csrf_hash = $('#mainContainer').find('input[name="' + this.csrf_token + '"]').val(); + + this.tablePlantillas = null; + this.deleteModal = null; + } + + init() { + + const self = this; + + this.headerSearcher(); + + this.deleteModal = new ConfirmDeleteModal('plantillasTarifasCliente'); + this.deleteModal.init(); + + this.#initTable(); + + // Editar en linea la fila + this.tablePlantillas.table.on('click', '.btn-edit-' + this.tablePlantillas.getAlias(), function (e) { + + const dataId = $(this).attr('data-id'); + + if (!Number.isNaN(Number(dataId))) { + window.location.href = '/clienteplantillaprecios/edit/' + dataId; + } + }); + + + // Eliminar la fila + this.tablePlantillas.table.on('click', '.btn-delete-' + this.tablePlantillas.getAlias(), function (e) { + const row = $(this).closest('tr')[0]._DT_RowIndex; + const dataId = $(this).attr('data-id'); + self.deleteModal.setData($(this).attr('data-id')); + self.deleteModal.show(() => { + + if (!Number.isNaN(Number(self.deleteModal.getData()))) { + + new Ajax( + '/clienteplantillaprecios/delete/' + dataId, + { + + }, + {}, + (data, textStatus, jqXHR) => { + + self.tablePlantillas.table.clearPipeline(); + self.tablePlantillas.table.row($(row)).invalidate().draw(); + + // Se borran las lineas asociadas + new Ajax( + "/clientes/clienteplantillaprecios/update/" + dataId, + { + [this.csrf_token]: this.csrf_hash + }, + {}, + () => { }, + (error) => { + console.log(error); + }).post(); + + popSuccessAlert(data.msg ?? jqXHR.statusText); + }, + (error) => { + console.log(error); + } + + ).get(); + self.deleteModal.hide(); + } + }); + }); + } + + #initTable() { + + const self = this; + + const columns = [ + { 'data': 'id' }, + { 'data': 'nombre' }, + + ]; + + const actions = ['edit', 'delete']; + + this.tablePlantillas = new Table( + $('#tableOfClienteplantillaprecios'), + 'plantillasTarifasCliente', + '/clienteplantillaprecios/datatable', + columns, + [] + ); + + + this.tablePlantillas.init({ + actions: actions, + colVisibility: false, + buttonsExport: true, + }); + + + this.tablePlantillas.table.on('init.dt', function () { + self.tablePlantillas.table.page.len(50).draw(); + }); + + } + + headerSearcher() { + + const self = this; + + $('#tableOfClienteplantillaprecios thead tr').clone(false).appendTo('#tableOfClienteplantillaprecios thead'); + $('#tableOfClienteplantillaprecios thead tr:eq(1) th').each(function (i) { + + if (!$(this).hasClass("noFilter")) { + + $(this).html(''); + + $('input', this).on('change clear', function () { + if (self.tablePlantillas.table.column(i).search() !== this.value) { + self.tablePlantillas.table + .column(i) + .search(this.value) + .draw(); + } + }); + } + else { + $(this).html(''); + } + }); + + + } + +} + +document.addEventListener('DOMContentLoaded', function () { + + new PlantillasTarifasClienteList().init(); +}); \ No newline at end of file From d02e7e03f44edc180c337519586adc799c6a8342 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jaime=20Jim=C3=A9nez?= Date: Wed, 4 Dec 2024 14:08:37 +0100 Subject: [PATCH 14/18] arraglado bug tarifas cliente --- .../Models/Clientes/ClientePreciosModel.php | 2 +- .../viewClienteplantillapreciosForm.php | 278 +----------------- .../safekat/pages/cliente/tarifasCliente.js | 46 +-- .../pages/plantillasTarifasCliente/edit.js | 79 +---- 4 files changed, 42 insertions(+), 363 deletions(-) diff --git a/ci4/app/Models/Clientes/ClientePreciosModel.php b/ci4/app/Models/Clientes/ClientePreciosModel.php index adeef70b..953eec5b 100755 --- a/ci4/app/Models/Clientes/ClientePreciosModel.php +++ b/ci4/app/Models/Clientes/ClientePreciosModel.php @@ -153,7 +153,7 @@ class ClientePreciosModel extends \App\Models\BaseModel // Se cargan los valores de la plantilla $plantillaModel = model('App\Models\Clientes\ClientePlantillaPreciosLineasModel'); - $values = $plantillaModel->getResource($plantilla_id)->get()->getResultObject(); + $values = $plantillaModel->getResource([],$plantilla_id)->get()->getResultObject(); foreach ($values as $value) { $this->db ->table($this->table . " t1") diff --git a/ci4/app/Views/themes/vuexy/form/clientes/plantillaprecios/viewClienteplantillapreciosForm.php b/ci4/app/Views/themes/vuexy/form/clientes/plantillaprecios/viewClienteplantillapreciosForm.php index 17d94304..1c161027 100644 --- a/ci4/app/Views/themes/vuexy/form/clientes/plantillaprecios/viewClienteplantillapreciosForm.php +++ b/ci4/app/Views/themes/vuexy/form/clientes/plantillaprecios/viewClienteplantillapreciosForm.php @@ -42,7 +42,7 @@
-
ID
@@ -75,282 +75,6 @@ endSection() ?> - - section('additionalInlineJs') ?> - /* - const lastColNr_lineas = $('#tableOfPlantillasPreciosLineas').find("tr:first th").length - 1; - - const url = window.location.href; - const url_parts = url.split('/'); - - let id = -1; - if(url_parts[url_parts.length-2] == 'edit'){ - id = url_parts[url_parts.length-1]; - } - - const actionBtns_lineas = function(data) { - return ` - - - - `; - }; - - - const tipo_linea = [ - {label:'', value:'interior'}, - {label:'', value: 'cubierta'}, - {label:'', value: 'sobrecubierta'} - ]; - - const tipo_maquina = [ - {label: '', value:'toner'}, - {label: '', value:'inkjet'}, - ]; - - const tipo_impresion = [ - {label: '', value:'negro'}, - {label: '', value:'negrohq'}, - {label: '', value:'color'}, - {label: '', value:'colorhq'}, - ]; - - var editor = new $.fn.dataTable.Editor( { - ajax: { - url: "", - headers: { - : v, - }, - }, - table : "#tableOfPlantillasPreciosLineas", - idSrc: 'id', - fields: [ { - name: "tipo", - type: "select", - options: tipo_linea - }, { - name: "tipo_maquina", - type: "select", - options: tipo_maquina - }, { - name: "tipo_impresion", - type: "select", - options: tipo_impresion - }, { - name: "tiempo_min" - }, { - name: "tiempo_max" - }, { - name: "precio_hora" - }, { - name: "margen" - }, { - name: "user_updated_id", - type:'hidden', - - }, { - name: "updated_at", - type:'hidden', - - }, { - "name": "plantilla_id", - "type": "hidden" - },{ - "name": "deleted_at", - "type": "hidden" - },{ - "name": "is_deleted", - "type": "hidden" - }, - ] - } ); - - editor.on( 'preSubmit', function ( e, d, type ) { - if ( type === 'create'){ - d.data[0]['plantilla_id'] = id; - } - else if(type === 'edit' ) { - for (v in d.data){ - d.data[v]['plantilla_id'] = id; - } - } - }); - - - editor.on( 'postSubmit', function ( e, json, data, action ) { - - yeniden(json.); - - const domain = window.location.origin - fetch(domain + "/clientes/clienteprecios/update/" + -1 , { - method: "POST", - body: JSON.stringify({ - plantilla_id: id, - : v - }), - headers: { - "Content-type": "application/json; charset=UTF-8" - } - }) - }); - - editor.on( 'submitSuccess', function ( e, json, data, action ) { - - theTable.clearPipeline(); - theTable.draw(); - }); - - - var theTable = $('#tableOfPlantillasPreciosLineas').DataTable( { - serverSide: true, - processing: true, - autoWidth: true, - responsive: true, - lengthMenu: [ 10, 25, 50, 100], - order: [[ 0, "asc" ], [ 1, "asc" ], [ 2, "asc" ], [ 3, "asc" ]], - pageLength: 50, - lengthChange: true, - searching: false, - paging: true, - info: false, - dom: '<"mt-4"><"float-end"B><"float-start"l> - <"mt-4 mb-3"p>', - ajax : $.fn.dataTable.pipeline( { - url: '', - data: { - plantilla_id: id, - }, - method: 'POST', - headers: {'X-Requested-With': 'XMLHttpRequest'}, - async: true, - }), - columns: [ - { 'data': 'tipo' , - 'render': function ( data, type, row, meta ) { - if(data=='interior') - return ''; - else if(data=='cubierta') - return ''; - else if(data=='sobrecubierta') - return ''; - } - }, - { 'data': 'tipo_maquina', - 'render': function ( data, type, row, meta ) { - if(data=='toner') - return ''; - else if(data=='inkjet') - return ''; - } - }, - { 'data': 'tipo_impresion', - 'render': function ( data, type, row, meta ) { - if(data=='negro') - return ''; - else if(data=='negrohq') - return ''; - else if(data=='color') - return ''; - else if(data=='colorhq') - return ''; - } - }, - { 'data': 'tiempo_min' }, - { 'data': 'tiempo_max' }, - { 'data': 'precio_hora' }, - { 'data': 'margen' }, - { 'data': 'user_updated_id', - 'render': function ( data, type, row, meta ) { - return row.user_updated - } - }, - { 'data': 'updated_at' }, - { - data: actionBtns_lineas, - className: 'row-edit dt-center' - } - ], - columnDefs: [ - { - orderable: false, - searchable: false, - targets: [lastColNr_lineas] - }, - {"orderData": [ 0, 1 ], "targets": 0 }, - - ], - language: { - url: "/themes/vuexy/vendor/libs/datatables-sk/plugins/i18n/es-ES.json" - }, - buttons: [ - { - extend: 'collection', - text: 'Exportar', - buttons:[ - 'copy', 'csv', 'excel', 'print', { - extend: 'pdfHtml5', - orientation: 'landscape', - pageSize: 'A4' - } - ] - }, - { - className: 'btn btn-primary me-sm-3 me-1', - extend: "createInline", - editor: editor, - formOptions: { - submitTrigger: -1, - submitHtml: '' - } - } ] - } ); - - - - // Activate an inline edit on click of a table cell - $('#tableOfPlantillasPreciosLineas').on( 'click', 'tbody span.edit', function (e) { - editor.inline( - theTable.cells(this.parentNode.parentNode, '*').nodes(), - { - cancelHtml: '', - cancelTrigger: 'span.cancel', - submitHtml: '', - submitTrigger: 'span.edit', - submit: 'allIfChanged' - } - ); - } ); - - - // Delete row - $(document).on('click', '.btn-delete', function(e) { - $(".btn-remove").attr('data-id', $(this).attr('data-id')); - }); - - $(document).on('click', '.btn-remove', function(e) { - const dataId = $(this).attr('data-id'); - const row = $(this).closest('tr'); - if ($.isNumeric(dataId)) { - $.ajax({ - url: `/clientes/clienteplantillaprecioslineas/delete/${dataId}`, - method: 'GET', - }).done((data, textStatus, jqXHR) => { - $('#confirm2delete').modal('toggle'); - theTable.clearPipeline(); - theTable.row($(row)).invalidate().draw(); - popSuccessAlert(data.msg ?? jqXHR.statusText); - }).fail((jqXHR, textStatus, errorThrown) => { - popErrorAlert(jqXHR.responseJSON.messages.error) - }) - } - }); - */ -endSection() ?> - - - section('css') ?> diff --git a/httpdocs/assets/js/safekat/pages/cliente/tarifasCliente.js b/httpdocs/assets/js/safekat/pages/cliente/tarifasCliente.js index d973be42..6006e064 100644 --- a/httpdocs/assets/js/safekat/pages/cliente/tarifasCliente.js +++ b/httpdocs/assets/js/safekat/pages/cliente/tarifasCliente.js @@ -267,26 +267,36 @@ class tarifasClienteView { #changePlantilla() { - self = this; + const self = this; const data = $('#plantillas').select2('data'); if (data.length > 0) { - const id = data[0].id; - new Ajax( - '/clienteprecios/changeplantilla', - { - 'cliente_id': self.clienteId, - 'plantilla_id': id, - [this.csrf_token]: this.csrf_hash - }, - {}, - () => { - self.tableTarifas.table.clearPipeline(); - self.tableTarifas.table.draw(); - }, - (error) => { - console.log(error); - } - ).post(); + if (data[0].id == 0) { + self.#borrarPlantillaTarifa(self.clienteId); + self.tableTarifas.table.clearPipeline(); + self.tableTarifas.table.draw(); + + } + else { + + + const id = data[0].id; + new Ajax( + '/clienteprecios/changeplantilla', + { + 'cliente_id': self.clienteId, + 'plantilla_id': id, + [this.csrf_token]: this.csrf_hash + }, + {}, + () => { + self.tableTarifas.table.clearPipeline(); + self.tableTarifas.table.draw(); + }, + (error) => { + console.log(error); + } + ).post(); + } } diff --git a/httpdocs/assets/js/safekat/pages/plantillasTarifasCliente/edit.js b/httpdocs/assets/js/safekat/pages/plantillasTarifasCliente/edit.js index 03156c92..cbd17b78 100644 --- a/httpdocs/assets/js/safekat/pages/plantillasTarifasCliente/edit.js +++ b/httpdocs/assets/js/safekat/pages/plantillasTarifasCliente/edit.js @@ -15,6 +15,8 @@ class PlantillasTarifasClienteForm { this.csrf_token = getToken(); this.csrf_hash = $('#mainContainer').find('input[name="' + this.csrf_token + '"]').val(); + this.btnApply = $('#btnApply'); + this.tablePlantilla = null; this.deleteModal = null; @@ -22,6 +24,7 @@ class PlantillasTarifasClienteForm { this.ajaxEditor = null; this.changedRows = []; + this.deletedRows = []; } init() { @@ -50,7 +53,8 @@ class PlantillasTarifasClienteForm { submitHtml: '', cancelTrigger: row.find('span.cancel')[0], submitTrigger: row.find('span.edit')[0], - submit: 'allIfChanged' + submit: 'allIfChanged', + drawType: 'none' } ); }); @@ -123,47 +127,14 @@ class PlantillasTarifasClienteForm { this.ajaxEditor.init(); - this.localEditor.editor.on('postEdit', function (e, json, data) { - /*console.log(self.tablePlantilla.table.row(0).data()); - self.tablePlantilla.table.rows().every( function ( rowIdx ) { - var rowData = this.data(); - if(rowData.id == data.id){ - self.tablePlantilla.table.row(rowIdx).data({ - id: data.id, - tipo: 'interior', // 'interior', 'cubierta', etc. - tipo_maquina: 'toner', // 'toner', 'inkjet' - tipo_impresion: 'negro', // 'negro', 'color', etc. - tiempo_min: 0, - tiempo_max: 1, - precio_hora: 1, - margen: 100, - user_updated: 'yo', - updated_at: '200000' - }).draw(false); - } - }) - //self.tablePlantilla.table.row(0).data(data2).draw(false); - - /*self.tablePlantilla.table.row(0).data({ - id: 1, - tipo: 'interior', // 'interior', 'cubierta', etc. - tipo_maquina: 'toner', // 'toner', 'inkjet' - tipo_impresion: 'negro', // 'negro', 'color', etc. - tiempo_min: 0, - tiempo_max: 1, - precio_hora: 1, - margen: 100, - user_updated: 'yo', - updated_at: '200000' - }).draw(false);*/ let row = self.tablePlantilla.table.row('#' + data.id); + if (row.length) { - console.log('Data:', data) + let rowData = row.data(); - console.log('Datos de la fila:', rowData); - + // Actualizar los datos de la fila self.tablePlantilla.table.row('#' + data.id).data({ id: data.id, @@ -174,41 +145,15 @@ class PlantillasTarifasClienteForm { tiempo_max: data.tiempo_max, precio_hora: data.precio_hora, margen: "150", - user_updated_id: data.user_updated_id, + user_updated_id: data.user_updated, user_updated: data.user_updated, updated_at: data.updated_at - }).draw(true); // Usar invalidate() si es necesario - rowData = row.data(); - console.log('Datos de la fila actualizados:', rowData); - } else { - console.warn('No se encontró la fila con ID row_' + data.id); - } - /* - if (row.length > 0) { - self.tablePlantilla.table.row(row[0]).data({ - id: data.id, - tipo: data.tipo, // 'interior', 'cubierta', etc. - tipo_maquina: data.tipo_maquina, // 'toner', 'inkjet' - tipo_impresion: data.tipo_impresion, // 'negro', 'color', etc. - tiempo_min: data.tiempo_min, - tiempo_max: data.tiempo_max, - precio_hora: data.precio_hora, - margen: data.margen, - user_updated: data.user_updated, - updated_at: data.updated_at - }).invalidate().draw(false); - - console.log('---'); - console.log(self.tablePlantilla.table.row(row[0]).data()) - }*/ + }); - - - // check if this id exists + // check if this id exists if (!self.changedRows.includes(data.id)) self.changedRows.push(data.id); - - + } }); /* From 8f907b276217ae1d294c07f562e5c008815c7881 Mon Sep 17 00:00:00 2001 From: amazuecos Date: Wed, 4 Dec 2024 18:19:29 +0100 Subject: [PATCH 15/18] remove this.selectUsers repeated --- .../js/safekat/pages/configuracion/messages/messagePage.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/httpdocs/assets/js/safekat/pages/configuracion/messages/messagePage.js b/httpdocs/assets/js/safekat/pages/configuracion/messages/messagePage.js index b97191b4..ce8d102b 100644 --- a/httpdocs/assets/js/safekat/pages/configuracion/messages/messagePage.js +++ b/httpdocs/assets/js/safekat/pages/configuracion/messages/messagePage.js @@ -14,7 +14,7 @@ class MessagePage { this.formNewDirectMessage = this.modalNewMessage.item.find("#formNewDirectMessage") this.alert = new Alert($("#alertDirectMessage")) this.selectUsers = $("#select-users") - this.selectUsers = $("#select-departments") + this.selectDepartments = $("#select-departments") this.selectPlaceholder = { id: '0', @@ -25,7 +25,7 @@ class MessagePage { text: "Seleccione un departamento" } this.selectMessageUsers = new ClassSelect(this.selectUsers, '/chat/users/all', this.selectPlaceholder, true) - this.selectChatDepartment = new ClassSelect(this.selectUsers, '/chat/department/select', this.selectDepartmentPlaceholder, true) + this.selectChatDepartment = new ClassSelect(this.selectDepartments, '/chat/department/select', this.selectDepartmentPlaceholder, true) } init() { From 16cec58431460e75572672375c073c145c4d34ae Mon Sep 17 00:00:00 2001 From: amazuecos Date: Wed, 4 Dec 2024 18:26:37 +0100 Subject: [PATCH 16/18] default message when no notifications --- ci4/app/Language/es/Chat.php | 3 ++- ci4/app/Views/themes/vuexy/main/defaultlayout.php | 3 ++- httpdocs/assets/js/safekat/components/chat.js | 2 ++ 3 files changed, 6 insertions(+), 2 deletions(-) diff --git a/ci4/app/Language/es/Chat.php b/ci4/app/Language/es/Chat.php index 1aca873e..0f130fb1 100644 --- a/ci4/app/Language/es/Chat.php +++ b/ci4/app/Language/es/Chat.php @@ -28,5 +28,6 @@ return [ "add_notification" => "Notificación", "check_as_unviewed" => "Marcar como no leídos", "add_notification_message" => "Envía a los usuarios añadidos una notificación con los mensajes presentes en el chat.", - "chat_title_presupuesto" => 'Presupuesto[{title,string,0}][{id}]' + "chat_title_presupuesto" => 'Presupuesto[{title,string,0}][{id}]', + "no_messages_notification" => 'No hay mensajes que revisar por el momento' ]; \ No newline at end of file diff --git a/ci4/app/Views/themes/vuexy/main/defaultlayout.php b/ci4/app/Views/themes/vuexy/main/defaultlayout.php index 40358745..c2cccd59 100644 --- a/ci4/app/Views/themes/vuexy/main/defaultlayout.php +++ b/ci4/app/Views/themes/vuexy/main/defaultlayout.php @@ -136,8 +136,9 @@ $picture = "/assets/img/default-user.png";
diff --git a/httpdocs/assets/js/safekat/components/chat.js b/httpdocs/assets/js/safekat/components/chat.js index 6099c028..8d0e7f06 100644 --- a/httpdocs/assets/js/safekat/components/chat.js +++ b/httpdocs/assets/js/safekat/components/chat.js @@ -722,9 +722,11 @@ export const showNotificationMessages = (dom) => { dom.empty() $("#chat-notification-number") if (data.totalMessages > 0) { + $("#chat-message-notification-title").addClass("d-none") $("#chat-notification-number").removeClass("d-none") $("#chat-notification-number").text(data.totalMessages ?? 0) } else { + $("#chat-message-notification-title").removeClass("d-none") $("#chat-notification-number").addClass("d-none") $("#chat-notification-number").text(0) } From ea4d4327b7a28e9835964fadc6f7bfa6da6b2a9e Mon Sep 17 00:00:00 2001 From: amazuecos Date: Wed, 4 Dec 2024 18:31:18 +0100 Subject: [PATCH 17/18] fix chat_department as object --- ci4/app/Controllers/Configuracion/Users.php | 2 +- ci4/app/Views/themes/vuexy/form/user/_userFormItems.php | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/ci4/app/Controllers/Configuracion/Users.php b/ci4/app/Controllers/Configuracion/Users.php index 82cf1422..7864620f 100755 --- a/ci4/app/Controllers/Configuracion/Users.php +++ b/ci4/app/Controllers/Configuracion/Users.php @@ -265,7 +265,7 @@ class Users extends \App\Controllers\GoBaseController 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; diff --git a/ci4/app/Views/themes/vuexy/form/user/_userFormItems.php b/ci4/app/Views/themes/vuexy/form/user/_userFormItems.php index 3e75ae63..e7e5b32a 100644 --- a/ci4/app/Views/themes/vuexy/form/user/_userFormItems.php +++ b/ci4/app/Views/themes/vuexy/form/user/_userFormItems.php @@ -61,11 +61,11 @@ $selectedChatDepartments = isset($chatDepartmentUser) && is_array($chatDepartmentUser) ? $chatDepartmentUser : []; $selectedKeywords = array_map(fn($chatDepartment) => $chatDepartment->name, $selectedChatDepartments); foreach ($chatDepartments as $item) : - $isSelected = in_array($item["name"], $selectedKeywords) ? 'selected' : ''; + $isSelected = in_array($item->name, $selectedKeywords) ? 'selected' : ''; ?> - From 9fa31c5d8e4e42f64e24b37045e65f2dade7e90c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jaime=20Jim=C3=A9nez?= Date: Thu, 5 Dec 2024 00:15:08 +0100 Subject: [PATCH 18/18] terminado --- ci4/app/Config/Routes.php | 1 + .../Clientes/Clienteplantillaprecios.php | 17 + .../Clienteplantillaprecioslineas.php | 9 +- .../ClientePlantillaPreciosLineasModel.php | 2 +- .../Models/Clientes/ClientePreciosModel.php | 6 +- .../viewClienteplantillapreciosForm.php | 6 +- .../js/safekat/components/modalYesNo.js | 69 ++++ .../assets/js/safekat/components/table.js | 3 +- .../pages/plantillasTarifasCliente/edit.js | 333 +++++++++++++++--- 9 files changed, 383 insertions(+), 63 deletions(-) create mode 100644 httpdocs/assets/js/safekat/components/modalYesNo.js diff --git a/ci4/app/Config/Routes.php b/ci4/app/Config/Routes.php index 8bf72145..a665e363 100644 --- a/ci4/app/Config/Routes.php +++ b/ci4/app/Config/Routes.php @@ -396,6 +396,7 @@ $routes->group('clienteprecios', ['namespace' => 'App\Controllers\Clientes'], fu $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']); diff --git a/ci4/app/Controllers/Clientes/Clienteplantillaprecios.php b/ci4/app/Controllers/Clientes/Clienteplantillaprecios.php index 0c65fc90..ae43ffee 100755 --- a/ci4/app/Controllers/Clientes/Clienteplantillaprecios.php +++ b/ci4/app/Controllers/Clientes/Clienteplantillaprecios.php @@ -247,6 +247,23 @@ 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()) { diff --git a/ci4/app/Controllers/Clientes/Clienteplantillaprecioslineas.php b/ci4/app/Controllers/Clientes/Clienteplantillaprecioslineas.php index 83cfd625..4e933a3a 100755 --- a/ci4/app/Controllers/Clientes/Clienteplantillaprecioslineas.php +++ b/ci4/app/Controllers/Clientes/Clienteplantillaprecioslineas.php @@ -134,6 +134,8 @@ 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( 'is_deleted' ), Field::inst( 'updated_at' ), Field::inst( 'tiempo_min' ) ->getFormatter( 'Format::toDecimalChar')->setFormatter( 'Format::fromDecimalChar') @@ -197,21 +199,20 @@ class Clienteplantillaprecioslineas extends \App\Controllers\BaseResourceControl } }) ->on('preCreate', function ($editor, &$values) { - $session = session(); $datetime = (new \CodeIgniter\I18n\Time("now")); $editor ->field('user_updated_id') - ->setValue($session->id_user); + ->setValue(auth()->user()->id); $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($session->id_user); + ->setValue(auth()->user()->id); $editor ->field('updated_at') ->setValue($datetime->format('Y-m-d H:i:s')); diff --git a/ci4/app/Models/Clientes/ClientePlantillaPreciosLineasModel.php b/ci4/app/Models/Clientes/ClientePlantillaPreciosLineasModel.php index 9e1b6852..4a948f0e 100755 --- a/ci4/app/Models/Clientes/ClientePlantillaPreciosLineasModel.php +++ b/ci4/app/Models/Clientes/ClientePlantillaPreciosLineasModel.php @@ -160,7 +160,7 @@ class ClientePlantillaPreciosLineasModel extends \App\Models\BaseModel else { $builder->groupStart(); foreach ($search as $col_search) { - if ($col_search[0] > 0 && $col_search[0] < 4) + if ($col_search[1] > 0 && $col_search[0] < 4) $builder->where(self::SORTABLE[$col_search[0]], $col_search[2]); else $builder->like(self::SORTABLE[$col_search[0]], $col_search[2]); diff --git a/ci4/app/Models/Clientes/ClientePreciosModel.php b/ci4/app/Models/Clientes/ClientePreciosModel.php index 953eec5b..5a50ac6a 100755 --- a/ci4/app/Models/Clientes/ClientePreciosModel.php +++ b/ci4/app/Models/Clientes/ClientePreciosModel.php @@ -178,7 +178,6 @@ class ClientePreciosModel extends \App\Models\BaseModel function update_from_plantilla($plantilla_id = 0){ - $session = session(); $datetime = (new \CodeIgniter\I18n\Time("now")); $date_value = $datetime->format('Y-m-d H:i:s'); @@ -187,6 +186,7 @@ class ClientePreciosModel extends \App\Models\BaseModel ->table($this->table . " t1") ->select("t1.cliente_id AS id") ->where('t1.plantilla_id', $plantilla_id) + ->where('t1.is_deleted', 0) ->distinct() ->get()->getResultObject(); @@ -200,7 +200,7 @@ class ClientePreciosModel extends \App\Models\BaseModel // Se cargan los valores de la plantilla $plantillaModel = model('App\Models\Clientes\ClientePlantillaPreciosLineasModel'); - $values = $plantillaModel->getResource($plantilla_id)->get()->getResultObject(); + $values = $plantillaModel->getResource([], $plantilla_id)->get()->getResultObject(); foreach ($values as $value) { $this->db ->table($this->table . " t1") @@ -215,7 +215,7 @@ class ClientePreciosModel extends \App\Models\BaseModel ->set('margen', $value->margen) ->set('user_updated_id', $value->user_updated_id) ->set('updated_at', $value->updated_at) - ->set('user_created_id', $session->id_user) + ->set('user_created_id', auth()->user()->id) ->set('created_at', $date_value) ->insert(); } diff --git a/ci4/app/Views/themes/vuexy/form/clientes/plantillaprecios/viewClienteplantillapreciosForm.php b/ci4/app/Views/themes/vuexy/form/clientes/plantillaprecios/viewClienteplantillapreciosForm.php index 1c161027..5eefbee4 100644 --- a/ci4/app/Views/themes/vuexy/form/clientes/plantillaprecios/viewClienteplantillapreciosForm.php +++ b/ci4/app/Views/themes/vuexy/form/clientes/plantillaprecios/viewClienteplantillapreciosForm.php @@ -42,9 +42,13 @@
- + +
diff --git a/httpdocs/assets/js/safekat/components/modalYesNo.js b/httpdocs/assets/js/safekat/components/modalYesNo.js new file mode 100644 index 00000000..2a88cc59 --- /dev/null +++ b/httpdocs/assets/js/safekat/components/modalYesNo.js @@ -0,0 +1,69 @@ +class ModalYesNo { + + constructor(text= "", alias = "") { + + this.modalId = alias !== "" ? `yesNoModal-${alias}`: 'yesNoModal'; + + this.btnCancelId = alias !== "" ? `btnCancelModal-${alias}` : 'btnCancelModal'; + this.btnConfirmId = alias !== "" ? `btnYesModal-${alias}` : 'btnYesModal'; + + this.modalHtml = ` + + `; + } + + init() { + + // Insertar el modal en el body del documento si no existe + if (!document.getElementById(this.modalId)) { + document.body.insertAdjacentHTML('beforeend', this.modalHtml); + } + document.getElementById(this.btnCancelId).addEventListener('click', () => { + const modal = new bootstrap.Modal(document.getElementById(this.modalId)); + modal.hide(); + }); + } + + getModalId() { + return '#' + this.modalId; + } + + // Método para mostrar el modal + show(callback) { + + // Mostrar el modal usando Bootstrap + const modal = new bootstrap.Modal(document.getElementById(this.modalId)); + modal.show(); + + // Configurar el evento de confirmación de eliminación + document.getElementById(this.btnConfirmId).addEventListener('click', () => { + callback(); // Llamar al callback que el usuario haya proporcionado + modal.hide(); // Cerrar el modal + }); + } + + // Método para ocultar el modal si es necesario + hide() { + const modal = new bootstrap.Modal(document.getElementById(this.modalId)); + modal.hide(); + } +} + + +export default ModalYesNo; \ No newline at end of file diff --git a/httpdocs/assets/js/safekat/components/table.js b/httpdocs/assets/js/safekat/components/table.js index af794fe0..4e662ad1 100644 --- a/httpdocs/assets/js/safekat/components/table.js +++ b/httpdocs/assets/js/safekat/components/table.js @@ -49,6 +49,7 @@ let Table = function ( columns.push( { 'data': self.actionBtns.bind(self), // Vincular correctamente el contexto + 'defaultContent': '', 'className': 'row-edit dt-center', } ); @@ -92,7 +93,7 @@ let Table = function ( autoWidth: true, responsive: true, scrollX: true, - stateSave: false, + stateSave: true, lengthMenu: [5, 10, 25, 50, 75, 100, 250, 500, 1000, 2500], order: order, orderCellsTop: true, diff --git a/httpdocs/assets/js/safekat/pages/plantillasTarifasCliente/edit.js b/httpdocs/assets/js/safekat/pages/plantillasTarifasCliente/edit.js index cbd17b78..5fa6071c 100644 --- a/httpdocs/assets/js/safekat/pages/plantillasTarifasCliente/edit.js +++ b/httpdocs/assets/js/safekat/pages/plantillasTarifasCliente/edit.js @@ -1,6 +1,6 @@ import Table from '../../components/table.js'; import TableEditor from '../../components/tableEditor.js'; -import ConfirmDeleteModal from '../../components/ConfirmDeleteModal.js'; +import ModalYesNo from '../../components/modalYesNo.js'; import Ajax from '../../components/ajax.js'; import { getToken } from '../../common/common.js'; @@ -16,15 +16,13 @@ class PlantillasTarifasClienteForm { this.csrf_hash = $('#mainContainer').find('input[name="' + this.csrf_token + '"]').val(); this.btnApply = $('#btnApply'); + this.btnUndo = $('#btnUndo'); this.tablePlantilla = null; - this.deleteModal = null; + this.modalYesNo = null; this.localEditor = null; this.ajaxEditor = null; - - this.changedRows = []; - this.deletedRows = []; } init() { @@ -33,12 +31,17 @@ class PlantillasTarifasClienteForm { this.headerSearcher(); - this.deleteModal = new ConfirmDeleteModal('plantillasTarifasCliente'); - this.deleteModal.init(); + + this.modalYesNo = new ModalYesNo( + "Aplicar los cambios afectarán a TODOS los clientes que tengan asociada esta plantilla de precios.
" + + "¿Esta seguro de que deseas aplicar los cambios?", + ); + this.modalYesNo.init(); + + this.#initEditor(); this.#initTable(); - this.#initEditor(); // Editar en linea la fila this.tablePlantilla.table.on('click', 'tbody span.edit', function (e) { @@ -58,6 +61,37 @@ class PlantillasTarifasClienteForm { } ); }); + + this.tablePlantilla.table.on('click', '.btn-delete-' + this.tablePlantilla.getAlias(), function (e) { + + self.tablePlantilla.table.settings()[0].oFeatures.bServerSide = false; + + const row = $(this).attr('data-id'); + self.btnApply.removeClass('d-none'); + self.btnUndo.removeClass('d-none'); + + $('#' + row).css('background-color', '#ffcccc'); + $('#' + row).addClass('row-deleted'); + + // find closest span.edit + $('#' + row).find('span.edit').addClass('d-none'); + $('#' + row).find('.btn-delete-' + self.tablePlantilla.getAlias()).addClass('d-none'); + }); + + this.btnApply.on('click', function (e) { + self.modalYesNo.show(self.#applyChanges.bind(self)); + }); + + this.btnUndo.on('click', function (e) { + + self.tablePlantilla.table.settings()[0].oFeatures.bServerSide = true; + + self.tablePlantilla.table.clearPipeline(); + self.tablePlantilla.table.draw(); + + self.btnApply.addClass('d-none'); + self.btnUndo.addClass('d-none'); + }); } @@ -86,7 +120,8 @@ class PlantillasTarifasClienteForm { const editorFields = [ { name: "id", - type: "readonly" + type: "readonly", + def: new Date().toISOString().slice(0, 19).replace('T', ' ') }, { name: "tipo", type: "select", @@ -107,7 +142,26 @@ class PlantillasTarifasClienteForm { name: "precio_hora" }, { name: "margen" - }, + }, { + name: "user_updated", + type: "hidden", + def: '' + }, { + name: "updated_at", + type: "hidden", + def: '' + }, { + name: "deleted_at", + type: "hidden", + }, { + name: "is_deleted", + type: "hidden", + }, { + name: "plantilla_id", + type: "hidden", + def: this.plantillaId + } + ]; this.localEditor = new TableEditor( $('#tableOfPlantillasPreciosLineas'), @@ -127,14 +181,42 @@ class PlantillasTarifasClienteForm { this.ajaxEditor.init(); + this.localEditor.editor.on('preCreate', function (e, d, type) { + + self.tablePlantilla.table.settings()[0].oFeatures.bServerSide = false; + + }); + + // add class and change background color of row in postCreate + this.localEditor.editor.on('postCreate', function (e, json, data) { + + const row = self.tablePlantilla.table.row('#' + json.data[0].id); + + let rowNode = row.node(); + + $(rowNode).addClass('row-created'); + $(rowNode).css('background-color', '#C9E2C7'); + + self.btnApply.removeClass('d-none'); + self.btnUndo.removeClass('d-none'); + }); + this.localEditor.editor.on('postEdit', function (e, json, data) { + self.tablePlantilla.table.settings()[0].oFeatures.bServerSide = false; + let row = self.tablePlantilla.table.row('#' + data.id); - + + let rowNode = row.node(); + + // Añadir una clase usando jQuery + if (!$(rowNode).hasClass('row-created')) { + $(rowNode).addClass('row-edited'); + $(rowNode).css('background-color', '#E9DEAC'); + } + if (row.length) { - - let rowData = row.data(); - + // Actualizar los datos de la fila self.tablePlantilla.table.row('#' + data.id).data({ id: data.id, @@ -144,56 +226,199 @@ class PlantillasTarifasClienteForm { tiempo_min: data.tiempo_min, tiempo_max: data.tiempo_max, precio_hora: data.precio_hora, - margen: "150", + margen: data.margen, user_updated_id: data.user_updated, user_updated: data.user_updated, updated_at: data.updated_at - }); + }); - // check if this id exists - if (!self.changedRows.includes(data.id)) - self.changedRows.push(data.id); + self.btnApply.removeClass('d-none'); + self.btnUndo.removeClass('d-none'); } }); - /* - this.editorTarifas.editor.on('preSubmit', function (e, d, type) { - if (type === 'create') { - d.data[0]['cliente_id'] = self.clienteId; - } + this.ajaxEditor.editor.on('preEdit', function (e, d, type) { + self.tablePlantilla.table.settings()[0].oFeatures.bServerSide = true; }); - - this.editorTarifas.editor.on('submitSuccess', function (e, json, data, action) { - - self.tablePlantilla.table.clearPipeline(); - self.tablePlantilla.table.draw(); + + this.ajaxEditor.editor.on('preCreate', function (e, d, type) { + self.tablePlantilla.table.settings()[0].oFeatures.bServerSide = true; }); - - - this.editorTarifas.editor.on('postEdit', function (e, json, data, action) { - self.#borrarPlantillaTarifa(self.clienteId); - self.selectorPlantilla.offChange(); - self.selectorPlantilla.setOption(0, 'Personalizado'); - self.selectorPlantilla.onChange(self.#changePlantilla.bind(this)); - }) - - this.editorTarifas.editor.on('postCreate', function (e, json, data, action) { - self.#borrarPlantillaTarifa(self.clienteId); - self.selectorPlantilla.offChange(); - self.selectorPlantilla.setOption(0, 'Personalizado'); - self.selectorPlantilla.onChange(self.#changePlantilla.bind(this)); - }) - - this.editorTarifas.editor.on('postCancel', function (e, json, data) { - // Restaurar botones de acción por fila - self.tablePlantilla.table.rows().nodes().each(function (node) { - $(node).find('span.edit').removeClass('d-none'); - $(node).find('span.cancel, span.submit').addClass('d-none'); - }); - });*/ } + #applyChanges() { + + const self = this; + + const deletedRows = self.tablePlantilla.table.rows('.row-deleted').data().toArray(); + const editedRows = self.tablePlantilla.table.rows('.row-edited').data().toArray(); + const createdRows = self.tablePlantilla.table.rows('.row-created').data().toArray(); + + if (editedRows.length != 0) { + let error = self.#checkInterval(editedRows); + if (error) { + if (error == 1) { + popErrorAlert('Hay filas EDITADAS con el tiempo mínimo mayor que el tiempo máximo'); + } + else if (error == 2) { + popErrorAlert('Hay filas EDITADAS con intervalos [Tiempo min., Tiempo max] solapados'); + } + return; + } + } + + if (createdRows.length != 0) { + let error = self.#checkInterval(editedRows); + if (error) { + if (error == 1) { + popErrorAlert('Hay filas CREADAS con el tiempo mínimo mayor que el tiempo máximo'); + } + else if (error == 2) { + popErrorAlert('Hay filas CREADAS con intervalos [Tiempo min., Tiempo max] solapados'); + } + return; + } + } + + if (deletedRows.length != 0) { + + let rowIds = deletedRows.map(row => '#' + row.id); + + // Iterar sobre cada fila y actualizar los campos necesarios + self.ajaxEditor.editor + .edit(rowIds, false) // Editar múltiples filas (acepta un array) + .multiSet({ + deleted_at: new Date().toISOString().slice(0, 19).replace('T', ' '), + is_deleted: 1 + }) // Establecer valores comunes para todas las filas + .submit(); + } + + + + if (editedRows.length != 0) { + + let rowIds = editedRows.map(row => '#' + row.id); + let updatedFields = {}; + + // Iterar sobre las filas editadas y construir el objeto actualizado + editedRows.forEach(row => { + + updatedFields['tipo'] = updatedFields['tipo'] || {}; + updatedFields['tipo'][row.id] = row.tipo; + + updatedFields['tipo_maquina'] = updatedFields['tipo_maquina'] || {}; + updatedFields['tipo_maquina'][row.id] = row.tipo_maquina; + + updatedFields['tipo_impresion'] = updatedFields['tipo_impresion'] || {}; + updatedFields['tipo_impresion'][row.id] = row.tipo_impresion; + + updatedFields['tiempo_min'] = updatedFields['tiempo_min'] || {}; + updatedFields['tiempo_min'][row.id] = row.tiempo_min; + + updatedFields['tiempo_max'] = updatedFields['tiempo_max'] || {}; + updatedFields['tiempo_max'][row.id] = row.tiempo_max; + + updatedFields['precio_hora'] = updatedFields['precio_hora'] || {}; + updatedFields['precio_hora'][row.id] = row.precio_hora; + + updatedFields['margen'] = updatedFields['margen'] || {}; + updatedFields['margen'][row.id] = row.margen; + }); + + self.ajaxEditor.editor.edit(rowIds, false).multiSet(updatedFields) + .submit() + } + + + if (createdRows.length != 0) { + + let updatedFields = {}; + + let count = 0; + // Iterar sobre las filas editadas y construir el objeto actualizado + createdRows.forEach(row => { + + updatedFields['id'] = updatedFields['id'] || {}; + updatedFields['id'][row.id] = count; + + updatedFields['tipo'] = updatedFields['tipo'] || {}; + updatedFields['tipo'][count] = row.tipo; + + updatedFields['tipo_maquina'] = updatedFields['tipo_maquina'] || {}; + updatedFields['tipo_maquina'][count] = row.tipo_maquina; + + updatedFields['tipo_impresion'] = updatedFields['tipo_impresion'] || {}; + updatedFields['tipo_impresion'][count] = row.tipo_impresion; + + updatedFields['tiempo_min'] = updatedFields['tiempo_min'] || {}; + updatedFields['tiempo_min'][count] = row.tiempo_min; + + updatedFields['tiempo_max'] = updatedFields['tiempo_max'] || {}; + updatedFields['tiempo_max'][count] = row.tiempo_max; + + updatedFields['precio_hora'] = updatedFields['precio_hora'] || {}; + updatedFields['precio_hora'][count] = row.precio_hora; + + updatedFields['margen'] = updatedFields['margen'] || {}; + updatedFields['margen'][count] = row.margen; + + updatedFields['plantilla_id'] = updatedFields['plantilla_id'] || {}; + updatedFields['plantilla_id'][count] = self.plantillaId; + + count++; + }); + + self.ajaxEditor.editor.create(createdRows.length, false).multiSet(updatedFields) + .submit() + } + + if (deletedRows.length != 0 || editedRows.length != 0 || createdRows.length != 0) { + + new Ajax( + '/clienteprecios/update', + { + [self.csrf_token]: self.csrf_hash, + plantilla_id: self.plantillaId + }, + {}, + () => { + window.location.reload(); + }, + (error) => { + console.log(error); + } + ).post(); + + } + + + } + + #checkInterval(rows) { + + // obtener todas las filas de la tabla que no tengan la clase row-deleted + let rowsNotDeletedDT = this.tablePlantilla.table.rows(':not(.row-deleted)').nodes().toArray(); + for (let row of rowsNotDeletedDT) { + let rowData = this.tablePlantilla.table.row(row).data(); + for (let rowEdited of rows) { + if (rowEdited.tiempo_min > rowEdited.tiempo_max) { + + return 1; + } + if (rowData.tipo == rowEdited.tipo && rowData.tipo_maquina == rowEdited.tipo_maquina && rowData.tipo_impresion == rowEdited.tipo_impresion) { + // check overlapping intervals + if (rowEdited.tiempo_min >= rowData.tiempo_min || rowEdited.tiempo_min <= rowData.tiempo_max) { + return 2; + } + } + } + } + return 0; + + } + #initTable() { const self = this; @@ -252,7 +477,7 @@ class PlantillasTarifasClienteForm { columns, [ { name: 'plantilla_id', value: this.plantillaId } - ],'id' + ], 'id' ); @@ -260,6 +485,8 @@ class PlantillasTarifasClienteForm { actions: actions, colVisibility: false, buttonsExport: true, + buttonNewWithEditor: true, + editor: self.localEditor.editor, });