Bladeren bron

Create controller, view and migration to captive portal

Felipe Torretto 5 jaren geleden
bovenliggende
commit
74618adbb6

+ 22 - 0
app/DoctrineMigrations/Version20191026202258.php

@@ -0,0 +1,22 @@
+<?php
+
+namespace Application\Migrations;
+
+use Doctrine\DBAL\Migrations\AbstractMigration;
+use Doctrine\DBAL\Schema\Schema;
+
+final class Version20191026202258 extends AbstractMigration
+{
+    public function up(Schema $schema)
+    {
+        $this->addSql('CREATE TABLE captive_portal (id INT AUTO_INCREMENT NOT NULL, ip VARCHAR(15) NOT NULL, ip_range INT UNSIGNED DEFAULT 0 NOT NULL, html_page LONGTEXT NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB');
+        $this->addSql('CREATE TABLE captive_portal_audit (id INT NOT NULL, rev INT NOT NULL, ip VARCHAR(15) DEFAULT NULL, ip_range INT UNSIGNED DEFAULT 0, html_page LONGTEXT DEFAULT NULL, revtype VARCHAR(4) NOT NULL, INDEX rev_fd45fb19d647cf3f4fd978037cad8566_idx (rev), PRIMARY KEY(id, rev)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB');
+
+    }
+
+    public function down(Schema $schema)
+    {
+        $this->addSql('DROP TABLE captive_portal');
+        $this->addSql('DROP TABLE captive_portal_audit');
+    }
+}

+ 23 - 0
src/FTTHBundle/Admin/CaptivePortalAdmin.php

@@ -0,0 +1,23 @@
+<?php
+
+namespace FTTHBundle\Admin;
+
+use Base\AdminBundle\Admin\BaseAdmin;
+use Sonata\AdminBundle\Route\RouteCollection;
+
+class CaptivePortalAdmin extends BaseAdmin
+{
+    public function getDashboardActions()
+    {
+        $actions = parent::getDashboardActions();
+        $actions['configuration']['template'] = 'FTTHBundle:CaptivePortal:config_button.html.twig';
+        unset($actions['create']);
+        unset($actions['list']);
+        return $actions;
+    }
+
+    protected function configureRoutes(RouteCollection $collection)
+    {
+        $collection->add('configuration');
+    }
+}

+ 0 - 122
src/FTTHBundle/Admin/PortalCaptiveAdmin.php

@@ -1,122 +0,0 @@
-<?php
-
-namespace FTTHBundle\Admin;
-
-use Base\AdminBundle\Admin\BaseAdmin;
-use Sonata\AdminBundle\Datagrid\DatagridMapper;
-use Sonata\AdminBundle\Datagrid\ListMapper;
-use Sonata\AdminBundle\Form\FormMapper;
-use Sonata\AdminBundle\Show\ShowMapper;
-
-class PortalCaptiveAdmin extends BaseAdmin
-{
-
-    /**
-     * @param DatagridMapper $datagridMapper
-     */
-    protected function configureDatagridFilters(DatagridMapper $datagridMapper)
-    {
-        $datagridMapper
-            ->add('profile')
-            ->add('model');
-    }
-
-    /**
-     * @param ListMapper $listMapper
-     */
-    protected function configureListFields(ListMapper $listMapper)
-    {
-        $listMapper
-            ->add('model')
-            ->add('profile')
-            ->add('vlan')
-            ->add('vlanProfile')
-            ->add('onuProfile')
-            ->add('vlans')
-            ->add('trafficProfileIn')
-            ->add('trafficProfileOut')
-            ->add('tcontprofile')
-            ->add('base')
-            ->add('created')
-            ->add('_action', null, array(
-                'actions' => array(
-                    'use' => array('template' => 'FTTHBundle:ONUTemplate:action_use.html.twig'),
-                    'edit' => array(),
-                    'delete' => array()),
-            ));
-    }
-
-    /**
-     * @param FormMapper $formMapper
-     */
-    protected function configureFormFields(FormMapper $formMapper)
-    {
-        $formMapper
-            ->tab('default')
-            ->with('')
-            ->add('model')
-            ->add('profile')
-            ->add('vlans', null, array(
-                'required' => false,
-                'multiple' => true,
-            ))
-            ->add('vlan')
-            ->add('vlanProfile')
-            ->add('onuProfile')
-            ->add('trafficProfileIn')
-            ->add('trafficProfileOut')
-            ->add('tcontprofile')
-            ->add('catv')
-            ->end()
-            ->with('Extra')
-            ->add('extraData')
-            ->end()
-            ->end();
-    }
-
-    /**
-     * @param ShowMapper $showMapper
-     */
-    protected function configureShowFields(ShowMapper $showMapper)
-    {
-        $showMapper
-            ->tab('default')
-            ->with('')
-            ->add('model')
-            ->add('profile')
-            ->add('vlans')
-            ->add('vlan')
-            ->add('vlanProfile')
-            ->add('onuProfile')
-            ->add('trafficProfileIn')
-            ->add('trafficProfileOut')
-            ->add('tcontprofile')
-            ->add('created')
-            ->end()
-            ->with('Extra')
-            ->add('extraData')
-            ->end()
-            ->end();
-    }
-
-    /**
-     * @param string $action
-     * @param Object $object
-     *
-     * @return array
-     */
-    public function configureActionButtons($action, $object = null)
-    {
-        $actions = parent::configureActionButtons($action, $object);
-        $actions['disable_base'] = array('template' => 'FTTHBundle:ONUTemplate:disable_base_button.html.twig');
-
-        return $actions;
-    }
-
-    public function configure()
-    {
-        $this->setTemplate('create', 'FTTHBundle:ONUTemplate:form.html.twig');
-        $this->setTemplate('edit', 'FTTHBundle:ONUTemplate:form.html.twig');
-    }
-
-}

+ 52 - 99
src/FTTHBundle/Controller/CaptivePortalController.php

@@ -2,114 +2,67 @@
 
 namespace FTTHBundle\Controller;
 
-use Symfony\Bundle\FrameworkBundle\Controller\Controller;
-use Symfony\Component\HttpFoundation\Request;
-use Symfony\Component\HttpFoundation\JsonResponse;
-use Symfony\Component\HttpFoundation\Response;
-use FTTHBundle\Entity\ONU;
-use FTTHBundle\Entity\PreSale;
-use MapBundle\Entity\Location;
-use WebserviceBundle\Form\Type\RemoteClientType;
-use MapBundle\Form\Type\RemoteMapType;
 use FOS\RestBundle\Controller\Annotations\RouteResource;
+use FTTHBundle\Entity\CaptivePortal;
+use Sonata\AdminBundle\Controller\CRUDController;
+use Symfony\Component\Form\Extension\Core\Type\TextareaType;
+use Symfony\Component\Form\Extension\Core\Type\TextType;
+use Symfony\Component\HttpFoundation\RedirectResponse;
+use Symfony\Component\HttpFoundation\Request;
 
 /**
  * CaptivePortal controller.
+ * @RouteResource("CaptivePortal")
  */
-class CaptivePortalController extends Controller
+class CaptivePortalController extends CRUDController
 {
-
-    public function portalAction(Request $request)
+    public function configurationAction(Request $request)
     {
-
-        $client = $request->query->get('client');
-        $psn = $request->query->get('psn');
-        $preSale = $request->query->get('preSale');
-        $preSales = $errors = array();
-        $result = false;
-
-        if(!is_null($client) && !is_null($psn)) {
-
-            $em = $this->get("doctrine.orm.entity_manager");
-            $em->getFilters()->disable('tenancy_filter');
-            $preSales = $em->getRepository(PreSale::class)->findBy(array('clientId' => $client));
-            $onu = $em->getRepository(ONU::class)->findOneBy(array('ponSerialNumber' => $psn));
-        
-            if(empty($preSales)) $errors[] = "We don't register a pending installation to this client.";
-
-            if(is_null($onu)) $errors[] = "ONU doesn't exist.";
-
-            if(!is_null($preSale) && !is_null($onu)) {
-                $sale = $em->getRepository(PreSale::class)->findOneById($preSale);
-
-                if($sale) {
-                    $this->updateOnu($sale->getClientId(), $sale->getProfile(), $onu, $sale->getAddress(), $em);
-
-                    $onu = $em->getRepository(ONU::class)->findOneBy(array('ponSerialNumber' => $psn));
-
-                    if($onu->getClientId() == $sale->getClientId() && $onu->getProfile() == $sale->getProfile()) {
-                        $result = true;
-                        $em->remove($sale);
-                        $em->flush();
-
-                    }
-                }
+        $flashbag = $this->get('session')->getFlashBag();
+        $translator = $this->get('translator');
+
+        $em = $this->getDoctrine()->getManager();
+        $captivePortalRepository = $em->getRepository(CaptivePortal::class);
+
+        $configurations = $captivePortalRepository->findAll();
+        $captivePortal = empty($configurations) ? new CaptivePortal() : end($configurations);
+
+        $form = $this->createFormBuilder($captivePortal)
+            ->add('ip', TextType::class, [
+                'attr' => [
+                    'class' => 'col-xs-12',
+                    'data-mask' => '000.000.000.000',
+                ],
+                'label' => $translator->trans('form.label_captiveportal_ip', [], 'FTTHBundle'),
+            ])
+            ->add('ip_range', TextType::class, [
+                'attr' => [
+                    'class' => 'col-xs-12',
+                    'data-mask' => '00',
+                ],
+                'label' => $translator->trans('form.label_captiveportal_ip_range', [], 'FTTHBundle'),
+            ])
+            ->add('html_page', TextareaType::class, [
+                'attr' => ['class' => 'col-xs-12'],
+                'label' => $translator->trans('form.label_captiveportal_html', [], 'FTTHBundle'),
+            ])
+            ->getForm();
+
+        $request = Request::createFromGlobals();
+        $form->handleRequest($request);
+        if ($form->isSubmitted()) {
+            if ($form->isValid()) {
+                $em->persist($captivePortal);
+                $em->flush();
+                $flashbag->add('success', $translator->trans('msg_captiveportal_success', [], 'FTTHBundle'));
+            } else {
+                $flashbag->add('warning', $translator->trans('msg_captiveportal_required_fields', [], 'FTTHBundle'));
             }
-            $em->getFilters()->enable('tenancy_filter');
+            return new RedirectResponse($this->admin->generateUrl('configuration'));
         }
 
-        return $this->render('FTTHBundle:Portal:index.html.twig', array(
-            'result' => $result,
-            'errors' => $errors,
-            'preSales' => $preSales,
-            'client' => $client,
-            'psn' => $psn
-        ));
+        return $this->render('FTTHBundle:CaptivePortal:form.html.twig', [
+            'form' => $form->createView(),
+        ]);
     }
-
-    private function updateOnu($clientId, $profile, $onu, $address, $em) {
-
-        if(!is_null($address) && $this->getParameter('googlemaps_api_key')) {
-            $key = $this->getParameter('googlemaps_api_key');
-            $addr = urlencode($address);
-            
-            try {
-                $data = $this->getSslPage("https://maps.googleapis.com/maps/api/geocode/json?address={$addr}&key={$key}");
-                $data = json_decode($data,true);
-            } catch(\Exception $e) {
-                $data = array();
-            }
-
-            if($data['status'] == 'OK') {
-                $geoInformation = $data['results'][0];
-                $extraData = array();
-                $extraData['formatted_address'] = $geoInformation['formatted_address'];
-                $extraData['lat'] = $geoInformation['geometry']['location']['lat'];
-                $extraData['lng'] = $geoInformation['geometry']['location']['lng'];
-                $extraData['zoom'] = 18;
-                
-                $location = new Location();
-                $location->setJsonExtraData($extraData);
-                
-                $onu->setLocation($location);
-                $onu->setJsonExtraData($extraData);
-            }
-        } 
-
-        $onu->setClientId($clientId);
-        $onu->setProfile($profile);
-
-        $em->persist($onu);
-        $em->flush();
-    }
-
-    function getSslPage($url) {
-        $ch = curl_init();
-        curl_setopt($ch, CURLOPT_URL, $url);
-        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
-        $result = curl_exec($ch);
-        curl_close($ch);
-        return $result;
-    }
-
 }

+ 107 - 0
src/FTTHBundle/Entity/CaptivePortal.php

@@ -0,0 +1,107 @@
+<?php
+
+namespace FTTHBundle\Entity;
+
+use Doctrine\ORM\Mapping as ORM;
+use Symfony\Component\Validator\Constraints as Assert;
+
+/**
+ * @ORM\Entity
+ */
+class CaptivePortal
+{
+    /**
+     * @var int
+     *
+     * @ORM\Column(name="id", type="integer", nullable=false)
+     * @ORM\Id
+     * @ORM\GeneratedValue(strategy="AUTO")
+     */
+    private $id;
+
+    /**
+     * @var string
+     *
+     * @ORM\Column(type="string", length=15, nullable=false)
+     * @Assert\NotBlank()
+     */
+    private $ip;
+
+    /**
+     * @var string
+     *
+     * @ORM\Column(type="integer", options={"unsigned":true, "default":5})
+     * @Assert\NotBlank()
+     */
+    private $ipRange;
+
+    /**
+     * @var string
+     *
+     * @ORM\Column(type="text")
+     * @Assert\NotBlank()
+     */
+    private $htmlPage;
+
+    /**
+     * @return int
+     */
+    public function getId()
+    {
+        return $this->id;
+    }
+
+    /**
+     * @return string
+     */
+    public function getIp()
+    {
+        return $this->ip;
+    }
+
+    /**
+     * @param string $ip
+     * @return CaptivePortal
+     */
+    public function setIp($ip)
+    {
+        $this->ip = $ip;
+        return $this;
+    }
+
+    /**
+     * @return string
+     */
+    public function getIpRange()
+    {
+        return $this->ipRange;
+    }
+
+    /**
+     * @param string $ipRange
+     * @return CaptivePortal
+     */
+    public function setIpRange($ipRange)
+    {
+        $this->ipRange = $ipRange;
+        return $this;
+    }
+
+    /**
+     * @return string
+     */
+    public function getHtmlPage()
+    {
+        return $this->htmlPage;
+    }
+
+    /**
+     * @param string $htmlPage
+     * @return CaptivePortal
+     */
+    public function setHtmlPage($htmlPage)
+    {
+        $this->htmlPage = $htmlPage;
+        return $this;
+    }
+}

+ 8 - 8
src/FTTHBundle/Resources/config/services.yml

@@ -16,14 +16,6 @@ services:
         calls:
             - [setTranslationDomain, [FTTHBundle]]
 
-    sonata.admin.portalcaptive:
-        class: FTTHBundle\Admin\PortalCaptiveAdmin
-        arguments: [~, FTTHBundle\Entity\ONUTemplate, BaseAdminBundle:CRUD]
-        tags:
-            - { name: sonata.admin, manager_type: orm, group: FTTH, label: PortalCaptive, label_catalogue: FTTHBundle, label_translator_strategy: sonata.admin.label.strategy.underscore }
-        calls:
-            - [setTranslationDomain, [FTTHBundle]]
-
     sonata.admin.olt:
         class: FTTHBundle\Admin\OLTAdmin
         arguments: [~, FTTHBundle\Entity\OLT, WorkflowBundle:CRUD]
@@ -139,6 +131,14 @@ services:
         calls:
             - [setTranslationDomain, [FTTHBundle]]
 
+    sonata.admin.captiveportal:
+        class: FTTHBundle\Admin\CaptivePortalAdmin
+        arguments: [~, FTTHBundle\Entity\CaptivePortal, FTTHBundle:CaptivePortal]
+        tags:
+            - { name: sonata.admin, manager_type: orm, group: FTTH, label: CaptivePortal, label_catalogue: FTTHBundle, label_translator_strategy: sonata.admin.label.strategy.underscore }
+        calls:
+            - [setTranslationDomain, [FTTHBundle]]
+
     ftth.twig_show_file_system_extension:
        class: FTTHBundle\Twig\ShowFileSystemExtension
        arguments: ["@service_container"]

+ 8 - 1
src/FTTHBundle/Resources/translations/FTTHBundle.es.yml

@@ -10,7 +10,7 @@ NAP: NAP
 Profile: Perfil
 olt_execute_time: Tiempo(min) entre consultas a OLT
 ONUTemplate: Plantilla ONU
-PortalCaptive: Portal Captive
+CaptivePortal: Portal Cautivo
 olt_discovery_configuration: Configuración Autodiscovery
 autodiscovery: Autodiscovery
 PreSale: Preventa
@@ -182,6 +182,9 @@ form:
     label_discovery_profile: Perfíl
     label_date: Fecha
     label_radius_auth: Autenticación en Radius
+    label_captiveportal_ip: IP
+    label_captiveportal_ip_range: Rango de IP
+    label_captiveportal_html: HTML
 
 list:
     label_id: Id
@@ -384,10 +387,13 @@ msg_no_onu_in_map: No existen ONUs definidas en el módulo de Mapas.
 msg_select_map: Seleccione el Mapa desde el que se importarán las ONUs y el cliente al que se asociarán.
 import: Importador
 button_import: Importar
+button_save: Guardar
 alert_select_map_client: Debe seleccionar un mapa y cliente
 msg_import_onu: Importar ONUs
 msg_init_import: Iniciando importación, espere un momento.
 msg_end_import: FIN :)
+msg_captiveportal_required_fields: Los datos del portal cautivo no están definidos.
+msg_captiveportal_success: Los datos del portal cautivo se han guardado con éxito.
 nap.capacity.max: El NAP seleccionado sobrepasó su capacidad de %capacity% ONUs. Tiene %count% ONUs asociadas
 Address: Dirección
 out_of_range: FUERA DE RANGO
@@ -411,6 +417,7 @@ msg_use_template_onu_in_create_onu_ftth: Se encuentra en uso una plantilla de ON
 client_filter_help: Ingresar nombre de cliente, ID o externalID
 error_onu_position: La posición dentro del puerto seleccionada ya se encuentra asignada a otra ONU
 
+Configuration: Configuración
 Stats: Estadísticas
 Show stats: Mostrar detalle
 Set 0 to disable autodiscovery or set a x number to scan each x minutes the ONUs connected but without configuration: Seleccione 0 para deshabilitar la función 'Autodiscovery' o seleccione un valor x para escanear cada x minutos las ONUs conectadas pero sin configurar. 

+ 4 - 0
src/FTTHBundle/Resources/views/CaptivePortal/config_button.html.twig

@@ -0,0 +1,4 @@
+<a class="btn btn-link btn-flat" href="{{ admin.generateUrl('configuration') }}">
+    <i class="fa fa-gear"></i>
+    {{ 'Configuration'|trans({}, 'FTTHBundle') }}
+</a>

+ 119 - 0
src/FTTHBundle/Resources/views/CaptivePortal/form.html.twig

@@ -0,0 +1,119 @@
+{% extends 'SonataAdminBundle:CRUD:base_list.html.twig' %}
+
+{% block stylesheets %}
+    {{ parent() }}
+
+    <style>
+        footer {
+            z-index: 1100;
+        }
+
+        .container-fluid {
+            padding-left: 0px;
+            padding-right: 0px;
+        }
+
+        .container-fluid div.row {
+            padding-left: 15px;
+            padding-right: 15px;
+        }
+
+        .bold-title {
+            font-weight: bold
+        }
+
+        #console-message {
+            box-shadow: none;
+            border-top: 0px;
+            max-height: 330px;
+            overflow: auto;
+        }
+
+        input {
+            margin-bottom: 15px;
+        }
+    </style>
+{% endblock %}
+
+{% block actions %}
+{% endblock %}
+
+{% block tab_menu %}
+    <ol class="nav navbar-top-links breadcrumb">
+        <li><a href="{{ url('sonata_admin_dashboard') }}"><i class="fa fa-home"></i></a></li>
+        <li class="active"><span>{{ 'CaptivePortal'|trans({}, 'FTTHBundle') }}</span></li>
+    </ol>
+{% endblock %}
+
+{% block title %}
+{% endblock %}
+
+{% block navbar_title %}
+{% endblock %}
+
+{% block list_filters_actions %}
+{% endblock %}
+
+{% block list_filters %}
+{% endblock %}
+
+{% block list_table %}
+{% endblock %}
+
+{% block sonata_wrapper %}
+    {{ parent() }}
+    <footer class="footer">
+        <span id="statusBar" class="statusBar">Listo.</span>
+    </footer>
+{% endblock %}
+
+{% block content %}
+    {{ form_start(form) }}
+    <div id='wrapper' class="box box-primary">
+        <div id='page-content-wrapper'>
+            <div class="row">
+                <div class="col-md-12">
+                    <div>
+                        <div class="box-header">
+                            <h4 class="box-title">
+                                {{ 'CaptivePortal'|trans({}, 'FTTHBundle') }}
+                            </h4>
+                        </div>
+                        <div class="box-body">
+                            <div class="sonata-ba-collapsed-fields">
+                                <div class="form-group clearfix">
+                                    {{ form_widget(form) }}
+                                </div>
+                            </div>
+                        </div>
+                    </div>
+                </div>
+            </div>
+        </div>
+    </div>
+
+    <div class="sonata-ba-form-actions well well-small form-actions">
+        <button class="btn btn-success" type="submit" id="btn_import">
+            <i class="fa fa-save" aria-hidden="true"></i>&nbsp
+            {{ 'button_save'|trans({}, 'FTTHBundle') }}
+        </button>
+    </div>
+    {{ form_end(form) }}
+
+    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.16/jquery.mask.js"></script>
+    <script src="https://cdn.ckeditor.com/4.13.0/standard/ckeditor.js"></script>
+    <script>
+      CKEDITOR.replace('form[html_page]', {
+        fullPage: true,
+        allowedContent: true,
+        autoGrow_onStartup: true,
+        enterMode: CKEDITOR.ENTER_BR,
+      });
+      CKEDITOR.editorConfig = function (config) {
+        config.font_defaultLabel = 'Arial';
+        config.fontSize_defaultLabel = '12px';
+        config.language = 'fr';
+        config.uiColor = '#AADC6E';
+      };
+    </script>
+{% endblock %}