<?php
/**
* Created by PhpStorm.
* User: sebastiantovar
* Date: 2019-04-08
* Time: 18:07
*/
namespace App\EventSubscriber;
use App\Entity\App\Category;
use App\Entity\App\CustomModule;
use App\Entity\App\Entity\Entity;
use App\Entity\App\MediaObject;
use App\Entity\App\Notification;
use App\Entity\App\Role;
use App\Entity\App\Task\TaskStatusLog;
use App\Entity\App\Ticket\IncidenceType;
use App\Entity\App\Ticket\TicketPriority;
use App\Entity\App\Ticket\TicketState;
use App\Entity\App\Ticket\TicketType;
use App\Entity\App\User;
use App\MessageHandler\ChatMessage;
use App\MessageHandler\LogMessage;
use App\MessageHandler\Message;
use Doctrine\ORM\EntityManagerInterface;
use ApiPlatform\Core\EventListener\EventPriorities;
use Symfony\Component\Intl\Countries;
use Symfony\Component\Intl\Currencies;
use Symfony\Component\Intl\Timezones;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
class GlobalConfigurationSerializeSubscriber implements EventSubscriberInterface
{
private $tokenStorage;
private $params;
private $em;
private $translator;
public function __construct(
EntityManagerInterface $entityManager,
ParameterBagInterface $params,
TokenStorageInterface $tokenStorage,
TranslatorInterface $trans
) {
$this->em = $entityManager;
$this->params = $params;
$this->tokenStorage = $tokenStorage;
$this->translator = $trans;
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents() {
return [
KernelEvents::VIEW => ['onKernelView', EventPriorities::POST_SERIALIZE]
];
}
/**
* @param ViewEvent $event
* @throws \Exception
*/
public function onKernelView(ViewEvent $event)
{
$result = $event->getControllerResult();
$request = $event->getRequest();
$route = $request->attributes->get('_route');
//Obtenemos el idioma de la request para las traducciones del global config
$headerLangs = $request->headers->get("accept-language");
if(!empty($headerLangs)){
$lang = explode(",",$headerLangs)[0];
}
$routes = array(
'api_global_configurations_get_collection'
);
if (!in_array($route, $routes))
return;
$localeDefault = 'en';
if (isset($_GET['locale']) && in_array($_GET['locale'], ['en', 'es'])) {
$localeDefault = $_GET['locale'];
}
$languages = [
'en' => 'english',
'es' => 'spanish'
];
$ticketSources = ['app', 'web', 'bot', 'calendar'];
$ticketFrequency = ['daily','week', 'month', 'year'];
$requestStateStatic = ['on hold', 'rejected'];
$order = [
'on hold' => 0,
'rejected' => 1,
'in process' => 2,
'started' => 3,
'paused' => 4,
'finished' => 5,
'cancelled' => 6
];
$requestStates = [];
$allStates = [];
$ticketStates = $this->em->getRepository(TicketState::class)->findAll();
foreach ($ticketStates as $ticketState) {
$dataState = array(
'id' => $ticketState->getId(),
'name' => $ticketState->getName()
);
$serializedTicketStates[] = $dataState;
$pos = $order[$ticketState->getName()];
$allStates[$pos] = $dataState;
if (!in_array($ticketState->getName(), $requestStateStatic)) {
$ticketsStates[] = $dataState;
}
if (in_array($ticketState->getName(), $requestStateStatic)) {
$requestStates[] = $dataState;
}
}
ksort($allStates);
$priorities = $this->em->getRepository(TicketPriority::class)->findAll();
foreach ($priorities as $priority) {
$serializedPriorities[] = array(
'id' => $priority->getId(),
'name' => $priority->getName()
);
}
$countriesNames = Countries::getNames($localeDefault);
$codeCountries = require $this->params->get('SETTING_FILES_DIR').'/CodeCountries.php';
$countries = [
'ES' => [
'id' => 'ES',
'name' => Countries::getName('ES', $localeDefault),
'prefix' => '+34'
],
'US' => [
'id' => 'US',
'name' => Countries::getName('US', $localeDefault),
'prefix' => '+1'
],
'MX' => [
'id' => 'MX',
'name' => Countries::getName('MX',$localeDefault),
'prefix' => '+52'
],
'CO' => [
'id' => 'CO',
'name' => Countries::getName('CO', $localeDefault),
'prefix' => '+57'
],
];
foreach ($countriesNames as $code => $name) {
if (!array_keys($countries, $code)) {
$prefix = null;
if (isset($codeCountries[$code])) {
$prefix = '+' . $codeCountries[$code];
}
$countries[$code] = array(
'id' => $code,
'name' => $name,
'prefix' => $prefix
);
}
}
$taskStates[] = array(
'id' => 1,
'name' => TaskStatusLog::STATUS_TASK_IN_PROCESS
);
$taskStates[] = array(
'id' => 2,
'name' => TaskStatusLog::STATUS_TASK_STARTED
);
$taskStates[] = array(
'id' => 3,
'name' => TaskStatusLog::STATUS_TASK_PAUSED
);
$taskStates[] = array(
'id' => 4,
'name' => TaskStatusLog::STATUS_TASK_CANCELLED
);
$taskStates[] = array(
'id' => 5,
'name' => TaskStatusLog::STATUS_TASK_FINISHED
);
$customModules = $this->em->getRepository(CustomModule::class)->findAll();
foreach ($customModules as $customModule) {
$serializedCustomModules[] = array(
'id' => $customModule->getId(),
'name' => $customModule->getName()
);
}
if (isset($_GET['platform']) && strtolower($_GET['platform']) == 'desktop') {
$result = [];
$result['dateFormats'] = [
1 => [
'label' => 'day-month-year',
'format' => 'dd-MM-yyyy'
],
2 => [
'label' => 'month-day-year',
'format' => 'MM-dd-yyyy'
]
];
$result['locale'] = $localeDefault;
$result['version_web'] = $this->params->get('VERSION_WEB');
$result['ticketStates'] = $allStates ?? null;
$result['workOrderStates'] = $ticketsStates ?? null;
$result['requestStates'] = $requestStates;
$result['customModules'] = $serializedCustomModules ?? null;
$result['taskStates'] = $taskStates;
$result['ticketSources'] = $ticketSources;
$result['ticketFrequency'] = $ticketFrequency;
$result['priorities'] = $serializedPriorities ?? null;
$result['languages'] = $languages;
$result['countries'] = $countries;
$result['typeCategories'] = [
Category::TYPE_RESOURCE => 'ResourceAndTool',
Category::TYPE_MAINTENANCE_ELEMENT => 'Maintenance Element',
Category::TYPE_TASK => 'Task',
Category::TYPE_USER => 'User',
Category::TYPE_LOCATION => 'Location'
];
$result['chat'] = [
'type' => ['ticket', 'task'],
'state' => ['active', 'closed'],
'channel' => ['private', 'public', 'presence'],
'event' => ['NEW_CHAT', 'MESSAGE_READ']
];
$result['files'] = [
'maxSize' => MediaObject::max_size,
'mimeTypes' => 'jpeg, jpg, png, mp4, m4v, x-m4v, JPEG, quicktime, mp4, mpeg, pdf, octet-stream, text, doc, excel, powerpoint'
];
$currencyNames = Currencies::getNames($localeDefault);
$currencies = array();
$allowedCurrencies = [
'VES', 'BOB', 'CLE', 'CRC', 'SVC', 'NIO', 'CZK', 'DKK', 'SKK', 'EEK', 'ISK', 'NOK', 'SEK', 'BRR',
'AED', 'AUD', 'CAD', 'BMD', 'KYD', 'TTD', 'USD', 'JMD', 'NZD', 'CVE', 'MZE', 'EUR', 'CHF', 'HNL',
'GBP', 'MCF', 'ARS', 'BOP', 'CLP', 'COP', 'DOP', 'PHP', 'MXN', 'UYU', 'GTQ', 'ZAR', 'BRL', 'QAR',
'IRR', 'OMR', 'SAR', 'YER', 'RUB', 'PEN', 'ECS', 'JPY', 'CNY'
];
foreach ($currencyNames as $code => $name) {
if (in_array($code, $allowedCurrencies)) {
$currencies[$code] = array(
'id' => $code,
'name' => $name, //. $this->getRegionOfCurrencies($code)
'symbol' => Currencies::getSymbol($code, $localeDefault)
);
}
}
$result['currencies'] = $currencies;
$timezones = [];
$offsets = [];
$now = new \DateTime('now', new \DateTimeZone('UTC'));
foreach(Timezones::getNames($localeDefault) as $timezone => $timezoneName) {
if ($timezone !== 'Asia/Qostanay') {
$now->setTimezone(new \DateTimeZone($timezone));
$offsets[] = $offset = $now->getOffset();
$timezones[$timezone] = '('.Timezones::getGmtOffset($timezone).') '.$this->format_timezone_name(
$timezoneName
);
}
}
array_multisort($offsets, $timezones);
$result['timezone'] = $timezones;
$result['useUnits'] = [
1 => array(
'id' => 1,
'name' => 'Units',
'nomenclature' => 'u'
),
2 => array(
'id' => 2,
'name' => 'liters',
'nomenclature' => 'l'
),
3 => array(
'id' => 3,
'name' => 'kilograms',
'nomenclature' => 'Kg'
),
4 => array(
'id' => 4,
'name' => 'grams',
'nomenclature' => 'g'
),
5 => array(
'id' => 5,
'name' => 'milliliters',
'nomenclature' => 'ml'
),
6 => array(
'id' => 6,
'name' => 'kilometers',
'nomenclature' => 'km'
),
7 => array(
'id' => 7,
'name' => 'meters',
'nomenclature' => 'm'
),
8 => array(
'id' => 8,
'name' => 'centimeters',
'nomenclature' => 'cm'
),
9 => array(
'id' => 9,
'name' => 'square_meter',
'nomenclature' => 'm2'
),
10 => array(
'id' => 10,
'name' => 'hour',
'nomenclature' => 'h'
),
11 => array(
'id' => 11,
'name' => 'minutes',
'nomenclature' => 'min'
),
12 => array(
'id' => 12,
'name' => 'seconds',
'nomenclature' => 's'
)
];
$entities=[];
foreach (Entity::Entities as $entity){
$entity["label"] = $this->translator->trans('customFields.entities.'.$entity["label"],[],'messages',$lang);
$entities[]=$entity;
};
$result['customField'] = array(
'entities' => $entities,
'types' =>[
['label' => $this->translator->trans('customFields.types.string',[],'messages',$lang), 'id' => 'string'],
['label' => $this->translator->trans('customFields.types.numeric',[],'messages',$lang), 'id' => 'number'],
['label' => $this->translator->trans('customFields.types.date',[],'messages',$lang), 'id' => 'date']]);
$result['week'] = [
'monday' => 'Monday',
'tuesday' => 'Tuesday',
'wednesday' => 'Wednesday',
'thursday' => 'Thursday',
'friday' => 'Friday',
'saturday' => 'Saturday',
'sunday' => 'Sunday'
];
$result['hourDay'] = [
'00:00' => '00:00',
'01:00' => '01:00',
'02:00' => '02:00',
'03:00' => '03:00',
'04:00' => '04:00',
'05:00' => '05:00',
'06:00' => '06:00',
'07:00' => '07:00',
'08:00' => '08:00',
'09:00' => '09:00',
'10:00' => '10:00',
'11:00' => '11:00',
'12:00' => '12:00',
'13:00' => '13:00',
'14:00' => '14:00',
'15:00' => '15:00',
'16:00' => '16:00',
'17:00' => '17:00',
'18:00' => '18:00',
'19:00' => '19:00',
'20:00' => '20:00',
'21:00' => '21:00',
'22:00' => '22:00',
'23:00' => '23:00'
];
$roles = $this->em->getRepository(Role::class)->findAll();
foreach ($roles as $role) {
$result['roles'][$role->getName()] = $role->getWeight();
}
$result = json_encode($result);
$event->setControllerResult($result);
return;
}
$ticketTypes = $this->em->getRepository(TicketType::class)->findAll();
foreach ($ticketTypes as $ticketType) {
$serializedTicketTypes[] = array(
'id' => $ticketType->getId(),
'name' => $ticketType->getName()
);
}
$incidenceTypes = $this->em->getRepository(IncidenceType::class)->findAll();
foreach ($incidenceTypes as $incidenceType) {
if ($incidenceType->getEnabled()) {
$serializedIncidenceTypes[] = array(
'id' => $incidenceType->getId(),
'name' => $incidenceType->getName()
);
}
}
$resultDesnormalized = json_decode($result, true);
$result = array();
$result['versionApp'] = [
'IOS' => $this->params->get('VERSION_APP_IOS'),
'ANDROID' => $this->params->get('VERSION_APP_ANDROID')
];
$result['versionAppStatus'] = [
'IOS' => $this->params->get('VERSION_APP_IOS_STATUS'),
'ANDROID' => $this->params->get('VERSION_APP_ANDROID_STATUS')
];
$result['versionAppRequest'] = [
'IOS' => $this->params->get('VERSION_APP_REQUEST_IOS'),
'ANDROID' => $this->params->get('VERSION_APP_REQUEST_ANDROID')
];
$result['versionAppOperator'] = [
'IOS' => $this->params->get('VERSION_APP_OPERATOR_IOS'),
'ANDROID' => $this->params->get('VERSION_APP_OPERATOR_ANDROID')
];
$result['apiVersion'] = $resultDesnormalized[0]['apiVersion'] ?? null;
$result['priorities'] = $serializedPriorities ?? null;
$result['ticketType'] = $serializedTicketTypes ?? null;
$result['incidenceTypes'] = $serializedIncidenceTypes ?? null;
$result['ticketStates'] = $serializedTicketStates ?? null;
$result['taskStates'] = $taskStates;
$result['ticketSources'] = $ticketSources;
$result['languages'] = $languages;
$result['countries'] = $countries;
$result['dateFormats'] = [
1 => [
'label' => 'day-month-year',
'format' => 'dd-MM-yyyy'
],
2 => [
'label' => 'month-day-year',
'format' => 'MM-dd-yyyy'
]
];
$result = json_encode($result);
$event->setControllerResult($result);
}
protected function format_GMT_offset($offset) {
$hours = intval($offset / 3600);
$minutes = abs(intval($offset % 3600 / 60));
return 'GMT' . ($offset ? sprintf('%+03d:%02d', $hours, $minutes) : '');
}
protected function format_timezone_name($name) {
$name = str_replace('/', ', ', $name);
$name = str_replace('_', ' ', $name);
$name = str_replace('St ', 'St. ', $name);
$name = str_replace('(', '- ', $name);
$name = str_replace(')', '', $name);
return $name;
}
/**
* @param string $code
* @return mixed|string
*/
protected function getRegionOfCurrencies(string $code)
{
$list = array(
'DZD' => 'Algeria',
'USD' => 'USA',
'EUR' => 'European Monetary Union',
'XCD' => 'Eastern Carribean States',
'AMD' => 'Armenia',
'AUD' => 'Australia',
'AZN' => 'Azerbaijan',
'XAF' => 'African Financial Community',
'VES' => 'Venezuela',
'BOB' => 'Bolivia',
'CRC' => 'Costa rica',
'SVC' => 'Salvador',
'NIO' => 'Nicaragua',
'CZK' => 'Czech Republic',
'DKK' => 'Denmark',
'NOK' => 'Northern Mariana Islands',
'SEK' => 'SWEDEN',
'BSD' => 'Bahamas',
'CUC' => 'Cuba',
'CUP' => 'Cuba',
'JPY' => 'Japan',
'CNY' => 'China'
);
if (isset($list[$code])) {
return ' - '.$list[$code];
}
return '';
}
}