Herramientas Informaticas

Categoría: MYSQL;CONECTAR PHP MYSQL

Cómo crear un módulo de kardex de inventario en CodeIgniter 4 #12

El kardex de inventario es un documento o sistema de registro que permite llevar un control de las entradas y salidas de mercancías o productos en un almacén. En él se registran los datos básicos de cada producto, como el código, la descripción, la unidad de medida, el precio unitario y el stock.

El kardex de inventario es una herramienta fundamental para la gestión del inventario. Permite conocer la cantidad de cada producto en existencia, así como su valor total. También ayuda a identificar las tendencias de consumo y a detectar posibles problemas de desabastecimiento.

El kardex de inventario se puede llevar de forma manual o automatizada. En el caso de la gestión manual, el registro se realiza en una hoja de cálculo o en un libro. En el caso de la gestión automatizada, el registro se realiza en un sistema informático.

Los datos que se registran en el kardex de inventario son los siguientes:

  • Código: Identificador único del producto.
  • Descripción: Nombre o descripción del producto.
  • Unidad de medida: Unidad en la que se mide el producto (unidades, kilos, metros, etc.).
  • Precio unitario: Precio de venta o de compra del producto.
  • Stock inicial: Cantidad de producto en existencia al inicio del periodo.
  • Entradas: Cantidad de producto que ha entrado en el almacén durante el periodo.
  • Salidas: Cantidad de producto que ha salido del almacén durante el periodo.
  • Stock final: Cantidad de producto en existencia al final del periodo.

El kardex de inventario se actualiza con cada movimiento de inventario. Cuando se recibe un producto, se registra la entrada con la cantidad recibida y el precio unitario. Cuando se vende un producto, se registra la salida con la cantidad vendida y el precio unitario.

El kardex de inventario es una herramienta esencial para la gestión del inventario. Permite conocer la cantidad de cada producto en existencia, así como su valor total. También ayuda a identificar las tendencias de consumo y a detectar posibles problemas de desabastecimiento.

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

CI4JCPOS – INTRODUCCION #01

En esta serie de publicaciones vamos a hacer un sistema de punto de venta con el Framework de PHP CodeIgniter 4

El sistema será igual al JCPOS que ya veníamos haciendo pero con todas las ventajas que ofrece CodeIgniter

Primero crearemos el proyecto con Composer

composer create-project codeigniter4/appstarter ci4jcpos

Creamos nuestra base de datos en phpmyadmin con el nombre ci4jcpos

CREATE SCHEMA ci4jcpos DEFAULT CHARACTER SET utf8 COLLATE utf8_spanish2_ci

Ahora instalamos la plantilla boilerplate el cual nos instalara la plantilla adminlte3 con el administrador de usuario auth, lo instalamos corriendo el siguiente comando dentro del proyecto

En mi caso yo deje en así app/config/database.php

    public array $default = [
        'DSN'      => '',
        'hostname' => '127.0.0.1',
        'username' => 'root',
        'password' => '',
        'database' => 'ci4jcpos',
        'DBDriver' => 'MySQLi',
        'DBPrefix' => '',
        'pConnect' => false,
        'DBDebug'  => true,
        'charset'  => 'utf8',
        'DBCollat' => 'utf8_general_ci',
        'swapPre'  => '',
        'encrypt'  => false,
        'compress' => false,
        'strictOn' => false,
        'failover' => [],
        'port'     => 3306,
    ];
composer require julio101290/boilerplate

Ahora siguiente las instrucciones del paquete https://packagist.org/packages/julio101290/boilerplate corremos el comando migrate para auth

php spark auth:publish

Publish Migration? [y, n]: y
  created: Database/Migrations/2017-11-20-223112_create_auth_tables.php
  Remember to run `spark migrate -all` to migrate the database.
Publish Models? [y, n]: n
Publish Entities? [y, n]: n
Publish Controller? [y, n]: n
Publish Views? [y, n]: n
Publish Filters? [y, n]: n
Publish Config file? [y, n]: y
  created: Config/Auth.php
Publish Language file? [y, n]: n

En app/config/auth.php modifcamos la matriz/arreglo de $views y la dejamos asi

       public $views = [
        'login'           => 'julio101290\boilerplate\Views\Authentication\login',
        'register'        => 'julio101290\boilerplate\Views\Authentication\register',
        'forgot'          => 'julio101290\boilerplate\Views\Authentication\forgot',
        'reset'           => 'julio101290\boilerplate\Views\Authentication\reset',
        'emailForgot'     => 'julio101290\boilerplate\Views\Authentication\emails\forgot',
        'emailActivation' => 'julio101290\boilerplate\Views\Authentication\emails\activation',
    ];

En app/config/filters.php en la matriz aliases agregamos los siguientes valores, ojo, no quitar los que estaban, solo agregar los que hacen falta

public $aliases = [
    'login'      => \Myth\Auth\Filters\LoginFilter::class,
    'role'       => \julio101290\boilerplate\Filters\RoleFilter::class,
    'permission' => \julio101290\boilerplate\Filters\PermissionFilter::class,
];

Instalamos boilerplate con el siguiente comando

php spark boilerplate:install

En App/config/validation.php agregamos lo siguiente en la matriz de $$rulesSet

public $$ruleSets = [
    \Myth\Auth\Authentication\Passwords\ValidationRules::class,
];

En App/entities/users.php en la matriz $cast lo dejamos así

 protected $casts = [
        'username' => 'string',
        'email' => 'string',
        'firstname' => 'string',
        'lastname' => 'string',
        'active' => 'boolean',
        'force_pass_reset' => 'boolean',
    ];

En app/controller/home.php lo dejamos así para que entre directamente al administrador

<?php

namespace App\Controllers;

class Home extends BaseController
{
    public function index()
    {
        return redirect()->to("/admin");
    }
}

En app/config/constants.php al final del archivo le agregamos la siguiente constante para que nos permita debugear, una vez que este en producción se tiene que quitar


define("ENVIRONMENT","development");

En app/config/app.php le quita a la variable $indexPage el valor dejandolo en blanco, la variable defaultLocale y supportedLocales la dejamos con el valor “es”

public string $indexPage = '';
public string $defaultLocale = 'es';
public array $supportedLocales = ['en'];

En el archivo app/config/boilerplate.php asignamos el nombre de la app y en $i18n que es para el lenguaje de los datatables lo dejamos como Spanish

Y listo ya tenemos nuestro login y adminlte3 listo para agregarle los módulos
Video Demostrativo

Control de Llamadas Creado con CodeIgniter

Un pequeño proyecto creado en el Instituto Tecnológico de Los Mochis en el cual se daban los derechos a los usuarios para realizar llamadas así como sacar reportes entre otras utilidades.

 

Para crear este sitio se uso el Framework PHP llamado CodeIgniter, MySQL, JavaScript, Ajax,JQuery  Y JQuery Mobile

 

Sin título

El sistema cuenta con soporte visual para dispositivos móviles gracias a JQuery mobile.

 

PROBAR SITIO

Función PHP que cuenta el numero de filas en una consulta

php-logo

Para obtener estadísticas necesitamos el numero de filas de una consulta, ejemplo, numero total de usuarios activos etc.

A continuación les dejo la función que obtiene el numero de filas de una consulta

Supongamos que el archivo se llama consulta.php y esta en la carpeta modelo

//LOS VALORES QUE PONDRIAMOS AQUI SERIA EL CAMPO Y LUEGO EL DATO CON EL QUE QUEREMOS COMPARAR

function datoBuscar($campo,$dato){

    

    include ("configuracion.php");

    $enlace = conectar_mysql($servidor,$usuario,$contra,$bd);

        

    $alumnos = "SELECT $campo FROM vmlzj_comprofiler WHERE $campo='$dato'";

    $resultado = mysql_query($alumnos,$enlace);

        

    $numeroFilas = mysql_num_rows($resultado);

        

    return $numeroFilas;

}

Para mandarlo llamar seria de la siguiente manera

 

<?php 

include ("conexionmysql.php");

//SE INCLUYE EL ARCHIVO

include ("modelo/consultas.php");

 

$egreT = datoBuscar("campo","datoAcomparar"); 

 

 

?>

Les dejo también la función de conectar_mysql()

<?php

/*******************************************************************************************************************

*                             DESCRIPCION: ESTE ARCHIVO TIENE LA FUNCIONDE CONECTAR CON LA BASE DE DATOS.             *

*                             PROGRAMADOR:                                                                         *

*                             FECHA:          01/07/2012                                                               *

********************************************************************************************************************/

 

function conectar_mysql($direccion,$usuario,$password,$basededatos)

    {

    global $enlace;

    if(!($enlace=mysql_connect($direccion,$usuario,$password)))

        {

        echo " alert('error de conexion')";

        exit();

        }

    if(!(mysql_select_db($basededatos,$enlace)))

        {

        echo " alert('error al conectar con la base de datos')";

        exit();

        }

    return $enlace;

    }

?>

CREAR UN ARCHIVO PDF DESDE PHP

A CONTINUACIÓN LES DEJO UN ARHIVO PARA PODER GENERAR UN ARCHIVO PDF CON PHP.

PARA ELLO UTILIZAREMOS LA LIBRERIA DE EZPDF

ABAJO EL CODIGO FUENTE

   1: <?php

   2:  

   3: //DomPDF 

   4:  

   5:  

   6: require_once('class.ezpdf.php'); //IMPORTAMOS LA LIBRERIA DE EZPDF

   7: include ('conexionmysql.php');   //IMPORTAMOS LA LIBRERIA PARA REALIZAR LA CONEXIÓN CON MYSQL

   8:  

   9: $pdf =& new Cezpdf('LETTER');                //SELECCIONAMOS EL EL TAMAÑO DE HOJA DEL ARCHIVO PDF, EN ESTE CASO SERA TAMAÑO CARTA

  10: $pdf->selectFont('../fonts/courier.afm');    //SELECCIONAMOS EL TIPO DE LETRA

  11: $pdf->ezSetCmMargins(1,1,1.5,1.5);           //AQUI VA LOS MARGENES DE LAHOJA

  12:  

  13:     

  14:     //GUARDAREMOS EN UNA VARIABLE LOS DATOS PARA LA CONEXIÓN AL GESTOR DE BASE DE DATOS

  15:     $direccion1="localhost";

  16:     $usuario1="root";

  17:     $password1="";

  18:     $basededatos1="bd_itlm";

  19:  

  20:  

  21:     //NOS CONECTAMOS A LA BASE DE DATOS LLAMANDO LA FUNCIÓN cononectar_mysql() UTILIZANDO LAS VARIABLES DE ARRIBA

  22:     conectar_mysql("$direccion1","$usuario1","$password1","$basededatos1");

  23:  

  24:  

  25: //GUARDAMOS LA CADENA PARA REALIZAR LA CONSULTA

  26: $Presta = "SELECT * FROM usuarios ORDER BY id ASC";

  27:  

  28: //EJECUTAMOS LA CONSULTA Y GUARDAMOS EL RESULTADO EN UNA VARIABLE

  29: $resPres = mysql_query($Presta);

  30:  

  31: //GUARDAMOS EL NUEMRO DE FILAS EN OTRA VARIABLE

  32: $total_presta = mysql_num_rows($resPres);

  33:  

  34:  

  35: $ixx = 0;

  36: while($datatmp = mysql_fetch_assoc($resPres)){

  37:     $ixx = $ixx+1;

  38:     $data[] = array_merge($datatmp, array('num'=>$ixx));

  39: }

  40: $titles = array(

  41:                 'id'=>'id',

  42:                 'usuario'=>'solicitante',

  43:                 'clave'=>'clave',

  44:             );

  45: $options = array(

  46:                 'shadeCol'=>array(0.9,0.9,0.9),

  47:                 'xOrientation'=>'center',

  48:                 'width'=>500

  49:             );

  50: $txttit = "Instituto Tecnológico de Los Mochisn";

  51: $txttit.= "Reporte general de prestamos de edificiosn";

  52:  

  53: $pdf->ezimage("escudo.jpg",0,150,'none','center');        

  54: $pdf->ezText($txttit, 12);

  55: $pdf->ezTable($data, $titles, '', $options);

  56: $pdf->ezText("nnn", 10);

  57: $pdf->ezText("Fecha: ".date("d/m/Y"), 10);

  58: $pdf->ezText("Hora: ".date("H:i:s")."nn", 10);

  59: ob_end_clean();                        

  60: $pdf->ezStream();

  61: ?>

LES DEJO LAS LIBRERIAS Y CODIGOS FUENTE PARA QUE LO PUEDAN DESCARGAR, EN ESTE ENLACE ESTA TODO JUNTO CON EL EJEMPLO

DESCARGAR

 

 

EN ESTE ENLACE ESTA NOMAS LA LIBRERIA ORIGINAL PARA GENERAR EL PDF

DESCARGAR EZPDF

Acceso a un sistema con PHP, MySQL

 

php-logo

Utilizando las funciones de MySQL AES_ENCRYPT

   1: 

   2:  

   3: INGRESO AL SISTEMA 

   4: <?php

   5: /*******************************************************************************************************************

   6: *                             DESCRIPCION: ESTE ARCHIVO TIENE LA FUNCION DE CONECTAR CON LA BASE DE DATOS.             *

   7: *                             PROGRAMADOR: JULIO CESAR LEYVA RODRIGUEZ.                                               *

   8: *                             FECHA:          01/07/2012                                                               *

   9: ********************************************************************************************************************/

  10:  

  11:  

  12:  

  13: function conectar_mysql($direccion,$usuario,$password,$basededatos)

  14:     {

  15:     global $enlace;

  16:     if(!($enlace=mysql_connect($direccion,$usuario,$password)))

  17:         {

  18:         echo " alert('error de conexion')";

  19:         exit();

  20:         }

  21:     if(!(mysql_select_db($basededatos,$enlace)))

  22:         {

  23:         echo " alert('error al conectar con la base de datos')";

  24:         exit();

  25:         }

  26:     return $enlace;

  27:     }

  28:     

  29: function desconectar()

  30:     {

  31:     mysql_close($enlace);

  32:     }

  33:  

  34:     

  35:     

  36:     /*FUNCION QUE TE PERMITIRA VALIDAR SI UN CAMPO TE TEXTO ESTA VACIO

  37: 

  38:     Esta función se puede usar en un condición "if" */

  39:  

  40:      

  41:  

  42:      function validar_campo($campo)

  43:  

  44:         {

  45:  

  46:         if($campo=="")

  47:  

  48:            return(true);

  49:  

  50:           

  51:  

  52:        else

  53:  

  54:            return(false);

  55:  

  56:        }

  57:     function buscar($data)

  58:     {

  59:         

  60:     $total = mysql_num_rows(mysql_query($data));

  61:     if($total==0)

  62:         return(false);

  63:     else

  64:         return(true);

  65:     }

  66:     

  67:     ?>

  68:     

  69:     <form id "acceso" name "acceso" method="post" action="index.php">

  70:     

  71:     <table  border='0' align="Center">

  72:         

  73:         

  74:         

  75:             

  76:                 <img align="Center" src="http://1.bp.blogspot.com/_JrrrT5TM9lQ/SV8pjlllv0I/AAAAAAAAACQ/OpyoqSeY_SY/s320/escudo.jpg" 

  77:                     border="0" width="200" height="200">

  78:             

  79:         

  80:     

  81:     

  82:     <table align="center">

  83:         

  84:         

  85:             <td align = "center">

  86:         

  87:             USUARIO

  88:             

  89:             

  90:         

  91:         

  92:             

  93:             

  94:             <input name="usuario" type="text"/>

  95:             

  96:         

  97:         

  98:         

  99:         

 100:             <td align = "center">

 101:         

 102:             PASSWORD

 103:             

 104:             

 105:         

 106:         

 107:             

 108:             

 109:             <input name="pass" type="password"/>

 110:             

 111:         

 112:         

 113:         

 114:             <td align="center">

 115:              <input type="submit" name="Submit" value="Accesar">

 116:             

 117:         

 118:     

 119:     

 120:     

 121: <?php

 122: $usuario=@$_POST['usuario'];

 123: $password=@$_POST['pass'];

 124: $llave="millave";

 125: if(validar_campo($usuario)==false && validar_campo($password)==false)

 126:     {

 127:     $direccion1="localhost";

 128:     $usuario1="root";

 129:     $password1="";

 130:     $basededatos1="bd_itlm";

 131:     conectar_mysql($direccion1,$usuario1,$password1,$basededatos1);

 132:  

 133:     

 134:      $busqueda = "SELECT * FROM usuarios WHERE usuario='$usuario' AND 

 135:                                             clave=AES_ENCRYPT('$password','$llave')";

 136:     

 137:     if(buscar($busqueda)==true)

 138:         {

 139:         Echo " alert('ENCONTRADO')";

 140:         }

 141:     else

 142:         {

 143:         Echo " alert('NO ENCONTRADO')";

 144:         }

 145:     }

 146: ?>

 147:     

 148: 

Script para conectar PHP con Mysql

php-logo
Les dejo un código que hice hace unos meses, lo hice para hacer eso de la conexión en una sola línea y no andar perdiendo tiempo
Son dos funciones hasta ahora, una para conectar y otra para desconectar,he pensado hacer el de liberar resultados entre otros pero aun no le veo ventaja.
A veces es necesario hacer esto para ahorrar tiempo, cuando utilizas muchas veces la misma conexión.

   1: <?php
   2: /*******************************************************************************************************************
   3: *                             DESCRIPCION: ESTE ARCHIVO TIENE LA FUNCION DE CONECTAR CON LA BASE DE DATOS.             *
   4: *                             PROGRAMADOR: JULIO CESAR LEYVA RODRIGUEZ.                                               *
   5: *                             FECHA:          01/07/2012                                                               *
   6: ********************************************************************************************************************/
   7:  
   8: function conectar_mysql($direccion,$usuario,$password,$basededatos)
   9:     {
  10:     global $enlace;
  11:     if(!($enlace=mysql_connect($direccion,$usuario,$password)))
  12:         {
  13:         echo " alert('error de conexion')";
  14:         exit();
  15:         }
  16:     if(!(mysql_select_db($basededatos,$enlace)))
  17:         {
  18:         echo " alert('error al conectar con la base de datos')";
  19:         exit();
  20:         }
  21:     return $enlace;
  22:     }
  23:     
  24: function desconectar()
  25:     {
  26:     mysql_close($enlace);
  27:     }
  28: ?>

Ya en el momento de invocarla seria

   1: <?php
   2:  
   3: include "conexionmysql.php";
   4:  
   5: //ESTOS DATOS LOS PUEDES TENER EN OTRO ARCHIVO PHP TE AHORRARIA TIEMPO
   6: $direccion="mysql12.000webhost.com";
   7: $usuario="a5270459_tec";
   8: $pass="Tec101290";
   9: $bd="a5270459_tec";
  10:  
  11: conectar_mysql("$direccion","$usuario","$pass","$bd");
  12:  
  13: ?>

O también lo puedes hacer directamente sin variables

   1: <?php
   2:  
   3: include "conexionmysql.php";
   4:  
   5:  
   6: conectar_mysql("localhost","tuUsuraio","tuPassword","TuBaseDeDatos");
   7:  
   8: ?>

A si este ultimo no les sale traten sin las comillas x) no recuerdo en este momento si llevan x)

Creado con WordPress & Tema de Anders Norén