<?php
namespace App\Controller;
use App\Entity\License;
use App\Repository\LicenseRepository;
use App\Form\LicenseType;
use App\Form\LicenseSearchType;
use App\Entity\Company;
use App\Entity\LicenseCompany;
use App\Repository\LicenseCompanyRepository;
use App\Form\LicenseCompanyType;
use App\Form\LicenseCompanySearchType;
use App\Service\UtilService;
use Doctrine\DBAL\Types\TextType;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Knp\Component\Pager\PaginatorInterface;
use Symfony\Component\HttpFoundation\Request;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Symfony\Contracts\Translation\TranslatorInterface;
use Doctrine\ORM\Query\Expr\Join;
use Doctrine\Persistence\ManagerRegistry;
/**
* @Route({"en": "/license",
* "es": "/licencia"})
*/
class LicenseController extends AbstractController
{
public const PAGE_ELEMENTS = 25;
private $translator;
private $util;
private $em;
private $method = "AES-256-CBC";
private $key = "AD2#s3cret0";
private $options = 0;
private $iv = '2234547891511121';
/**
* LicenseController constructor.
*/
public function __construct(
TranslatorInterface $translator,
ManagerRegistry $doctrine,
UtilService $utilService)
{
$this->translator = $translator;
$this->util = $utilService;
$this->em = $doctrine->getManager();
}
/**
* @Route({"en": "/list",
* "es": "/listado"}, name="license_index", methods={"GET","POST"})
*/
public function index(Request $request, LicenseCompanyRepository $licenseCompanyRepository, PaginatorInterface $paginator): Response
{
$em = $this->em;
$license = [];
$form = $this->createForm(licenseCompanySearchType::class, $license, ['method' => 'GET']);
$form->handleRequest($request);
$orderBy = null;
$filters = [
['field'=>'license','title'=>'Licencia'],
['field'=>'company','title'=>'Empresa'],
['field'=>'date_added','title'=>'Alta'],
['field'=>'date_start','title'=>'Inicio'],
['field'=>'date_end','title'=>'Fin'],
['field'=>'state','title'=>'Estado']
];
if ($form->isSubmitted() && $form->isValid())
{
$orderBy = $request->query->get('order_by');
$licenses = $licenseCompanyRepository->findByName($form->getData(), $orderBy);
} else {
$licenses = $licenseCompanyRepository->buscarTodos(2);
}
// Creating pagnination
$pagination = $paginator->paginate(
$licenses,
$request->query->getInt('page', 1),
self::PAGE_ELEMENTS
);
$lc = new LicenseCompany();
$formLc = $this->createForm(licenseCompanyType::class, $lc);
$formLc->handleRequest($request);
if ($formLc->isSubmitted() && $formLc->isValid())
{
$today = new \DateTime();
$today->setTime(0,0,0);
$company = $formLc->get('company')->getData();
$license = $formLc->get('license')->getData();
$renewal = $formLc->get('renewal')->getData();
$renewalType = $formLc->get('renewal_type')->getData();
$start = $formLc->get('date_start')->getData();
$end = $formLc->get('date_end')->getData();
if(empty($company) || empty($license)){
$this->addFlash('danger', $this->translator->trans('Debe seleccionar empresa y licencia para poder efectuar la asignación'));
return $this->redirectToRoute('license_index');
}
elseif(empty($start) || empty($end)){
$this->addFlash('danger', $this->translator->trans('Debe seleccionar inicio y fin de la licencia'));
return $this->redirectToRoute('license_index');
}
elseif($today>$end || $start>=$end){
$this->addFlash('danger', $this->translator->trans('Revise las fechas de inicio y fin de la licencia'));
return $this->redirectToRoute('license_index');
}
elseif($company->getType()==2 && !in_array($license->getType(),[1,2])){
$this->addFlash('danger', $this->translator->trans('A las empresas tipo service bureaus solo se pueden asignar licencias de tipo service bureau'));
return $this->redirectToRoute('license_index');
}
elseif($company->getType()==1 && in_array($license->getType(),[1,2])){
$this->addFlash('danger', $this->translator->trans('No se pueden asignar licencias service bureau a un OEM'));
return $this->redirectToRoute('license_index');
}
$lc->setDateAdded(new \DateTime());
$lc->setState($start>$today ? 1 : 2);
if(empty($renewal)){
$lc->setRenewal(1);
}
$lc->setRenewalType($renewalType);
$em->persist($lc);
//Si estamos renovando una licencia vencida la convertimos a renovada
$lcOld = $company->getLicenseCompany();
if($lcOld && $lcOld->getState()==3){
$lcOld->setState(4);
}
//Asignamos nueva licencia a la empresa
$company->setLicenseCompany($lc);
$em->flush();
$this->addFlash('success', $this->translator->trans('Asignación realizada correctamente'));
return $this->redirectToRoute('license_index');
}
return $this->render('license/index.html.twig', [
'pagination' => $pagination,
'search_form' => $form->createView(),
'assign_form' => $formLc->createView(),
'filters' => $filters,
'order_by' => $orderBy,
'navbarTitle' => $this->translator->trans("Licencias contratadas")
]);
}
/**
* @Route({"en": "/assigned/edit/{id}",
* "es": "/asignada/editar/{id}"}, name="license_assigned_edit", methods={"GET","POST"})
*/
public function assigned_edit(Request $request, LicenseCompany $lc): Response
{
$em = $this->em;
$form = $this->createForm(licenseCompanyType::class, $lc);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid())
{
$today = new \DateTime();
$today->setTime(0,0,0);
$company = $lc->getCompany();
$license = $form->get('license')->getData();
$start = $form->get('date_start')->getData();
$end = $form->get('date_end')->getData();
if(empty($license)){
$this->addFlash('danger', $this->translator->trans('Debe seleccionar licencia para poder efectuar la asignación'));
return $this->redirectToRoute('license_index');
}
elseif(empty($start) || empty($end)){
$this->addFlash('danger', $this->translator->trans('Debe seleccionar inicio y fin de la licencia'));
return $this->redirectToRoute('license_index');
}
elseif($today>$end || $start>=$end){
$this->addFlash('danger', $this->translator->trans('Revise las fechas de inicio y fin de la licencia'));
return $this->redirectToRoute('license_index');
}
elseif($company->getType()==2 && !in_array($license->getType(),[1,2])){
$this->addFlash('danger', $this->translator->trans('A las empresas tipo service bureaus solo se pueden asignar licencias de tipo service bureau'));
return $this->redirectToRoute('license_index');
}
elseif($company->getType()==1 && in_array($license->getType(),[1,2])){
$this->addFlash('danger', $this->translator->trans('No se pueden asignar licencias service bureau a un OEM'));
return $this->redirectToRoute('license_index');
}
$lc->setState($start>$today ? 1 : 2);
$lc->setDateUpdated(new \DateTime());
$em->flush();
$this->addFlash('success', $this->translator->trans('Asignación editada correctamente'));
return $this->redirectToRoute('license_index');
}
return $this->render('license/assigned_edit.html.twig', [
'form' => $form->createView(),
'lc' => $lc,
'navbarTitle' => $this->translator->trans("Editar licencia asignada")
]);
}
/**
* @Route({"en": "/enterprise/new",
* "es": "/enterprise/nueva"}, name="license_enterprise_new", methods={"GET","POST"})
*/
public function enterprise_new(Request $request, LicenseRepository $licenseRepository): Response
{
$em = $this->em;
$license = new License();
$companies = $em->createQueryBuilder()
->select('c')
->from(Company::class,'c')
->leftJoin('c.licenseCompany','lc')
->where('lc.state IS NULL OR lc.state IN (3,5)')
->getQuery()->getResult();
if(empty($companies)){
$this->addFlash('danger', $this->translator->trans('Todas las empresas tienen una licencia asignada'));
return $this->redirectToRoute('license_index');
}
$form = $this->createForm(LicenseType::class, $license, ['lc'=>null]);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$today = new \DateTime();
$today->setTime(0,0,0);
$company = $form->get('company')->getData();
$start = $form->get('date_start')->getData();
$end = $form->get('date_end')->getData();
$renewal = $form->get('renewal')->getData();
$renewal_type = $form->get('renewal_type')->getData();
if(empty($company)){
$this->addFlash('danger', $this->translator->trans('Debe seleccionar empresa a la que se asignará la licencia Enterprise'));
return $this->redirectToRoute('license_enterprise_new');
}
elseif(empty($start) || empty($end)){
$this->addFlash('danger', $this->translator->trans('Debe seleccionar inicio y fin de la licencia Enterprise'));
return $this->redirectToRoute('license_enterprise_new');
}
elseif($today>$end || $start>=$end){
$this->addFlash('danger', $this->translator->trans('Revise las fechas de inicio y fin de la licencia'));
return $this->redirectToRoute('license_enterprise_new');
}
$license->setType(6);
$license->setUserAdmin(false);
$em->persist($license);
$lc = new LicenseCompany();
$lc->setLicense($license);
$lc->setCompany($company);
$lc->setDateAdded(new \DateTime());
$lc->setDateStart($start);
$lc->setDateEnd($end);
$lc->setRenewal($renewal);
$lc->setRenewalType($renewal_type);
$lc->setState($start>$today ? 1 : 2);
$em->persist($lc);
//Si estamos renovando una licencia vencida la convertimos a renovada
$lcOld = $company->getLicenseCompany();
if($lcOld && $lcOld->getState()==3){
$lcOld->setState(4);
}
//Asignamos nueva licencia a la empresa
$company->setLicenseCompany($lc);
$em->flush();
$this->addFlash('success', $this->translator->trans('Licencia creada correctamente'));
return $this->redirectToRoute('license_index');
}
return $this->render('license/enterprise_new.html.twig', [
'license' => $license,
'form' => $form->createView(),
'navbarTitle' => $this->translator->trans("Crear licencia Enterprise")
]);
}
/**
* @Route({"en": "/enterprise/edit/{id}",
* "es": "/enterprise/editar/{id}"}, name="license_enterprise_edit", methods={"GET","POST"})
*/
public function enterprise_edit(Request $request, LicenseCompany $lc): Response
{
$em = $this->em;
$company = $lc->getCompany();
$license = $lc->getLicense();
$form = $this->createForm(LicenseType::class, $license, ['lc'=>$lc]);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$today = new \DateTime();
$today->setTime(0,0,0);
$start = $form->get('date_start')->getData();
$end = $form->get('date_end')->getData();
$renewal = $form->get('renewal')->getData();
$renewal_type = $form->get('renewal_type')->getData();
if(empty($start) || empty($end)){
$this->addFlash('danger', $this->translator->trans('Debe seleccionar inicio y fin de la licencia Enterprise'));
return $this->redirectToRoute('license_enterprise_edit',['id'=>$lc->getId()]);
}
elseif($today>$end || $start>=$end){
$this->addFlash('danger', $this->translator->trans('Revise las fechas de inicio y fin de la licencia'));
return $this->redirectToRoute('license_enterprise_edit',['id'=>$lc->getId()]);
}
$license = $form->getData();
$lc->setDateUpdated(new \DateTime());
$lc->setDateStart($start);
$lc->setDateEnd($end);
$lc->setRenewal($renewal);
$lc->setRenewalType($renewal_type);
$lc->setState($start>$today ? 1 : 2);
$em->flush();
$this->addFlash('success', $this->translator->trans('Licencia editada correctamente'));
return $this->redirectToRoute('license_index');
}
return $this->render('license/enterprise_edit.html.twig', [
'license' => $license,
'lc' => $lc,
'form' => $form->createView(),
'navbarTitle' => $this->translator->trans("Editar licencia Enterprise").' - '.$license->getName()
]);
}
/**
* @Route({"en": "/delete/{id}",
* "es": "/eliminar/{id}"}, name="license_delete", methods={"POST"})
*/
public function delete(Request $request, licenseCompany $lc, LicenseRepository $licenseRepository): Response
{
$em = $this->em;
$rmData = $request->request->get('license_remove_data');
if(empty($lc)){
$this->addFlash('danger', $this->translator->trans('Error inesperado'));
}
elseif($this->getUser()->getRole()!='ROLE_ADMIN'){
$this->addFlash('danger', $this->translator->trans('Sólo un usuario Superadministrador puede gestionar licencias'));
}
else{
if($rmData){
$rmAccount = $this->util->rmAccount($lc->getCompany());
if($rmAccount['error']){
$this->addFlash('danger', $rmAccount['msg']);
}
else{
$this->addFlash('success', $this->translator->trans('Datos y archivos eliminados satisfactoriamente'));
}
}
$lc->setState(5);
$lc->setDateUpdated(new \DateTime());
$em->flush();
$this->addFlash('success', $this->translator->trans('Licencia dada de baja satisfactoriamente'));
}
return $this->redirectToRoute('license_index');
}
/**
* @Route({"en": "/code",
* "es": "/codigo"}, name="license_code")
*/
public function licenseCode(Request $request) {
$form = $this->createFormBuilder()
->add('code', \Symfony\Component\Form\Extension\Core\Type\TextType::class,['label' => 'Codigo'])
->add('save', SubmitType::class, ['label' => 'Canjear'])
->getForm();
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->em;
$decryptedData = openssl_decrypt( $start = $form->get('code')->getData(), $this->method, $this->key, $this->options, $this->iv);
$data = explode(';',$decryptedData);
if( count($data) != 2) {
$this->addFlash('danger', $this->translator->trans('codigo no valido'));
return $this->redirectToRoute('license_code');
}
$company = $em->getRepository(Company::class)->findOneBy(array('id' => $data[0]));
if(!$company) {
$this->addFlash('danger', $this->translator->trans('codigo no valido'));
return $this->redirectToRoute('license_code');
}
$lc = $company->getLicenseCompany();
$dateEnd = $lc->getDateEnd();
$renewal = $lc->getRenewal();
$renewalType = $lc->getRenewalType();
$license = $lc->getLicense();
$company = $lc->getCompany();
$lc->setState(LicenseCompany::RENEWED);
$dt = new \DateTime();
$dt->setTimestamp($data[1]);
$now = new \DateTime();
if($now > $dt) {
$this->addFlash('success', $this->translator->trans('codigo caducado el '.$dt->format('d-m-Y')));
return $this->render('license/code.html.twig', [
'form' => $form->createView(),
'navbarTitle' => $this->translator->trans("Canjear código")
]);
}
$lc = new LicenseCompany();
$lc->setLicense($license);
$lc->setCompany($company);
$lc->setDateAdded(new \DateTime());
$lc->setDateStart($dateEnd);
$lc->setDateEnd($dt);
$lc->setRenewal($renewal);
$lc->setRenewalType($renewalType);
$lc->setState(2);
$em->persist($lc);
//Si estamos renovando una licencia vencida la convertimos a renovada
$lcOld = $company->getLicenseCompany();
if($lcOld && $lcOld->getState()==LicenseCompany::EXPIRED){
$lcOld->setState(LicenseCompany::RENEWED);
}
//Asignamos nueva licencia a la empresa
$company->setLicenseCompany($lc);
$em->persist($lc);
$em->flush();
$this->addFlash('success', $this->translator->trans('codigo canjeado con exito, Licencia renovada hasta el '.$dt->format('d-m-Y')));
}
return $this->render('license/code.html.twig', [
'form' => $form->createView(),
'navbarTitle' => $this->translator->trans("Canjear código")
]);
}
/**
* @Route({"en": "/createLicenseCode/{company}/{endDate}",
* "es": "/createLicenseCode/{company}/{endDate}"}, name="create_license_code", methods={"GET"})
*/
public function createLicenseCode(Request $request,$company,$endDate) {
$data = $company.';'.$endDate;
$encryptedData = openssl_encrypt($data, $this->method, $this->key, $this->options, $this->iv);
return new JsonResponse(
array(
'company' => $company,
'endate' => $endDate,
'encryptedData' => $encryptedData,
)
);
}
}