Merge branch 'main' into 'mod/presupuesto_admin'

Main

See merge request jjimenez/safekat!461
This commit is contained in:
2025-01-03 15:47:04 +00:00
7 changed files with 463 additions and 272 deletions

View File

@ -9,18 +9,18 @@ const SK_PERMISSION_MATRIX = [
"plantilla-tarifa.edit",
"plantilla-tarifa.delete",
"plantilla-tarifa.menu",
"perfil.create",
"perfil.edit",
"perfil.delete",
"perfil.menu",
"presupuesto.create",
"presupuesto.edit",
"presupuesto.delete",
"presupuesto.menu",
"pedidos-activos.view",
"pedidos-activos.menu",
"pedidos-finalizados.view",
"pedidos-finalizados.menu",
"pedidos-cancelados.view",
"pedidos-cancelados.menu",
"pedidos-todos.view",
"pedidos-todos.menu",
"presupuesto-cliente.create",
"presupuesto-cliente.edit",
"presupuesto-cliente.delete",
"presupuesto-cliente.menu",
"tarifa-preimpresion.create",
"tarifa-preimpresion.edit",
"tarifa-preimpresion.delete",
@ -41,6 +41,10 @@ const SK_PERMISSION_MATRIX = [
"tarifa-envio.edit",
"tarifa-envio.delete",
"tarifa-envio.menu",
"tarifa-extra.create",
"tarifa-extra.edit",
"tarifa-extra.delete",
"tarifa-extra.menu",
"proveedores.create",
"proveedores.edit",
"proveedores.delete",
@ -57,6 +61,10 @@ const SK_PERMISSION_MATRIX = [
"paises.edit",
"paises.delete",
"paises.menu",
"formas-pago.create",
"formas-pago.edit",
"formas-pago.delete",
"formas-pago.menu",
"maquinas.create",
"maquinas.edit",
"maquinas.delete",
@ -81,12 +89,36 @@ const SK_PERMISSION_MATRIX = [
"roles-permisos.edit",
"roles-permisos.delete",
"roles-permisos.menu",
"ubicaciones.create",
"ubicaciones.edit",
"ubicaciones.delete",
"ubicaciones.menu",
"series-facturas.create",
"series-facturas.edit",
"series-facturas.delete",
"series-facturas.menu",
],
"cliente-admin" => [
"pedidos-activos.view",
"pedidos-activos.menu",
"perfil.edit",
"perfil.menu",
"direcciones.create",
"direcciones.edit",
"direcciones.delete",
"direcciones.menu",
"presupuesto-cliente.create",
"presupuesto-cliente.edit",
"presupuesto-cliente.delete",
"presupuesto-cliente.menu",
],
"cliente-editor" => [
"perfil.create",
"perfil.edit",
"perfil.delete",
"perfil.menu",
"direcciones.create",
"direcciones.edit",
"direcciones.delete",
"direcciones.menu",
"presupuesto-cliente.create",
"presupuesto-cliente.edit",
"presupuesto-cliente.delete",
@ -97,15 +129,8 @@ const SK_PERMISSION_MATRIX = [
"token.menu",
],
"produccion" => [
"clientes.create",
"clientes.edit",
"clientes.menu",
"direcciones.create",
"direcciones.edit",
"direcciones.menu",
"presupuesto.create",
"presupuesto.edit",
"presupuesto.menu",
"token.token",
"token.menu",
],
"maquina" => [
"token.token",
@ -138,18 +163,18 @@ const SK_PERMISSION_MATRIX = [
"plantilla-tarifa.edit",
"plantilla-tarifa.delete",
"plantilla-tarifa.menu",
"perfil.create",
"perfil.edit",
"perfil.delete",
"perfil.menu",
"presupuesto.create",
"presupuesto.edit",
"presupuesto.delete",
"presupuesto.menu",
"pedidos-activos.view",
"pedidos-activos.menu",
"pedidos-finalizados.view",
"pedidos-finalizados.menu",
"pedidos-cancelados.view",
"pedidos-cancelados.menu",
"pedidos-todos.view",
"pedidos-todos.menu",
"presupuesto-cliente.create",
"presupuesto-cliente.edit",
"presupuesto-cliente.delete",
"presupuesto-cliente.menu",
"tarifa-preimpresion.create",
"tarifa-preimpresion.edit",
"tarifa-preimpresion.delete",
@ -170,6 +195,10 @@ const SK_PERMISSION_MATRIX = [
"tarifa-envio.edit",
"tarifa-envio.delete",
"tarifa-envio.menu",
"tarifa-extra.create",
"tarifa-extra.edit",
"tarifa-extra.delete",
"tarifa-extra.menu",
"proveedores.create",
"proveedores.edit",
"proveedores.delete",
@ -210,5 +239,13 @@ const SK_PERMISSION_MATRIX = [
"roles-permisos.edit",
"roles-permisos.delete",
"roles-permisos.menu",
"ubicaciones.create",
"ubicaciones.edit",
"ubicaciones.delete",
"ubicaciones.menu",
"series-facturas.create",
"series-facturas.edit",
"series-facturas.delete",
"series-facturas.menu",
],
];

View File

@ -17,6 +17,10 @@ const SK_PERMISSIONS = [
'presupuesto.edit' => 'Can edit',
'presupuesto.delete' => 'Can delete',
'presupuesto.menu' => 'Menu shall be visualize',
'presupuesto-cliente.create' => 'Can create',
'presupuesto-cliente.edit' => 'Can edit',
'presupuesto-cliente.delete' => 'Can delete',
'presupuesto-cliente.menu' => 'Menu shall be visualize',
'pedidos-activos.view' => 'Can view',
'pedidos-activos.menu' => 'Menu shall be visualize',
'pedidos-finalizados.view' => 'Can view',

View File

@ -26,12 +26,13 @@ class Test extends BaseController
public function index()
{
/*
$model = model("\App\Models\Pedidos\PedidoLineaModel");
$data = $model->obtenerLineasPedidoSinFacturar(999);
*/
$model = model("\App\Models\Clientes\ClientePreciosModel");
$model->debug_all_clientes_to_defecto();
echo '<pre>';
echo 'OK';
echo '</pre>';
xdebug_info();
//xdebug_info();

View File

@ -25,21 +25,22 @@ class ClientePreciosModel extends \App\Models\BaseModel
];
protected $allowedFields = [
"cliente_id",
"cliente_id",
"plantilla_id",
"tipo",
"tipo_maquina",
"tipo_impresion",
"tiempo_min",
"tiempo_max",
"precio_hora",
"margen",
"is_deleted",
"deleted_at",
"created_at",
"tipo",
"tipo_maquina",
"tipo_impresion",
"tiempo_min",
"tiempo_max",
"precio_hora",
"margen",
"is_deleted",
"deleted_at",
"created_at",
"updated_at",
"user_created_id",
"user_updated_id"];
"user_updated_id"
];
protected $returnType = "App\Entities\Clientes\ClientePreciosEntity";
@ -82,14 +83,14 @@ class ClientePreciosModel extends \App\Models\BaseModel
"rules" => "required|decimal",
],
];
protected $validationMessages = [
"cliente_id" => [
"required" => "ClientePrecios.validation.required",
],
"tipo" => [
"required" => "ClientePrecios.validation.required",
@ -111,7 +112,8 @@ class ClientePreciosModel extends \App\Models\BaseModel
],
];
function clean_plantilla_id($cliente_id = 0){
function clean_plantilla_id($cliente_id = 0)
{
$this->db
->table($this->table . " t1")
->where('cliente_id', $cliente_id)
@ -119,7 +121,8 @@ class ClientePreciosModel extends \App\Models\BaseModel
->update();
}
function set_plantilla_id($cliente_id = 0, $plantilla_id = null){
function set_plantilla_id($cliente_id = 0, $plantilla_id = null)
{
$this->db
->table($this->table . " t1")
->where('cliente_id', $cliente_id)
@ -127,8 +130,9 @@ class ClientePreciosModel extends \App\Models\BaseModel
->update();
}
function delete_values($cliente_id = 0){
function delete_values($cliente_id = 0)
{
$session = session();
$datetime = (new \CodeIgniter\I18n\Time("now"));
$date_value = $datetime->format('Y-m-d H:i:s');
@ -141,19 +145,76 @@ class ClientePreciosModel extends \App\Models\BaseModel
->set('user_updated_id', $session->id_user)
->update();
}
function copy_from_plantilla($cliente_id = 0, $plantilla_id = 0){
function debug_all_clientes_to_defecto()
{
$plantilla_id = 5; // por defecto
// Se borran los valores existentes para todos los clientes en una sola consulta
$modelCliente = model('App\Models\Clientes\ClienteModel');
$clientes = $modelCliente->select('id')->where('is_deleted', 0)->findAll();
// Se borra la tabla
$this->db->table($this->table)->truncate();
// Preparar los datos para `insertBatch`
$data = [];
$date_value = date('Y-m-d H:i:s'); // Asume que $date_value es la fecha actual
$userId = auth()->user()->id; // ID del usuario actual
$plantillaModel = model('App\Models\Clientes\ClientePlantillaPreciosLineasModel');
$values = $plantillaModel->getResource([], $plantilla_id)->get()->getResultObject();
$batchSize = 1000;
$data = [];
foreach ($clientes as $index => $cliente) {
foreach ($values as $value) {
$data[] = [
'cliente_id' => $cliente->id,
'plantilla_id' => $plantilla_id,
'tipo' => $value->tipo,
'tipo_maquina' => $value->tipo_maquina,
'tipo_impresion' => $value->tipo_impresion,
'tiempo_min' => $value->tiempo_min,
'tiempo_max' => $value->tiempo_max,
'precio_hora' => $value->precio_hora,
'margen' => $value->margen,
'user_updated_id' => $value->user_updated_id,
'updated_at' => $value->updated_at,
'user_created_id' => $userId,
'created_at' => $date_value,
];
if (count($data) === $batchSize) {
$this->db->table($this->table)->insertBatch($data);
$data = [];
}
}
}
// Insertar los datos restantes
if (!empty($data)) {
$this->db->table($this->table)->insertBatch($data);
}
}
function copy_from_plantilla($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 borran los valores existentes
$this->delete_values($cliente_id);
// 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")
@ -176,9 +237,10 @@ class ClientePreciosModel extends \App\Models\BaseModel
}
function update_from_plantilla($plantilla_id = 0){
function update_from_plantilla($plantilla_id = 0)
{
$datetime = (new \CodeIgniter\I18n\Time("now"));
/*$datetime = (new \CodeIgniter\I18n\Time("now"));
$date_value = $datetime->format('Y-m-d H:i:s');
// Se obtienen todos los id de clientes que usen esa tarifa
@ -217,8 +279,65 @@ class ClientePreciosModel extends \App\Models\BaseModel
->set('updated_at', $value->updated_at)
->set('user_created_id', auth()->user()->id)
->set('created_at', $date_value)
->insert();
->insertBatch($values);
}
}*/
// Se borran los valores existentes para todos los clientes en una sola consulta
$clientes = $this->db
->table($this->table . " t1")
->select("t1.cliente_id AS id")
->where('t1.plantilla_id', $plantilla_id)
->where('t1.is_deleted', 0)
->distinct()
->get()->getResultArray();
// Extraer solo los IDs de los clientes
$clienteIds = array_map(fn($cliente) => $cliente['id'], $clientes);
// Borrar los valores existentes para esos clientes en una sola consulta
if (!empty($clienteIds)) {
$this->db->table($this->table)->whereIn('cliente_id', $clienteIds)->delete();
}
// Preparar los datos para `insertBatch`
$data = [];
$date_value = date('Y-m-d H:i:s'); // Asume que $date_value es la fecha actual
$userId = auth()->user()->id; // ID del usuario actual
$plantillaModel = model('App\Models\Clientes\ClientePlantillaPreciosLineasModel');
$values = $plantillaModel->getResource([], $plantilla_id)->get()->getResultObject();
$batchSize = 1000;
$data = [];
foreach ($clientes as $cliente) {
foreach ($values as $value) {
$data[] = [
'cliente_id' => $cliente['id'],
'plantilla_id' => $plantilla_id,
'tipo' => $value->tipo,
'tipo_maquina' => $value->tipo_maquina,
'tipo_impresion' => $value->tipo_impresion,
'tiempo_min' => $value->tiempo_min,
'tiempo_max' => $value->tiempo_max,
'precio_hora' => $value->precio_hora,
'margen' => $value->margen,
'user_updated_id' => $value->user_updated_id,
'updated_at' => $value->updated_at,
'user_created_id' => $userId,
'created_at' => $date_value,
];
if (count($data) === $batchSize) {
$this->db->table($this->table)->insertBatch($data);
$data = [];
}
}
}
// Insertar todos los datos de una vez
if (!empty($data)) {
$this->db->table($this->table)->insertBatch($data);
}
}
@ -227,8 +346,9 @@ class ClientePreciosModel extends \App\Models\BaseModel
// - tipo_maquina: 'toner', 'inkjet'
// - tipo_impresion: 'negro', 'color', 'negrohq', 'colorhq'
function get_precio_hora($cliente_id, $config, $tiempo){
function get_precio_hora($cliente_id, $config, $tiempo)
{
// Se cargan los valores de la plantilla
$values = $this->db
->table($this->table . " t1")
@ -241,14 +361,14 @@ class ClientePreciosModel extends \App\Models\BaseModel
->where('tiempo_max >=', $tiempo)
->where('is_deleted', 0)
->get()->getResultObject();
if(count($values)>0){
if (count($values) > 0) {
return [floatval(($values[0])->precio_hora), floatval(($values[0])->margen)];
}
return [null, null];
}
/**
* Get resource data.
*
@ -268,7 +388,7 @@ class ClientePreciosModel extends \App\Models\BaseModel
);
$builder->join("users t2", "t1.user_updated_id = t2.id", "left");
$builder->where('t1.is_deleted', 0);
$builder->where('t1.cliente_id', $cliente_id);
@ -277,30 +397,31 @@ class ClientePreciosModel extends \App\Models\BaseModel
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]);
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 getPlantilla($cliente_id = -1){
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){
if (count($values) > 0) {
return $values[0];
}
@ -309,11 +430,12 @@ class ClientePreciosModel extends \App\Models\BaseModel
public function checkIntervals($data = [], $id_linea = null, $cliente_id = null){
public function checkIntervals($data = [], $id_linea = null, $cliente_id = null)
{
helper('general');
if(floatval($data["tiempo_min"])>= floatval($data["tiempo_max"])){
if (floatval($data["tiempo_min"]) >= floatval($data["tiempo_max"])) {
return lang('ClientePrecios.errors.error_tiempo_range');
}
@ -329,29 +451,36 @@ class ClientePreciosModel extends \App\Models\BaseModel
foreach ($rows as $row) {
if (!is_null($id_linea)){
if($row->id == $id_linea){
if (!is_null($id_linea)) {
if ($row->id == $id_linea) {
continue;
}
}
if(check_overlap(floatval($data["tiempo_min"]), floatval($data["tiempo_max"]),
$row->tiempo_min, $row->tiempo_max)){
return lang('ClientePrecios.errors.error_tiempo_overlap');
if (
check_overlap(
floatval($data["tiempo_min"]),
floatval($data["tiempo_max"]),
$row->tiempo_min,
$row->tiempo_max
)
) {
return lang('ClientePrecios.errors.error_tiempo_overlap');
}
}
return "";
}
public function get_plantilla_precios($cliente_id = -1){
public function get_plantilla_precios($cliente_id = -1)
{
$value = $this->db
->table($this->table)
->select("plantilla_id")
->where("is_deleted", 0)
->where("cliente_id", $cliente_id)
->limit(1)->get()->getResultObject();
if(count($value)>0){
if (count($value) > 0) {
return $value[0]->plantilla_id;
}
return null;

View File

@ -10,9 +10,13 @@
<div class="card-header">
<h3 class="card-title"><?= $boxTitle ?? $pageTitle ?></h3>
</div><!--//.card-header -->
<form id="clientePlantillaPreciosForm" method="post" class="card-body" action="<?= $formAction ?>">
<?= csrf_field() ?>
<?= view("themes/_commonPartialsBs/_alertBoxes") ?>
<?= view("themes/vuexy/form/presupuestos/cliente/loader") ?>
<?= !empty($validation->getErrors()) ? $validation->listErrors("bootstrap_style") : "" ?>
<?= view("themes/vuexy/form/clientes/plantillaprecios/_ClienteplantillapreciosFormItems") ?>
<div class="pt-4">
@ -84,6 +88,7 @@
href="<?= site_url('themes/vuexy/css/datatables-editor/editor.dataTables.min.css') ?>">
<link rel="stylesheet"
href="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/buttons/buttons.bootstrap5.min.css") ?>">
<link rel="stylesheet" href="<?= site_url('themes/vuexy/css/presupuestoCliente.css') ?>">
<?= $this->endSection() ?>
<?= $this->section('additionalExternalJs') ?>

View File

@ -45,9 +45,7 @@ class ModalYesNo {
$('#' + this.btnConfirmId).on('click', () => {
self.callback(); // Llamar al callback que el usuario haya proporcionado
$('#' + self.modalId).modal('hide');
self.callback(); // Llamar al callback que el usuario haya proporcionado
});
}

View File

@ -242,8 +242,8 @@ class PlantillasTarifasClienteForm {
const row = self.tablePlantilla.table.row('#' + json.data[0].id);
if (row.length) {
self.rowsCreated.push(row);
if (json.data[0]) {
self.rowsCreated.push(json.data[0]);
}
let rowNode = row.node();
@ -263,9 +263,6 @@ class PlantillasTarifasClienteForm {
let rowNode = row.node();
// Añadir una clase usando jQuery
if (!$(rowNode).hasClass('row-created')) {
$(rowNode).addClass('row-edited');
@ -298,8 +295,14 @@ class PlantillasTarifasClienteForm {
if (index != -1) {
self.rows[index] = data;
}
if (self.rowsEdited.indexOf(row.id) == -1)
self.rowsEdited.push(row.id);
if (self.rowsEdited.some(row => row.id === data.id)) {
const index = self.rowsEdited.findIndex(row => row.id === data.id);
self.rowsEdited[index] = data;
} else {
self.rowsEdited.push(data);
}
}
});
@ -317,165 +320,179 @@ class PlantillasTarifasClienteForm {
const self = this;
if (this.rowsEdited.length != 0) {
let error = self.#checkInterval(self.rowsEdited);
if (error) {
if (error == 1) {
popErrorAlert('Hay filas EDITADAS con el tiempo mínimo mayor que el tiempo máximo');
try {
self.modalYesNo.hide();
$('#loader').modal('show');
if (this.rowsEdited.length != 0) {
let error = self.#checkInterval(self.rowsEdited);
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;
}
else if (error == 2) {
popErrorAlert('Hay filas EDITADAS con intervalos [Tiempo min., Tiempo max] solapados');
}
return;
}
}
if (this.rowsCreated.length != 0) {
let error = self.#checkInterval(self.rowsCreated.map(row => row.data()));
if (error) {
if (error == 1) {
popErrorAlert('Hay filas CREADAS con el tiempo mínimo mayor que el tiempo máximo');
if (this.rowsCreated.length != 0) {
let error = self.#checkInterval(self.rowsCreated);
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;
}
else if (error == 2) {
popErrorAlert('Hay filas CREADAS con intervalos [Tiempo min., Tiempo max] solapados');
}
if (this.rowsDeleted.length != 0) {
let rowIds = self.rowsDeleted.map(row => '#' + row);
// 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 (this.rowsEdited.length != 0) {
let rowIds = this.rowsEdited.map(row => '#' + row.id);
let updatedFields = {};
// Iterar sobre las filas editadas y construir el objeto actualizado
this.rowsEdited.forEach(row2Edit => {
const row = this.tablePlantilla.table.row('#' + row2Edit.id).data();
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 (this.rowsCreated.length != 0) {
let updatedFields = {};
let count = 0;
// Iterar sobre las filas editadas y construir el objeto actualizado
this.rowsCreated.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(self.rowsCreated.length, false).multiSet(updatedFields)
.submit()
}
new Ajax(
'/clienteprecios/update',
{
[self.csrf_token]: self.csrf_hash,
plantilla_id: self.plantillaId
},
{},
() => {
self.tablePlantilla.table.settings()[0].oFeatures.bServerSide = true;
new Ajax(
'/clienteplantillaprecioslineas/getrows',
{
[self.csrf_token]: self.csrf_hash,
plantilla_id: self.plantillaId
},
{},
(response) => {
self.rows = response.data;
self.rowsDeleted = [];
self.rowsEdited = [];
self.rowsCreated = [];
self.tablePlantilla.table.clearPipeline();
self.tablePlantilla.table.draw(true);
$('#loader').modal('hide');
},
(error) => {
console.log(error);
$('#loader').modal('hide');
}).post();
},
(error) => {
console.log(error);
$('#loader').modal('hide');
}
return;
}
).post();
} catch (e) {
console.log(e);
$('#loader').modal('hide');
}
if (this.rowsDeleted.length != 0) {
let rowIds = self.rowsDeleted.map(row => '#' + row);
// 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 (this.rowsEdited.length != 0) {
let rowIds = this.rowsEdited.map(row => '#' + this.tablePlantilla.table.row(row).data().id);
let updatedFields = {};
// Iterar sobre las filas editadas y construir el objeto actualizado
this.rowsEdited.forEach(row2Edit => {
const row = this.tablePlantilla.table.row(row2Edit).data();
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 (this.rowsCreated.length != 0) {
let updatedFields = {};
let count = 0;
// Iterar sobre las filas editadas y construir el objeto actualizado
this.rowsCreated.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(self.rowsCreated.length, false).multiSet(updatedFields)
.submit()
}
new Ajax(
'/clienteprecios/update',
{
[self.csrf_token]: self.csrf_hash,
plantilla_id: self.plantillaId
},
{},
() => {
self.tablePlantilla.table.settings()[0].oFeatures.bServerSide = true;
new Ajax(
'/clienteplantillaprecioslineas/getrows',
{
[self.csrf_token]: self.csrf_hash,
plantilla_id: self.plantillaId
},
{},
(response) => {
self.rows = response.data;
self.rowsDeleted = [];
self.rowsEdited = [];
self.rowsCreated = [];
self.tablePlantilla.table.clearPipeline();
self.tablePlantilla.table.draw(true);
},
(error) => {
console.log(error);
}).post();
},
(error) => {
console.log(error);
}
).post();
}
@ -693,35 +710,35 @@ class PlantillasTarifasClienteForm {
selector.on('change', function () {
if (!self.tablePlantilla.table.settings()[0].oFeatures.bServerSide) {
if (!self.tablePlantilla.table.settings()[0].oFeatures.bServerSide) {
var val = $(this).val(); // El valor seleccionado
var searchVal = "";
var val = $(this).val(); // El valor seleccionado
var searchVal = "";
// Determinar el texto renderizado que debe buscarse
if (val === "negro") {
searchVal = window.language.ClientePrecios.negro;
} else if (val === "negrohq") {
searchVal = window.language.ClientePrecios.negrohq;
} else if (val === "color") {
searchVal = window.language.ClientePrecios.color;
} else if (val === "colorhq") {
searchVal = window.language.ClientePrecios.colorhq;
}
const allRows = [...self.rows, ...self.rowsCreated.map(row => row.data())];
// Actualizar los datos de la tabla
self.tablePlantilla.table.clear().rows.add(allRows).draw();
self.tablePlantilla.table.column(i).search(searchVal ? '^' + searchVal + '$' : '', true, false).draw();
}
else {
// Aplicar el filtro sobre los valores renderizados
var val = $.fn.dataTable.util.escapeRegex(
$(this).val()
);
self.tablePlantilla.table.column(i).search(val).draw();
// Determinar el texto renderizado que debe buscarse
if (val === "negro") {
searchVal = window.language.ClientePrecios.negro;
} else if (val === "negrohq") {
searchVal = window.language.ClientePrecios.negrohq;
} else if (val === "color") {
searchVal = window.language.ClientePrecios.color;
} else if (val === "colorhq") {
searchVal = window.language.ClientePrecios.colorhq;
}
const allRows = [...self.rows, ...self.rowsCreated.map(row => row.data())];
// Actualizar los datos de la tabla
self.tablePlantilla.table.clear().rows.add(allRows).draw();
self.tablePlantilla.table.column(i).search(searchVal ? '^' + searchVal + '$' : '', true, false).draw();
}
else {
// Aplicar el filtro sobre los valores renderizados
var val = $.fn.dataTable.util.escapeRegex(
$(this).val()
);
self.tablePlantilla.table.column(i).search(val).draw();
}
});
}