Herramientas Informaticas

Creando CRUD de sucursales #09

Bien como ya saben para hacer una venta se requiere saber de que sucursal es así como ciertas configuraciones particulares por sucursal como la configuración de las series electrónicas para el timbrado del CFDI, así como los datos que saldran en las impresiones de los reportes, como la dirección etc

Por esta ocasión agregaremos lo siguientes datos, posterior mente se pueden agregar mas si se necesitan

  • Empresa
  • Llave
  • Nombre
  • Colonia
  • Ciudad
  • Diferencia horaria
  • Impuesto
  • Fecha de apertura
  • Telefono
  • Fax
  • Arqueo de caja
Leer Mas: Creando CRUD de sucursales #09

Primeramente creamos el archivo de migración app/database/migrations/2023-02-14110147_Branchoffices.php , se dan cuenta que dice Branchoffice, es por que en su momento lo quise empezar en ingles para practicar

<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

class Branchoffices extends Migration {

    public function up() {
        // Branchoffices
        $this->forge->addField([
                'id' => ['type' => 'int', 'constraint' => 11, 'unsigned' => true, 'auto_increment' => true],
                'key' => ['type' => 'varchar', 'constraint' => 8, 'null' => false],
                'name' => ['type' => 'varchar', 'constraint' => 256, 'null' => true],
                'cologne' => ['type' => 'varchar', 'constraint' => 64, 'null' => true],
                'city' => ['type' => 'varchar', 'constraint' => 128, 'null' => true],
                'postalCode' => ['type' => 'varchar', 'constraint' => 5, 'null' => true],
                'timeDifference' => ['type' => 'varchar', 'constraint' => 4, 'null' => true],
                'tax' => ['type' => 'varchar', 'constraint' => 4, 'null' => true],
                'dateAp' => ['type' => 'date', 'null'  => true],
                'phone'  => ['type' => 'varchar', 'constraint'  => 16, 'null'  => true],
                'fax'  => ['type' => 'varchar', 'constraint'  => 16, 'null'  => true],
                'companie'  => ['type' => 'varchar', 'constraint'  => 8, 'null'  => true],
                'arqueoCaja'  => ['type' => 'varchar', 'constraint'  => 5, 'null'  => true],
                'created_at'  => ['type' => 'datetime', 'null'  => true],
                'updated_at'  => ['type' => 'datetime', 'null'  => true],
                'deleted_at'  => ['type' => 'datetime', 'null'  => true],
        ]);

        $this->forge->addKey('id', true);

        $this->forge->createTable('branchoffices', true);
    }

    public function down() {
        $this->forge->dropTable('branchoffices', true);
    }

}

Una ve creado el archivo ejecutamos el comando que crea la tabla

también necesitamos la tabla de sucursales por usuario app/database/migrations/2023-02-14110147_Branchoffices.php

<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

class UsuariosSucursal extends Migration
{
    public function up()
    {
        // Usuariosempresa
        $this->forge->addField([
            'id'                    => ['type' => 'int', 'constraint' => 11, 'unsigned' => true, 'auto_increment' => true],
            'idEmpresa'             => ['type' => 'int', 'constraint' => 11, 'null' => true],
            'idSucursal'             => ['type' => 'int', 'constraint' => 11, 'null' => true],
            'idUsuario'             => ['type' => 'int', 'constraint' => 11, 'null' => true],
            'status'             => ['type' => 'varchar', 'constraint' => 8, 'null' => true],

            'created_at'       => ['type' => 'datetime', 'null' => true],
            'updated_at'       => ['type' => 'datetime', 'null' => true],
            'deleted_at'       => ['type' => 'datetime', 'null' => true],
        ]);

        $this->forge->addKey('id', true);
        $this->forge->createTable('usuarios_sucursal', true);
    }
    public function down()
    {
        $this->forge->dropTable('usuarios_sucursal', true);
    }
}
php spark migrate

Creamos el archivo app/models/BranchofficeModel.php con los métodos necesarios de lectura y reglas de validación

<?php

namespace App\Models;

use CodeIgniter\Model;

class BranchofficesModel extends Model{

    protected $table      = 'branchoffices';
    protected $primaryKey = 'id';
    protected $useAutoIncrement = true;
    protected $returnType     = 'array';
    protected $useSoftDeletes = true;
    protected $allowedFields = ['id'
    ,'key'
    ,'name'
    ,'cologne'
    ,'city'
    ,'postalCode'
    ,'timeDifference'
    ,'tax'
    ,'dateAp'
    ,'phone'
    ,'fax'
    ,'companie'
    ,'arqueoCaja'
    ,'created_at
    ','deleted_at'
    ,'updated_at'];
    protected $useTimestamps = true;
    protected $createdField  = 'created_at';
    protected $deletedField  = 'deleted_at';

    protected $validationRules    =  [
         'key ' => 'is_unique[branchoffices.key]',

    ];
    protected $validationMessages = [];
    protected $skipValidation     = false;
    
    
        public function mdlSucursalesPorUsuario($usuario){


        $resultado =$this->db->table('branchoffices a, usuarios_sucursal b')
        ->select('a.id,a.name,key,a.created_at,a.updated_at,a.deleted_at')
        ->where('a.id', 'b.idSucursal', FALSE)
        ->where('b.status', 'on')
        ->where('b.idUsuario', $usuario)->get()->getResultArray();

        return $resultado;

    }

}
        

Creamos el archivo del modelo usuarios por sucursal app/model/UsuariosSucursalModel.php

<?php

namespace App\Models;

use CodeIgniter\Model;

class UsuariosSucursalModel extends Model
{
    protected $table      = 'usuarios_sucursal';
    protected $primaryKey = 'id';
    protected $useAutoIncrement = true;
    protected $returnType     = 'array';
    protected $useSoftDeletes = true;
    protected $allowedFields = ['id', 'idEmpresa', 'idSucursal', 'idUsuario', 'status', 'created_at', 'updated_at', 'deleted_at'];
    protected $useTimestamps = true;
    protected $createdField  = 'created_at';
    protected $deletedField  = 'deleted_at';
    protected $validationRules    =  [];
    protected $validationMessages = [];
    protected $skipValidation     = false;


    public function mdlSucursalesPorUsuario($sucursal, $empresasID)
    {

        $result = $this->db->table('users a, usuariosempresa b')
            ->select(
                'ifnull(a.id,0) as id
                ,a.username
                ,b.idEmpresa
                ,' . $sucursal . ' as idSucursal
                ,ifnull((select status 
                            from usuarios_sucursal z
                            where z.idUsuario = a.id
                                and z.idEmpresa=b.idEmpresa
                                    and z.idSucursal=' . $sucursal . '
                                    ),\'off\') as status
                                        
                ,ifnull((select id 
                        from usuarios_sucursal z
                        where z.idUsuario = a.id
                            and z.idEmpresa=b.idEmpresa
                                and z.idSucursal=' . $sucursal . '
                                ),0) as idSucursalUsuario
                '

            )

            ->where('a.id', 'b.idUsuario', FALSE)
            ->where('b.idEmpresa', $empresasID);

        return $result;
    }
}

Creamos el archivo app/controller/BranchofficesController.php

<?php

namespace App\Controllers;

use App\Controllers\BaseController;
use \App\Models\{
    BranchofficesModel
};
use App\Models\LogModel;
use CodeIgniter\API\ResponseTrait;
use App\Models\EmpresasModel;
use App\Models\UsuariosSucursalModel;

class BranchofficesController extends BaseController {

    use ResponseTrait;

    protected $log;
    protected $branchoffices;
    protected $empresas;
    protected $usuariosPorSucursal;

    public function __construct() {
        $this->branchoffices = new BranchofficesModel();
        $this->log = new LogModel();
        $this->empresas = new EmpresasModel();
        $this->usuariosPorSucursal = new UsuariosSucursalModel();
        helper('menu');
    }

    public function index() {

        helper('auth');

        $idUser = user()->id;
        $titulos["empresas"] = $this->empresas->mdlEmpresasPorUsuario($idUser);

        if (count($titulos["empresas"]) == "0") {

            $empresasID[0] = "0";
        } else {

            $empresasID = array_column($titulos["empresas"], "id");
        }



        if ($this->request->isAJAX()) {




            $datos = $this->branchoffices->select('id
            ,key
            ,name
            ,cologne
            ,city
            ,postalCode
            ,timeDifference
            ,tax,dateAp
            ,phone
            ,fax
            ,companie
            ,created_at
            ,deleted_at
            ,updated_at')->where('deleted_at', null)
            ->whereIn('companie', $empresasID);;

            return \Hermawan\DataTables\DataTable::of($datos)->toJson(true);
        }


       // $empresas = $this->empresas->select("id,nombre")->asObject()->findAll();

       // $titulos["empresas"] = $empresas;
        $titulos["title"] = lang('branchoffices.title');
        $titulos["subtitle"] = lang('branchoffices.subtitle');

        return view('branchoffices', $titulos);
    }

    /**
     * Read Branchoffices
     */
    public function getBranchoffices() {


        $idBranchoffices = $this->request->getPost("idBranchoffices");
        $datosBranchoffices = $this->branchoffices->find($idBranchoffices);

        echo json_encode($datosBranchoffices);
    }

    /**
     * Save or update Branchoffices
     */
    public function save() {


        helper('auth');
        $userName = user()->username;
        $idUser = user()->id;

        $datos = $this->request->getPost();

        if ($datos["idBranchoffices"] == 0) {


            try {


                if ($this->branchoffices->save($datos) === false) {

                    $errores = $this->branchoffices->errors();

                    foreach ($errores as $field => $error) {

                        echo $error . " ";
                    }

                    return;
                }

                $dateLog["description"] = lang("vehicles.logDescription") . json_encode($datos);
                $dateLog["user"] = $userName;

                $this->log->save($dateLog);

                echo "Guardado Correctamente";
            } catch (\PHPUnit\Framework\Exception $ex) {


                echo "Error al guardar " . $ex->getMessage();
            }
        } else {


            if ($this->branchoffices->update($datos["idBranchoffices"], $datos) == false) {

                $errores = $this->branchoffices->errors();
                foreach ($errores as $field => $error) {

                    echo $error . " ";
                }

                return;
            } else {

                $dateLog["description"] = lang("branchoffices.logUpdated") . json_encode($datos);
                $dateLog["user"] = $userName;

                $this->log->save($dateLog);
                echo "Actualizado Correctamente";

                return;
            }
        }

        return;
    }

    /**
     * Delete Branchoffices
     * @param type $id
     * @return type
     */
    public function delete($id) {

        $infoBranchoffices = $this->branchoffices->find($id);
        helper('auth');
        $userName = user()->username;

        if (!$found = $this->branchoffices->delete($id)) {
            return $this->failNotFound(lang('branchoffices.msg.msg_get_fail'));
        }



        $logData["description"] = lang("branchoffices.logDeleted") . json_encode($infoBranchoffices);
        $logData["user"] = $userName;

        $this->log->save($logData);
        return $this->respondDeleted($found, lang('branchoffices.msg_delete'));
    }

    public function usuariosPorSucursal($sucursal) {

        helper('auth');

        $idUser = user()->id;

        $datosSucursal = $this->branchoffices->select("companie as empresa")->where("id",$sucursal)->first();

        if(isset($datosSucursal["empresa"])){

            $idEmpresa = $datosSucursal["empresa"];

        }else{

            $idEmpresa = -1;

        }
        

        $usuarios = $this->usuariosPorSucursal->mdlSucursalesPorUsuario($sucursal, $idEmpresa);

        return \Hermawan\DataTables\DataTable::of($usuarios)->toJson(true);
    }

    /**
     * Activar Desactivar Usuario Por Empresa
     */
    public function ActivarDesactivar() {

        $datos = $this->request->getPost();

        if ($datos["id"] > 0) {

            //ACTUALIZA SI  EXISTE

            if ($this->usuariosPorSucursal->update($datos["id"], $datos) === false) {
                $errores = $this->usuariosPorSucursal->errors();
                foreach ($errores as $field => $error) {
                    echo $error . " ";
                }
                return;
            }

            echo "ok";
        } else {

            //INSERTA SI  NO EXISTE
            if ($this->usuariosPorSucursal->save($datos) === false) {

                $errores = $this->usuariosPorSucursal->errors();

                foreach ($errores as $key => $error) {

                    echo $error . " ";
                }

                return;
            }



            echo "ok";
        }
    }

    /**
     * Get Storages via AJax
     */
    public function getSucursalesAjax() {

        $request = service('request');
        $postData = $request->getPost();

        $response = array();

        // Read new token and assign in $response['token']
        $response['token'] = csrf_hash();

        helper('auth');
        $userName = user()->username;
        $idUser = user()->id;

        $sucursalesPorUsuario = $this->usuariosPorSucursal->select("*")
                        ->where("idUsuario", $idUser)
                        ->where("status", "on")->findAll();

        $sucursalesPorUsuario = array_column($sucursalesPorUsuario, "idSucursal");
        if (!isset($postData['searchTerm'])) {
            // Fetch record
            $sucursales = new BranchofficesModel();
            $listSucursales = $sucursales->select('id,key,name')->where("deleted_at", null)
                    ->whereIn("id", $sucursalesPorUsuario)
                    ->where("companie", $postData["idEmpresa"])
                    ->orderBy('id')
                    ->orderBy('key')
                    ->orderBy('name')
                    ->findAll();
        } else {
            $searchTerm = $postData['searchTerm'];

            // Fetch record
            $sucursales = new BranchofficesModel();
            $listSucursales = $sucursales->select('id,key,name')
                    ->where("deleted_at", null)
                    ->whereIn("id", $sucursalesPorUsuario)
                    ->where("companie", $postData["idEmpresa"])
                    ->like('name', $searchTerm)
                    ->orLike('id', $searchTerm)
                    ->orLike('key', $searchTerm)
                    ->findAll();
        }

        $data = array();
        $data[] = array(
            "id" => 0,
            "text" => "0 Todas las sucursales",
        );

        foreach ($listSucursales as $sucursal) {
            $data[] = array(
                "id" => $sucursal['id'],
                "text" => $sucursal['key'] . ' ' . $sucursal['name'],
            );
        }

        $response['data'] = $data;

        return $this->response->setJSON($response);
    }

}

Creamos el archivo del controlador para usuarios por sucursal app/controller/UsuariosSucursalController.php

<?php

namespace App\Controllers;

use App\Controllers\BaseController;
use \App\Models\{
    UsuariosSucursalModel
};
use App\Models\LogModel;
use CodeIgniter\API\ResponseTrait;

class UsuariosSucursalController extends BaseController {

    use ResponseTrait;

    protected $log;
    protected $usuariosSucursal;

    public function __construct() {
        $this->usuariosSucursal = new UsuariosSucursalModel();
        $this->log = new LogModel();
        helper('menu');
    }

    public function index() {
        if ($this->request->isAJAX()) {
            $datos = $this->usuariosSucursal>select('id,idEmpresa,idSucursal,idUsuario,status,created_at,updated_at,deleted_at')->where('deleted_at', null);
            return \Hermawan\DataTables\DataTable::of($datos)->toJson(true);
        }
        $titulos["title"] = "Usuarios Sucursal";
        $titulos["subtitle"] = "Usuarios Por Sucursal";
        return view('usuariosAlmacen', $titulos);
    }

    /**
     * Read Usuariosempresa
     */
    public function getUsuariosAlmacen() {
        $idUsuariosAlmacen = $this->request->getPost("idUsuariosSucursal");
        $datosUsuariosAlmacen = $this->usuariosAlmacen->find($idUsuariosAlmacen);
        echo json_encode($datosUsuariosAlmacen);
    }

    /**
     * Save or update Usuariosempresa
     */
    public function save() {
        helper('auth');
        $userName = user()->username;
        $idUser = user()->id;
        $datos = $this->request->getPost();
        if ($datos["idUsuariosSucursal"] == 0) {
            try {
                if ($this->usuariosSucursal->save($datos) === false) {
                    $errores = $this->usuariosSucursal->errors();
                    foreach ($errores as $field => $error) {
                        echo $error . " ";
                    }
                    return;
                }
                $dateLog["description"] = "Usuarios Por Sucursal" . json_encode($datos);
                $dateLog["user"] = $userName;
                $this->log->save($dateLog);
                echo "Guardado Correctamente";
            } catch (\PHPUnit\Framework\Exception $ex) {
                echo "Error al guardar " . $ex->getMessage();
            }
        } else {
            if ($this->usuariosSucursal->update($datos["idUsuariossucursal"], $datos) == false) {
                $errores = $this->usuariosSucursal->errors();
                foreach ($errores as $field => $error) {
                    echo $error . " ";
                }
                return;
            } else {
                $dateLog["description"] = lang("usuariosSucursal.logUpdated") . json_encode($datos);
                $dateLog["user"] = $userName;
                $this->log->save($dateLog);
                echo "Actualizado Correctamente";
                return;
            }
        }
        return;
    }

    /**
     * Delete Usuariosempresa
     * @param type $id
     * @return type
     */
    public function delete($id) {
        $infoUsuariosSucursal = $this->usuariosSucursal->find($id);
        helper('auth');
        $userName = user()->username;
        if (!$found = $this->usuariosSucursal->delete($id)) {
            return $this->failNotFound(lang('usuariosempresa.msg.msg_get_fail'));
        }
        $this->usuariosSucursal->purgeDeleted();
        $logData["description"] = "Datos Anteriores Usuarios Por Sucursal" . json_encode($infoUsuariosSucursal);
        $logData["user"] = $userName;
        $this->log->save($logData);
        return $this->respondDeleted($found, lang('usuariossucursal.msg_delete'));
    }

}

Creamos el archivo principal de la vista de sucursales app/views/branchoffice.php este archivo hará una inclusión a los modales de usuarios por sucursal y captura de sucursales

<?= $this->include('load/toggle') ?>
<?= $this->include('julio101290\boilerplate\Views\load\select2') ?>
<?= $this->include('julio101290\boilerplate\Views\load\datatables') ?>
<?= $this->include('julio101290\boilerplate\Views\load\nestable') ?>
<!-- Extend from layout index -->
<?= $this->extend('julio101290\boilerplate\Views\layout\index') ?>

<!-- Section content -->
<?= $this->section('content') ?>

<?= $this->include('modulesBranchoffices/modalCaptureBranchoffices') ?>
<?= $this->include('modulesBranchoffices/usuariosSucursalModal') ?>

<!-- SELECT2 EXAMPLE -->
<div class="card card-default">
    <div class="card-header">
        <div class="float-right">
            <div class="btn-group">

                <button class="btn btn-primary btnAddBranchoffices" data-toggle="modal" data-target="#modalAddBranchoffices"><i class="fa fa-plus"></i>

                    <?= lang('branchoffices.add') ?>

                </button>

            </div>
        </div>
    </div>
    <div class="card-body">
        <div class="row">
            <div class="col-md-12">
                <div class="table-responsive">
                    <table id="tableBranchoffices" class="table table-striped table-hover  va-middle tableBranchoffices">
                        <thead>
                            <tr>

                                <th>#</th>
                                <th><?= lang('branchoffices.fields.key') ?></th>
                                <th><?= lang('branchoffices.fields.name') ?></th>
                                <th><?= lang('branchoffices.fields.cologne') ?></th>
                                <th><?= lang('branchoffices.fields.city') ?></th>
                                <th><?= lang('branchoffices.fields.postalCode') ?></th>
                                <th><?= lang('branchoffices.fields.timeDifference') ?></th>
                                <th><?= lang('branchoffices.fields.tax') ?></th>
                                <th><?= lang('branchoffices.fields.dateAp') ?></th>
                                <th><?= lang('branchoffices.fields.phone') ?></th>
                                <th><?= lang('branchoffices.fields.fax') ?></th>
                                <th><?= lang('branchoffices.fields.companie') ?></th>
                                <th><?= lang('branchoffices.fields.created_at') ?></th>
                                <th><?= lang('branchoffices.fields.deleted_at') ?></th>
                                <th><?= lang('branchoffices.fields.updated_at') ?></th>

                                <th><?= lang('branchoffices.fields.actions') ?> </th>

                            </tr>
                        </thead>
                        <tbody>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
<!-- /.card -->

<?= $this->endSection() ?>


<?= $this->section('js') ?>
<script>
    /**
     * Cargamos la tabla
     */

    var tableBranchoffices = $('#tableBranchoffices').DataTable({
        processing: true,
        serverSide: true,
        autoWidth: false,
        responsive: true,
        order: [
            [1, 'asc']
        ],

        ajax: {
            url: '<?= base_url('admin/branchoffices') ?>',
            method: 'GET',
            dataType: "json"
        },
        columnDefs: [{
                orderable: false,
                targets: [15],
                searchable: false,
                targets: [15]

            }],
        columns: [{
                'data': 'id'
            },

            {
                'data': 'key'
            },

            {
                'data': 'name'
            },

            {
                'data': 'cologne'
            },

            {
                'data': 'city'
            },

            {
                'data': 'postalCode'
            },

            {
                'data': 'timeDifference'
            },

            {
                'data': 'tax'
            },

            {
                'data': 'dateAp'
            },

            {
                'data': 'phone'
            },

            {
                'data': 'fax'
            },

            {
                'data': 'companie'
            },

            {
                'data': 'created_at'
            },

            {
                'data': 'deleted_at'
            },

            {
                'data': 'updated_at'
            },

            {
                "data": function (data) {
                    return `<td class="text-right py-0 align-middle">
                         <div class="btn-group btn-group-sm">
                             <button class="btn btn-warning btnEditBranchoffices" data-toggle="modal" idBranchoffices="${data.id}" data-target="#modalAddBranchoffices">  <i class=" fa fa-edit"></i></button>
                             <button class="btn btn-danger btn-delete" data-id="${data.id}"><i class="fas fa-trash"></i></button>
                             <button class="btn btn-success btn-users" data-id="${data.id}" data-toggle="modal" data-target="#modalUsuariosSucursal"><i class="fas fa-users"></i></button>
                         </div>
                         </td>`
                }
            }
        ]
    });



    $(document).on('click', '#btnSaveBranchoffices', function (e) {


        var idBranchoffices = $("#idBranchoffices").val();
        var key = $("#key").val();
        var name = $("#name").val();
        var cologne = $("#cologne").val();
        var city = $("#city").val();
        var postalCode = $("#postalCode").val();
        var timeDifference = $("#timeDifference").val();
        var tax = $("#tax").val();
        var dateAp = $("#dateAp").val();
        var phone = $("#phone").val();
        var fax = $("#fax").val();
        var companie = $("#companie").val();

        if ($("#arqueoCaja").is(':checked')) {

            var arqueoCaja = "on";

        } else {

            var arqueoCaja = "off";

        }


        $("#btnSaveBranchoffices").attr("disabled", true);

        var datos = new FormData();
        datos.append("idBranchoffices", idBranchoffices);
        datos.append("key", key);
        datos.append("name", name);
        datos.append("cologne", cologne);
        datos.append("city", city);
        datos.append("postalCode", postalCode);
        datos.append("timeDifference", timeDifference);
        datos.append("tax", tax);
        datos.append("dateAp", dateAp);
        datos.append("phone", phone);
        datos.append("fax", fax);
        datos.append("companie", companie);
        datos.append("arqueoCaja", arqueoCaja);


        $.ajax({

            url: "<?= base_url('admin/branchoffices/save') ?>",
            method: "POST",
            data: datos,
            cache: false,
            contentType: false,
            processData: false,
            success: function (respuesta) {
                if (respuesta.match(/Correctamente.*/)) {

                    Toast.fire({
                        icon: 'success',
                        title: "Guardado Correctamente"
                    });

                    tableBranchoffices.ajax.reload();
                    $("#btnSaveBranchoffices").removeAttr("disabled");


                    $('#modalAddBranchoffices').modal('hide');
                } else {

                    Toast.fire({
                        icon: 'error',
                        title: respuesta
                    });

                    $("#btnSaveBranchoffices").removeAttr("disabled");


                }

            }

        }

        )

    });



    /**
     * Carga datos actualizar
     */


    /*=============================================
     EDITAR Branchoffices
     =============================================*/
    $(".tableBranchoffices").on("click", ".btnEditBranchoffices", function () {

        var idBranchoffices = $(this).attr("idBranchoffices");

        var datos = new FormData();
        datos.append("idBranchoffices", idBranchoffices);

        $.ajax({

            url: "<?= base_url('admin/branchoffices/getBranchoffices') ?>",
            method: "POST",
            data: datos,
            cache: false,
            contentType: false,
            processData: false,
            dataType: "json",
            success: function (respuesta) {


                console.log(respuesta["dateAp"]);
                $("#idBranchoffices").val(respuesta["id"]);

                $("#key").val(respuesta["key"]);
                $("#name").val(respuesta["name"]);
                $("#cologne").val(respuesta["cologne"]);
                $("#city").val(respuesta["city"]);
                $("#postalCode").val(respuesta["postalCode"]);
                $("#timeDifference").val(respuesta["timeDifference"]);
                $("#tax").val(respuesta["tax"]);
                $("#dateAp").val(respuesta["dateAp"]);
                $("#phone").val(respuesta["phone"]);
                $("#fax").val(respuesta["fax"]);
                $("#companie").val(respuesta["companie"]);
                $("#companie").trigger("change");

                var arqueoCaja = respuesta["arqueoCaja"];

                if (arqueoCaja == "null" || arqueoCaja == "NULL") {

                    arqueoCaja = respuesta["arqueoCaja"];
                }

                $("#arqueoCaja").bootstrapToggle(arqueoCaja);


            }

        })

    })


    /*=============================================
     ELIMINAR branchoffices
     =============================================*/
    $(".tableBranchoffices").on("click", ".btn-delete", function () {

        var idBranchoffices = $(this).attr("data-id");

        Swal.fire({
            title: '<?= lang('boilerplate.global.sweet.title') ?>',
            text: "<?= lang('boilerplate.global.sweet.text') ?>",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            confirmButtonText: '<?= lang('boilerplate.global.sweet.confirm_delete') ?>'
        })
                .then((result) => {
                    if (result.value) {
                        $.ajax({
                            url: `<?= base_url('admin/branchoffices') ?>/` + idBranchoffices,
                            method: 'DELETE',
                        }).done((data, textStatus, jqXHR) => {
                            Toast.fire({
                                icon: 'success',
                                title: jqXHR.statusText,
                            });


                            tableBranchoffices.ajax.reload();
                        }).fail((error) => {
                            Toast.fire({
                                icon: 'error',
                                title: error.responseJSON.messages.error,
                            });
                        })
                    }
                })
    })
</script>
<?= $this->endSection() ?>

ahora creamos el archivo app/modulosBranchoffices/modalCaptureBranchoffice.php con el siguiente código

<?= $this->include('load/toggle') ?>
<?= $this->include('julio101290\boilerplate\Views\load\select2') ?>
<?= $this->include('julio101290\boilerplate\Views\load\datatables') ?>
<?= $this->include('julio101290\boilerplate\Views\load\nestable') ?>
<!-- Extend from layout index -->
<?= $this->extend('julio101290\boilerplate\Views\layout\index') ?>

<!-- Section content -->
<?= $this->section('content') ?>

<?= $this->include('modulesBranchoffices/modalCaptureBranchoffices') ?>
<?= $this->include('modulesBranchoffices/usuariosSucursalModal') ?>

<!-- SELECT2 EXAMPLE -->
<div class="card card-default">
    <div class="card-header">
        <div class="float-right">
            <div class="btn-group">

                <button class="btn btn-primary btnAddBranchoffices" data-toggle="modal" data-target="#modalAddBranchoffices"><i class="fa fa-plus"></i>

                    <?= lang('branchoffices.add') ?>

                </button>

            </div>
        </div>
    </div>
    <div class="card-body">
        <div class="row">
            <div class="col-md-12">
                <div class="table-responsive">
                    <table id="tableBranchoffices" class="table table-striped table-hover  va-middle tableBranchoffices">
                        <thead>
                            <tr>

                                <th>#</th>
                                <th><?= lang('branchoffices.fields.key') ?></th>
                                <th><?= lang('branchoffices.fields.name') ?></th>
                                <th><?= lang('branchoffices.fields.cologne') ?></th>
                                <th><?= lang('branchoffices.fields.city') ?></th>
                                <th><?= lang('branchoffices.fields.postalCode') ?></th>
                                <th><?= lang('branchoffices.fields.timeDifference') ?></th>
                                <th><?= lang('branchoffices.fields.tax') ?></th>
                                <th><?= lang('branchoffices.fields.dateAp') ?></th>
                                <th><?= lang('branchoffices.fields.phone') ?></th>
                                <th><?= lang('branchoffices.fields.fax') ?></th>
                                <th><?= lang('branchoffices.fields.companie') ?></th>
                                <th><?= lang('branchoffices.fields.created_at') ?></th>
                                <th><?= lang('branchoffices.fields.deleted_at') ?></th>
                                <th><?= lang('branchoffices.fields.updated_at') ?></th>

                                <th><?= lang('branchoffices.fields.actions') ?> </th>

                            </tr>
                        </thead>
                        <tbody>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
<!-- /.card -->

<?= $this->endSection() ?>


<?= $this->section('js') ?>
<script>
    /**
     * Cargamos la tabla
     */

    var tableBranchoffices = $('#tableBranchoffices').DataTable({
        processing: true,
        serverSide: true,
        autoWidth: false,
        responsive: true,
        order: [
            [1, 'asc']
        ],

        ajax: {
            url: '<?= base_url('admin/branchoffices') ?>',
            method: 'GET',
            dataType: "json"
        },
        columnDefs: [{
                orderable: false,
                targets: [15],
                searchable: false,
                targets: [15]

            }],
        columns: [{
                'data': 'id'
            },

            {
                'data': 'key'
            },

            {
                'data': 'name'
            },

            {
                'data': 'cologne'
            },

            {
                'data': 'city'
            },

            {
                'data': 'postalCode'
            },

            {
                'data': 'timeDifference'
            },

            {
                'data': 'tax'
            },

            {
                'data': 'dateAp'
            },

            {
                'data': 'phone'
            },

            {
                'data': 'fax'
            },

            {
                'data': 'companie'
            },

            {
                'data': 'created_at'
            },

            {
                'data': 'deleted_at'
            },

            {
                'data': 'updated_at'
            },

            {
                "data": function (data) {
                    return `<td class="text-right py-0 align-middle">
                         <div class="btn-group btn-group-sm">
                             <button class="btn btn-warning btnEditBranchoffices" data-toggle="modal" idBranchoffices="${data.id}" data-target="#modalAddBranchoffices">  <i class=" fa fa-edit"></i></button>
                             <button class="btn btn-danger btn-delete" data-id="${data.id}"><i class="fas fa-trash"></i></button>
                             <button class="btn btn-success btn-users" data-id="${data.id}" data-toggle="modal" data-target="#modalUsuariosSucursal"><i class="fas fa-users"></i></button>
                         </div>
                         </td>`
                }
            }
        ]
    });



    $(document).on('click', '#btnSaveBranchoffices', function (e) {


        var idBranchoffices = $("#idBranchoffices").val();
        var key = $("#key").val();
        var name = $("#name").val();
        var cologne = $("#cologne").val();
        var city = $("#city").val();
        var postalCode = $("#postalCode").val();
        var timeDifference = $("#timeDifference").val();
        var tax = $("#tax").val();
        var dateAp = $("#dateAp").val();
        var phone = $("#phone").val();
        var fax = $("#fax").val();
        var companie = $("#companie").val();

        if ($("#arqueoCaja").is(':checked')) {

            var arqueoCaja = "on";

        } else {

            var arqueoCaja = "off";

        }


        $("#btnSaveBranchoffices").attr("disabled", true);

        var datos = new FormData();
        datos.append("idBranchoffices", idBranchoffices);
        datos.append("key", key);
        datos.append("name", name);
        datos.append("cologne", cologne);
        datos.append("city", city);
        datos.append("postalCode", postalCode);
        datos.append("timeDifference", timeDifference);
        datos.append("tax", tax);
        datos.append("dateAp", dateAp);
        datos.append("phone", phone);
        datos.append("fax", fax);
        datos.append("companie", companie);
        datos.append("arqueoCaja", arqueoCaja);


        $.ajax({

            url: "<?= base_url('admin/branchoffices/save') ?>",
            method: "POST",
            data: datos,
            cache: false,
            contentType: false,
            processData: false,
            success: function (respuesta) {
                if (respuesta.match(/Correctamente.*/)) {

                    Toast.fire({
                        icon: 'success',
                        title: "Guardado Correctamente"
                    });

                    tableBranchoffices.ajax.reload();
                    $("#btnSaveBranchoffices").removeAttr("disabled");


                    $('#modalAddBranchoffices').modal('hide');
                } else {

                    Toast.fire({
                        icon: 'error',
                        title: respuesta
                    });

                    $("#btnSaveBranchoffices").removeAttr("disabled");


                }

            }

        }

        )

    });



    /**
     * Carga datos actualizar
     */


    /*=============================================
     EDITAR Branchoffices
     =============================================*/
    $(".tableBranchoffices").on("click", ".btnEditBranchoffices", function () {

        var idBranchoffices = $(this).attr("idBranchoffices");

        var datos = new FormData();
        datos.append("idBranchoffices", idBranchoffices);

        $.ajax({

            url: "<?= base_url('admin/branchoffices/getBranchoffices') ?>",
            method: "POST",
            data: datos,
            cache: false,
            contentType: false,
            processData: false,
            dataType: "json",
            success: function (respuesta) {


                console.log(respuesta["dateAp"]);
                $("#idBranchoffices").val(respuesta["id"]);

                $("#key").val(respuesta["key"]);
                $("#name").val(respuesta["name"]);
                $("#cologne").val(respuesta["cologne"]);
                $("#city").val(respuesta["city"]);
                $("#postalCode").val(respuesta["postalCode"]);
                $("#timeDifference").val(respuesta["timeDifference"]);
                $("#tax").val(respuesta["tax"]);
                $("#dateAp").val(respuesta["dateAp"]);
                $("#phone").val(respuesta["phone"]);
                $("#fax").val(respuesta["fax"]);
                $("#companie").val(respuesta["companie"]);
                $("#companie").trigger("change");

                var arqueoCaja = respuesta["arqueoCaja"];

                if (arqueoCaja == "null" || arqueoCaja == "NULL") {

                    arqueoCaja = respuesta["arqueoCaja"];
                }

                $("#arqueoCaja").bootstrapToggle(arqueoCaja);


            }

        })

    })


    /*=============================================
     ELIMINAR branchoffices
     =============================================*/
    $(".tableBranchoffices").on("click", ".btn-delete", function () {

        var idBranchoffices = $(this).attr("data-id");

        Swal.fire({
            title: '<?= lang('boilerplate.global.sweet.title') ?>',
            text: "<?= lang('boilerplate.global.sweet.text') ?>",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            confirmButtonText: '<?= lang('boilerplate.global.sweet.confirm_delete') ?>'
        })
                .then((result) => {
                    if (result.value) {
                        $.ajax({
                            url: `<?= base_url('admin/branchoffices') ?>/` + idBranchoffices,
                            method: 'DELETE',
                        }).done((data, textStatus, jqXHR) => {
                            Toast.fire({
                                icon: 'success',
                                title: jqXHR.statusText,
                            });


                            tableBranchoffices.ajax.reload();
                        }).fail((error) => {
                            Toast.fire({
                                icon: 'error',
                                title: error.responseJSON.messages.error,
                            });
                        })
                    }
                })
    })
</script>
<?= $this->endSection() ?>

Ahora sigue el código del modal para capturar/editar los datos de la sucursal

<?= $this->include('load/toggle') ?>
<?= $this->include('julio101290\boilerplate\Views\load\select2') ?>
<?= $this->include('julio101290\boilerplate\Views\load\datatables') ?>
<?= $this->include('julio101290\boilerplate\Views\load\nestable') ?>
<!-- Extend from layout index -->
<?= $this->extend('julio101290\boilerplate\Views\layout\index') ?>

<!-- Section content -->
<?= $this->section('content') ?>

<?= $this->include('modulesBranchoffices/modalCaptureBranchoffices') ?>
<?= $this->include('modulesBranchoffices/usuariosSucursalModal') ?>

<!-- SELECT2 EXAMPLE -->
<div class="card card-default">
    <div class="card-header">
        <div class="float-right">
            <div class="btn-group">

                <button class="btn btn-primary btnAddBranchoffices" data-toggle="modal" data-target="#modalAddBranchoffices"><i class="fa fa-plus"></i>

                    <?= lang('branchoffices.add') ?>

                </button>

            </div>
        </div>
    </div>
    <div class="card-body">
        <div class="row">
            <div class="col-md-12">
                <div class="table-responsive">
                    <table id="tableBranchoffices" class="table table-striped table-hover  va-middle tableBranchoffices">
                        <thead>
                            <tr>

                                <th>#</th>
                                <th><?= lang('branchoffices.fields.key') ?></th>
                                <th><?= lang('branchoffices.fields.name') ?></th>
                                <th><?= lang('branchoffices.fields.cologne') ?></th>
                                <th><?= lang('branchoffices.fields.city') ?></th>
                                <th><?= lang('branchoffices.fields.postalCode') ?></th>
                                <th><?= lang('branchoffices.fields.timeDifference') ?></th>
                                <th><?= lang('branchoffices.fields.tax') ?></th>
                                <th><?= lang('branchoffices.fields.dateAp') ?></th>
                                <th><?= lang('branchoffices.fields.phone') ?></th>
                                <th><?= lang('branchoffices.fields.fax') ?></th>
                                <th><?= lang('branchoffices.fields.companie') ?></th>
                                <th><?= lang('branchoffices.fields.created_at') ?></th>
                                <th><?= lang('branchoffices.fields.deleted_at') ?></th>
                                <th><?= lang('branchoffices.fields.updated_at') ?></th>

                                <th><?= lang('branchoffices.fields.actions') ?> </th>

                            </tr>
                        </thead>
                        <tbody>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
<!-- /.card -->

<?= $this->endSection() ?>


<?= $this->section('js') ?>
<script>
    /**
     * Cargamos la tabla
     */

    var tableBranchoffices = $('#tableBranchoffices').DataTable({
        processing: true,
        serverSide: true,
        autoWidth: false,
        responsive: true,
        order: [
            [1, 'asc']
        ],

        ajax: {
            url: '<?= base_url('admin/branchoffices') ?>',
            method: 'GET',
            dataType: "json"
        },
        columnDefs: [{
                orderable: false,
                targets: [15],
                searchable: false,
                targets: [15]

            }],
        columns: [{
                'data': 'id'
            },

            {
                'data': 'key'
            },

            {
                'data': 'name'
            },

            {
                'data': 'cologne'
            },

            {
                'data': 'city'
            },

            {
                'data': 'postalCode'
            },

            {
                'data': 'timeDifference'
            },

            {
                'data': 'tax'
            },

            {
                'data': 'dateAp'
            },

            {
                'data': 'phone'
            },

            {
                'data': 'fax'
            },

            {
                'data': 'companie'
            },

            {
                'data': 'created_at'
            },

            {
                'data': 'deleted_at'
            },

            {
                'data': 'updated_at'
            },

            {
                "data": function (data) {
                    return `<td class="text-right py-0 align-middle">
                         <div class="btn-group btn-group-sm">
                             <button class="btn btn-warning btnEditBranchoffices" data-toggle="modal" idBranchoffices="${data.id}" data-target="#modalAddBranchoffices">  <i class=" fa fa-edit"></i></button>
                             <button class="btn btn-danger btn-delete" data-id="${data.id}"><i class="fas fa-trash"></i></button>
                             <button class="btn btn-success btn-users" data-id="${data.id}" data-toggle="modal" data-target="#modalUsuariosSucursal"><i class="fas fa-users"></i></button>
                         </div>
                         </td>`
                }
            }
        ]
    });



    $(document).on('click', '#btnSaveBranchoffices', function (e) {


        var idBranchoffices = $("#idBranchoffices").val();
        var key = $("#key").val();
        var name = $("#name").val();
        var cologne = $("#cologne").val();
        var city = $("#city").val();
        var postalCode = $("#postalCode").val();
        var timeDifference = $("#timeDifference").val();
        var tax = $("#tax").val();
        var dateAp = $("#dateAp").val();
        var phone = $("#phone").val();
        var fax = $("#fax").val();
        var companie = $("#companie").val();

        if ($("#arqueoCaja").is(':checked')) {

            var arqueoCaja = "on";

        } else {

            var arqueoCaja = "off";

        }


        $("#btnSaveBranchoffices").attr("disabled", true);

        var datos = new FormData();
        datos.append("idBranchoffices", idBranchoffices);
        datos.append("key", key);
        datos.append("name", name);
        datos.append("cologne", cologne);
        datos.append("city", city);
        datos.append("postalCode", postalCode);
        datos.append("timeDifference", timeDifference);
        datos.append("tax", tax);
        datos.append("dateAp", dateAp);
        datos.append("phone", phone);
        datos.append("fax", fax);
        datos.append("companie", companie);
        datos.append("arqueoCaja", arqueoCaja);


        $.ajax({

            url: "<?= base_url('admin/branchoffices/save') ?>",
            method: "POST",
            data: datos,
            cache: false,
            contentType: false,
            processData: false,
            success: function (respuesta) {
                if (respuesta.match(/Correctamente.*/)) {

                    Toast.fire({
                        icon: 'success',
                        title: "Guardado Correctamente"
                    });

                    tableBranchoffices.ajax.reload();
                    $("#btnSaveBranchoffices").removeAttr("disabled");


                    $('#modalAddBranchoffices').modal('hide');
                } else {

                    Toast.fire({
                        icon: 'error',
                        title: respuesta
                    });

                    $("#btnSaveBranchoffices").removeAttr("disabled");


                }

            }

        }

        )

    });



    /**
     * Carga datos actualizar
     */


    /*=============================================
     EDITAR Branchoffices
     =============================================*/
    $(".tableBranchoffices").on("click", ".btnEditBranchoffices", function () {

        var idBranchoffices = $(this).attr("idBranchoffices");

        var datos = new FormData();
        datos.append("idBranchoffices", idBranchoffices);

        $.ajax({

            url: "<?= base_url('admin/branchoffices/getBranchoffices') ?>",
            method: "POST",
            data: datos,
            cache: false,
            contentType: false,
            processData: false,
            dataType: "json",
            success: function (respuesta) {


                console.log(respuesta["dateAp"]);
                $("#idBranchoffices").val(respuesta["id"]);

                $("#key").val(respuesta["key"]);
                $("#name").val(respuesta["name"]);
                $("#cologne").val(respuesta["cologne"]);
                $("#city").val(respuesta["city"]);
                $("#postalCode").val(respuesta["postalCode"]);
                $("#timeDifference").val(respuesta["timeDifference"]);
                $("#tax").val(respuesta["tax"]);
                $("#dateAp").val(respuesta["dateAp"]);
                $("#phone").val(respuesta["phone"]);
                $("#fax").val(respuesta["fax"]);
                $("#companie").val(respuesta["companie"]);
                $("#companie").trigger("change");

                var arqueoCaja = respuesta["arqueoCaja"];

                if (arqueoCaja == "null" || arqueoCaja == "NULL") {

                    arqueoCaja = respuesta["arqueoCaja"];
                }

                $("#arqueoCaja").bootstrapToggle(arqueoCaja);


            }

        })

    })


    /*=============================================
     ELIMINAR branchoffices
     =============================================*/
    $(".tableBranchoffices").on("click", ".btn-delete", function () {

        var idBranchoffices = $(this).attr("data-id");

        Swal.fire({
            title: '<?= lang('boilerplate.global.sweet.title') ?>',
            text: "<?= lang('boilerplate.global.sweet.text') ?>",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            confirmButtonText: '<?= lang('boilerplate.global.sweet.confirm_delete') ?>'
        })
                .then((result) => {
                    if (result.value) {
                        $.ajax({
                            url: `<?= base_url('admin/branchoffices') ?>/` + idBranchoffices,
                            method: 'DELETE',
                        }).done((data, textStatus, jqXHR) => {
                            Toast.fire({
                                icon: 'success',
                                title: jqXHR.statusText,
                            });


                            tableBranchoffices.ajax.reload();
                        }).fail((error) => {
                            Toast.fire({
                                icon: 'error',
                                title: error.responseJSON.messages.error,
                            });
                        })
                    }
                })
    })
</script>
<?= $this->endSection() ?>

Bien ahora en app/config/routes.php agregamos las siguientes rutas dentro del grupo admin

    
    $routes->resource('branchoffices', [
        'filter' => 'permission:branchoffices-permission',
        'controller' => 'branchofficesController',
        'except' => 'show'
    ]);

    $routes->post('branchoffices/save', 'BranchofficesController::save');
    $routes->post('branchoffices/getBranchoffices', 'BranchofficesController::getBranchoffices');

$routes->get('sucursales/usuariosPorSucursal/(:any)', 'BranchofficesController::usuariosPorSucursal/$1');
    $routes->post('sucursales/activarDesactivar', 'BranchofficesController::activarDesactivar');
    $routes->post('sucursales/getSucursalesAjax', 'BranchofficesController::getSucursalesAjax');

Creamos el menú de sucursales con los siguientes datos

Y listo ya tenemos nuestro modulo hecho

Video demostrativo

Anterior

Creando CRUD de productos #07

Siguiente

Creando CRUD de Series Electrónicas #10

2 comentarios

  1. Cardoso Bralio

    SALUDOS falto mensionar la modificacion del modelo empresas es decir el mdlEmpresasPorUsuarios. de la cual se creo otra tabla mas llamada Empresas_usuarios ………. supongo ya que me genero errores al hacer estos pasos

Deja un comentario

Creado con WordPress & Tema de Anders Norén

Discover more from Cesar Systems

Subscribe now to keep reading and get access to the full archive.

Continue Reading