falta borrar direcciones cliente

This commit is contained in:
2023-12-18 00:10:47 +01:00
parent d9083aac2d
commit c435ba5a9f
9 changed files with 257 additions and 182 deletions

View File

@ -234,6 +234,7 @@ class Cliente extends \App\Controllers\GoBaseResourceController
$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);
$this->viewData['ccaaList'] = $this->getCcaaListItems($clienteEntity->ccaa_id ?? null);
$this->viewData['userList'] = $this->getUserListItems($clienteEntity->comercial_id ?? null);
$this->viewData['userList2'] = $this->getUserListItems2($clienteEntity->soporte_id ?? null);
$this->viewData['formaDePagoList'] = $this->getFormaDePagoListItems($clienteEntity->forma_pago_id ?? null);
@ -354,6 +355,14 @@ class Cliente extends \App\Controllers\GoBaseResourceController
return $data;
}
protected function getCcaaListItems($selId = null)
{
$ccaaModel = model('App\Models\Configuracion\ComunidadAutonomaModel');
$onlyActiveOnes = true;
$data = $ccaaModel->getAllForMenu('id, nombre', 'nombre', $onlyActiveOnes);
return $data;
}
protected function getUserListItems($selId = null)
{

View File

@ -20,7 +20,14 @@ class Clientedirecciones extends \App\Controllers\GoBaseResourceController
protected static $pluralObjectName = 'Direcciones de cliente';
protected static $pluralObjectNameCc = 'direccionesDeCliente';
protected static $controllerSlug = 'cliente-direcciones';
protected static $controllerSlug = 'clientedirecciones';
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger) {
$this->soft_delete = false;
$this->viewData = ['usingServerSideDataTable' => true]; // JJO
}
public function datatable()
{
@ -38,7 +45,7 @@ class Clientedirecciones extends \App\Controllers\GoBaseResourceController
$order = ClienteDireccionesModel::SORTABLE[$requestedOrder >= 0 ? $requestedOrder : 1];
$dir = $reqData['order']['0']['dir'] ?? 'asc';
$id_C = $reqData['id_cliente'] ?? -1;
$id_C = $reqData['cliente_id'] ?? -1;
$resourceData = $this->model->getResource($search, $id_C)->orderBy($order, $dir)->limit($length, $start)->get()->getResultObject();
@ -61,7 +68,7 @@ class Clientedirecciones extends \App\Controllers\GoBaseResourceController
include(APPPATH . "ThirdParty/DatatablesEditor/DataTables.php");
// Build our Editor instance and process the data coming from _POST
$response = Editor::inst($db, 'clientes_direcciones')
$response = Editor::inst($db, 'cliente_direcciones')
->fields(
Field::inst('att')
->validator('Validate::notEmpty', array(
@ -70,24 +77,77 @@ class Clientedirecciones extends \App\Controllers\GoBaseResourceController
->validator( Validate::maxLen( 100 ) , array(
'message' => lang('ClienteDirecciones.validation.max_length'))
),
)
/*->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['paginas_min'] = $data['data'][$pkey]['paginas_min'];
$process_data['paginas_max'] = $data['data'][$pkey]['paginas_max'];
$response = $this->model->checkIntervals($process_data, $pkey, $data['data'][$pkey]['papel_impresion_id']);
// No se pueden duplicar valores al crear o al editar
if (!empty($response)) {
return $response;
}
Field::inst('alias')
->validator('Validate::notEmpty', array(
'message' => lang('ClienteDirecciones.validation.required'))
)
->validator( Validate::maxLen( 100 ) , array(
'message' => lang('ClienteDirecciones.validation.max_length'))
),
Field::inst('email')
->validator('Validate::notEmpty', array(
'message' => lang('ClienteDirecciones.validation.required'))
)
->validator( Validate::maxLen( 100 ) , array(
'message' => lang('ClienteDirecciones.validation.max_length'))
),
Field::inst('direccion')
->validator('Validate::notEmpty', array(
'message' => lang('ClienteDirecciones.validation.required'))
)
->validator( Validate::maxLen( 255 ) , array(
'message' => lang('ClienteDirecciones.validation.max_length'))
),
Field::inst('municipio')
->validator('Validate::notEmpty', array(
'message' => lang('ClienteDirecciones.validation.required'))
)
->validator( Validate::maxLen( 100 ) , array(
'message' => lang('ClienteDirecciones.validation.max_length'))
),
Field::inst('cp')
->validator('Validate::notEmpty', array(
'message' => lang('ClienteDirecciones.validation.required'))
)
->validator( Validate::maxLen( 20 ) , array(
'message' => lang('ClienteDirecciones.validation.max_length'))
),
Field::inst('telefono')
->validator('Validate::notEmpty', array(
'message' => lang('ClienteDirecciones.validation.required'))
)
->validator( Validate::maxLen( 40 ) , array(
'message' => lang('ClienteDirecciones.validation.max_length'))
),
Field::inst('provincia')
->validator( function ( $val, $data, $field, $host ) {
if ($data['pais_id'] == 1) { // Si es españa provincia y CCAA es obligatorio
if (strlen( $val ) > 100)
return lang('ClienteDirecciones.validation.max_length');
else if (strlen( $val ) == 0)
lang('ClienteDirecciones.validation.required');
else
return true;
}
return true;
}
}
})*/
),
Field::inst('ccaa_id')
->validator( function ( $val, $data, $field, $host ) {
if ($data['pais_id'] == 1) { // Si es españa provincia y CCAA es obligatorio
if (strlen( $val ) > 100)
lang('ClienteDirecciones.validation.required');
else
return true;
}
return true;
}
),
Field::inst('pais_id')->validator('Validate::notEmpty', array(
'message' => lang('ClienteDirecciones.validation.required'))),
Field::inst('cliente_id'),
)
->debug(true)
->process($_POST)
->data();

View File

@ -17,9 +17,9 @@ class Test extends BaseController
public function index()
{
$model = model('App\Models\Presupuestos\TipoPresupuestoServiciosDefectoModel');
$model = model('App\Models\Clientes\ClienteDireccionesModel');
echo '<pre>';
var_dump($model->get_tarifas(4,0,"manipulado"));
var_dump($model->getResource("", 1420)->get()->getResultArray());
echo '</pre>';
}

View File

@ -1,18 +0,0 @@
<?php
namespace App\Entities\Configuracion;
use CodeIgniter\Entity;
class ComunidadesAutonomasEntity extends \CodeIgniter\Entity\Entity
{
protected $attributes = [
"id" => null,
"nombre" => null,
"pais_id" => null,
"created_at" => null,
"updated_at" => null,
];
protected $casts = [
"pais_id" => "int",
];
}

View File

@ -1,97 +0,0 @@
<?php
namespace App\Models\Configuracion;
class ComunidadesAutonomasModel extends \App\Models\GoBaseModel
{
protected $table = "lg_comunidades_autonomas";
/**
* Whether primary key uses auto increment.
*
* @var bool
*/
protected $useAutoIncrement = true;
const SORTABLE = [
1 => "t1.id",
2 => "t1.nombre",
3 => "t1.pais_id",
4 => "t1.created_at",
5 => "t1.updated_at",
6 => "t2.nombre",
];
protected $allowedFields = ["nombre", "pais_id"];
protected $returnType = "App\Entities\Configuracion\ComunidadesAutonomasEntity";
public static $labelField = "nombre";
protected $validationRules = [
"nombre" => [
"label" => "ComunidadesAutonomas.nombre",
"rules" => "trim|required|max_length[100]",
],
];
protected $validationMessages = [
"nombre" => [
"max_length" => "ComunidadesAutonomas.validation.nombre.max_length",
"required" => "ComunidadesAutonomas.validation.nombre.required",
],
];
public function findAllWithPaises(string $selcols = "*", int $limit = null, int $offset = 0)
{
$sql =
"SELECT t1." .
$selcols .
", t2.nombre AS pais FROM " .
$this->table .
" t1 LEFT JOIN lg_paises t2 ON t1.pais_id = t2.id";
if (!is_null($limit) && intval($limit) > 0) {
$sql .= " LIMIT " . $limit;
}
if (!is_null($offset) && intval($offset) > 0) {
$sql .= " OFFSET " . $offset;
}
$query = $this->db->query($sql);
$result = $query->getResultObject();
return $result;
}
/**
* Get resource data.
*
* @param string $search
*
* @return \CodeIgniter\Database\BaseBuilder
*/
public function getResource(string $search = "")
{
$builder = $this->db
->table($this->table . " t1")
->select(
"t1.id AS id, t1.nombre AS nombre, t1.created_at AS created_at, t1.updated_at AS updated_at, t2.nombre AS pais"
);
$builder->join("lg_paises t2", "t1.pais_id = t2.id", "left");
return empty($search)
? $builder
: $builder
->groupStart()
->like("t1.id", $search)
->orLike("t1.nombre", $search)
->orLike("t1.created_at", $search)
->orLike("t1.updated_at", $search)
->orLike("t2.id", $search)
->orLike("t1.id", $search)
->orLike("t1.nombre", $search)
->orLike("t1.pais_id", $search)
->orLike("t1.created_at", $search)
->orLike("t1.updated_at", $search)
->orLike("t2.nombre", $search)
->groupEnd();
}
}

View File

@ -1,4 +1,4 @@
<div id="createNewAddress" class="modal fade addModal">
<div id="addressForm" action='create' class="modal fade addModal">
<div class="modal-dialog modal-lg modal-simple">
<div class="modal-content">
<div class="modal-header">
@ -34,10 +34,10 @@
<div id='divPais' class="col-md-12 col-lg-12 pl-4">
<div class="mb-3">
<label for="add_paisId" class="form-label">
<label for="add_pais_id" class="form-label">
<?=lang('ClienteDirecciones.pais') ?>*
</label>
<select id="add_paisId" tabindex="4" class="form-control select2bs" style="width: 100%;" >
<select id="add_pais_id" tabindex="4" class="form-control select2bs" style="width: 100%;" >
<option value="" disabled selected><?=lang('ClienteDirecciones.selectPais') ?></option>
<?php foreach ($paisList as $item) : ?>
<option value="<?=$item->id ?>">
@ -54,7 +54,12 @@
<?=lang('ClienteDirecciones.ccaa') ?>*
</label>
<select id="add_ccaa" tabindex="5" class="form-control select2bs" style="width: 100%;" >
<option value="" disabled selected><?=lang('ClienteDirecciones.selectCcaa') ?></option>
<?php foreach ($ccaaList as $item) : ?>
<option value="<?=$item->id ?>">
<?=$item->nombre ?>
</option>
<?php endforeach; ?>
</select>
</div><!--//.mb-3 -->
</div>
@ -124,23 +129,19 @@
<?= $this->section("additionalInlineJs") ?>
$('#cancelAdd').on('click', function(){
$('#createNewAddress').modal("hide");
$('#addressForm').modal("hide");
})
$('#saveAdd').on('click', function(){
editorAddress
.create( false )
.set( 'alias', $('#add_alias').val() )
.set( 'att', $('#add_att').val() )
.submit();
saveAdd_callback()
})
$('#add_paisId').on('change', function(){
var nombre_pais = $("#add_paisId option:selected" ).text().trim();
$('#add_pais_id').on('change', function(){
var nombre_pais = $("#add_pais_id option:selected" ).text().trim();
if(nombre_pais.localeCompare('España')==0){
$('#divPais').removeClass('col-lg-12').addClass('col-lg-6')
$('#divMunicipio').removeClass('col-lg-12').addClass('col-lg-6')
@ -155,12 +156,12 @@ $('#add_paisId').on('change', function(){
// clear modal items when close
$('#createNewAddress').on('hidden.bs.modal', function () {
$('#addressForm').on('hidden.bs.modal', function () {
$('#add_alias').val("")
$('#add_att').val("")
$('#add_email').val("")
$('#add_direccion').val("")
$("#add_paisId").val("").change()
$("#add_pais_id").val("").change()
$("#add_ccaa").val("").change()
$('#add_municipio').val("")
$('#add_provincia').val("")

View File

@ -588,7 +588,7 @@
<th><?= lang('ClienteDirecciones.ccaa') ?></th>
<th><?= lang('ClienteDirecciones.pais') ?></th>
<th><?= lang('ClienteDirecciones.telefono') ?></th>
<th class="text-nowrap"><?= lang('Basic.global.Action') ?></th>
<th class="text-nowrap" style="min-width:100px;"><?= lang('Basic.global.Action') ?></th>
</tr>
</thead>
<tbody>
@ -641,6 +641,26 @@
<?php if ($formAction !== site_url('cliente/add')){ ?>
<?= $this->section("additionalInlineJs") ?>
/****************************************
Funcionamiento general
*****************************************/
$(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)
}
});
<?=$this->endSection() ?>
<?= $this->section("additionalInlineJs") ?>
const lastColNr = $('#tableOfClienteContactos').find("tr:first th").length - 1;
const url = window.location.href;
@ -824,6 +844,52 @@
/****************************************
Direcciones cliente
*****************************************/
const actionBtns_add = function(data) {
return `
<span class="edit-add"><a href="javascript:void(0);"><i class="ti ti-pencil ti-sm btn-edit-add mx-2" data-id="${data.id}"></i></a></span>
<a href="javascript:void(0);"><i class="ti ti-trash ti-sm btn-delete-add mx-2" data-id="${data.id}" data-bs-toggle="modal" data-bs-target="#confirm2delete"></i></a>
<span class="cancel"></span>
`;
};
function saveAdd_callback(){
if($('#addressForm').attr('action')=='create'){
editorAddress
.create( false )
.set( 'cliente_id', id )
.set( 'alias', $('#add_alias').val() )
.set( 'att', $('#add_att').val() )
.set( 'email', $('#add_email').val() )
.set( 'direccion', $('#add_direccion').val() )
.set( 'pais_id', $("#add_pais_id option:selected").val())
.set( 'ccaa_id', $("#add_ccaa option:selected").val())
.set( 'municipio', $('#add_municipio').val() )
.set( 'provincia', $('#add_provincia').val() )
.set( 'cp', $('#add_cp').val() )
.set( 'telefono', $('#add_telefono').val() )
.submit();
}
else{ // edit
editorAddress
.edit( '#tableOfDireccionesEnvio tbody tr:eq('+$("#addressForm").attr('row-index')+ ')', false )
.set( 'cliente_id', id )
.set( 'alias', $('#add_alias').val() )
.set( 'att', $('#add_att').val() )
.set( 'email', $('#add_email').val() )
.set( 'direccion', $('#add_direccion').val() )
.set( 'pais_id', $("#add_pais_id option:selected").val())
.set( 'ccaa_id', $("#add_ccaa option:selected").val())
.set( 'municipio', $('#add_municipio').val() )
.set( 'provincia', $('#add_provincia').val() )
.set( 'cp', $('#add_cp').val() )
.set( 'telefono', $('#add_telefono').val() )
.submit();
}
}
const editorAddress = new DataTable.Editor({
ajax: {
url: "<?= route_to('editorOfClienteDirecciones') ?>",
@ -842,13 +908,13 @@ const editorAddress = new DataTable.Editor({
}, {
name: "direccion"
}, {
name: "municipioId"
name: "municipio"
}, {
name: "provinciaId"
name: "provincia"
}, {
name: "ccaaId"
name: "ccaa_id"
}, {
name: "paisId"
name: "pais_id"
}, {
name: "cp"
}, {
@ -862,13 +928,35 @@ const editorAddress = new DataTable.Editor({
});
editorAddress.on( 'postSubmit', function ( e, json, data, action ) {
if (action === 'create') {
yeniden(json.<?= csrf_token() ?>);
$( ".error-text-form" ).remove();
if('fieldErrors' in json){
if(json.fieldErrors.length > 0){
json.fieldErrors.forEach((error) => {
$('#add_' + error.name).after("<p class='error_in_form_text'>" + error.status + '</p>')
$('#add_' + error.name).after(
"<p style='font-size: 11px !important;" +
"padding: 0 !important; " +
"color: #b11f1f !important;' " +
"class='error-text-form'>" + error.status + '</p>')
})
}
}
else{
$('#addressForm').modal("hide");
}
})
editorAddress.on( 'submitSuccess', function ( e, json, data, action ) {
tableDirecciones.clearPipeline();
tableDirecciones.draw();
});
editorAddress.on( 'close', function ( e, json, data, action ) {
$('#tableOfDireccionesEnvio').DataTable().ajax.reload();
})
const lastColNr2 = $('#tableOfDireccionesEnvio').find("tr:first th").length - 1;
@ -900,14 +988,21 @@ var tableDirecciones = $('#tableOfDireccionesEnvio').DataTable( {
{ 'data': 'att' },
{ 'data': 'email' },
{ 'data': 'direccion' },
{ 'data': 'municipioId' },
{ 'data': 'provinciaId' },
{ 'data': 'ccaaId' },
{ 'data': 'paisId' },
{ 'data': 'cp' },
{ 'data': 'municipio' },
{ 'data': 'provincia' },
{ 'data': 'ccaa_id' ,
"render": function (data, type, row, meta) {
return row.ccaa_nombre;
}
},
{ 'data': 'pais_id' ,
"render": function (data, type, row, meta) {
return row.pais;
}},
{ 'data': 'telefono' },
{
data: actionBtns,
data: actionBtns_add,
className: 'row-edit dt-center'
}
],
@ -927,24 +1022,55 @@ var tableDirecciones = $('#tableOfDireccionesEnvio').DataTable( {
className: 'btn btn-primary float-end me-sm-3 me-1',
text: "<?= lang('Basic.global.addNew'); ?>",
action: function ( e, dt, node, config ) {
var $newAddDialog = $("#createNewAddress");
$newAddDialog.modal('show');
$("#btnYesConfirmDialog").off('click').click(function () {
$newAddDialog.modal("hide");
});
$("#btnNoConfirmDialog").off('click').click(function () {
$newAddDialog.modal("hide");
});
}
$("#addressForm").attr('action','create')
var $newAddDialog = $("#addressForm")
$newAddDialog.modal('show')
}
} ]
} );
$('#tableOfDireccionesEnvio').on( 'click', 'tbody span.edit-add', function (e) {
const row = $(this).closest('tr');
const data = tableDirecciones.row(row).data()
$("#addressForm").attr('action','edit')
$("#addressForm").attr('row-index',row[0]._DT_RowIndex)
$('#add_alias').val(data.alias)
$('#add_att').val(data.att)
$('#add_email').val(data.email)
$('#add_direccion').val(data.direccion)
$("#add_pais_id").val(data.pais_id).change()
$("#add_ccaa").val(data.ccaa_id).change()
$('#add_municipio').val(data.municipio)
$('#add_provincia').val(data.provincia)
$('#add_cp').val(data.cp)
$('#add_telefono').val(data.cp)
var $newAddDialog = $("#addressForm")
$newAddDialog.modal('show')
})
$(document).on('click', '.btn-delete-add', function(e) {
$(".btn-remove").attr('data-id', $(this).attr('data-id'));
$(".btn-remove").attr('table-id', '#tableOfDireccionesEnvio');
});
function delete_direccion_envio(dataId){
$.ajax({
url: `/clientedirecciones/delete/${dataId}`,
method: 'GET',
}).done((data, textStatus, jqXHR) => {
$('#confirm2delete').modal('toggle');
tableDirecciones.clearPipeline();
tableDirecciones.ajax.reload();
popSuccessAlert(data.msg ?? jqXHR.statusText);
}).fail((jqXHR, textStatus, errorThrown) => {
popErrorAlert(jqXHR.responseJSON.messages.error)
})
}
<?=$this->endSection() ?>

View File

@ -39,7 +39,7 @@
var key = e.which;
if(key == 13) // the enter key code
{ e.preventDefault()
if($('#createNewAddress').hasClass('show')){
if($('#addressForm').hasClass('show')){
$("#saveAdd").click();
}else{
@ -231,5 +231,6 @@
<link rel="stylesheet" href="<?= site_url('themes/vuexy/css/datatables-editor/editor.dataTables.min.css') ?>">
<link rel="stylesheet" href="https://cdn.datatables.net/buttons/2.2.3/css/buttons.bootstrap5.min.css">
<link rel="stylesheet" href="<?= site_url('themes/vuexy/css/sk-datatables.css') ?>">
<link rel="stylesheet" href="<?= site_url('themes/vuexy/css/safekat.css') ?>">
<?=$this->endSection() ?>

View File

@ -114,10 +114,3 @@
text-align: center;
margin-top: 1rem;
}
.error_in_form_text{
font-size: 11px;
padding: 0;
color: #b11f1f;
}