jueves, 25 de julio de 2013

Base de datos con codigo QR


Un sistema simple de patrimonio para una pequeña pime con codigo QR
Si tenemos una impresora de codigo QR y un lector o smartphone con lector de QR
podemos tener un sistema de inventario bastante simple e interesante.

En etapa de testeo v0.3



Una vez que tenemos el server instalado y funcionando.
por las dudas, dejo los paquetes que instale yo antes de hacer todo:
apache2 mysql-server php5 php5-mysql php5-gd libapache2-mod-php5


descargamos el Yii framekork


Entrar al directorio del apache:
jonathan@cfh ~$ cd /var/www/

Descargar el tar del framework:
jonathan@cfh /var/www$ wget http://yii.googlecode.com/files/yii-1.1.13.e9e4a0.tar.gz

Descomprimir:
jonathan@cfh /var/www$ tar -xzvf yii-1.1.13.e9e4a0.tar.gz

cambiar nombre para mas comodidad:(detalle personal)
jonathan@cfh /var/www$ sudo mv yii-1.1.13.e9e4a0 yii

Esta parte no estoy 100% seguro, asi que momentaneamente le asigno todos los permisos a la carpeta para poder trabajar
sin problemas, una vez finalizado obiamente debemos poner los permisos apropiados para no dejar "regalado" el servidor.
Cuando termine de analizarlo colocare bien que permisos corresponden a cada carpeta.

Asignar permisos:
jonathan@cfh /var/www$ sudo chmod -R 777 yii

Entrar al Framework
jonathan@cfh /var/www$ cd yii/framework/

Para crear nuestra nueva aplicacion web debemos colocar el siguiente comando:
jonathan@cfh /var/www/yii/framework$ ./yiic webapp  /var/www/miproyecto

./yiic = es el script para crear la aplicacion web
webapp = es el codigo que genera dicha aplicacion
/var/www/miproyecto = ruta donde queremos nuestro proyecto.



Hasta ahora ya tenemos creado la interfas web. Ahora hay que configurar la conexión a la DB,
y personalizar minimamente la interfaz y el framework en gral.


ahora vamos a configurar la conexion del framework con mysql

root@@cfh:/var/www# vim projectone/protected/config/main.php


Buscar lo siguiente:
        // autoloading model and component classes
        'import'=>array(
                'application.models.*',
                'application.components.*',
                'application.extensions.*',          // <----- Y agregar estas dos lineas
                'application.extensions.qrcode',     // <-----


En la parte de Modulos, vamos habilitar Gii (que es para crear formularios y ese tipo de cosas desde la interfaz web)

        'modules'=>array(
                // uncomment the following to enable the Gii tool

                'gii'=>array(
                        'class'=>'system.gii.GiiModule',
                        'password'=>'mipassword',
                        // If removed, Gii defaults to localhost only. Edit carefully to taste.
                        'ipFilters'=>array('127.0.0.1','::1','192.168.15.*','192.168.2.*','192.168.3.*'), // <--- Agregar las IP o redes que pueden tener acceso al framework

Habilitar estos manejadores de url: (Descomentar)

                'urlManager'=>array(
                        'urlFormat'=>'path',
                        'rules'=>array(
                                '<controller:\w+>/<id:\d+>'=>'<controller>/view',
                                '<controller:\w+>/<action:\w+>/<id:\d+>'=>'<controller>/<action>',
                                '<controller:\w+>/<action:\w+>'=>'<controller>/<action>',
                        ),
                ),

Configurar la base de datos:

                'db'=>array(
                        'connectionString' => 'mysql:host=ipdelserver;dbname=nombredemiDB',
                        'emulatePrepare' => true,
                        'username' => 'root',
                        'password' => 'pass_mysql',
                        'charset' => 'utf8',
                ),

:x!  (guardar y salir en vim)









Descargar la libreria de QR
root@@cfh:/var/www# wget http://www.yiiframework.com/extension/qr-code-generator/files/qrcode.zip

Descomprimir
root@@cfh:/var/www# unzip qrcode

copiar dentro de la carpeta de extencniones del framework
root@@cfh:/var/www# cp -rf qrcode /var/www/projectone/protected/extensions/


root@@cfh:/var/www# vim /var/www/projectone/protected/extensions/qrcode/QRCodeGenerator.php


Reemplazar /uploads por la carpeta donde estaran las imagenes del QR

    public function init()
    {
        if (is_null($this->data))
            throw new CException(Yii::t(get_class($this), 'Data must not be empty'));

                if (is_null($this->filename)){
                        $this->filename = $this->data.'.png';
                }

        if (!$this->filePath){
//            $this->filePath = realpath(Yii::app()->getBasePath().'/../uploads'); <---- Original reemplazar por el de abajo
            $this->filePath = realpath('/var/www/projectone/images');
        }

        if(!is_dir($this->filePath)){
            throw new CHttpException(500, "{$this->filePath} does not exists.");
        }else if(!is_writable($this->filePath)){
            throw new CHttpException(500, "{$this->filePath} is not writable.");
        }

        if (!isset($this->fileUrl)){
            $this->fileUrl = Yii::app()->baseUrl . '/images';
        }

:x!  (guardar y salir en vim)
















crear el index que tendra el QRcode
root@@cfh:/var/www# vim /var/www/projectone/protected/views/site/qr.php

Agregar lo siguente:

<?php
/* @var $this SiteController */

$this->pageTitle=Yii::app()->name;
?>

<h1>Acá va el QR</h1>
<br><br>

<?php $this->widget('application.extensions.qrcode.QRCodeGenerator',array(
    'data' => 'hola',
    'subfolderVar' => false,
    'matrixPointSize' => 5,
    'displayImage'=>true, // default to true, if set to false display a URL path
    'errorCorrectionLevel'=>'L', // available parameter is L,M,Q,H
    'matrixPointSize'=>4, // 1 to 10 only
)) ?>
:x!  (guardar y salir en vim)



root@@cfh:/var/www# vim /var/www/projectone/protected/views/layouts/main.php

                <?php $this->widget('zii.widgets.CMenu',array(
                        'items'=>array(
                                array('label'=>'Home', 'url'=>array('/site/index')),
                                array('label'=>'QR', 'url'=>array('/site/qr')),           // <-------- Agregar esta linea
                                array('label'=>'About', 'url'=>array('/site/page', 'view'=>'about')),
                                array('label'=>'Contact', 'url'=>array('/site/contact')),
                                array('label'=>'Login', 'url'=>array('/site/login'), 'visible'=>Yii::app()->user->isGuest),
                                array('label'=>'Logout ('.Yii::app()->user->name.')', 'url'=>array('/site/logout'), 'visible'=>!Yii::app()->user->isGuest)
                        ),

:x!  (guardar y salir en vim)



root@@cfh:/var/www# vim /var/www/projectone/protected/controllers/SiteController.php


        public function actionIndex()
        {
                // renders the view file 'protected/views/site/index.php'
                // using the default layout 'protected/views/layouts/main.php'
                $this->render('index');
        }
// Agregar las lineas de abajo
        public function actionQr()
        {
                // renders the view file 'protected/views/site/index.php'
                // using the default layout 'protected/views/layouts/main.php'
                $this->render('qr');
        }
:x!  (guardar y salir en vim)



######################## MySql

Habilitar conexiones remotas para mysql (MOMENTANEAMENTE) ya que estoy trabajando en un equipo remoto.
jonathan@cfh /var/www$ vim /etc/mysql/my.cnf

y comentar la linea "bind-address = 127.0.0.1"
quedando de esta forma:
#bind-address = 127.0.0.1

salir y reiniciar el servicio de mysql
jonathan@cfh /var/www$ sudo /etc/init.d/mysql restart


Entrar a mysql:
jonathan@cfh /var/www$ mysql -u root -p
Enter password:


Asignar permisos para conexión remota.
mysql> GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY 'mipassword' WITH GRANT OPTION;
Query OK, 0 rows affected (0.00 sec)

mysql> FLUSH PRIVILEGES;
Query OK, 0 rows affected (0.00 sec)





Para mi proyecto hice una DB básica para un sistema de inventario simple. (Doy por hecho que ya tienen la db creada)

crear tablas:

---------------------------------- TABLA CATEGORIAS ---------------------------------
CREATE TABLE `category` (                                                            
            `id` int(11) NOT NULL AUTO_INCREMENT,                                              
            `name` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,          
            PRIMARY KEY (`id`),                                                                
            UNIQUE KEY `nombre` (`name`)                                                      
          ) ENGINE=InnoDB DEFAULT CHARSET=utf8 CHECKSUM=1 DELAY_KEY_WRITE=1 ROW_FORMAT=DYNAMIC ;


---------------------------------- TABLA OFICINAS ---------------------------------
CREATE TABLE `office` (                                                        
          `id` int(11) NOT NULL AUTO_INCREMENT,                                        
          `number` int(11) NOT NULL,                                                  
          `name` varchar(100) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,
          `desc` varchar(100) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,
          PRIMARY KEY (`id`),                                                          
          UNIQUE KEY `number` (`number`)                                              
        ) ENGINE=InnoDB DEFAULT CHARSET=latin1  ;        

---------------------------------- TABLA ESTADO ---------------------------------
CREATE TABLE `status` (                                                              
          `id` int(11) NOT NULL AUTO_INCREMENT,                                              
          `name` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,          
          PRIMARY KEY (`id`),                                                                
          UNIQUE KEY `nombre` (`name`)                                                      
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8 CHECKSUM=1 DELAY_KEY_WRITE=1 ROW_FORMAT=DYNAMIC;

---------------------------------- TABLA USUARIOS ---------------------------------
CREATE TABLE `user` (                                                                
          `id` int(11) NOT NULL,                                                            
          `name` varchar(100) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,          
          `surname` varchar(100) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,    
          PRIMARY KEY (`id`)                                                                
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8 CHECKSUM=1 DELAY_KEY_WRITE=1 ROW_FORMAT=DYNAMIC;


---------------------------------- TABLA OBJETOS ---------------------------------
CREATE TABLE `object` (                                                                                      
          `id` int(11) NOT NULL AUTO_INCREMENT,                                                                      
          `category_id` int(11) NOT NULL,                                                                            
          `office_id` int(11) NOT NULL,                                                                              
          `status_id` int(11) NOT NULL,                                                                              
          `user_id` int(11) DEFAULT NULL,                                                                            
          `notes` varchar(200) COLLATE utf8_unicode_ci DEFAULT NULL,                                                  
          `internal_code` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL,                                          
          `external_code` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL,                                          
          `fact_code` varchar(250) COLLATE utf8_unicode_ci DEFAULT NULL,                                              
          `created_at` datetime DEFAULT NULL,                                                                        
          `updated_at` datetime DEFAULT NULL,                                                                        
          `description` varchar(200) COLLATE utf8_unicode_ci DEFAULT NULL,                                            
          PRIMARY KEY (`id`),                                                                                        
          KEY `categoria_id_idx` (`category_id`),                                                                    
          KEY `oficina_id_idx` (`office_id`),                                                                        
          KEY `estado_id_idx` (`status_id`),                                                                          
          KEY `persona_id_idx` (`user_id`),                                                                          
          CONSTRAINT `FK_object_category` FOREIGN KEY (`category_id`) REFERENCES `category` (`id`) ON UPDATE CASCADE,
          CONSTRAINT `FK_object_offices` FOREIGN KEY (`office_id`) REFERENCES `office` (`number`) ON UPDATE CASCADE,  
          CONSTRAINT `FK_object_status` FOREIGN KEY (`status_id`) REFERENCES `status` (`id`) ON UPDATE CASCADE,      
          CONSTRAINT `FK_object_user` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON UPDATE CASCADE              
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci CHECKSUM=1 DELAY_KEY_WRITE=1 ROW_FORMAT=DYNAMIC;  

---------------------------------- FIN TABLAS ---------------------------------



Salir de mysql
mysql> quit
Bye















































http://www.yiiframework.com/extension/qr-code-generator/files/qrcode.zip











<?php $this->widget('application.extensions.qrcode.QRCodeGenerator',array(
    'data' => 'http://www.bryantan.info',
    'subfolderVar' => false,
    'matrixPointSize' => 5,
    'displayImage'=>true, // default to true, if set to false display a URL path
    'errorCorrectionLevel'=>'L', // available parameter is L,M,Q,H
    'matrixPointSize'=>4, // 1 to 10 only
)) ?>









EXTRAS:


LISTA DE PAQUETES EXACTOS

 dpkg -l | grep -i apache
ii  apache2                               2.2.22-13                 armhf        Apache HTTP Server metapackage
ii  apache2-mpm-prefork                   2.2.22-13                 armhf        Apache HTTP Server - traditional non-threaded model
ii  apache2-utils                         2.2.22-13                 armhf        utility programs for webservers
ii  apache2.2-bin                         2.2.22-13                 armhf        Apache HTTP Server common binary files
ii  apache2.2-common                      2.2.22-13                 armhf        Apache HTTP Server common files
ii  libapache2-mod-php5                   5.4.4-14+deb7u3           armhf        server-side, HTML-embedded scripting language (Apache 2 module)
ii  libapr1                               1.4.6-3                   armhf        Apache Portable Runtime Library
ii  libaprutil1                           1.4.1-3                   armhf        Apache Portable Runtime Utility Library
ii  libaprutil1-dbd-sqlite3               1.4.1-3                   armhf        Apache Portable Runtime Utility Library - SQLite3 Driver
ii  libaprutil1-ldap                      1.4.1-3                   armhf        Apache Portable Runtime Utility Library - LDAP Driver


dpkg -l | grep -i mysql
ii  libdbd-mysql-perl                     4.021-1                   armhf        Perl5 database interface to the MySQL database
ii  libmysqlclient16                      5.1.62-1                  armhf        MySQL database client library
ii  libmysqlclient18:armhf                5.5.31+dfsg-0+wheezy1     armhf        MySQL database client library
ii  mysql-client-5.5                      5.5.31+dfsg-0+wheezy1     armhf        MySQL database client binaries
ii  mysql-common                          5.5.31+dfsg-0+wheezy1     all          MySQL database common files, e.g. /etc/mysql/my.cnf
ii  mysql-server                          5.5.31+dfsg-0+wheezy1     all          MySQL database server (metapackage depending on the latest version)
ii  mysql-server-5.5                      5.5.31+dfsg-0+wheezy1     armhf        MySQL database server binaries and system database setup
ii  mysql-server-core-5.5                 5.5.31+dfsg-0+wheezy1     armhf        MySQL database server binaries
ii  php5-mysql                            5.4.4-14+deb7u3           armhf        MySQL module for php5

dpkg -l | grep -i php
ii  libapache2-mod-php5                   5.4.4-14+deb7u3           armhf        server-side, HTML-embedded scripting language (Apache 2 module)
ii  php5                                  5.4.4-14+deb7u3           all          server-side, HTML-embedded scripting language (metapackage)
ii  php5-cli                              5.4.4-14+deb7u3           armhf        command-line interpreter for the php5 scripting language
ii  php5-common                           5.4.4-14+deb7u3           armhf        Common files for packages built from the php5 source
ii  php5-gd                               5.4.4-14+deb7u3           armhf        GD module for php5
ii  php5-mysql                            5.4.4-14+deb7u3           armhf        MySQL module for php5


Sistema Operativo - Raspbian (RaspberryPi)
Linux raspberrypi 3.6.11+ #474 PREEMPT Thu Jun 13 17:14:42 BST 2013 armv6l GNU/Linux










Helps:
http://www.yiiframework.com/
http://www.yiiframework.com/extension/qr-code-generator/

No hay comentarios:

Publicar un comentario