Merge branch 'dev/plantillas_clientes3' into 'main'

Dev/plantillas clientes3

See merge request jjimenez/safekat!103
This commit is contained in:
2024-01-02 20:02:26 +00:00
14 changed files with 1057 additions and 24 deletions

View File

@ -352,6 +352,12 @@ $routes->group('cliente', ['namespace' => 'App\Controllers\Clientes'], function
});
$routes->resource('cliente', ['namespace' => 'App\Controllers\Clientes', 'controller' => 'Cliente', 'except' => 'show,new,create,update']);
$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->resource('clienteprecios', ['namespace' => 'App\Controllers\Clientes', 'controller' => 'Clienteprecios', 'except' => 'show,new,create,update']);
$routes->group('clienteplantillaprecios', ['namespace' => 'App\Controllers\Clientes'], function ($routes) {
$routes->get('', 'Clienteplantillaprecios::index', ['as' => 'clienteplantillapreciosList']);
@ -360,6 +366,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->resource('clienteplantillaprecios', ['namespace' => 'App\Controllers\Clientes', 'controller' => 'Clienteplantillaprecios', 'except' => 'show,new,create,update']);

View File

@ -231,6 +231,7 @@ class Cliente extends \App\Controllers\GoBaseResourceController
//var_dump($clienteEntity); dd();
$this->viewData['clienteEntity'] = $clienteEntity;
$this->viewData['precioTemplate'] = $this->getPrecioTemplate($id);
$this->viewData['comunidadAutonomaList'] = $this->getComunidadAutonomaListItems($clienteEntity->comunidad_autonoma_id ?? null);
$this->viewData['provinciaList'] = $this->getProvinciaListItems($clienteEntity->provincia_id ?? null);
$this->viewData['paisList'] = $this->getPaisListItems($clienteEntity->pais_id ?? null);
@ -438,4 +439,25 @@ class Cliente extends \App\Controllers\GoBaseResourceController
return $data;
}
protected function getPrecioTemplate($cliente_id){
$modelPreciosCliente = model('App\Models\Clientes\ClientePreciosModel');
$plantilla_id = $modelPreciosCliente->get_plantilla_precios($cliente_id);
if (is_null($plantilla_id)){
return null;
}
$modelPlantillaPreciosCliente = model('App\Models\Clientes\ClientePlantillaPreciosModel');
$plantilla = $modelPlantillaPreciosCliente->where("id", $plantilla_id)->where("is_deleted", 0)->first();
if ($plantilla == false){
return null;
}
else{
return (object)array(
"value" => $plantilla_id,
"label" => $plantilla->nombre
);
}
}
}

View File

@ -66,6 +66,32 @@ class Clienteplantillaprecios extends \App\Controllers\GoBaseResourceController
}
// Este metodo aqui se usa para poner el is_deleted a 1 cuando se borra una
// plantilla desde la lista
public function update($requestedId = null)
{
$requestMethod = $this->request->getMethod();
if ($requestMethod === 'post') :
if ($requestedId == null) :
return;
endif;
$model = model('App\Models\Clientes\ClientePlantillaPreciosLineasModel');
$model->delete_values($requestedId);
$newTokenHash = csrf_hash();
$csrfTokenName = csrf_token();
$data = [
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
endif; // ($requestMethod === 'post')
}
public function add()
{
// JJO
@ -79,6 +105,8 @@ class Clienteplantillaprecios extends \App\Controllers\GoBaseResourceController
$postData = $this->request->getPost();
$cliente_id = $postData['cliente_id'] ?? -1;
$sanitizedData = $this->sanitized($postData, $nullIfEmpty);
// JJO
@ -108,16 +136,25 @@ class Clienteplantillaprecios extends \App\Controllers\GoBaseResourceController
$message = lang('Basic.global.saveSuccess', [lang('Basic.global.record')]) . '.';
if ($thenRedirect) :
if (!empty($this->indexRoute)) :
//return redirect()->to(route_to($this->indexRoute))->with('sweet-success', $message);
return redirect()->to(site_url('/clientes/clientesplantillaprecios/edit/' . $id))->with('message', $message);
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 redirect()->to(route_to($this->indexRoute))->with('sweet-success', $message);
return redirect()->to(site_url('/clientes/clienteplantillaprecios/edit/' . $id))->with('message', $message);
else:
return $this->redirect2listView('sweet-success', $message);
endif;
else:
return $this->redirect2listView('sweet-success', $message);
$this->session->setFlashData('sweet-success', $message);
endif;
else:
$this->session->setFlashData('sweet-success', $message);
endif;
}
endif; // $noException && $successfulResult
@ -240,6 +277,36 @@ class Clienteplantillaprecios extends \App\Controllers\GoBaseResourceController
}
}
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 = [];
}
$newTokenHash = csrf_hash();
$csrfTokenName = csrf_token();
$data = [
'menu' => $menu,
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
}

View File

@ -47,6 +47,39 @@ class Clienteplantillaprecioslineas extends \App\Controllers\GoBaseResourceContr
}
public function update($requestedId = null){
$requestMethod = $this->request->getMethod();
if ($requestMethod === 'post') :
if ($requestedId == null) :
return;
endif;
$postData = $this->request->getJSON();
$plantilla_id = $postData->plantilla_id ?? -1;
// Se ha actualizado un registro por lo que no es una plantilla
if($plantilla_id == -1){
$this->model->clean_plantilla_id($requestedId);
}
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')
}
public function datatable()

View File

@ -0,0 +1,230 @@
<?php namespace App\Controllers\Clientes;
use App\Controllers\GoBaseResourceController;
use App\Models\Collection;
use App\Entities\Clientes\ClientePreciosEntity;
use App\Models\Clientes\ClientePreciosModel;
use DataTables\Editor;
use DataTables\Editor\Field;
use DataTables\Editor\Validate;
class ClientePrecios extends \App\Controllers\GoBaseResourceController
{
protected $modelName = ClientePreciosModel::class;
protected $format = 'json';
protected static $singularObjectName = 'Cliente precios';
protected static $singularObjectNameCc = 'ClientePrecios';
protected static $pluralObjectName = 'Clientes precios';
protected static $pluralObjectNameCc = 'clientesprecios';
protected static $controllerSlug = 'ClientePrecios';
protected static $viewPath = 'themes/backend/vuexy/form/clientes/cliente';
protected $indexRoute = 'clientepreciosList';
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
$this->viewData['pageTitle'] = lang('ClientesPrecios.plantillaPrecios_module');
$this->viewData['usingSweetAlert'] = true;
// Se indica que este controlador trabaja con soft_delete
$this->soft_delete = true;
// Se indica el flag para los ficheros borrados
$this->delete_flag = 1;
$this->viewData = ['usingServerSideDataTable' => true]; // JJO
parent::initController($request, $response, $logger);
}
public function update($requestedId = null)
{
$requestMethod = $this->request->getMethod();
if ($requestMethod === 'post') :
if ($requestedId == null) :
return;
endif;
$postData = $this->request->getJSON();
$plantilla_id = $postData->plantilla_id ?? -1;
// Se ha actualizado un registro por lo que no es una plantilla
if($plantilla_id == -1){
$this->model->clean_plantilla_id($requestedId);
}
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')
}
public function datatable()
{
if ($this->request->isAJAX()) {
$reqData = $this->request->getPost();
if (!isset($reqData['draw']) || !isset($reqData['columns'])) {
$errstr = 'No data available in response to this specific request.';
$response = $this->respond(Collection::datatable([], 0, 0, $errstr), 400, $errstr);
return $response;
}
$start = $reqData['start'] ?? 0;
$length = $reqData['length'] ?? 5;
$requestedOrder = $reqData['order']['0']['column'] ?? 0;
$requestedOrder2 = $reqData['order']['1']['column'] ?? $requestedOrder;
$requestedOrder3 = $reqData['order']['2']['column'] ?? $requestedOrder;
$requestedOrder4 = $reqData['order']['3']['column'] ?? $requestedOrder;
$requestedOrder5 = $reqData['order']['4']['column'] ?? $requestedOrder;
$order = ClientePreciosModel::SORTABLE[$requestedOrder > 0 ? $requestedOrder : 0];
$order2 = ClientePreciosModel::SORTABLE[$requestedOrder2 >= 0 ? $requestedOrder2 : $requestedOrder];
$order3 = ClientePreciosModel::SORTABLE[$requestedOrder3 >= 0 ? $requestedOrder3 : $requestedOrder];
$order4 = ClientePreciosModel::SORTABLE[$requestedOrder4 >= 0 ? $requestedOrder4 : $requestedOrder];
$order5 = ClientePreciosModel::SORTABLE[$requestedOrder4 >= 0 ? $requestedOrder5 : $requestedOrder];
$dir = $reqData['order']['0']['dir'] ?? 'asc';
$dir2 = $reqData['order']['1']['dir'] ?? $dir;
$dir3 = $reqData['order']['2']['dir'] ?? $dir;
$dir4= $reqData['order']['3']['dir'] ?? $dir;
$dir5= $reqData['order']['4']['dir'] ?? $dir;
$cliente_id = $reqData['cliente_id'] ?? 0;
$resourceData = $this->model->getResource($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()
));
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
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' )
->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' )
->validator( 'Validate::notEmpty',array(
'message' => lang('ClientePrecios.validation.required'))
)
->validator('Validate::numeric', array(
'message' => lang('ClientePrecios.validation.decimal'))
),
Field::inst( 'tiempo_max' )
->validator( 'Validate::notEmpty',array(
'message' => lang('ClientePrecios.validation.required'))
)
->validator('Validate::numeric', array(
'message' => lang('ClientePrecios.validation.decimal'))
),
Field::inst( 'precio_hora' )
->validator( 'Validate::notEmpty',array(
'message' => lang('ClientePrecios.validation.required'))
)
->validator('Validate::numeric', array(
'message' => lang('ClientePrecios.validation.decimal'))
),
Field::inst( 'margen' )
->validator( 'Validate::notEmpty',array(
'message' => lang('ClientePrecios.validation.required'))
)
->validator('Validate::numeric', array(
'message' => lang('ClientePrecios.validation.decimal'))
),
)
->validator(function ($editor, $action, $data) {
if ($action === Editor::ACTION_CREATE || $action === Editor::ACTION_EDIT) {
foreach ($data['data'] as $pkey => $values) {
// Si no se quiere borrar...
if ($data['data'][$pkey]['is_deleted'] != 1) {
$process_data['tiempo_min'] = $data['data'][$pkey]['tiempo_min'];
$process_data['tiempo_max'] = $data['data'][$pkey]['tiempo_max'];
$process_data['tipo'] = $data['data'][$pkey]['tipo'];
$process_data['tipo_maquina'] = $data['data'][$pkey]['tipo_maquina'];
$process_data['tipo_impresion'] = $data['data'][$pkey]['tipo_impresion'];
$response = $this->model->checkIntervals($process_data, $pkey, $data['data'][$pkey]['cliente_id']);
// No se pueden duplicar valores al crear o al editar
if (!empty($response)) {
return $response;
}
}
}
}
})
->on('preCreate', function ($editor, &$values) {
$session = session();
$datetime = (new \CodeIgniter\I18n\Time("now"));
$editor
->field('user_updated_id')
->setValue($session->id_user);
$editor
->field('updated_at')
->setValue($datetime->format('Y-m-d H:i:s'));
})
->on('preEdit', function ($editor, &$values) {
$session = session();
$datetime = (new \CodeIgniter\I18n\Time("now"));
$editor
->field('user_updated_id')
->setValue($session->id_user);
$editor
->field('updated_at')
->setValue($datetime->format('Y-m-d H:i:s'));
})
->debug(true)
->process($_POST)
->data();
$newTokenHash = csrf_hash();
$csrfTokenName = csrf_token();
$response[$csrfTokenName] = $newTokenHash;
echo json_encode($response);
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
}

View File

@ -8,6 +8,11 @@ return [
'plantillaPrecios_list' => 'List Customer fees templates',
'nombre' => 'Name',
'plantilla_id' => 'Template ID',
'plantilla' => 'Prices template',
'convertir2plantilla' => 'Convert to template',
'convertir2plantillaText' => 'You have selected to convert the customer\'s current pricing table as a template.',
'convertir2plantillaText2' => 'Next, type the name for the template and hit Save',
'nombrePlantilla' => 'Name for the template',
'tipo' => 'Type',
'tipo_maquina' => 'Machine type',
'tipo_impresion' => 'Print type',
@ -35,10 +40,11 @@ return [
'required' => 'Field required',
'decimal' => 'Decimal number',
],
'errors' => [
'error_tiempo_range' => 'The field Min Time must be lower than the field Max Time',
'error_tiempo_overlap' => 'The range [Min Time, Max Time] is overlapped with another one for the selected type.',
]
'error_nombre_template' => 'The template name is required'
],
}
];

View File

@ -8,6 +8,11 @@ return [
'plantillaPrecios_list' => 'Lista Plantillas tarifas cliente',
'nombre' => 'Nombre',
'plantilla_id' => 'Plantilla ID',
'plantilla' => 'Plantilla de precios',
'convertir2plantilla' => 'Convertir a plantilla',
'convertir2plantillaText' => 'Ha seleccionado convertir la tabla de precios actual del cliente como una plantilla.',
'convertir2plantillaText2' => 'A continuación, escriba el nombre para la plantilla y pulse Guardar',
'nombrePlantilla' => 'Nombre para la plantilla',
'tipo' => 'Tipo',
'tipo_maquina' => 'Tipo de máquina',
'tipo_impresion' => 'Tipo de impresión',
@ -37,6 +42,7 @@ return [
'errors' => [
'error_tiempo_range' => 'El campo Tiempo Mín debe ser menor que el campo Tiempo Máx',
'error_tiempo_overlap' => 'El rango [Tiempo Min, Tiempo Máx] se solapa con otro con los mismos parámetros.',
'error_nombre_template' => 'El nombre de la plantilla es obligatorio'
]
];

View File

@ -111,6 +111,15 @@ class ClientePlantillaPreciosLineasModel extends \App\Models\GoBaseModel
];
function delete_values($plantilla_id = 0){
$this->db
->table($this->table . " t1")
->where('t1.plantilla_id', $plantilla_id)
->set('is_deleted', 1)
->update();
}
/**
* Get resource data.
*
@ -171,4 +180,32 @@ class ClientePlantillaPreciosLineasModel extends \App\Models\GoBaseModel
return "";
}
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();
foreach ($values as $value) {
$this->db
->table($this->table . " t1")
->set('plantilla_id', $plantilla_id)
->set('tipo', $value->tipo)
->set('tipo_maquina', $value->tipo_maquina)
->set('tipo_impresion', $value->tipo_impresion)
->set('tiempo_min', $value->tiempo_min)
->set('tiempo_max', $value->tiempo_max)
->set('margen', $value->margen)
->set('user_updated_id', $session->id_user)
->set('updated_at', $date_value)
->insert();
}
}
}

View File

@ -2,7 +2,7 @@
namespace App\Models\Clientes;
class ClientePlantillaPreciosLineasModel extends \App\Models\GoBaseModel
class ClientePreciosModel extends \App\Models\GoBaseModel
{
protected $table = "cliente_precios";
@ -13,6 +13,16 @@ class ClientePlantillaPreciosLineasModel extends \App\Models\GoBaseModel
*/
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",
];
protected $allowedFields = [
"cliente_id",
@ -101,5 +111,135 @@ class ClientePlantillaPreciosLineasModel extends \App\Models\GoBaseModel
],
];
function clean_plantilla_id($cliente_id = 0){
$this->db
->table($this->table . " t1")
->where('cliente_id', $cliente_id)
->set('plantilla_id', null)
->update();
}
function set_plantilla_id($cliente_id = 0, $plantilla_id = null){
$this->db
->table($this->table . " t1")
->where('cliente_id', $cliente_id)
->set('plantilla_id', $plantilla_id)
->update();
}
function delete_values($cliente_id = 0){
$this->db
->table($this->table . " t1")
->where('cliente_id', $cliente_id)
->set('is_deleted', 1)
->update();
}
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();
foreach ($values as $value) {
$this->db
->table($this->table . " t1")
->set('cliente_id', $cliente_id)
->set('plantilla_id', $plantilla_id)
->set('tipo', $value->tipo)
->set('tipo_maquina', $value->tipo_maquina)
->set('tipo_impresion', $value->tipo_impresion)
->set('tiempo_min', $value->tiempo_min)
->set('tiempo_max', $value->tiempo_max)
->set('margen', $value->margen)
->set('user_updated_id', $session->id_user)
->set('updated_at', $date_value)
->insert();
}
}
/**
* Get resource data.
*
* @param string $search
*
* @return \CodeIgniter\Database\BaseBuilder
*/
public function getResource($cliente_id = -1)
{
$builder = $this->db
->table($this->table . " t1")
->select(
"t1.id as id, t1.plantilla_id AS plantilla_id, t1.cliente_id AS cliente_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"
);
$builder->join("auth_user t2", "t1.user_updated_id = t2.id_user", "left");
$builder->where('t1.is_deleted', 0);
$builder->where('t1.cliente_id', $cliente_id);
return $builder;
}
public function checkIntervals($data = [], $id_linea = null, $cliente_id = null){
helper('general');
if(floatval($data["tiempo_min"])>= floatval($data["tiempo_max"])){
return lang('ClientePrecios.errors.error_tiempo_range');
}
$rows = $this->db
->table($this->table)
->select("id, tiempo_min, tiempo_max")
->where("is_deleted", 0)
->where("tipo", $data["tipo"])
->where("tipo_maquina", $data["tipo_maquina"])
->where("tipo_impresion", $data["tipo_impresion"])
->where("cliente_id", $cliente_id)
->get()->getResultObject();
foreach ($rows as $row) {
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');
}
}
return "";
}
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){
return $value[0]->plantilla_id;
}
return null;
}
}

View File

@ -181,7 +181,7 @@ abstract class GoBaseModel extends Model {
* @param null $searchStr
* @return array
*/
public function getSelect2MenuItems(array $columns2select = ['id', 'designation'], $resultSorting=null, bool $onlyActiveOnes=true, $searchStr = null) {
public function getSelect2MenuItems(array $columns2select = ['id', 'designation'], $resultSorting=null, bool $onlyActiveOnes=true, $searchStr = null, $isDeleteField=false) {
$theseConditionsAreMet = [];
@ -199,6 +199,9 @@ abstract class GoBaseModel extends Model {
$theseConditionsAreMet['active'] = true;
}
}
//JJO
if($isDeleteField)
$theseConditionsAreMet['is_deleted'] = 0;
$queryBuilder = $this->db->table($this->table);
$queryBuilder->select([$id, $text]);

View File

@ -16,6 +16,18 @@
</button>
</li>
<?php if ($formAction !== site_url('cliente/add')){ ?>
<li class="nav-item">
<button
type="button"
class="nav-link"
role="tab"
data-bs-toggle="tab"
data-bs-target="#tarifascliente"
aria-controls="tarifascliente"
aria-selected="false">
Tarifas
</button>
</li>
<li class="nav-item">
<button
type="button"
@ -554,6 +566,51 @@
<?php if ($formAction !== site_url('cliente/add')){ ?>
<div class="tab-pane fade" id="tarifascliente" role="tabpanel">
<?= view("themes/backend/vuexy/form/clientes/cliente/convert2templateModal") ?>
<div class='row'>
<div class="col-md-12 col-lg-4 px-4">
<div class="mb-3">
<label id="label_plantilla" for="plantillas" class="form-label">
<?= lang('ClientePrecios.plantilla') ?>
</label>
<select id="plantillas" name="plantillas" class="form-control select2bs2" style="width: 100%;">
</select>
</div>
</div>
</div>
<div class='row'>
<div class="col-md-12 col-lg-4 px-4">
<button id="convert2template" type="button" class="btn btn-secondary waves-effect waves-light float-start"><?= lang("ClientePrecios.convertir2plantilla")?></button>
</div>
</div>
<table id="tableOfPrecios" class="table table-striped table-hover" style="width: 100%;">
<thead>
<tr>
<th><?= lang('ClientePrecios.tipo') ?></th>
<th><?= lang('ClientePrecios.tipo_maquina') ?></th>
<th><?= lang('ClientePrecios.tipo_impresion') ?></th>
<th><?= lang('ClientePrecios.tiempo_min') ?></th>
<th><?= lang('ClientePrecios.tiempo_max') ?></th>
<th><?= lang('ClientePrecios.precio_hora') ?></th>
<th><?= lang('ClientePrecios.margen') ?></th>
<th><?= lang('ClientePrecios.user_updated_id') ?></th>
<th><?= lang('ClientePrecios.updated_at') ?></th>
<th>plantilla_id</th>
<th class="text-nowrap" style="min-width:100px"><?= lang('Basic.global.Action') ?></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<div class="tab-pane fade" id="contactos" role="tabpanel">
<table id="tableOfClienteContactos"
class="table table-striped table-hover" style="width: 100%;">
@ -651,26 +708,31 @@ $(document).on('click', '.btn-remove', function(e) {
const dataId = $(this).attr('data-id');
const tableId = $(this).attr('table-id');
console.log(dataId)
if ($.isNumeric(dataId)) {
if(tableId=='#tableOfDireccionesEnvio')
delete_direccion_envio(dataId)
else if(tableId=='#tableOfPrecios'){
const row = $(this).attr('row');
delete_precio(dataId, row)
}
}
});
const url = window.location.href;
const url_parts = url.split('/');
if(url_parts[url_parts.length-2] == 'edit'){
id = url_parts[url_parts.length-1];
}
else{
id = -1;
}
<?=$this->endSection() ?>
<?= $this->section("additionalInlineJs") ?>
const lastColNr = $('#tableOfClienteContactos').find("tr:first th").length - 1;
const url = window.location.href;
const url_parts = url.split('/');
if(url_parts[url_parts.length-2] == 'edit'){
id = url_parts[url_parts.length-1];
}
else{
id = -1;
}
const actionBtns = function(data) {
return `
@ -840,6 +902,345 @@ $(document).on('click', '.btn-remove', function(e) {
<?=$this->endSection() ?>
<?= $this->section("additionalInlineJs") ?>
/**************************************
Tarifas cliente
***************************************/
$('#plantillas').select2({
allowClear: false,
ajax: {
url: '<?= route_to("menuItemsOfClienteplantillaprecios") ?>',
type: 'post',
dataType: 'json',
data: function (params) {
return {
id: 'id',
text: 'nombre',
searchTerm: params.term,
<?= csrf_token() ?? "token" ?> : <?= csrf_token() ?>v
};
},
delay: 60,
processResults: function (response) {
yeniden(response.<?= csrf_token() ?>);
return {
results: response.menu
};
},
cache: true
}
});
const lastColNr_lineas = $('#tableOfPrecios').find("tr:first th").length - 1;
const actionBtns_lineas = function(data) {
return `
<span class="edit"><a href="javascript:void(0);"><i class="ti ti-pencil ti-sm btn-edit mx-2" data-id="${data.id}"></i></a></span>
<a href="javascript:void(0);"><i class="ti ti-trash ti-sm btn-delete mx-2" data-id="${data.id}" data-bs-toggle="modal" data-bs-target="#confirm2delete"></i></a>
<span class="cancel"></span>
`;
};
const tipo_linea = [
{label:'<?= lang('ClientePrecios.interior') ?>', value:'interior'},
{label:'<?= lang('ClientePrecios.cubierta') ?>', value: 'cubierta'},
{label:'<?= lang('ClientePrecios.sobrecubierta') ?>', value: 'sobrecubierta'}
];
const tipo_maquina = [
{label: '<?= lang('ClientePrecios.toner') ?>', value:'toner'},
{label: '<?= lang('ClientePrecios.inkjet') ?>', value:'inkjet'},
];
const tipo_impresion = [
{label: '<?= lang('ClientePrecios.negro') ?>', value:'negro'},
{label: '<?= lang('ClientePrecios.negrohq') ?>', value:'negrohq'},
{label: '<?= lang('ClientePrecios.color') ?>', value:'color'},
{label: '<?= lang('ClientePrecios.colorhq') ?>', value:'colorhq'},
];
var editorPrecios = new $.fn.dataTable.Editor( {
ajax: {
url: "<?= route_to('editorOfClienteprecios') ?>",
headers: {
<?= csrf_token() ?? "token" ?> : <?= csrf_token() ?>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.<?= csrf_token() ?>);
});
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({
<?= csrf_token() ?? "token" ?> : <?= csrf_token() ?>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({
<?= csrf_token() ?? "token" ?> : <?= csrf_token() ?>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><t><"mt-4 mb-3"p>',
ajax : $.fn.dataTable.pipeline( {
url: '<?= route_to('dataTableOfClienteprecios') ?>',
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 '<?= lang('ClientePrecios.interior') ?>';
else if(data=='cubierta')
return '<?= lang('ClientePrecios.cubierta') ?>';
else if(data=='sobrecubierta')
return '<?= lang('ClientePrecios.sobrecubierta') ?>';
}
},
{ 'data': 'tipo_maquina',
'render': function ( data, type, row, meta ) {
if(data=='toner')
return '<?= lang('ClientePrecios.toner') ?>';
else if(data=='inkjet')
return '<?= lang('ClientePrecios.inkjet') ?>';
}
},
{ 'data': 'tipo_impresion',
'render': function ( data, type, row, meta ) {
if(data=='negro')
return '<?= lang('ClientePrecios.negro') ?>';
else if(data=='negrohq')
return '<?= lang('ClientePrecios.negrohq') ?>';
else if(data=='color')
return '<?= lang('ClientePrecios.color') ?>';
else if(data=='colorhq')
return '<?= lang('ClientePrecios.colorhq') ?>';
}
},
{ '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: "//cdn.datatables.net/plug-ins/1.13.4/i18n/<?= config('Basics')->i18n ?>.json"
},
buttons: [ {
className: 'btn btn-primary me-sm-3 me-1',
extend: "createInline",
editor: editorPrecios,
formOptions: {
submitTrigger: -1,
submitHtml: '<a href="javascript:void(0);"><i class="ti ti-device-floppy"></i></a>'
}
} ]
} );
const initPrecioTemplate = <?php echo json_encode($precioTemplate);?>;
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: '<a href="javascript:void(0);"><i class="ti ti-x"></i></a>',
cancelTrigger: 'span.cancel',
submitHtml: '<a href="javascript:void(0);"><i class="ti ti-device-floppy"></i></a>',
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');
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,
<?= csrf_token() ?? "token" ?> : <?= csrf_token() ?>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");
})
<?= $this->endSection() ?>
<?= $this->section("additionalInlineJs") ?>
/****************************************
Direcciones cliente

View File

@ -0,0 +1,65 @@
<div id="convert2Template" class="modal fade addModal">
<div class="modal-dialog modal-lg modal-simple">
<div class="modal-content">
<div class="modal-header">
<h4 id="labelTitleConfirmDialog" class="modal-title"><?= lang('ClientePrecios.convertir2plantilla') ?></h4>
</div>
<div class="modal-body">
<div id='error-nombre'></div>
<div class="mb-3">
<p><?= lang('ClientePrecios.convertir2plantillaText') ?></p>
<p><?= lang('ClientePrecios.convertir2plantillaText2') ?></p>
</div><!--//.mb-3 -->
<div class="mb-3">
<label for="nombre_plantilla" class="form-label">
<?= lang('ClientePrecios.nombrePlantilla') ?>
</label>
<input type="text" id="nombre_plantilla" maxLength="100" class="form-control new-address">
</div><!--//.mb-3 -->
</div>
<div class="modal-footer">
<button id="saveTemplate"
type="button"
class="btn btn-primary"
><?= lang('App.global_save') ?></button>
<button id="cancelTemplate"
type="button"
class="btn btn-default"
><?= lang('App.user_delete_btn_cancel') ?></button>
</div>
</div>
</div>
</div>
<?= $this->section("additionalInlineJs") ?>
$('#saveTemplate').on('click', function(){
if($('#nombre_plantilla').val().length == 0){
popErrorAlert('<?= lang('ClientePrecios.errors.error_nombre_template') ?>', 'error-nombre')
}
else{
data = new FormData();
data.append('cliente_id', id)
data.append('nombre', $('#nombre_plantilla').val())
data.append('<?= csrf_token() ?? "token" ?>', <?= csrf_token() ?>v)
fetch('<?= route_to("createClienteplantillaprecios");?>' , {
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");
})
<?=$this->endSection() ?>

View File

@ -41,8 +41,11 @@
{ e.preventDefault()
if($('#addressForm').hasClass('show')){
$("#saveAdd").click();
}else{
}
else if ($('#convert2Template').hasClass('show')){
$("#saveTemplate").click();
}
else{
$('#saveForm').click();
}
}

View File

@ -86,6 +86,19 @@
$('#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({
<?= csrf_token() ?? "token" ?> : <?= csrf_token() ?>v
}),
headers: {
"Content-type": "application/json; charset=UTF-8"
}
})
popSuccessAlert(data.msg ?? jqXHR.statusText);
}).fail((jqXHR, textStatus, errorThrown) => {
popErrorAlert(jqXHR.responseJSON.messages.error)