src/Base/ControllerBase.php line 1865

Open in your IDE?
  1. <?php
  2. namespace App\Base;
  3. use App\Controller\MasterBalanceController;
  4. use App\Entity\Account;
  5. use App\Entity\Company;
  6. use App\Entity\Driver;
  7. use App\Entity\DriverLicense;
  8. use App\Entity\GasPrices;
  9. use App\Entity\KmMultiplier;
  10. use App\Entity\LicenseOrder;
  11. use App\Entity\LicensePricing;
  12. use App\Entity\Licenses;
  13. use App\Entity\LogEntry;
  14. use App\Entity\LogEntry2// balance log
  15. use App\Entity\Message;
  16. use App\Entity\Vehicle;
  17. use App\Entity\Trailer;
  18. use App\Entity\User;
  19. use App\Entity\Document;
  20. use App\Entity\Setting;
  21. use App\Entity\Balance// generic, added for COM-831
  22. use App\Entity\InvoiceStore// generic, added for COM-831
  23. use App\Entity\WorkPeriod;
  24. use App\Entity\DayAssignment;
  25. use App\Entity\DayTitle;
  26. use App\Entity\AttendanceRegisterParams;
  27. use App\Entity\ProtocolParams;
  28. use App\Entity\Attachment// COM-787
  29. use App\Entity\TachographFile;
  30. use App\Entity\DriverActivity;
  31. use App\Entity\DriverManualActivity;
  32. use App\Entity\DriverBorderCrossing;
  33. use App\Entity\DriverActiveDay;
  34. use App\Entity\DriverMinimumWagePeriod;
  35. use App\Entity\DriverSpecialEvent;
  36. use App\Entity\DriverWeeklyRestTimeException;
  37. use App\Entity\DriverActivityProofSheet;
  38. use App\Entity\Report;
  39. use App\Entity\Report2;
  40. use App\Entity\TravelRoute;
  41. use App\Entity\ToDoItem;
  42. use App\Entity\ToDoItemException// COM-502
  43. use App\Entity\Consumption;
  44. use App\Entity\DailyAllowance;
  45. use App\Entity\Statistic//COM-349
  46. use App\Entity\ConsumptionsTanking//COM-431
  47. //use App\Entity\EmailServerConnection; //COM-819
  48. use App\Entity\EmailTachographFile//COM-819
  49. use App\Entity\TachoSolveOrder// COM-822
  50. use App\Entity\TachoSolveClient// COM-822
  51. use App\Entity\ApiConnection//COM-API
  52. use App\Entity\Penalty;
  53. use App\Entity\CustomField;
  54. use App\Entity\CustomFieldValue;
  55. use App\Entity\CustomFieldLabel;
  56. use App\Entity\RawDbRecord;
  57. use App\Repository\ConsumptionRepository//???
  58. use App\Services\TimeCalculator;
  59. use App\Services\SettingsLoader;
  60. use App\Services\DataUpdater;
  61. use App\Services\FormsHelper;
  62. use App\Services\StringHelper;
  63. use App\Services\EmailNotifier;
  64. use App\Services\NameConverter;
  65. use App\Services\DataSynchronizer;
  66. use App\Services\DatabaseConnector;
  67. use App\Services\RoutingHelper;
  68. use App\Services\PenaltyHelper;
  69. use App\Services\DocumentHelper;
  70. use App\Services\LoggingHelper;
  71. use App\Services\LicenseHelper;
  72. use App\Services\MessageHelper;
  73. use App\Services\CalculationHelper;
  74. use App\Services\BalanceHelper;
  75. use App\Services\AIHelper// COM-695
  76. use App\Services\DriverVehicleDataHelper// COM-API
  77. use App\Services\ApiHelper// COM-796
  78. use App\Services\TachoSolveManager// COM-822
  79. use App\Services\RateLimiter// generic API, added for COM-822
  80. use App\Type\BalanceTypeEnum;
  81. use App\Type\TypeEnum;
  82. use App\Type\BooleanEnum;
  83. use App\Type\UserRoleEnum;
  84. use App\Type\DriverActivityTypeEnum;
  85. use App\Type\DriverSpecialEventEnum;
  86. use App\Type\DayTitleTypeEnum;
  87. use App\Type\ReportClass;
  88. use App\Type\ReportQuickFilterType;
  89. use App\Type\ReportStatusType;
  90. use App\Type\CustomFieldCategoryEnum;
  91. use App\Type\CustomFieldTypeEnum;
  92. use App\Type\LogChangeTypeEnum;
  93. use App\Type\LogItemTypeEnum;
  94. use App\Type\LicenseTypeEnum;
  95. use App\Type\ToDoItemTypeEnum;
  96. use App\Type\CompanyConfigStatusTypeEnum;
  97. use App\Type\MinimalWageCountryEnum;
  98. use App\Type\BroadcastMessageReactionEnum// COM-469
  99. use App\Type\CompanyAdminTypeEnum//COM-481
  100. use App\Type\EntityTypeEnum// generic, added for COM-787
  101. use App\Type\AttachmentTypeEnum// COM-787
  102. use App\Type\ApiOriginTypeEnum// COM-815
  103. use App\Type\CompanySpecialTypeEnum// COM-831
  104. use App\Type\ApplicationTypeEnum// COM-796
  105. use App\Type\AccountTypeEnum// COM-815.a
  106. #use App\Controller\MainController;
  107. use Symfony\Bundle\FrameworkBundle\Controller\Controller;
  108. use Symfony\Component\DependencyInjection\ContainerBuilder;
  109. use Symfony\Component\HttpFoundation\Request;
  110. use Symfony\Component\HttpFoundation\Response;
  111. use Symfony\Component\HttpFoundation\JsonResponse;
  112. use Symfony\Component\HttpFoundation\RedirectResponse;
  113. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  114. use Symfony\Component\HttpFoundation\Session\Storage\SessionStorageInterface;
  115. use Symfony\Component\HttpFoundation\Cookie;
  116. use Symfony\Component\Routing\Annotation\Route;
  117. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  118. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  119. use Symfony\Component\Security\Core\Exception\AccessDeniedException;
  120. use Symfony\Component\Serializer\Serializer;
  121. #use Symfony\Component\Serializer\Encoder\XmlEncoder;
  122. use Symfony\Component\Serializer\Encoder\JsonEncoder;
  123. use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
  124. use Doctrine\Common\Collections\ArrayCollection;
  125. use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
  126. use Symfony\Component\Translation\TranslatorInterface;
  127. use Psr\Log\LoggerInterface;
  128. use Sinergi\BrowserDetector\Browser;
  129. use SunCat\MobileDetectBundle\DeviceDetector\MobileDetector;
  130. class ControllerBase extends Controller
  131. {
  132.     protected $translator;
  133.     protected $session;
  134.     protected $logger;
  135.     //protected $doctrine;
  136.     protected $router;
  137.     protected $mobileDetect;
  138.     protected $passwordEncoder;
  139.     protected $nc;
  140.     protected $db;
  141.     protected $symfonyLogger;
  142.         
  143.     protected $timeCalc;
  144.     protected $statHelper;
  145.     protected $settingsLoader;
  146.     protected $settings = array();
  147.     protected $gridHelper;
  148.     protected $formsHelper;
  149.     protected $stringHelper;
  150.     protected $penaltyHelper;
  151.     protected $docHelper;
  152.     protected $licenseHelper;
  153.     protected $messageHelper;
  154.     protected $calcHelper;
  155.     protected $balanceHelper;
  156.     protected $ai// COM-695
  157.     protected $dvHelper// COM-796
  158.     protected $apiHelper// COM-796
  159.     protected $tachoSolve// COM-822
  160.     
  161.     protected $emails;
  162.     protected $dataUpdater;
  163.     protected $dataImporter;
  164.     protected $dataSynchronizer;
  165.     protected $rateLimiter// generic API, added for COM-822
  166.     protected $currentYear;
  167.     protected $currentWeekName;
  168.     protected $currentDate;
  169.     protected $readOnly true;
  170.     protected $currentLanguage;
  171.     protected $breadcrumbs;
  172.     protected $returnURL;
  173.     public $overrideCurrentUser null// generic, added for COM-707
  174.     protected $showSettingsMenu;
  175.     protected $redirectRoute null;
  176.     protected $homeRoute 'companies.index.page';
  177.     protected $cookiesToSet null;
  178.     
  179.     protected $immediatelyAfterLogin false;
  180.     
  181.     protected $firstLoginConfigMode false;
  182.     protected $newCompanyConfigMode false;
  183.     protected $aiEnabled false// COM-709a
  184.     protected $aiPaidLicenseThisMonth false// COM-709a
  185.     protected $disableFlashMessages false;
  186.     protected $keepFlashMessageOpen false;
  187.     
  188.     protected $enableAttachments false// COM-787
  189.     protected $enableApi false// COM-815
  190.     protected $languages = [
  191.         'en',
  192.         'hu',
  193.         'de',
  194.         //'sk',
  195.         //'ro',
  196.         'pl'// COM-660
  197.         'it'// COM-793
  198.     ];
  199.     protected $defaultLanguage 'hu';
  200.     protected $interEndpointComm false;
  201.     protected $forceSessionFilter false;
  202.     protected $account;
  203.     protected $company;
  204.     protected $currentCountry null;
  205.     protected $currentCompanyConfigStatus null;
  206.     protected $module null;
  207.     protected $modulePath null;
  208.     protected $emptyEntity null;
  209.     protected $newEntity null;
  210.     protected $mainCountry 'hu';
  211.     protected $mainCity 'Budapest';
  212.     // used by report controllers only
  213.     protected $reportClass;
  214.     //protected $perDriverReportsAvailable = false;
  215.     //protected $perVehicleReportsAvailable = false;
  216.     protected $debug false;
  217.     protected $superAdminDebug false;
  218.     const LOGIN_EXPIRY 30999// minutes
  219.     const WARNING_BEFORE_LOGOUT 5// minutes
  220.     
  221.     const EMPTY_COMPANY_CLASSES = [
  222.         Company::class,
  223.         Driver::class,
  224.         Vehicle::class,
  225.         Trailer::class,
  226.         Document::class,
  227.     ];
  228.     const PARAMETER_CLASSES = [
  229.         WorkPeriod::class,
  230.         DayAssignment::class,
  231.         DayTitle::class,
  232.         AttendanceRegisterParams::class,
  233.         ProtocolParams::class,
  234.     ];
  235.     protected $validApiKeyName = [ // COM-796
  236.         'APP_API_KEY_FLOTTAWEB'
  237.         'APP_API_KEY_TECHSUPP_DEV',
  238.         'APP_API_KEY_MINI_RM'// miniRM
  239.         'APP_API_KEY_ANDROID'// droid
  240.     ];
  241.     private $modulesAllowedForRegularUsers = array(
  242.         'general' => array(
  243.             //'modeChange',
  244.             'keepAlive' => ['allow'=>true],
  245.         ),
  246.         'subproducts' => array(
  247.             'list' => ['allow'=>true],
  248.             'view' => ['allow'=>true],
  249.             //'create',
  250.             //'edit',
  251.             'history' => ['allow'=>true], // view/update history
  252.         ),
  253.         'statistics' => array(
  254.             'list' => ['allow'=>true],
  255.             'view' => ['allow'=>true],
  256.         ),
  257.         'posts' => array(
  258.             //'list',
  259.             //'view',
  260.             //'create',
  261.             //'edit',
  262.         ),
  263.         'users' => array(
  264.             //'list',
  265.             //'view',
  266.             //'create',
  267.             //'edit',
  268.             'password-change' => ['allow'=>true],
  269.         ),
  270.         'settings' => array(
  271.             'edit' => ['allow'=>true], // personal settings only
  272.             'view' => ['allow'=>true],
  273.         ),
  274.     );
  275.     public function __construct(TranslatorInterface $translatorSessionInterface $sessionLoggerInterface $symfonyLogger
  276.                                 UrlGeneratorInterface $routerUserPasswordEncoderInterface $passwordEncoder,
  277.                                 TimeCalculator $timeCalcSettingsLoader $settingsLoaderFormsHelper $formsHelper,
  278.                                 EmailNotifier $emailsDataUpdater $dataUpdaterStringHelper $stringHelper,
  279.                                 NameConverter $ncDataSynchronizer $dataSynchronizerDatabaseConnector $db,
  280.                                 PenaltyHelper $penaltyHelperDocumentHelper $docHelperLoggingHelper $logger,
  281.                                 LicenseHelper $licenseHelperMessageHelper $messageHelperCalculationHelper $calcHelper,
  282.                                 BalanceHelper $balanceHelper/*, OfflineActionsHelper $offlineHelper */,
  283.                                 AIHelper $ai// COM-695
  284.                                 DriverVehicleDataHelper $dvHelperApiHelper $apiHelper// COM-API
  285.                                 TachoSolveManager $tachoSolve// COM-822
  286.                                 RateLimiter $rateLimiter)  // generic API, added for COM-822
  287.     {
  288.         //dump('ControllerBase constructor');
  289.         //dump($this);
  290.         //dump('session', $session);
  291.         //dump(session_id());
  292.         //$session->set('jj-var', '12345');
  293.         $this->translator $translator;
  294.         $this->session $session;
  295.         $this->logger $logger;
  296.         $this->router $router;
  297.         
  298.         $this->mobileDetect = new MobileDetector();
  299.         //$this->mobileDetect->setCookieSamesite('None');
  300.         //dump($this->mobileDetect);
  301.         //dump('isMobile', $this->mobileDetect->isMobile());
  302.         
  303.         //$mobileDetector = $this->mobileDetect->get('mobile_detect.mobile_detector');
  304.         //dump('isMobile', $mobileDetector->isMobile());
  305.         //$mobileDetector->isTablet()
  306.         
  307.         $this->passwordEncoder $passwordEncoder;
  308.         $this->nc $nc;
  309.         $this->db $db;
  310.         $this->penaltyHelper $penaltyHelper;
  311.         $this->docHelper $docHelper;
  312.         $this->symfonyLogger $symfonyLogger;
  313.         
  314.         $this->timeCalc $timeCalc;
  315.         //$this->gridHelper = $gridHelper;
  316.         $this->formsHelper $formsHelper;
  317.         $this->stringHelper $stringHelper;
  318.         $this->emails $emails;
  319.         $this->dataUpdater $dataUpdater;
  320.         $this->dataSynchronizer $dataSynchronizer;
  321.         $this->rateLimiter $rateLimiter// generic API, added for COM-822
  322.         //$this->statHelper = $statHelper;
  323.         $this->settingsLoader $settingsLoader;
  324.         $this->settingsLoader->setTimeCalc($this->timeCalc);
  325.         //$this->settings = $this->settingsLoader->getSettings();
  326.         //dump('ControllerBase', $this->settingsLoader);
  327.         $this->licenseHelper $licenseHelper;
  328.         $this->licenseHelper->setParent($this);
  329.         
  330.         $this->messageHelper $messageHelper;
  331.         $this->messageHelper->setParent($this);
  332.         
  333.         $this->calcHelper $calcHelper;
  334.         $this->balanceHelper $balanceHelper;
  335.         $this->balanceHelper->setParent($this);
  336.         $this->ai $ai// COM-695
  337.         $this->ai->setParent($this); // COM-731
  338.         
  339.         $this->dvHelper $dvHelper// COM-796
  340.         $this->apiHelper $apiHelper// COM-796
  341.         $this->tachoSolve $tachoSolve// COM-822
  342.         
  343.         //$this->offlineHelper = $offlineHelper;
  344.         //$this->licenseHelper->setBalanceHelper($this->balanceHelper);
  345.         
  346.         // create empty entity of the right class (needed for e.g permissions checking)
  347.         if ($this->modulePath!=null) {
  348.             $this->emptyEntity = new $this->modulePath;
  349.         }
  350.         $this->currentLanguage $translator->getLocale();
  351.         date_default_timezone_set('Europe/Budapest');
  352.         //$this->helper = $helper;
  353.         //$this->helper->setParent($this);
  354.         /*if (isset($_COOKIE['ACE_settings_menu'])) {
  355.             $this->showSettingsMenu = ($_COOKIE['ACE_settings_menu']==='shown');
  356.         } else {
  357.             $this->showSettingsMenu = true;
  358.         }*/
  359.         //dump($_COOKIE['ACE_settings_menu']);
  360.         //$this->logger->error('MainController opened');
  361.         //die('888');
  362.         //dump($this);
  363.         //dump('keep-flash-message-open', $this->session->get('keep-flash-message-open'));
  364.         if ($this->session->get('keep-flash-message-open')!=null) {
  365.             if ($this->session->get('keep-flash-message-open')===true) {
  366.                 $this->keepFlashMessageOpen true;
  367.             }
  368.             $this->session->set('keep-flash-message-open'null);
  369.         }
  370.         // check browser
  371.         /*dump($this->mobileDetect);
  372.         dump("isMobile: [".$this->mobileDetect->isMobile()."]");
  373.         dump("isTablet: [".$this->mobileDetect->isTablet()."]");
  374.         dump("isIphone: [".$this->mobileDetect->isIphone()."]");
  375.         dump("isIpad: [".$this->mobileDetect->isIpad()."]");
  376.         dump("isIOS: [".$this->mobileDetect->isIOS()."]");
  377.         dump("isChrome: [".$this->mobileDetect->isChrome()."]");
  378.         dump("isSafari: [".$this->mobileDetect->isSafari()."]");*/
  379.     }
  380.     /*public function setBreadcrumbs($breadcrumbs) {
  381.         $this->breadcrumbs = $breadcrumbs;
  382.     }
  383.     public function setReturnURL($returnURL) {
  384.         $this->returnURL = $returnURL;
  385.     }
  386.     public function getControllerUser() {
  387.         return $this->getUser();
  388.     }
  389.     public function getCurrentYear() {
  390.         return $this->currentYear;
  391.     }
  392.     
  393.     public function getCurrentYear() {
  394.         return $this->currentYear;
  395.     }*/
  396.     public function getCompany() {
  397.         return $this->company;
  398.     }
  399.     public function getCurrentUser() {
  400.         return $this->getUser();
  401.     }
  402.     public function getCurrentLanguage() {
  403.         return $this->currentLanguage;
  404.     }
  405.     
  406.     public function getCurrentCountry() {
  407.         return $this->currentCountry;
  408.     }
  409.     public function getCurrentSession() { // generic, added for COM-822
  410.         return $this->session;
  411.     }
  412.         
  413.     public function getBalanceHelper() {
  414.         return $this->balanceHelper;
  415.     }
  416.     
  417.     public function addFlash2($type$text) {
  418.         $this->addFlash($type$text);
  419.     }
  420.     public function triggerBalanceChange($changeType$details=null$calculateWithoutWrite=false) {
  421.         $this->balanceHelper->triggerBalanceChange($changeType$details$calculateWithoutWrite);
  422.     }
  423.     public function triggerDriverTokenBalanceChange($changeType$details=null$calculateWithoutWrite=false) {
  424.         $this->balanceHelper->triggerDriverTokenBalanceChange($changeType$details$calculateWithoutWrite);
  425.     }
  426.     protected function handlePageOpen(&$request$module=null$action=null$entity=null) {
  427.         return $this->handleControllerAction($request$module$action$entityfalse);
  428.     }
  429.     protected function handleControllerAction(&$request$module=null$action=null$entity=null$ajaxCall=false$parms=null) {
  430.         //dump("handlePageOpen(request, $module, $action, entity)");
  431.         //dump($request);
  432.         //dump($entity);
  433.         //dump("user: ", $this->getUser());
  434.         //dump('session', $this->session, session_id());
  435.         //dump(1);
  436.         //dd('--');
  437.         
  438.         // login expiry
  439.         //dump(time() - $this->session->getMetadataBag()->getLastUsed(), self::LOGIN_EXPIRY * 60);
  440.         /*if (time() - $this->session->getMetadataBag()->getLastUsed() > self::LOGIN_EXPIRY * 60) {
  441.             //dump('invalid');
  442.             $this->session->invalidate();
  443.             $this->redirectRoute = 'b_logout';
  444.             return false;
  445.         }*/
  446.         //dump(2);
  447.         //echo "($module || $action)\n";
  448.         // check module
  449.         if ($request==null || $module==null || $action==null) {
  450.             $this->redirectRoute $this->homeRoute;
  451.             return false;
  452.         }
  453.         $this->timeCalc->refreshTimeZone();
  454.         //dump(3);
  455.         $thisUserType = ($this->getUser()==null) ? null $this->getUser()->getRolesUnconverted();
  456.         // check if we are immediately after login and in default route (companies list)
  457.         //dump($request); die();
  458.         if ($this->session->get('immediatelyAfterLogin')!==null && $this->session->get('immediatelyAfterLogin')===true) {
  459.             $this->immediatelyAfterLogin true;
  460.             // clear it, don't need it again
  461.             $this->session->set('immediatelyAfterLogin'false);
  462.             //$this->session->set('immediatelyAfterLoginActions', [
  463.             //    'vehicleLicenseCheck'
  464.             //]);
  465.             // right after login, we can go to previous page opened, or to default companies.index.page (per the security yaml config)
  466.             // check which one it is
  467.             if ($request->attributes->get('_route')=='companies.index.page') {
  468.                 // it's companies.index.page, but not every user should or can go there
  469.                 // correct it here - choose the proper route, and redirect there
  470.                 $newRoute RoutingHelper::getDefaultRoute($thisUserType);
  471.                 if ($newRoute!='companies.index.page') {
  472.                     $this->redirectRoute $newRoute;
  473.                     return false;
  474.                 }
  475.             }
  476.         
  477.         }
  478.         if ($this->getUser()==null) {
  479.             $this->redirectRoute 'b_logout';
  480.             return false;
  481.         }
  482.         //dump('3a', $module, $this->getUser()->getUsername()); ///
  483.         // set language & locale
  484.         $this->setLanguageAndLocale($request);
  485.         //dump('3a.1');
  486.         $this->calcHelper->setLanguage($this->currentLanguage);
  487.         //dump('3a.2');
  488.         // check if logged in (if in a logged-in area)
  489.         if ($module!='general' && $this->getUser()==null) {
  490.             // no user means login session expired, send to login page
  491.             $this->redirectRoute 'b_login';
  492.             //dump('3b');
  493.             return false;
  494.         }
  495.         
  496.         //dump('4');
  497.         // get account info from current user
  498.         $this->account $this->getUser()->getAccount();
  499.         //dump('account', $this->getUser()->getAccount());
  500.         //dump('primaryCompany', $this->account->__get('primaryCompany'));
  501.         //var_dump('getCurrentCompanyViewed '.$this->getUser()->getCurrentCompanyViewed()->getName());
  502.         // COM-815 ==>
  503.         // check if company is still allowed for this user
  504.         $allowedCompanyIdsForUser = [];
  505.         foreach($this->getUser()->__get('administeredCompanies') as $dbAllowedCompany) {
  506.             $allowedCompanyIdsForUser[] = $dbAllowedCompany->getId();
  507.         }
  508.         //var_dump('allowedCompanyIdsForUser', $allowedCompanyIdsForUser);
  509.         if ($this->getUser()->getCurrentCompanyViewed()!=null &&
  510.             count($allowedCompanyIdsForUser)>&&
  511.             ($this->getUser()->getRolesUnconverted()==UserRoleEnum::ROLE_USER || $this->getUser()->getRolesUnconverted()==UserRoleEnum::ROLE_ADMIN) && // COM-815a
  512.             !in_array($this->getUser()->getCurrentCompanyViewed()->getId(), $allowedCompanyIdsForUser)) {
  513.             //var_dump("OVERWRITE WITH ", $allowedCompanyIdsForUser[0] ?? 'x');
  514.             $firstAllowedCompany $this->getDoctrine()->getRepository(Company::class)->findOneById($allowedCompanyIdsForUser[0]);
  515.             //var_dump('firstAllowedCompany id: ', $firstAllowedCompany->getId());
  516.             $this->getUser()->__set('currentCompanyViewed'$firstAllowedCompany);
  517.             //var_dump('user company id: ', $this->getUser()->getCurrentCompanyViewed()->getId());
  518.           
  519.             $rc $this->getUser()->save$this->getDoctrine()->getManager(), false );
  520.             //dump('update rc='.$rc);
  521.             if (!$rc) {
  522.                 die('user save error');
  523.                 //return false;
  524.             }
  525.         }
  526.         // <== COM-815
  527.         $companyInDb true;
  528.         /**** --> NO, creates other problems, better to change the user's last company
  529.         // handle the (rare/development) case when company was deleted
  530.         try {
  531.             $tmpName = $this->getUser()->getCurrentCompanyViewed()->getName();
  532.         } catch(EntityNotFoundException $e) {
  533.             $companyInDb = false;
  534.         } catch(\EntityNotFoundException $e) {
  535.             $companyInDb = false;
  536.         } catch(Exception $e) {
  537.             $companyInDb = false;
  538.         } catch(\Exception $e) {
  539.             $companyInDb = false;
  540.         }
  541.         dump('companyInDb', $companyInDb);
  542.         
  543.         //dump($this->getUser()->getCurrentCompanyViewed());
  544.         //dump($this->getUser()->getCurrentCompanyViewed()->deleted);
  545.         //$verifiedCompany = $this->getDoctrine()->getRepository(Company::class)->findOneById($this->getUser()->getCurrentCompanyViewed());
  546.         ****/
  547.         // COM-843 ==>
  548.         if ($module!='general' && $action!='check-session') {
  549.             $this->getUser()->__setDateTime('lastActionAt''now');
  550.             $this->getUser()->__set('lastModule'$module);
  551.             $this->getUser()->__set('lastActionType'$action);
  552.             $rc $this->getUser()->save$this->getDoctrine()->getManager(), false );
  553.             //dump('update rc='.$rc);
  554.             if (!$rc) {
  555.                 die('user save error');
  556.                 //return false;
  557.             }
  558.         }
  559.         // <== COM-843
  560.         
  561.         //dump($this->getUser()->getCurrentCompanyViewed()); //die();
  562.         ///superadmin-tacho-solve-orders/download-file/8123
  563.         // get company from current user (if exists)
  564.         if ($companyInDb &&
  565.             $this->getUser()->getCurrentCompanyViewed()!=null &&
  566.             $this->getUser()->getCurrentCompanyViewed()->__get('deleted')==false) {    // COM-643
  567.             // user already chose a company - get the company from the user's last choice
  568.             $this->company $this->getUser()->getCurrentCompanyViewed();
  569.             //var_dump('1: '.$this->company->getName());
  570.             
  571.             // in case it's not loaded
  572.             if ($this->account==null) {
  573.                 $this->account $this->company->getAccount();
  574.             }
  575.         } else {
  576.         
  577.             // user didn't choose a company yet
  578.             if ($this->getUser()->getRolesUnconverted()==UserRoleEnum::ROLE_SUPER_ADMIN ||
  579.                 $this->getUser()->getRolesUnconverted()==UserRoleEnum::ROLE_TRANSLATOR) { // COM-794
  580.                 
  581.                 // allowed to not have a company
  582.                 //dump('2');
  583.                 
  584.             } else {
  585.                 // find this account's main company
  586.                 if ($this->account->__get('primaryCompany')!=null &&
  587.                     $this->account->__get('primaryCompany')->__get('deleted')==false) {        // COM-643
  588.                     
  589.                     // use that company
  590.                     //dump('using primary company');
  591.                     $this->company $this->account->__get('primaryCompany');
  592.                     //dump('3');
  593.                     
  594.                 } else {
  595.                 
  596.                     // find any company of this account - JNOTE: earliest/assigned
  597.                     $accountCompanies $this->account->__get('companies');
  598.                     //dump('4');
  599.                     foreach($accountCompanies as $accountCompany) {
  600.                         //dump('accountCompany', $accountCompany);
  601.                         if ($accountCompany->__get('deleted')==true) continue;        // COM-643
  602.                         $this->company $accountCompany;
  603.                         //$this->account = $this->company->getAccount();
  604.                         break;
  605.                     }
  606.                     
  607.                 }    
  608.             }
  609.             
  610.         }
  611.         //var_dump('this->company: '.$this->company->name);
  612.         //dump('account type', $this->account->__get('type'));
  613.         $this->currentCountry = ($this->company!=null) ? $this->company->getCountry() : null;
  614.         //dump($this);
  615.         // COM-SEC
  616.         // check the entity being accessed belongs to this company
  617.         if ($entity!=null && $entity->getId()!='') {
  618.         
  619.             //dump('entity company check');
  620.         
  621.             if ($module=='companies') { //T
  622.             
  623.                 if ($entity->getAccount() != $this->account) {
  624.                     //dd('1');
  625.                     
  626.                     $this->redirectRoute 'noaccess.page';
  627.                     return false;
  628.                 
  629.                 }
  630.             
  631.             } else if ($module=='users') { //T
  632.             
  633.                 if ($entity->getAccount() != $this->account) {
  634.                 
  635.                     //dd('2');
  636.                     
  637.                     $this->redirectRoute 'noaccess.page';
  638.                     return false;
  639.                 
  640.                 }
  641.         
  642.             } else if (property_exists($entity'company') &&
  643.                        $entity->getCompany() != $this->company) {
  644.                 if ($request->isXmlHttpRequest()==false) {
  645.                     //dd('3');
  646.                     $this->redirectRoute 'noaccess.page';
  647.                     return false;
  648.                 } else {
  649.                 
  650.                 
  651.                 }
  652.                 //die('no permission');
  653.                     
  654.             }
  655.             
  656.             //JNOTE: check AJAX?
  657.             
  658.         }
  659.         /****
  660.         $requestCompanyId = $request->request->get('companyId');    
  661.         //dump('requestCompanyId', $requestCompanyId);
  662.         //dump('this->company', $this->company);
  663.         //dump('module', $module);
  664.         //dump('entity', $entity);
  665.         // check if company is correct for this entity
  666.         $companyChanged = false;
  667.         if ($requestCompanyId!=null && $this->company->getId()!=$requestCompanyId) {
  668.             // we know that the company id has changed, by a post parameter in an AJAX call
  669.             $companyChanged = true;
  670.             //$newRoute = RoutingHelper::getDefaultRoute($thisUserType);
  671.             //die($newRoute);
  672.             //$this->redirectRoute = $newRoute;    
  673.             //return false;
  674.         } else if ($entity!=null && $entity->getId()!=null && 
  675.                    !in_array($module, ['companies', 'penalties'])) {
  676. //JNOTE: check if companies list for different account??
  677.             // check if the company changed, by looking at current entity, etc
  678.             // this is used more for page opens (e.g. editing driver 78),
  679.             // but can also catch any AJAX problems (e.g. if the id on the page gets hacked, or if there is some error in the code)
  680.             
  681.             //dump('entity', $entity);
  682.             if ($module=='users') {
  683.                 //dump($entity, $this->company, $this->account);
  684.                 if ($entity->getAccount()!=$this->company->getAccount()) {
  685.                     $companyChanged = true;
  686.                 }
  687.             } else if ($module=='messages') {
  688.                 // check from or to
  689.             } else if (property_exists($entity, 'company')) {
  690.                 if ($entity->getCompany()!=$this->company) {
  691.                     $companyChanged = true;
  692.                 }
  693.             }
  694.         }
  695.         ****/
  696.         if (0&&$companyChanged) {
  697.             $newRoute RoutingHelper::getDefaultRoute($thisUserType);
  698.             //die($newRoute);
  699.             $this->redirectRoute $newRoute;    
  700.             return false;
  701.         }
  702.         
  703.         if (isset($_SERVER['APP_DEVELOPER_USER']) && $_SERVER['APP_DEVELOPER_USER']==$this->getUser()->getUsername()) {
  704.             $this->superAdminDebug true;
  705.         }
  706.         // now that we know the company, we can load the settings
  707.         $this->settings $this->settingsLoader->getSettings$this->company );
  708.         //dump($this->settings);
  709.         // and prepare the logger for saving data for this company
  710.         $this->logger->setCompany$this->company );
  711.         // and prepare the license helper, for any license/order actions
  712.         $activeLicense null;
  713.         if ($this->company!=null) {
  714.             $this->balanceHelper->setCompany$this->company );
  715.             $this->licenseHelper->setCompany$this->company );
  716.             $activeLicense $this->licenseHelper->getActiveLicense$this->company->getId() );
  717.             $this->messageHelper->setCompany$this->company );
  718.             //dump($activeLicense);
  719.         }
  720.         
  721.         /*if (isset($activeLicense['action']) && $activeLicense['action']=='redirect') {
  722.         
  723.             // JNOTE
  724.         
  725.         } else if ($activeLicense['sum']['license_type']==LicenseTypeEnum::DRIVER) {
  726.             //dump('activeLicense', $activeLicense);
  727.             
  728.             $this->licenseHelper->getDriverLicenseForDriver(958, $this->company, LicenseTypeEnum::DRV_LIC_AETR, 
  729.                                                             '2010-02', //$startDate, 
  730.                                                             '2011-01', //$endDate = false, 
  731.                                                             $driverLicenseAssignments);
  732.             //dump('driverLicenseAssignments', $driverLicenseAssignments);
  733.         }*/
  734.         
  735.         
  736.         //dd('--');
  737.         // check user permission (voters) - except for general module (login, etc.)
  738.         // MUST be here - voters check licenseHelper
  739.         if ($module!='general') {
  740.             //dd("denyAccessUnlessGranted", $action, $entity);
  741.             $this->denyAccessUnlessGranted($action$entity);
  742.             // NOTE: control won't go here; 
  743.             // - if it's a page, the user is sent to the "no access" page
  744.             // - if ajax request, an error JSON is returned
  745.             //die('XXX');
  746.         }
  747.         
  748.         //dump('4');
  749.         // This session variable is used to log out the user automatically. (After self::LOGIN_EXPIRY is reached, the page will log the user out.)
  750.         // The last user action must be kept here, because just a javascript timer on the page is not enough. Reason:
  751.         // - The JS timer would have to be per page, but multiple pages can be open (different browser tabs), each with different page open time,
  752.         //   and tabs out of focus (opened earlier) can log out all other tabs (opened later).
  753.         // - Hence, the timer must be on the server side.
  754.         if ($module!='general' || $action!='check-session') {
  755.             // Save the last user action time (other than automated check-session). This starts the countdown,
  756.             // which will log the user out, once self::LOGIN_EXPIRY is reached on the current page. (Due to page open, or ajax call.)
  757.             $this->session->set('last-user-action-time'time());
  758.             //dump('updating last-user-action-time', $this->session->get('last-user-action-time'));
  759.         }
  760.         // get info about current company & account
  761.         $numCompaniesInAccount 0;
  762.         if ($this->account!=null) {
  763.             $numCompaniesInAccount count($this->account->getCompanies());
  764.         }
  765.         
  766.         // get current company config status
  767.         $this->currentCompanyConfigStatus null;
  768.         if ($activeLicense!=null) {
  769.             $this->currentCompanyConfigStatus $this->checkCurrentCompanyConfigStatus($activeLicense);
  770.         }
  771.         //dump("currentCompanyConfigStatus: $this->currentCompanyConfigStatus, numCompaniesInAccount: $numCompaniesInAccount"); //die();    
  772.         //dump('activeLicense', $activeLicense); die();
  773.         // get current company AI status - COM-709a
  774.         if (!$this->firstLoginConfigMode)  {
  775.         
  776.             // check if AI enabled
  777.             if (in_array($this->getUser()->getRolesUnconverted(), [UserRoleEnum::ROLE_SUPER_ADMIN,
  778.                                                                    UserRoleEnum::ROLE_ACCOUNT_OWNER,
  779.                                                                    UserRoleEnum::ROLE_ADMIN])) {
  780.                 $this->aiEnabled true;
  781.                 //dump('aiEnabled');
  782.                 
  783.             }
  784.             
  785.             // COM-831
  786.             // AI is disabled for ToDo-only companies
  787.             if ($this->company!==null && $this->company->__get('specialType')==CompanySpecialTypeEnum::TODO_ONLY) {
  788.                 $this->aiEnabled false;
  789.             }
  790.             
  791.             // get company paid AI status
  792.             if ($this->aiEnabled) {
  793.                 $currentMonthNum intval(date('m'));
  794.                 $currentMonthAIPaidLicense $this->settings['ai']['tipMonthlyLicences'][$currentMonthNum-1];
  795.                 //dump('currentMonthAIPaidLicense: '.$currentMonthAIPaidLicense);
  796.                 // COM-731
  797.                 if (isset($_SERVER['APP_AI_ALWAYS_ALLOW_PAID_FOR_COMPANY_TYPES']) &&
  798.                     $_SERVER['APP_AI_ALWAYS_ALLOW_PAID_FOR_COMPANY_TYPES']!='' &&
  799.                     $this->company!==null) {
  800.                     $companyTypesAllowingPaidAI explode(','$_SERVER['APP_AI_ALWAYS_ALLOW_PAID_FOR_COMPANY_TYPES']);
  801.                     if (in_array($this->company->__get('adminType'), $companyTypesAllowingPaidAI)) {
  802.                     
  803.                         $this->aiPaidLicenseThisMonth true;
  804.                         //dump('auto allow paid Bob, company type: '.$this->company->__get('adminType'));
  805.                         //dump('.');
  806.                         
  807.                     } else {
  808.                     
  809.                         if ($currentMonthAIPaidLicense==1) {
  810.                             $this->aiPaidLicenseThisMonth true;
  811.                             //dump('aiPaidLicenseThisMonth');
  812.                         }
  813.                     }
  814.                     
  815.                 } else {
  816.                     if ($currentMonthAIPaidLicense==1) {
  817.                         $this->aiPaidLicenseThisMonth true;
  818.                         //dump('aiPaidLicenseThisMonth');
  819.                     }
  820.                 }
  821.                 
  822.             }
  823.             
  824.             if ($this->superAdminDebug && !($request->isXmlHttpRequest())) {
  825.                 //dump("aiEnabled: $this->aiEnabled, aiPaidLicenseThisMonth: $this->aiPaidLicenseThisMonth");
  826.             }
  827.         
  828.         }
  829.         // API -- COM-815
  830.         $inputArray['apiAllowed'] = '0';
  831.         if ($this->getUser()->getRolesUnconverted()==UserRoleEnum::ROLE_SUPER_ADMIN ||
  832.             $this->getUser()->getRolesUnconverted()==UserRoleEnum::ROLE_ACCOUNT_OWNER) {
  833.     
  834.             if (isset($_SERVER['APP_API_COMPANY_IDS']) && $_SERVER['APP_API_COMPANY_IDS']!='' && 
  835.                 $this->company!==null) {
  836.                 $apiCompanyIds explode(','$_SERVER['APP_API_COMPANY_IDS']);
  837.                 //dump($apiCompanyIds);
  838.                 if (in_array($this->company->getId(), $apiCompanyIds)) {
  839.     
  840.                     $this->enableApi true;
  841.                 
  842.                     $inputArray['apiAllowed'] = '1';
  843.                     //dump('IN');
  844.                 
  845.                 }
  846.                     
  847.             }
  848.         
  849.         }
  850.         
  851. /*
  852.         const INITIAL            =   0;     // company created, no config yet
  853.         const CONFIG_COMPLETE    =  50;     // config complete, order not placed
  854.         const ORDER_PLACED        =  75;     // order placed, not completed
  855.         const ACTIVE            = 100;     // order completed/company activated
  856.         const LICENSE_EXPIRED    = 110;     // previously active company, license expired
  857.         if ($numCompaniesInAccount == 1) {
  858.             
  859.             if ($companyConfigurationStep < 7) {
  860.                 
  861.                 // didn't complete configuration, must be forced to edit the config popup
  862.                 $this->newCompanyConfigMode = true;
  863.                     
  864.             } else {
  865.                 
  866.                 // completed config, check if balance is set    
  867.         // apply permissions based on user role & company configuration state
  868.         if ($this->getUser()->getRolesUnconverted()==UserRoleEnum::ROLE_ACCOUNT_OWNER) {
  869.             $companyH = ($this->company->configurationStep >= 7);
  870.             
  871.             //dump("numCompaniesInAccount: $numCompaniesInAccount, companyConfigurationStep: $companyConfigurationStep");
  872.             dump('num companies in account', count($this->account->getCompanies()));
  873.             dump('configurationStep', $this->company->configurationStep);
  874.             // no user means login session expired, send to login page
  875.             $this->redirectRoute = 'b_login';
  876.             //dump('3b');
  877.             return false;
  878. */
  879.         // NOTE: overwite this, since calls to this functions are not all done correctly, and there is no time to fix them all up (July 21)
  880.         $ajaxCall = ($request->isXmlHttpRequest());
  881.         //dump("ajaxCall: $ajaxCall");
  882.         //dump("currentCompanyConfigStatus: $this->currentCompanyConfigStatus, numCompaniesInAccount: $numCompaniesInAccount"); //die();    
  883.         //dump($ajaxCall, $module, $action, $parms);
  884.         // special logic to bypass further permission checks
  885.         if ($ajaxCall && $module=='general' && $action=='check-session') {
  886.             // check session, no need
  887.             return true;
  888.         } else if ($ajaxCall &&
  889.                    $module=='general' && $action=='general' &&
  890.                    isset($parms['lastConfigStep']) && $parms['lastConfigStep']===true) {
  891.             // if on last step of configuration popup, we can't continue (or the code below will throw 'no-access-to-company-with-no-license')
  892.             return true;
  893.         } else if ($ajaxCall && $module=='general' && $action=='message-reaction') {  // COM-792
  894.             // if on broadcast mesage popup, we can't continue (or the code below will throw 'no-access-to-company-with-no-license')
  895.             return true;
  896.         } else if ($ajaxCall &&
  897.                    $module=='companies' && $action=='view' &&
  898.                    isset($parms['changeToCompany'])) {
  899.             // allow change to new company - this will be followed by a page reload (at new company), 
  900.             // and then this logic will be re-run for the new company (allowing or disallowing access as needed)
  901.             
  902.             // NOTE: if user on 'no-access-to-company-with-no-license' page, then changes company to another with a valid license,
  903.             // he will be moved to another page - see MainController::company_not_ready_page()
  904.             //$newCompany = $this->getDoctrine()->getRepository(Company::class)->findOneById($parms['changeToCompany']);
  905.             
  906.             return true;
  907.         }
  908.         //// that's all needed if this is an ajax call
  909.         //if ($ajaxCall==true) return true;
  910.         //dump($this->getUser()->__get('firstLoginConfigAt'));
  911.         //// PAGE OPEN ONLY FROM HERE ON DOWN
  912.         $onNoAccessPage = ($request->getPathInfo() == '/no-access');
  913.         $onNoAccessCompanyNotReadyPage = ($request->getPathInfo() == '/company-not-ready');
  914.         $onBalancePage = (substr($request->getPathInfo(),0,8) == '/balance');
  915.         // check for which pages the user is allowed to access - based on user type, and company config stage
  916.         if ($this->getUser()->getRolesUnconverted()==UserRoleEnum::ROLE_SUPER_ADMIN) {
  917.         
  918.             // Compass user - full access, no need to create popup, send to any page, or do anything else;
  919.             // just proceed
  920.         
  921.         } else if ($this->getUser()->getRolesUnconverted()==UserRoleEnum::ROLE_ACCOUNT_OWNER) {
  922.                 
  923.             // Registered user - can configure company, order/extend licenses
  924.             // (access depends on company config status)
  925.             //dump('ROLE_ACCOUNT_OWNER', $this->currentCompanyConfigStatus, ($this->currentCompanyConfigStatus==CompanyConfigStatusTypeEnum::CONFIG_COMPLETE));
  926.             if ($this->currentCompanyConfigStatus==CompanyConfigStatusTypeEnum::INITIAL) {
  927.             
  928.                 // initial status, need to show company config popup (cannot be closed)
  929.                 if ($this->getUser()->__get('firstLoginConfigAt')==null) {
  930.                     // first login, this user can only configure the company, can't do anything else
  931.                     $this->firstLoginConfigMode true;
  932.                 } else if ($this->company->__get('configurationStep') < 7) {
  933.             
  934.                     // new company, this user can 
  935.                     $this->newCompanyConfigMode true;
  936.                 }
  937.                 
  938.                 // JNOTE: need to differentiate between firstLoginConfigMode and newCompanyConfigMode above???
  939.             } else if ($this->currentCompanyConfigStatus==CompanyConfigStatusTypeEnum::CONFIG_COMPLETE) {
  940.             
  941.                 // config completed, need to send the user to the Balance page, so he places the order
  942.                 // place an order - and no access to other pages
  943.                 //dump('CONFIG_COMPLETE');
  944.                 if ($this->immediatelyAfterLogin) {
  945.                 
  946.                     // if right after login, go to balance only
  947.                     $allowedModules = [
  948.                         'balance',
  949.                     ];
  950.                 } else {
  951.                     // later, allow other pages too
  952.                     if ($numCompaniesInAccount==1) {
  953.                     
  954.                         // there is only one company, allow the following
  955.                         $allowedModules = [
  956.                             'documents',
  957.                             'balance',
  958.                             'messages',
  959.                             'companies',
  960.                         ];
  961.                     } else {
  962.                     
  963.                         // there is only one company, allow the same as above
  964.                         $allowedModules = [
  965.                             'documents',
  966.                             'balance',
  967.                             'messages',
  968.                             'companies',
  969.                             'users',
  970.                         ];
  971.                         
  972.                     }
  973.                     // JNOTE: those not available should be grayed out maybe
  974.                     
  975.                 }
  976.                 //dump('allowedModules', $allowedModules, $module, in_array($module, $allowedModules)); die();
  977.                 
  978.                 if (!in_array($module$allowedModules)) {
  979.                     throw new AccessDeniedException('no-access-to-company-with-no-license');
  980.                 }
  981.                 
  982.             } else if ($this->currentCompanyConfigStatus==CompanyConfigStatusTypeEnum::ORDER_PLACED) {
  983.             
  984.                 // order placed, now the user needs to wait for Compass to activate the license (e.g. when money comes in)
  985.                 //dump('ORDER_PLACED');
  986.                 if ($this->immediatelyAfterLogin) {
  987.                 
  988.                     // if right after login, go to balance only
  989.                     $allowedModules = [
  990.                         'balance',
  991.                     ];
  992.                 } else {
  993.                     // later, allow other pages too
  994.                     if ($numCompaniesInAccount==1) {
  995.                     
  996.                         // there is only one company, allow the following
  997.                         $allowedModules = [
  998.                             'documents',
  999.                             'balance',
  1000.                             'messages',
  1001.                             'companies',
  1002.                         ];
  1003.                     } else {
  1004.                     
  1005.                         // there is only one company, allow the same as above
  1006.                         $allowedModules = [
  1007.                             'documents',
  1008.                             'balance',
  1009.                             'messages',
  1010.                             'companies',
  1011.                             'users',
  1012.                         ];
  1013.                         
  1014.                     }
  1015.                     // JNOTE: those not available should be grayed out maybe
  1016.                     
  1017.                 }
  1018.                 //dump('allowedModules', $allowedModules, $module, in_array($module, $allowedModules)); die();
  1019.                 
  1020.                 if (!in_array($module$allowedModules)) {
  1021.                     throw new AccessDeniedException('no-access-to-company-with-no-license');
  1022.                 }
  1023.                 
  1024.             } else { // ACTIVE, LICENSE_EXPIRED
  1025.                 
  1026.                 // company is active, license is active (or expired): allow full access to this company
  1027.                 
  1028.             }
  1029.         } else if ($this->getUser()->getRolesUnconverted()==UserRoleEnum::ROLE_ADMIN ||
  1030.                      $this->getUser()->getRolesUnconverted()==UserRoleEnum::ROLE_UPLOAD_ONLY ||        // COM-639
  1031.                      $this->getUser()->getRolesUnconverted()==UserRoleEnum::ROLE_UPLOAD_PROTOCOL) {    // COM-639
  1032.             // Admin user - can order/extend licenses, cannot create or configure new companies
  1033.             // (access depends on company config status)
  1034.             
  1035.             if ($this->currentCompanyConfigStatus==CompanyConfigStatusTypeEnum::CONFIG_COMPLETE) {
  1036.             
  1037.                 // config completed, need to send the user to the Balance page, so he places the order
  1038.                 // place an order - and no access to other pages
  1039.                 //dump('CONFIG_COMPLETE');
  1040.                 if ($this->immediatelyAfterLogin) {
  1041.                 
  1042.                     // if right after login, go to balance only
  1043.                     $allowedModules = [
  1044.                         'balance',
  1045.                     ];
  1046.                 } else {
  1047.                     // later, allow other pages too
  1048.                     if ($numCompaniesInAccount==1) {
  1049.                     
  1050.                         // there is only one company, allow the following
  1051.                         $allowedModules = [
  1052.                             'documents',
  1053.                             'balance',
  1054.                             'messages',
  1055.                             'companies',
  1056.                         ];
  1057.                     } else {
  1058.                     
  1059.                         // there is only one company, allow the same as above
  1060.                         $allowedModules = [
  1061.                             'documents',
  1062.                             'balance',
  1063.                             'messages',
  1064.                             'companies',
  1065.                             'users',
  1066.                         ];
  1067.                         
  1068.                     }
  1069.                     // JNOTE: those not available should be grayed out maybe
  1070.                     
  1071.                 }
  1072.                 //dump('allowedModules', $allowedModules, $module, in_array($module, $allowedModules)); die();
  1073.                 
  1074.                 if (!in_array($module$allowedModules)) {
  1075.                     throw new AccessDeniedException('no-access-to-company-with-no-license');
  1076.                 }
  1077.                 
  1078.             } else if ($this->currentCompanyConfigStatus==CompanyConfigStatusTypeEnum::ORDER_PLACED) {
  1079.             
  1080.                 // order placed, now the user needs to wait for Compass to activate the license (e.g. when money comes in)
  1081.                 //dump('ORDER_PLACED');
  1082.                 if ($this->immediatelyAfterLogin) {
  1083.                 
  1084.                     // if right after login, go to balance only
  1085.                     $allowedModules = [
  1086.                         'balance',
  1087.                     ];
  1088.                 } else {
  1089.                     // later, allow other pages too
  1090.                     if ($numCompaniesInAccount==1) {
  1091.                     
  1092.                         // there is only one company, allow the following
  1093.                         $allowedModules = [
  1094.                             'documents',
  1095.                             'balance',
  1096.                             'messages',
  1097.                             'companies',
  1098.                         ];
  1099.                     } else {
  1100.                     
  1101.                         // there is only one company, allow the same as above
  1102.                         $allowedModules = [
  1103.                             'documents',
  1104.                             'balance',
  1105.                             'messages',
  1106.                             'companies',
  1107.                             'users',
  1108.                         ];
  1109.                         
  1110.                     }
  1111.                     // JNOTE: those not available should be grayed out maybe
  1112.                     
  1113.                 }
  1114.                 //dump('allowedModules', $allowedModules, $module, in_array($module, $allowedModules)); die();
  1115.                 
  1116.                 if (!in_array($module$allowedModules)) {
  1117.                     throw new AccessDeniedException('no-access-to-company-with-no-license');
  1118.                 }
  1119.                 
  1120.             } else { // ACTIVE, LICENSE_EXPIRED
  1121.                 
  1122.                 // company is active, license is active (or expired): allow full access to this company
  1123.                 
  1124.             }
  1125.         } else if ($this->getUser()->getRolesUnconverted()==UserRoleEnum::ROLE_TRANSLATOR) {        // COM-794
  1126.         
  1127.             // no company permission/configuration check needed
  1128.         
  1129.         } else { // VIEWER
  1130.         
  1131.             // Viewer user - limited access to some pages only
  1132.             // (access depends on company config status)
  1133.             
  1134.             //dump('$this->currentCompanyConfigStatus (VIEWER types)', $this->currentCompanyConfigStatus);
  1135.         
  1136.             if ($this->currentCompanyConfigStatus==CompanyConfigStatusTypeEnum::ACTIVE ||
  1137.                 $this->currentCompanyConfigStatus==CompanyConfigStatusTypeEnum::LICENSE_EXPIRED) {
  1138.                 
  1139.                 // license is active or expired: allow access to this company
  1140.                 
  1141.                 /*if ($onNoAccessCompanyNotReadyPage) {
  1142.                 
  1143.                     $newRoute = RoutingHelper::getDefaultRoute( $this->getUser()->getRolesUnconverted() );
  1144.                     //return new Response(new RedirectResponse( $this->router->generate($newRoute) ));
  1145.                     //return new RedirectResponse($newRoute);
  1146.                     $this->redirectRoute = $newRoute;
  1147.                     return false;
  1148.                 
  1149.                     dd('onNoAccessCompanyNotReadyPage', $newRoute);
  1150.                     
  1151.                 }*/
  1152.                 
  1153.             } else {
  1154.                 
  1155.                 // do not allow access, send to an error page
  1156.                 if (!$onNoAccessCompanyNotReadyPage) {
  1157.                     throw new AccessDeniedException('no-access-to-not-configured-company');
  1158.                 }
  1159.                 
  1160.             }
  1161.         
  1162.         }
  1163.         /***
  1164.         // check for first login configuration
  1165.         if ($this->getUser()->getRolesUnconverted()==UserRoleEnum::ROLE_ACCOUNT_OWNER) {
  1166.         
  1167.             if ($this->getUser()->__get('firstLoginConfigAt')==null) {
  1168.                 // first login, this user can only configure the company, can't do anything else
  1169.                 $this->firstLoginConfigMode = true;
  1170.             } else if ($this->company->__get('configurationStep') < 7) {
  1171.             
  1172.                 // new company, this user can 
  1173.                 $this->newCompanyConfigMode = true;
  1174.             }
  1175.             
  1176.             // JNOTE: other user types should not be allowed to do this
  1177.         }
  1178.         ****/
  1179.         return true;
  1180.     }
  1181.     // COM-API
  1182.     protected function handleControllerApiAction(&$request$action=null$apiUser=null,
  1183.                                                  $apiKey=null$companyUuid=null$company=null) { //miniRM
  1184.         //dump("handleControllerApiAction request, $action, $apiKey, $companyUuid");
  1185.         /****
  1186.         // check module
  1187.         if ($request==null || $module==null || $action==null) {
  1188.             $this->redirectRoute = $this->homeRoute;
  1189.             return false;
  1190.         }
  1191.         ****/
  1192.         
  1193.         //$this->timeCalc->refreshTimeZone();
  1194.         // ----- CHECK RATE LIMIT (DDOS prevention) -----
  1195.         // apply limiting the request frequency to prevent DDOS
  1196.         /*$rc = $this->checkApiRequestRateLimit();
  1197.         if ($rc!==true) {
  1198.             return $rc;
  1199.         }*/
  1200.         if (0) {
  1201.             $this->rateLimiter->applyRateLimit($request); //$clientEmail, $apiType)
  1202.             die("----\n");
  1203.         }
  1204.         // ----- VALIDATE API KEY -----
  1205.         // get API key from Request & validate it
  1206.         if ($apiKey==null) { //miniRM
  1207.         
  1208.             $apiKey $request->request->get('apiKey');
  1209.             if ($apiKey==null) {
  1210.                 return 'missing-key';
  1211.             }
  1212.             
  1213.         }
  1214.         //echo "input apiKey: [$apiKey]\n";
  1215.         $apiKeyValid false;
  1216.         //$validApiKeyNames = ApiOriginTypeEnum::getValidApiKeyNames(); //API
  1217.         foreach($this->validApiKeyName as $apiKeyName) {
  1218.             //echo("$apiKeyName: "); echo($_SERVER[$apiKeyName]); echo("\n");
  1219.             if (isset($_SERVER[$apiKeyName])) {
  1220.                 if ($apiKey==$_SERVER[$apiKeyName]) {
  1221.                     $apiKeyValid true;
  1222.                     //dump("API key $apiKeyName matched");
  1223.                     break;
  1224.                 }
  1225.             }
  1226.         }
  1227.         //dump($this->validApiKeyName);
  1228.         if (!$apiKeyValid) {
  1229.             //dump('bad key');
  1230.             return 'invalid-key';         
  1231.         }
  1232.         // ----- CHECK RATE LIMIT (DDOS prevention) -----
  1233.         // apply limiting the request frequency to prevent DDOS
  1234.         //$this->rateLimiter->applyRateLimit($request);
  1235.         $originType null;
  1236.         $originId null;
  1237.         
  1238.         //die($apiKey.' ?= '.$_SERVER['APP_API_KEY_ANDROID']);
  1239.         
  1240.         $company null;
  1241.         $companyChosen false;
  1242.         // different logic based on app type (android, MiniRm)
  1243.         if (isset($_SERVER['APP_API_KEY_ANDROID']) && //COM-822
  1244.             $apiKey==$_SERVER['APP_API_KEY_ANDROID']) {
  1245.         
  1246.             //dd('tacho solve');
  1247.             $this->tachoSolve->setCurrentUser($apiUser);
  1248.             $ret $this->tachoSolve->processApiRequest($request);
  1249.             //dump('processApiRequest ret', $ret);
  1250.             //LoggingHelper::var_dump('processApiRequest::ret', $ret);
  1251.             if (!isset($ret['success'])) {
  1252.                 // error
  1253.                 return $ret;
  1254.             }
  1255.             
  1256.             // the company was either created in TachoSolveManager class, 
  1257.             // or it was loaded from the already-existing order
  1258.             if ($ret['currentCompany']!=null) {
  1259.             
  1260.                 //$this->company = null;
  1261.                 //$this->account = null;
  1262.                 $company $ret['currentCompany'];
  1263.                 //$this->account = $this->company->getAccount();
  1264.                 $companyChosen true;
  1265.             }
  1266.             $this->apiHelper->setTachoSolveMode();
  1267.             $this->apiHelper->setOriginType($ret['originType']);
  1268.             $this->apiHelper->setOriginId($ret['originId']);
  1269.         } else if (isset($_SERVER['APP_API_KEY_MINI_RM']) && // check for mini-RM -- COM-839
  1270.                    $apiKey==$_SERVER['APP_API_KEY_MINI_RM']) {
  1271.             //JNOTE-TEMP
  1272.             $ret = [
  1273.                 'originType' => ApplicationTypeEnum::API_MINI_RM,
  1274.                 'originId' => null,
  1275.             ];
  1276.             $company $this->getDoctrine()->getRepository(Company::class)->findOneById(225);
  1277.             $companyChosen true;
  1278.             $this->apiHelper->setMiniRmMode();
  1279.             $this->apiHelper->setOriginType($ret['originType']);
  1280.             $this->apiHelper->setOriginId($ret['originId']);
  1281.             // this tells the code to not clear EntityManager after each file (otherwise things don't work)
  1282.             $this->apiHelper->setMultiFileMode();
  1283.         } else {
  1284.         
  1285.             // default API        
  1286.             $this->apiHelper->setOriginType(ApplicationTypeEnum::API_CLIENT);
  1287.             //$this->apiHelper->setOriginId($originId);
  1288.             //JNOTE: check other API keys, etc.?
  1289.         
  1290.         }
  1291.         // COM-815
  1292.         //$originInfo = ApiOriginTypeEnum::getOriginFromApiKey($apiKey);
  1293.         //$this->apiHelper->setOriginType($originInfo['originType']);
  1294.         //$this->apiHelper->setOriginId($originInfo['originId']); //JNOTE
  1295.         if ($originType!==null$this->apiHelper->setOriginType($originType);
  1296.         if ($originId!==null$this->apiHelper->setOriginId($originId);
  1297.         // ----- VALIDATE COMPANY -----
  1298.         // get company from Request & validate it (all requests need company!)
  1299.         if ($companyChosen==false) {
  1300.             if ($companyUuid==null && $company==null) { //miniRM
  1301.         
  1302.                 //$companyUuid = $request->query->get('company');
  1303.                 $companyUuid $request->request->get('company');
  1304.                 //LoggingHelper::var_dump('companyUuid (query)', $companyUuid);
  1305.                 if ($companyUuid==null) {
  1306.                     return 'missing-company';
  1307.                 }
  1308.             
  1309.             } else if ($company!==null) {
  1310.         
  1311.                 $companyUuid $company->__get('uuid');
  1312.         
  1313.             }
  1314.         }
  1315.         // JNOTE: check format, check for injection
  1316.         // find company
  1317.         if ($companyChosen==false &&
  1318.              $company===null) {
  1319.         
  1320.             $companyRepository $this->getDoctrine()->getRepository(Company::class);
  1321.             $company $companyRepository->findOneBy([
  1322.                                                         'uuid' => $companyUuid//'a97eb1f8-ae46-11ef-905d-0050568c',
  1323.                                                         'deleted' => 0,
  1324.                                                     ]);
  1325.                                                     
  1326.         }
  1327.         //dd(); //'company', $company);
  1328.         //dump('company;', $company->getName());
  1329.         
  1330.         if ($company==null) {
  1331.             return 'invalid-company';
  1332.         }
  1333.         $this->company $company;
  1334.         $userRepository $this->getDoctrine()->getRepository(User::class);
  1335.         //$this->currentUser = $userRepository->findOneById($_SERVER['APP_API_USER_ID']);
  1336.         //$this->setUser($this->currentUser); //???
  1337.         
  1338.         /*
  1339.         use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  1340.         use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
  1341.         
  1342.         // main - your main firewall key    
  1343.         $token = new UsernamePasswordToken($user, null, 'main', $user->getRoles());
  1344.         $tokenStorage->setToken($token);
  1345.         */
  1346.         /****
  1347.         $thisUserType = ($this->getUser()==null) ? null : $this->getUser()->getRolesUnconverted();
  1348.         if ($this->getUser()==null) {
  1349.             $this->redirectRoute = 'b_logout';
  1350.             return false;
  1351.         }
  1352.         //dump('3a', $module, $this->getUser()->getUsername()); ///
  1353.         // set language & locale
  1354.         $this->setLanguageAndLocale($request);
  1355.         //dump('3a.1');
  1356.         $this->calcHelper->setLanguage($this->currentLanguage);
  1357.         ****/
  1358.         //dump('3a.2');
  1359.         $this->currentCountry = ($company!=null) ? $company->getCountry() : null;
  1360.         //dump($this);
  1361.         //if (isset($_SERVER['APP_DEVELOPER_USER']) && $_SERVER['APP_DEVELOPER_USER']==$this->getUser()->getUsername()) {
  1362.         //    $this->superAdminDebug = true;
  1363.         //}
  1364.         // now that we know the company, we can load the settings
  1365.         $this->settings $this->settingsLoader->getSettings$company );
  1366.         //dump($this->settings);
  1367.         // and prepare the logger for saving data for this company
  1368.         $this->logger->setCompany$company );
  1369.         // and prepare the license helper, for any license/order actions
  1370.         $activeLicense null;
  1371.         if ($this->company!=null) {
  1372.             $this->balanceHelper->setCompany$company );
  1373.             $this->licenseHelper->setCompany$company );
  1374.             $activeLicense $this->licenseHelper->getActiveLicense$company->getId() );
  1375.             $this->messageHelper->setCompany$company );
  1376.             //dump($activeLicense);
  1377.         }
  1378.         
  1379.         //dd('--');
  1380.         /****
  1381.         // check user permission (voters) - except for general module (login, etc.)
  1382.         // MUST be here - voters check licenseHelper
  1383.         if ($module!='general') {
  1384.             //dd("denyAccessUnlessGranted", $action, $entity);
  1385.             $this->denyAccessUnlessGranted($action, $entity);
  1386.             // NOTE: control won't go here; 
  1387.             // - if it's a page, the user is sent to the "no access" page
  1388.             // - if ajax request, an error JSON is returned
  1389.             //die('XXX');
  1390.         }
  1391.         ****/
  1392.         
  1393.         //dump('4');
  1394.         // get info about current company & account
  1395.         $numCompaniesInAccount 0;
  1396.         if ($this->account!=null) {
  1397.             $numCompaniesInAccount count($this->account->getCompanies());
  1398.         }
  1399.         
  1400.         
  1401.         // get current company config status
  1402.         $this->currentCompanyConfigStatus null;
  1403.         if ($activeLicense!=null) {
  1404.             $this->currentCompanyConfigStatus $this->checkCurrentCompanyConfigStatus($activeLicense);
  1405.         }
  1406.         //dump("currentCompanyConfigStatus: $this->currentCompanyConfigStatus, numCompaniesInAccount: $numCompaniesInAccount"); //die();    
  1407.         //dump('activeLicense', $activeLicense); die();
  1408.         // NOTE: overwite this, since calls to this functions are not all done correctly, and there is no time to fix them all up (July 21)
  1409.         //$ajaxCall = ($request->isXmlHttpRequest());
  1410.         //dump("ajaxCall: $ajaxCall");
  1411.         //dump("currentCompanyConfigStatus: $this->currentCompanyConfigStatus, numCompaniesInAccount: $numCompaniesInAccount"); //die();    
  1412.         //dump($ajaxCall, $module, $action, $parms);
  1413.         /****
  1414.         // special logic to bypass further permission checks
  1415.         if ($ajaxCall && $module=='general' && $action=='check-session') {
  1416.             // check session, no need
  1417.             return true;
  1418.         } else if ($ajaxCall &&
  1419.                    $module=='general' && $action=='general' &&
  1420.                    isset($parms['lastConfigStep']) && $parms['lastConfigStep']===true) {
  1421.             // if on last step of configuration popup, we can't continue (or the code below will throw 'no-access-to-company-with-no-license')
  1422.             return true;
  1423.         } else if ($ajaxCall && $module=='general' && $action=='message-reaction') {  // COM-792
  1424.             // if on broadcast mesage popup, we can't continue (or the code below will throw 'no-access-to-company-with-no-license')
  1425.             return true;
  1426.         } else if ($ajaxCall &&
  1427.                    $module=='companies' && $action=='view' &&
  1428.                    isset($parms['changeToCompany'])) {
  1429.             // allow change to new company - this will be followed by a page reload (at new company), 
  1430.             // and then this logic will be re-run for the new company (allowing or disallowing access as needed)
  1431.             
  1432.             // NOTE: if user on 'no-access-to-company-with-no-license' page, then changes company to another with a valid license,
  1433.             // he will be moved to another page - see MainController::company_not_ready_page()
  1434.             //$newCompany = $this->getDoctrine()->getRepository(Company::class)->findOneById($parms['changeToCompany']);
  1435.             
  1436.             return true;
  1437.         }
  1438.         ****/
  1439.         //// that's all needed if this is an ajax call
  1440.         //if ($ajaxCall==true) return true;
  1441.         //dump($this->getUser()->__get('firstLoginConfigAt'));
  1442.         return true;
  1443.     }
  1444.     private function checkApiRequestRateLimit() {
  1445.     
  1446.         $apiConnectionRepository $this->getDoctrine()->getRepository(ApiConnection::class);
  1447.     
  1448.         // check how many calls from this API address, ApiConnection::API_CALLS_PERIOD_SECONDS in the past
  1449.         $numRecentCalls $apiConnectionRepository->getNumRecentApiCallsFromIpAddress(ApiConnection::API_CALLS_PERIOD_SECONDS$_SERVER['REMOTE_ADDR']);
  1450.         //var_dump($numRecentCalls);
  1451.         //echo "numRecentCalls: $numRecentCalls\n";
  1452.         
  1453.         if ($numRecentCalls <= ApiConnection::MAX_NUM_API_CALLS_PER_PERIOD) {
  1454.         
  1455.             // rate limit not reached, add the record to db
  1456.             $apiConnection = new ApiConnection;
  1457.             $apiConnection->__set('ipAddress'$_SERVER['REMOTE_ADDR']);
  1458.             
  1459.             $rc $apiConnection->save$this->getDoctrine()->getManager() );
  1460.             if (!$rc) {
  1461.                 die('error creating apiConnection');
  1462.             }
  1463.             
  1464.             return true;
  1465.             
  1466.         } else {
  1467.         
  1468.             return 'too-many-requests';
  1469.             
  1470.         }
  1471.         
  1472.     }
  1473.     private function checkCurrentCompanyConfigStatus($activeLicense=null) {
  1474.         // if current company not selected (i.e. Compass user), return null
  1475.         if ($this->company===null) return null;
  1476.         //$numCompaniesInAccount = count($this->account->getCompanies());
  1477.         
  1478.         //dump('configurationStep', $this->company->configurationStep); //, $this->company);
  1479.         // check if company config completed
  1480.         if ($this->company->configurationStep 7) {
  1481.             return CompanyConfigStatusTypeEnum::INITIAL;
  1482.         }
  1483.         // check if order placed
  1484.         if ($activeLicense==null$activeLicense $this->licenseHelper->getActiveLicense$this->company->getId() );
  1485.         //dump('activeLicense', $activeLicense);
  1486.         if (isset($activeLicense['action']) && $activeLicense['action']==='redirect') {
  1487.         
  1488.             if (!isset($activeLicense['active_order']) || $activeLicense['active_order']===0) {
  1489.                 return CompanyConfigStatusTypeEnum::CONFIG_COMPLETE;
  1490.             } else {
  1491.                 return CompanyConfigStatusTypeEnum::ORDER_PLACED;
  1492.             }
  1493.         }
  1494.         
  1495.         // check if there is a license
  1496.         if (isset($activeLicense['sum'])) {
  1497.             $status CompanyConfigStatusTypeEnum::ACTIVE;
  1498.             
  1499.             // JNOTE: company license expired (LICENSE_EXPIRED) - need something here?
  1500.             return $status;
  1501.         }
  1502.         
  1503.         return false;
  1504.     }
  1505.     
  1506.     protected function setLanguageAndLocale($request) {
  1507.         //dump($this->session->get('language'));
  1508.         // set language & locale
  1509.         $language $request->query->get('lang');
  1510.         //$tmpLanguageRequest = (isset($request->query->get('lang')) && @$request->query->get('tmpLang')==1);
  1511.         if ($language==null$language $this->session->get('language');
  1512.         if ($language==null && isset($_COOKIE['lang']) && $_COOKIE['lang']!=''$language $_COOKIE['lang'];
  1513.         $newLanguage null;
  1514.         $newLocale null;
  1515.         if ($language!=null) {
  1516.             if ($language=='en') {
  1517.                 $newLanguage 'en';
  1518.             } else if ($language=='hu') {
  1519.                 $newLanguage 'hu';
  1520.                 $newLocale 'hu_HU.ISO8859-2';
  1521.             } else if ($language=='pl') {
  1522.                 $newLanguage 'pl';
  1523.             } else if ($language=='de') {
  1524.                 $newLanguage 'de';
  1525.             } else if ($language=='sk') {
  1526.                 $newLanguage 'sk';
  1527.             } else if ($language=='ro') {
  1528.                 $newLanguage 'ro';
  1529.             } else if ($language=='it') { // COM-793
  1530.                 $newLanguage 'it';
  1531.             } else {
  1532.                 $newLanguage 'hu';
  1533.                 $newLocale 'hu_HU.ISO8859-2';
  1534.             }
  1535.         } else {
  1536.             $referrerWithoutExtras '';
  1537.             if (isset($_SERVER['HTTP_REFERER']) && $_SERVER['HTTP_REFERER']!='') {
  1538.                 $referrerWithoutExtras str_replace('https://'''$_SERVER['HTTP_REFERER']);
  1539.                 $referrerWithoutExtras str_replace('/'''$referrerWithoutExtras);
  1540.             }
  1541.             if ($referrerWithoutExtras=='compass.techsupp.hu') {
  1542.                 $newLanguage 'pl';
  1543.                 echo "<!-- NEW LANG: pl -->";
  1544.             } else if (in_array($referrerWithoutExtras, ['www.flottaweb.com''www.flottaweb.eu''fe.flottaweb.eu'])) {
  1545.                 $newLanguage 'it';
  1546.                 echo "<!-- NEW LANG: it -->";
  1547.             } else {
  1548.                 $newLanguage 'hu';
  1549.                 $newLocale 'hu_HU.ISO8859-2';
  1550.             }
  1551.         }
  1552.         if ($newLanguage!=null) {
  1553.             //dump($newLanguage);
  1554.             $request->setLocale($newLanguage);
  1555.             $this->translator->setLocale($newLanguage);
  1556.             $this->currentLanguage $newLanguage;
  1557.             //if (!$tmpLanguageRequest) {
  1558.                 $this->session->set('language'$newLanguage);
  1559.                 setcookie('lang'$newLanguagetime()+3600*24*30'/');
  1560.             //}
  1561.         }
  1562.         if ($newLocale!=null) {
  1563.             setlocale(LC_COLLATE$newLocale);
  1564.         }
  1565.         //dump($request->getLocale());
  1566.     }
  1567.     protected function buildRenderArray($module$inputArray$entity=null$params=null) {
  1568.         $titleLabelId = ($entity==null) ? 'page.title' 'page.title.singular';
  1569.         // add to array
  1570.         $inputArray['page_title'] = $this->getPageName($moduletrue$titleLabelId); //$this->translator->trans('application.name', array(), 'general').' - '.
  1571.         //$this->translator->trans('page.title', array(), $module);
  1572.         $inputArray['page_content_title'] = $this->translator->trans($titleLabelId, array(), $module);
  1573.         if ($this->debug) {
  1574.             $inputArray['page_content_debug_info'] = ($entity==null) ? '' 'id:'.$entity->getId();
  1575.         } else {
  1576.             $inputArray['page_content_debug_info'] = '';
  1577.         }
  1578.         $inputArray['module'] = $module;
  1579.         $inputArray['previousModule'] = $this->session->get('previousModule') ?? '';
  1580.         $inputArray['currentUser'] = $this->getUser();
  1581.         $inputArray['currentLanguage'] = $this->currentLanguage;
  1582.         $inputArray['companyId'] = ($this->company==null) ? null $this->company->getId();
  1583.         $inputArray['currentCompanyId'] = ($this->company==null) ? null $this->company->getId(); // needed together with companyId (diff. files use diff. vars)
  1584.         $inputArray['company'] = $this->company;
  1585.         $inputArray['account'] = $this->account// COM-815
  1586.         $inputArray['languages'] = $this->languages;
  1587.         $inputArray['isAdmin'] = $this->getUser()->isAdmin();
  1588.         $inputArray['adminUserRoles'] = $this->getUser()->getAdminUserTypes();
  1589.         $inputArray['currentYear'] = $this->timeCalc->currentYear;
  1590.         $inputArray['currentDate'] = $this->timeCalc->currentDate// COM-549: fixed
  1591.         $inputArray['menuSection'] = (isset($_COOKIE['menuSection']) && $_COOKIE['menuSection']!='') ? $_COOKIE['menuSection'] : '';
  1592.         //$inputArray['breadcrumbs'] = $this->breadcrumbs;
  1593.         $inputArray['returnURL'] = $this->returnURL;
  1594.         $inputArray['APP_HOME_URL'] = $_SERVER['APP_HOME_URL'];
  1595.         $inputArray['LOGIN_EXPIRY'] = self::LOGIN_EXPIRY// * 60; //time() - $this->session->getMetadataBag()->getLastUsed();
  1596.         $inputArray['WARNING_BEFORE_LOGOUT'] = self::WARNING_BEFORE_LOGOUT;
  1597.         $inputArray['session_id'] = session_id();
  1598.         $inputArray['enableAutoLogout'] = (!isset($_SERVER['APP_DISABLE_AUTO_LOGOUT']) || $_SERVER['APP_DISABLE_AUTO_LOGOUT']!=true);
  1599.         $inputArray['currentCompanyConfigStatus'] = $this->currentCompanyConfigStatus;
  1600.         $inputArray['superAdminDebug'] = false// generic, added in COM-603
  1601.         $inputArray['APP_DEVELOPER_USER'] = $_SERVER['APP_DEVELOPER_USER']; // generic, added in COM-829
  1602.         if ($this->company==null) {
  1603.             $inputArray['currentCompanyConfigStep'] = -1;
  1604.         } else {
  1605.             $inputArray['currentCompanyConfigStep'] = $this->company->__get('configurationStep'); //COM-705
  1606.         }
  1607.         #$inputArray['APP_FORMS_JS_VERSION'] = $_SERVER['APP_FORMS_JS_VERSION'];
  1608.         #$inputArray['APP_LISTS_JS_VERSION'] = $_SERVER['APP_LISTS_JS_VERSION'];
  1609.         $inputArray['APP_REPORTS_JS_VERSION'] = $_SERVER['APP_REPORTS_JS_VERSION'];
  1610.         #$inputArray['APP_LANGUAGE_JS_VERSION'] = $_SERVER['APP_LANGUAGE_JS_VERSION'];
  1611.         
  1612.         // reset previous module
  1613.         $this->session->set('previousModule'$module);
  1614.         // account balance
  1615.         if ($this->account==null) {
  1616.             if ($this->company==null) {
  1617.                 $inputArray['accountBalance'] = '-';
  1618.             } else {
  1619.                 $accountOfCompany $this->company->getAccount();
  1620.                 $inputArray['accountBalance'] = $accountOfCompany->getBalance();
  1621.             }
  1622.         } else {
  1623.             $inputArray['accountBalance'] = $this->account->getBalance();
  1624.         }
  1625.         // all companies in this account
  1626.         $allAccountCompanies = [];
  1627.         if ($this->getUser()->getRolesUnconverted()==UserRoleEnum::ROLE_SUPER_ADMIN) {
  1628.             // COMPASS user (superadmin) - show grouped (by account) list of companies
  1629.             if (isset($_SERVER['APP_DEVELOPER_USER']) && $_SERVER['APP_DEVELOPER_USER']==$this->getUser()->getUsername()) {
  1630.                 $this->superAdminDebug true;
  1631.                 $inputArray['superAdminDebug'] = true// generic, added in COM-603
  1632.             }
  1633.             $dbCompanies $this->getDoctrine()->getRepository(Company::class)->getAllSortedByAccount();
  1634.             //dump('dbCompanies', $dbCompanies, $dbCompanies[282]);
  1635.             $companies = [];
  1636.             foreach($dbCompanies as $company) {
  1637.                 //dump($company->getId().': '.($companies[$company->getAccount()->getId()] ?? '--'));
  1638.                 if (!isset($companies[$company->getAccount()->getId()])) {
  1639.                     $registeredTypeUser $this->getDoctrine()->getRepository(User::class)->findOneBy([
  1640.                         'account' => $company->getAccount(),
  1641.                         'roles' => UserRoleEnum::ROLE_ACCOUNT_OWNER,
  1642.                         'deleted' => 0,
  1643.                     ]);
  1644.                     //dump('registeredTypeUser', $registeredTypeUser);
  1645.                     if ($registeredTypeUser==null) continue;
  1646.                 
  1647.                     $registeredUserName '';
  1648.                     if ($company->getAccount()->getName()!='') { // COM-387
  1649.                         $registeredUserName $company->getAccount()->getName(); // COM-387
  1650.                     } else if ($registeredTypeUser->getUsername()!=null && $registeredTypeUser->getName()!=null) {
  1651.                         $registeredUserName $registeredTypeUser->getName();
  1652.                         if ($registeredTypeUser->getName() !== $registeredTypeUser->getUsername()) {
  1653.                             $registeredUserName .= ' ('.$registeredTypeUser->getUsername().')';
  1654.                         }
  1655.                     } else if ($registeredTypeUser->getName()!=null) {
  1656.                         $registeredUserName $registeredTypeUser->getName();
  1657.                     } else if ($registeredTypeUser->getUsername()!=null) {
  1658.                         $registeredUserName $registeredTypeUser->getUsername();
  1659.                     } else {
  1660.                         $registeredUserName $company->getAccount()->getId();
  1661.                     }
  1662.                     
  1663.                     if ($this->superAdminDebug) {
  1664.                         $registeredUserName .= " (".$company->getAccount()->getId().")";
  1665.                     } else if (isset($_SERVER['APP_SHOW_DEBUG_IDS']) && $_SERVER['APP_SHOW_DEBUG_IDS']=='true') {
  1666.                         $registeredUserName .= " (".$company->getAccount()->getId().")";
  1667.                     }
  1668.                     $companies[$company->getAccount()->getId()] = [
  1669.                         //'ownerUsername' => $registeredTypeUser->getUsername(),
  1670.                         'ownerName' => $registeredUserName,
  1671.                         'companies' => [],
  1672.                     ];
  1673.                 }
  1674.                 $companyName $company->getName();
  1675.                 if ($this->superAdminDebug) {
  1676.                     $companyName .= ' ('.$company->getId().')';
  1677.                 } else if (isset($_SERVER['APP_SHOW_DEBUG_IDS']) && $_SERVER['APP_SHOW_DEBUG_IDS']=='true') {
  1678.                     $companyName .= ' ('.$company->getId().')';
  1679.                 }
  1680.                 $companies[$company->getAccount()->getId()]['companies'][] = [
  1681.                     'id' => $company->getId(),
  1682.                     'name' => $companyName,
  1683.                     'selected' => ($this->company!=null && $company->getId()==$this->company->getId()),
  1684.                 ];
  1685.             }
  1686.             //dump('companies', $companies); //die();
  1687.             // sort the list by account owner name
  1688.             usort($companies, function($r1$r2) {
  1689.                 $v1 $r1['ownerName'] ?? '';
  1690.                 $v2 $r2['ownerName'] ?? '';
  1691.                 
  1692.                 return strcasecmp($v1$v2);
  1693.                 if ($v1==$v2) return 0;
  1694.                 return ($v1 $v2) ? -1;
  1695.             });
  1696.             //dump('companies', $companies); //die();
  1697.             $inputArray['allAccountCompanies'] = $companies;
  1698.         } else {
  1699.             // any other user - use normal logic
  1700.             if ($this->account!=null) {
  1701.                 $companies null;
  1702.                 //dump('user', $this->getUser()->getRolesUnconverted());
  1703.                 // COM-815: only allow access to the companies that this user is allowed to administer
  1704.                 if ($this->getUser()->getRolesUnconverted()==UserRoleEnum::ROLE_ACCOUNT_OWNER) {
  1705.                     // REGISTERED USER - can access all companies in this account  
  1706.                     //$companies = $this->account->__get('companies'); // get non-deleted!!!!
  1707.                     $companies $this->getDoctrine()->getRepository(Company::class)->getAllSortedByAccount($this->account);
  1708.                     //dump('all non-compass companies', $companies);
  1709.                 } else { 
  1710.                     // ADMIN/VIEWER USER - can access only selected companies
  1711.                     $companies $this->getUser()->__get('administeredCompanies');
  1712.                     //dump('selected non-compass companies', $companies);
  1713.                     // if none found, it means that there is no setting in the db yet - it's a migration matter;
  1714.                     // in this case, read ALL the companies in this account, as before (to not break anything for existing users);
  1715.                     // the user can be set to access only some companies later, by a registered user
  1716.                     if ($companies==null || count($companies)==0) { //T
  1717.                         $companies $this->getDoctrine()->getRepository(Company::class)->getAllSortedByAccount($this->account);
  1718.                         //dump('all non-compass companies (2)', $companies);
  1719.                     }
  1720.                 }
  1721.                 if ($companies!=null) {
  1722.                     if ($this->account==null) {
  1723.                         // add a row for "no company"
  1724.                         $allAccountCompanies[] = [
  1725.                             'id' => 'null',
  1726.                             'name' => '- no company -',
  1727.                             'selected' => ($this->company==null),
  1728.                         ];
  1729.                     }
  1730.                     foreach($companies as $company) {
  1731.                         //dump('non-compass company', $company);
  1732.                         if ($company->getDeleted()==1) continue;
  1733.                         $allAccountCompanies[] = [
  1734.                             'id' => $company->getId(),
  1735.                             'name' => $company->getName(),
  1736.                             'selected' => ($this->company!=null && $company->getId()==$this->company->getId()),
  1737.                         ];
  1738.                     }
  1739.                     //dump($allAccountCompanies);
  1740.                 }
  1741.             }
  1742.             // sort the list by company name
  1743.             usort($allAccountCompanies, function($r1$r2) {
  1744.                 $v1 $r1['name'] ?? '';
  1745.                 $v2 $r2['name'] ?? '';
  1746.                 
  1747.                 return strcasecmp($v1$v2);
  1748.                 if ($v1==$v2) return 0;
  1749.                 return ($v1 $v2) ? -1;
  1750.             });
  1751.             //dump('allAccountCompanies', $allAccountCompanies); //die();
  1752.             $inputArray['allAccountCompanies'] = $allAccountCompanies;
  1753.         }
  1754.         // current company info
  1755.         if ($this->company==null) {
  1756.             $inputArray['currentCompanyName'] = '';
  1757.             $inputArray['currentCompanyId'] = '';
  1758.             $inputArray['companyAdminType'] = ''// COM-481
  1759.             $inputArray['companySpecialType'] = ''// COM-831
  1760.         } else {
  1761.             $inputArray['currentCompanyName'] = $this->company->getName();
  1762.             $inputArray['currentCompanyId'] = $this->company->getId();
  1763.             
  1764.             // COM-481
  1765.             $inputArray['companyAdminType'] = $this->company->__get('adminType');
  1766.             //dump('cat', $inputArray['companyAdminType']);
  1767.             if ( $inputArray['companyAdminType']===null) {
  1768.                 $inputArray['companyAdminType'] = 'no type';
  1769.             } else {
  1770.                 $inputArray['companyAdminType'] = CompanyAdminTypeEnum::LABELS$inputArray['companyAdminType'] ];
  1771.             }
  1772.             // COM-831
  1773.             if ($this->company->__get('specialType')!==null) {
  1774.                 $inputArray['companySpecialType'] = CompanySpecialTypeEnum::LABELS$this->company->__get('specialType') ];
  1775.             } else {
  1776.                 $inputArray['companySpecialType'] = '';
  1777.             }
  1778.         }
  1779.         // widgets
  1780.         $inputArray['widgets'] = [
  1781.             'balance' => false,
  1782.             'masterdata' => false,
  1783.             'dataproc' => false,
  1784.             'reports' => false,
  1785.         ];
  1786.         switch ($this->getUser()->getRolesUnconverted()) {
  1787.             case UserRoleEnum::ROLE_SUPER_ADMIN:
  1788.                 if ($this->company==null) {
  1789.                     $inputArray['widgets']['masterdata'] = true;
  1790.                 } else {
  1791.                     $inputArray['widgets']['balance'] = true;
  1792.                     $inputArray['widgets']['masterdata'] = true;
  1793.                     $inputArray['widgets']['dataproc'] = true;
  1794.                     $inputArray['widgets']['reports'] = true;
  1795.                 }
  1796.                 break;
  1797.             case UserRoleEnum::ROLE_ACCOUNT_OWNER:
  1798.                 $inputArray['widgets']['balance'] = true;
  1799.                 //$inputArray['widgets']['masterdata'] = true; // COM-695 - JNOTE??
  1800.                 $inputArray['widgets']['reports'] = true;
  1801.                 break;
  1802.             case UserRoleEnum::ROLE_ADMIN:
  1803.                 $inputArray['widgets']['balance'] = true;
  1804.                 $inputArray['widgets']['masterdata'] = true;
  1805.                 $inputArray['widgets']['dataproc'] = true;
  1806.                 $inputArray['widgets']['reports'] = true;
  1807.                 break;
  1808.             case UserRoleEnum::ROLE_USER:
  1809.                 $inputArray['widgets']['reports'] = true// COM-695 - JNOTE??
  1810.                 break;
  1811.             default:
  1812.                 break;
  1813.         }
  1814.         // COM-831
  1815.         // modify widget access for special company types
  1816.         if ($this->company!==null && $this->company->__get('specialType')==CompanySpecialTypeEnum::TODO_ONLY) {
  1817.             $inputArray['widgets']['balance'] = false;
  1818.             $inputArray['widgets']['masterdata'] = true;
  1819.             $inputArray['widgets']['dataproc'] = false;
  1820.             $inputArray['widgets']['reports'] = false;
  1821.         }
  1822.         // error/success messages (show only 1)
  1823.         $initialMessage '';
  1824.         //dump($request->getSession()->getFlashBag());
  1825.         if ($initialMessage=='') {
  1826.             foreach ($this->session->getFlashBag()->get('error', array()) as $message) {
  1827.                 if ($initialMessage!='') continue;
  1828.                 $message str_replace("'""\'"$message); // COM-809
  1829.                 $initialMessage .= "showMsg('$message', false, 5000);\n";
  1830.             }
  1831.         }
  1832.         if ($initialMessage=='') {
  1833.             foreach ($this->session->getFlashBag()->get('success', array()) as $message) {
  1834.                 if ($initialMessage!='') continue;
  1835.                 $message str_replace("'""\'"$message); // COM-809
  1836.                 if ($this->keepFlashMessageOpen) {
  1837.                     $initialMessage .= "showMsg('$message', true, null);\n";
  1838.                 } else {
  1839.                     $initialMessage .= "showMsg('$message', true);\n";
  1840.                 }
  1841.             }
  1842.         }
  1843.         $inputArray['initialMessage'] = $initialMessage;
  1844.         // new company config popup
  1845.         //dump('firstLoginConfigMode', $this->firstLoginConfigMode);
  1846.         $includeCompanyConfigPopup false;
  1847.         if ($this->firstLoginConfigMode ||
  1848.             $this->newCompanyConfigMode ||
  1849.             (isset($params['companyListPage']) && $params['companyListPage']==true))  {
  1850.         
  1851.             $includeCompanyConfigPopup true;
  1852.         }
  1853.         $inputArray['includeCompanyConfigPopup'] = $includeCompanyConfigPopup;
  1854.         // logic for specific permissions
  1855.         // vehicle license check
  1856.         $inputArray['enableVehicleCleanupPopup'] = false;
  1857.         $vehicleLicenseCheckAction null;
  1858.         if ($this->getUser()->getRolesUnconverted()==UserRoleEnum::ROLE_SUPER_ADMIN ||
  1859.             $this->getUser()->getRolesUnconverted()==UserRoleEnum::ROLE_ACCOUNT_OWNER ||
  1860.             $this->getUser()->getRolesUnconverted()==UserRoleEnum::ROLE_TRANSLATOR) { // COM-794
  1861.                 
  1862.             // license check not needed for Compass users
  1863.             $vehicleLicenseCheckAction 'not-needed (superadmin/registered/viewer)';
  1864.             if (0) {
  1865.                 $activeLicense $this->licenseHelper->getActiveLicense$this->company->getId() );
  1866.                 dump("licensed vehicles: {$activeLicense['sum']['currentNumVehicles']} / {$activeLicense['sum']['vehicleLicenses']}");
  1867.             }
  1868.                     
  1869.         } else {
  1870.             $activeLicense $this->licenseHelper->getActiveLicense$this->company->getId() );
  1871.             //dump('activeLicense', $activeLicense['sum']);
  1872.             if (isset($activeLicense['sum'])) {
  1873.         
  1874.                 if ($activeLicense['sum']['license_type']==LicenseTypeEnum::VEHICLE) {
  1875.                     // VEHICLE-based license            
  1876.                     //dump("licensed vehicles: {$activeLicense['sum']['currentNumVehicles']} / {$activeLicense['sum']['vehicleLicenses']}");
  1877.                     
  1878.                     if ($activeLicense['sum']['currentNumVehicles'] > $activeLicense['sum']['vehicleLicenses']) {        
  1879.                         $inputArray['enableVehicleCleanupPopup'] = true;
  1880.                         $vehicleLicenseCheckAction 'delete-necessary';
  1881.                     } else {
  1882.                         // # of vehicls is within the license, vehicle license check is not needed
  1883.                         $vehicleLicenseCheckAction 'completed';
  1884.                     }
  1885.                 
  1886.                 } else {
  1887.                     // not a vehicle-based license, vehicle license check is not needed
  1888.                     $vehicleLicenseCheckAction 'not-needed (not vehicle license)';
  1889.                 }                        
  1890.             
  1891.             } else {
  1892.                 // don't have a license yet, vehicle license check is not needed
  1893.                 $vehicleLicenseCheckAction 'not-needed (no license selected yet)';
  1894.             }
  1895.                     
  1896.         }
  1897.         //dump("vehicleLicenseCheckAction: $vehicleLicenseCheckAction");
  1898.         
  1899.         /****
  1900.         // if vehicle license check above is not needed, update session variable, to tell it that after-login vehicle license check is not needed
  1901.         if ($this->session->get('immediatelyAfterLoginActions')!==null &&
  1902.             in_array('vehicleLicenseCheck', $this->session->get('immediatelyAfterLoginActions')) &&
  1903.             ( $vehicleLicenseCheckAction===null ||
  1904.               substr($vehicleLicenseCheckAction,0,10)=='not-needed' ||
  1905.               $vehicleLicenseCheckAction=='completed') ) {            
  1906.             
  1907.             $immediatelyAfterLoginActions = $this->session->get('immediatelyAfterLoginActions');
  1908.             $newImmediatelyAfterLoginActions = [];
  1909.             foreach($immediatelyAfterLoginActions as $afterLoginAction) {
  1910.                 if ($afterLoginAction=='vehicleLicenseCheck') continue;
  1911.                 $newImmediatelyAfterLoginActions[] = $afterLoginAction;
  1912.             }
  1913.             //dump('newImmediatelyAfterLoginActions', $newImmediatelyAfterLoginActions);
  1914.             
  1915.             if (count($newImmediatelyAfterLoginActions)>0) {
  1916.                 $this->session->set('immediatelyAfterLoginActions', $newImmediatelyAfterLoginActions);
  1917.             } else {
  1918.                 $this->session->set('immediatelyAfterLoginActions', null);
  1919.             }
  1920.                 
  1921.         }
  1922.         ****/    
  1923.         $inputArray['showVehicleCleanupPopup'] = false;
  1924.         $inputArray['numVehicleLicenses'] = 0;
  1925.         $inputArray['numCurrentVehicles'] = 0;
  1926.         $inputArray['numVehiclesToDelete'] = 0;
  1927.         if ($inputArray['enableVehicleCleanupPopup']==true) {
  1928.             $inputArray['numVehicleLicenses'] = $activeLicense['sum']['vehicleLicenses'];
  1929.             $inputArray['numCurrentVehicles'] = $activeLicense['sum']['currentNumVehicles'];
  1930.             $inputArray['numVehiclesToDelete'] = $activeLicense['sum']['currentNumVehicles'] - $activeLicense['sum']['vehicleLicenses'];
  1931.             $inputArray['vehicleCleanupList'] = [];
  1932.             $vehicles $this->getDoctrine()->getRepository(Vehicle::class)->findAllSortedByDateCreated$this->company );
  1933.             //dump('vehicles', $vehicles, count($vehicles));
  1934.             foreach($vehicles as $vehicle) {
  1935.                 if ($vehicle->__get('hasTachograph')==false) continue;
  1936.                 $inputArray['vehicleCleanupList'][] = [
  1937.                     'id' => $vehicle->getId(),
  1938.                     'name' => $vehicle->getName().' ('.$vehicle->getId().')',
  1939.                     'date' => $vehicle->__getDateFormatted('createdAt'),
  1940.                 ];
  1941.             }
  1942.             $inputArray['vehicleCleanupList'] = json_encode($inputArray['vehicleCleanupList']);
  1943.             // show on page open
  1944.             //if ($this->session->get('immediatelyAfterLoginActions')!==null &&
  1945.             //    in_array('vehicleLicenseCheck', $this->session->get('immediatelyAfterLoginActions'))) {
  1946.                 
  1947.                 $inputArray['showVehicleCleanupPopup'] = true;
  1948.             //}
  1949.             
  1950.             //dump($inputArray);
  1951.         }
  1952.         /****        
  1953.         if ($this->session->get('immediatelyAfterLoginActions')!==null) {
  1954.             dump("immediatelyAfterLoginActions:", $this->session->get('immediatelyAfterLoginActions'));
  1955.             if ($this->company!==null) dump('company: '.$this->company->getName().' - '.$this->company->getId());
  1956.         
  1957.             $licenseChecksToComplete = [];
  1958.             
  1959.             // vehicle license check
  1960.             if (in_array('vehicleLicenseCheck', $this->session->get('immediatelyAfterLoginActions'))) {
  1961.             
  1962.             
  1963.                 // remove this login vehicle license check
  1964.                 if ($vehicleLicenseCheckAction===null ||
  1965.                     substr($vehicleLicenseCheckAction,0,10)=='not-needed' ||
  1966.                     $vehicleLicenseCheckAction=='completed') {
  1967.                 
  1968.                     $licenseChecksToComplete[] = 'vehicleLicenseCheck';
  1969.                     
  1970.                 }
  1971.             
  1972.             }
  1973.             
  1974.             if (count($licenseChecksToComplete)>0) {
  1975.             
  1976.                 $immediatelyAfterLoginActions = $this->session->get('immediatelyAfterLoginActions');
  1977.                 $newImmediatelyAfterLoginActions = [];
  1978.                 foreach($immediatelyAfterLoginActions as $afterLoginAction) {
  1979.                     if (in_array($afterLoginAction, $licenseChecksToComplete)) continue;
  1980.                     $newImmediatelyAfterLoginActions[] = $afterLoginAction;
  1981.                 }
  1982.                 dump('newImmediatelyAfterLoginActions', $newImmediatelyAfterLoginActions);
  1983.                 if (count($newImmediatelyAfterLoginActions)>0) {
  1984.                     $this->session->set('immediatelyAfterLoginActions', $newImmediatelyAfterLoginActions);
  1985.                 } else {
  1986.                     $this->session->set('immediatelyAfterLoginActions', null);
  1987.                 }
  1988.             
  1989.             }
  1990.         }
  1991.         ****/
  1992.         //dump('session var (0)', $this->session->get('broadcast-msgs'));
  1993.         $inputArray['broadcastMsg'] = [
  1994.             'show' => false,
  1995.         ];
  1996.         if (!$includeCompanyConfigPopup && 
  1997.             $this->company!==null) {   // generic, added for COM-794
  1998.         
  1999.             // broadcast msgs -- COM-469
  2000.             $brMsgPopupToShow $this->messageHelper->checkIfBroadcastMessagePopupNeedsToBeShown($this->company$this->getUser(),
  2001.                                                                                                  $this->session->get('broadcast-msgs'));
  2002.             //dump('brMsgPopupToShow', $brMsgPopupToShow);
  2003.             if ($brMsgPopupToShow===false) {
  2004.                 //$inputArray['broadcastMsg'] = [
  2005.                 //    'show' => false,
  2006.                 //];
  2007.             } else {
  2008.                 $inputArray['broadcastMsg'] = [
  2009.                     'show' => true,
  2010.                     'id' => $brMsgPopupToShow->__get('id'),
  2011.                     'type' => $brMsgPopupToShow->__get('type'),
  2012.                     'title' => $brMsgPopupToShow->__get('title'),
  2013.                     //'content' => str_replace("\n", "<br>", $brMsgPopupToShow->__get('content')),
  2014.                     'content' => $brMsgPopupToShow->__get('content'),
  2015.                 ];
  2016.                 $this->messageHelper->saveBroadcastMessageReaction($brMsgPopupToShow$this->company$this->getUser(), BroadcastMessageReactionEnum::SHOW);
  2017.             }
  2018.             
  2019.         }
  2020.         // language strings
  2021.         $allMessages $this->translator->getCatalogue()->all();
  2022.         $languageStrings['general'] = $allMessages['general'];
  2023.         $languageStrings['driver-vehicle-popup'] = $allMessages['driver-vehicle-popup'];
  2024.         $languageStrings['videos'] = $allMessages['videos']; //COM-785
  2025.         if (substr($this->module,0,7)=='report-') {
  2026.             $languageStrings['report-general'] = $allMessages['report-general'];
  2027.         }
  2028.         if ($this->module!='' && isset($allMessages[$this->module])) {
  2029.             $languageStrings[$this->module] = $allMessages[$this->module];
  2030.         }
  2031.         if ($this->module=='driver-activity-diagram') {
  2032.             $languageStrings['driver-activities'] = $allMessages['driver-activities'];
  2033.             $languageStrings['driver-special-events'] = $allMessages['driver-special-events'];
  2034.         }
  2035.         if ($this->module=='data-conflicts') { // COM-CONFLICTS
  2036.             $languageStrings['driver-activity-diagram'] = $allMessages['driver-activity-diagram'];
  2037.             $languageStrings['driver-activities'] = $allMessages['driver-activities'];
  2038.             $languageStrings['driver-special-events'] = $allMessages['driver-special-events'];
  2039.         }
  2040.         if ($includeCompanyConfigPopup)  {
  2041.             $languageStrings['registration'] = $allMessages['registration']; // need registration strings
  2042.         }
  2043.         if (in_array($module, ['drivers''vehicles'])) { // attachments -- COM-787
  2044.             $languageStrings['attachments'] = $allMessages['attachments'];
  2045.         }
  2046.         $inputArray['languageStrings_js'] = json_encode($languageStrings);
  2047.         
  2048.         //dump('allMessages', $allMessages, $this->module);
  2049.         
  2050.         // empty objects
  2051.         $inputArray['objects'] = [
  2052.             // master data
  2053.             'Account' => new Account,
  2054.             'Company' => new Company,
  2055.             'Driver' => new Driver,
  2056.             'Vehicle' => new Vehicle,
  2057.             'Trailer' => new Trailer,
  2058.             'User' => new User,
  2059.             // master data - dashboard
  2060.             'Document' => new Document,
  2061.             'Message' => new Message// generic, added for COM-831
  2062.             'LicensePricing'  => new LicensePricing,// generic, added for COM-831
  2063.             'Balance' => new Balance// generic, added for COM-831
  2064.             'InvoiceStore' => new InvoiceStore// generic, added for COM-831
  2065.             'Setting' => new Setting// generic, added for COM-831
  2066.             // parameters
  2067.             'WorkPeriod' => new WorkPeriod,
  2068.             'DayAssignment' => new DayAssignment,
  2069.             'DayTitle' => new DayTitle,
  2070.             'AttendanceRegisterParams' => new AttendanceRegisterParams,
  2071.             'ProtocolParams' => new ProtocolParams,
  2072.             // data processing
  2073.             'TachographFile' => new TachographFile,
  2074.             'DriverActivity' => new DriverActivity,
  2075.             'DriverManualActivity' => new DriverManualActivity,
  2076.             'DriverBorderCrossing' => new DriverBorderCrossing,
  2077.             'DriverActiveDay' => new DriverActiveDay,
  2078.             'DriverMinimumWagePeriod' => new DriverMinimumWagePeriod,
  2079.             'DriverSpecialEvent' => new DriverSpecialEvent,
  2080.             'DriverActivityProofSheet' => new DriverActivityProofSheet,
  2081.             // reports
  2082.             'Report' => new Report,
  2083.             'Report2' => new Report2,
  2084.             'LogEntry' => new LogEntry,
  2085.             'LogEntry2' => new LogEntry2,
  2086.             'TravelRoute' => new TravelRoute,
  2087.             'ToDoItem' => new ToDoItem,
  2088.             // other
  2089.             'Penalty' => new Penalty,
  2090.             'CustomField' => new CustomField,
  2091.             'LicensePricing' => new LicensePricing,
  2092.             'Consumption' => new Consumption,
  2093.             'KmMultiplier' => new KmMultiplier,
  2094.             'GasPrices' => new GasPrices,
  2095.             'DailyAllowance' => new DailyAllowance,
  2096.             'Statistic' => new Statistic//COM-349
  2097.             //'EmailServerConnection' => new EmailServerConnection, //COM-819
  2098.             'EmailTachographFile' => new EmailTachographFile// COM-819
  2099.         ];
  2100.         $inputArray['licensePermitsTodoModule'] = $this->licenseHelper->doesLicenseAllowModule_voterCheck('todo');
  2101.         $inputArray['licensePermitsDailyAllowanceModule'] = $this->licenseHelper->doesLicenseAllowModule_voterCheck('daily-allowance');
  2102.         
  2103.         // module access
  2104.         //$inputArray['moduleAccess'] = [
  2105.         //    // master data
  2106.         //    'Account' => new Account,
  2107.         
  2108.         //dump($inputArray, $params);
  2109.         // load help text
  2110.         $inputArray['helpContents'] = $this->docHelper->loadHelpHtmlFile($this->currentLanguage$this->module); // COM-783: added $module
  2111.         //dump('helpContents', $inputArray['helpContents']);
  2112.         // COM-783
  2113.         $allowHelpInlineEdit false;
  2114.         if ($inputArray['helpContents']===null) {
  2115.             if ($this->getUser()->getRolesUnconverted()==UserRoleEnum::ROLE_SUPER_ADMIN) {
  2116.                 $inputArray['helpContents'] = ''//'Help file does not exist, contact Janusz to configure it<br><br>';
  2117.                 //$inputArray['helpContents'] = '('.$this->docHelper->lastFileName.')';
  2118.             } else {
  2119.                 $inputArray['helpContents'] = '';
  2120.             }
  2121.         } else {
  2122.         
  2123.             if ($this->getUser()->getRolesUnconverted()==UserRoleEnum::ROLE_SUPER_ADMIN) {
  2124.                 //$allowHelpInlineEdit = true;
  2125.             }
  2126.             
  2127.         }
  2128.         $inputArray['allowHelpInlineEdit'] = $allowHelpInlineEdit;
  2129.         // load knowledge base (simple file for now)
  2130.         $inputArray['knowledgeBaseUrl'] = $this->generateUrl('documents.show-simple.action', [
  2131.             'type' => 'knowledge-base',
  2132.             'randomNumber' => rand(10000000009000000000),
  2133.         ]);
  2134.         // load TofU and other documents, if the user needs to accept these
  2135.         if ($includeCompanyConfigPopup)  {
  2136.             $inputArray['includeCompanyConfigPopup'] = $includeCompanyConfigPopup;
  2137.             $inputArray['firstLoginConfigMode'] = $this->firstLoginConfigMode;
  2138.             $inputArray['newCompanyConfigMode'] = $this->newCompanyConfigMode;
  2139. //JNOTE: maybe need this per company?
  2140.             
  2141.             if ($this->getUser()->getRolesUnconverted()==UserRoleEnum::ROLE_ACCOUNT_OWNER ||
  2142.                 $this->getUser()->getRolesUnconverted()==UserRoleEnum::ROLE_SUPER_ADMIN) {
  2143.                 //dump($this->settings, $this->company->getId()); die();
  2144.             
  2145.                 // full registration
  2146.                 $inputArray['registration']['term-of-use'] = $this->docHelper->loadHtmlFile('term-of-use'$this->currentLanguage);
  2147.                 $inputArray['registration']['contract'] = $this->docHelper->loadHtmlFile('contract'$this->currentLanguage);
  2148.                 $inputArray['registration']['gdpr'] = $this->docHelper->loadHtmlFile('gdpr'$this->currentLanguage);
  2149.                 $inputArray['registration']['cookies'] = $this->docHelper->loadHtmlFile('cookies'$this->currentLanguage); //COM-424
  2150.             
  2151.                 // countries
  2152.                 $inputArray['countriesArray'] = $this->formsHelper->getCountries($this->mainCountry);
  2153.                 //$inputArray['mainCountry'] = $this->mainCountry;
  2154.                 // cities
  2155.                 $inputArray['citiesArray'] = $this->formsHelper->getCities($this->mainCountry);
  2156.                 //$inputArray['mainCity'] = $this->mainCity;
  2157.                 // config settings
  2158.                 $configInitSettings = [
  2159.                     'blankContract' => '',
  2160.                     'mainCountry' => $this->mainCountry,
  2161.                     'mainCity' => $this->mainCity,
  2162.                     'account' => [
  2163.                         'name' => $this->account->getId(),
  2164.                     ],
  2165.                     'company' => [
  2166.                         'id' => null,
  2167.                         'name' => '',
  2168.                         'country' => $this->company->country// use current company's country as default
  2169.                         'city' => '',
  2170.                         'address' => '',
  2171.                         'postalCode' => '',
  2172.                         'email' => '',
  2173.                         'protocolCreator' => $this->company->protocolCreator,
  2174.                         'protocolApprover' => $this->company->protocolApprover,
  2175.                     ],
  2176.                     'configurationStep' => 0,
  2177.                     'licenseTypes' => [
  2178.                         'vehicle' => LicenseTypeEnum::VEHICLE,
  2179.                         'driver' => LicenseTypeEnum::DRIVER,
  2180.                         'usage' => LicenseTypeEnum::USAGE,
  2181.                     ],
  2182.                     'config-done' => [
  2183.                         'tofu-accepted' => ($this->settings['config-step']['tofu']!=''),
  2184.                         'contract-accepted' => ($this->settings['config-step']['contract']!=''),
  2185.                         'gdpr-accepted' => ($this->settings['config-step']['gdpr']!=''),
  2186.                         'cookies-accepted' => ($this->settings['config-step']['cookies']!=''),
  2187.                         'license-type-chosen' => $this->company->__get('licenseType'),
  2188.                     ],
  2189.                     'settings' 
  2190.                 ];
  2191.                 
  2192.                 // if first login mode, need to set initial popup fields to the already-created company
  2193.                 if ($this->firstLoginConfigMode) {
  2194.                 
  2195.                     $configInitSettings['company'] = [
  2196.                         'id' => $this->company->getId(),
  2197.                         // contract/general
  2198.                         'coName' => $this->company->getName(),
  2199.                         'coCountry' => $this->company->__get('country'),
  2200.                         'coAddrCity' => $this->company->__get('city'),
  2201.                         'coAddr' => $this->company->__get('address'),
  2202.                         'coAddrPCode' => $this->company->__get('postalCode'),
  2203.                         'coEmail' => $this->company->__get('email'),
  2204.                         
  2205.                         'coTaxNumber' => $this->company->__get('taxNumber'),
  2206.                         'coRegistrationNumber' => $this->company->__get('registrationNumber'),
  2207.                         'coEUTaxNumber' => $this->company->__get('europeanTaxNumber'),
  2208.                         'contractSign1' => $this->company->__get('contractSign1'),
  2209.                         'contractSign1Email' => $this->company->__get('contractSign1Email'),
  2210.                         'contractSign1Phone' => $this->company->__get('contractSign1Phone'),
  2211.                         'contractSign2' => $this->company->__get('contractSign2'),
  2212.                         'contractSign2Email' => $this->company->__get('contractSign2Email'),
  2213.                         'contractSign2Phone' => $this->company->__get('contractSign2Phone'),
  2214.                         // invoicing
  2215.                         //invoicingDataSameAsContract        coInvoicingDataSameAsContract
  2216.                         'coNameForInvoicing' => $this->company->__get('invoicingCompanyName'),
  2217.                         'coInvoicingAddrPCode' => $this->company->__get('invoicingPostalCode'),
  2218.                         'coInvoicingAddrCity' => $this->company->__get('invoicingCity'),
  2219.                         'coInvoicingAddr' => $this->company->__get('invoicingAddress'),
  2220.                         'coInvoicingCountry' => $this->company->__get('invoicingCountry'),
  2221.                         'coInvoicingTaxNumber' => $this->company->__get('invoicingTaxNumber'),
  2222.                         'coInvoicingEUTaxNumber' => $this->company->__get('invoicingEuropeanTaxNumber'),
  2223.                         // shipping
  2224.                         //coShippingDataSameAsContract        coShippingDataSameAsContract    
  2225.                         'coNameForShipping' => $this->company->__get('shippingCompanyName'),
  2226.                         'coContactNameForShipping' => $this->company->__get('shippingContactName'),
  2227.                         'coShippingAddrPCode' => $this->company->__get('shippingPostalCode'),
  2228.                         'coShippingAddrCity' => $this->company->__get('shippingCity'),
  2229.                         'coShippingAddr' => $this->company->__get('shippingAddress'),
  2230.                         'coShippingCountry' => $this->company->__get('shippingCountry'),
  2231.                         'coProtocolCreator' => $this->company->__get('protocolCreator'),
  2232.                         'coProtocolApprover' => $this->company->__get('protocolApprover'),
  2233.                     ];
  2234.                 
  2235.         // JNOTE: + accepted contact, etc. already - show
  2236.                     
  2237.                     $configInitSettings['configurationStep'] = $this->company->__get('configurationStep');
  2238.                     if ($configInitSettings['configurationStep']=='' || $configInitSettings['configurationStep']=='') {
  2239.                         $configInitSettings['configurationStep'] = 0;
  2240.                     }
  2241.                     
  2242.                 }
  2243.                 $inputArray['configInitSettings_js'] = json_encode($configInitSettings);
  2244.                 // need to include settings
  2245.                 $inputArray['settings'] = $this->settings;
  2246.                 $inputArray['minTimeBetweenShiftsDefault'] = Setting::CONFIG['rule.minTimeBetweenShifts']['default'];
  2247.                 $inputArray['defaultMinTimeBetweenShifts'] = ($inputArray['settings']['rule']['minTimeBetweenShifts']=='') ||
  2248.                     ($inputArray['settings']['rule']['minTimeBetweenShifts']==Setting::CONFIG['rule.minTimeBetweenShifts']['default']);
  2249.                 $inputArray['minWrongSwitchActivityLen'] = Setting::CONFIG['rule.minWrongSwitchActivityLen']['default'];
  2250.                 
  2251.             } else {
  2252.             
  2253.                 // should not have any users 
  2254.                 $inputArray['includeCompanyConfigPopup'] = false;
  2255.             
  2256.             }
  2257.         } else {
  2258.             $inputArray['includeCompanyConfigPopup'] = false;
  2259.         }
  2260.         if (!isset($inputArray['configInitSettings_js'])) $inputArray['configInitSettings_js'] = json_encode([]);
  2261.         /// CHECK BALANCE
  2262.         $this->getBalanceforCompany($this->company,$inputArray['license_balance']);
  2263.         //dump('balance: '.$this->company->getBalance());
  2264.         /// check new message
  2265.         $this->messageHelper->getNewMessage($inputArray['new_messages'], $this->getUser());
  2266.         
  2267.         // COM-695 - Bob
  2268.         $inputArray['enableAI'] = $this->aiEnabled// COM-709a
  2269.         //$inputArray['systemHintId'] = '';
  2270.         //$inputArray['systemHintMessage'] = '';
  2271.         $inputArray['systemHintsArray_js'] = json_encode([]);
  2272.         $inputArray['systemHintsIdsArray_js'] = json_encode([]);
  2273.         $inputArray['systemHintsAvail'] = 0;
  2274.         $inputArray['aiPaidLicenseThisMonth'] = $this->aiPaidLicenseThisMonth// COM-709a
  2275.         //$inputArray['systemHintsSpecialMsg'] = [
  2276.         //    'title' => '',
  2277.         //    'message' => '',
  2278.         //];
  2279.     //protected $aiEnabled = false;
  2280.     //protected $aiPaidLicenseThisMonth = false;
  2281.         if (!$this->firstLoginConfigMode)  {
  2282.             /*
  2283.             // show system tips, depending on user type
  2284.             if (in_array($this->getUser()->getRolesUnconverted(), [UserRoleEnum::ROLE_SUPER_ADMIN,
  2285.                                                                    UserRoleEnum::ROLE_ACCOUNT_OWNER,
  2286.                                                                    UserRoleEnum::ROLE_ADMIN])) {
  2287.                 $inputArray['enableAI'] = true;
  2288.                 
  2289.                 //dump('enableAI');
  2290.                 
  2291.             }
  2292.             */
  2293.             //if ($inputArray['enableAI']) {    
  2294.             if ($this->aiEnabled) {         // COM-709a                                                       
  2295.                 $systemHintsToShow $this->ai->getSystemTipsForCompany($this->companytrue3);
  2296.                 //dump('systemHintsToShow', $systemHintsToShow);
  2297.                 if ($systemHintsToShow!==null) {
  2298.             
  2299.                     //$inputArray['systemHintId'] = $systemHintInfoToShow['id'];
  2300.                     //$inputArray['systemHintMessage'] = $systemHintInfoToShow['msg'];
  2301.                     //$inputArray['systemHintsAvail'] = $systemHintInfoToShow['numAvail'];
  2302.                     //$inputArray['systemHintsArray'] = $systemHintsToShow;
  2303.                     $inputArray['systemHintsArray_js'] = json_encode($systemHintsToShow['tips']);
  2304.                     $inputArray['systemHintsAvail'] = $systemHintsToShow['numAvail'];
  2305.                 
  2306.                     $systemHintsIdsArray = [];
  2307.                     foreach($systemHintsToShow['tips'] as $tip) {
  2308.                         $systemHintsIdsArray[] = $tip['id'];
  2309.                     }
  2310.                     //dump('systemHintsIdsArray', $systemHintsIdsArray);
  2311.                     $inputArray['systemHintsIdsArray_js'] = json_encode($systemHintsIdsArray);
  2312.                 }
  2313.             }
  2314.             
  2315.             // show the validity of the instant schedule aid page
  2316.             //dump($this->settings);
  2317.             //$currentMonthNum = intval(date('m'));
  2318.             //$currentMonthAIPaidLicense = $this->settings['ai']['tipMonthlyLicences'][$currentMonthNum-1];
  2319.             //dump('currentMonthAIPaidLicense: '.$currentMonthAIPaidLicense);
  2320.             //if ($currentMonthAIPaidLicense==1) {
  2321.             if ($this->aiPaidLicenseThisMonth) { // COM-709a
  2322.                 // if now is enabled, check when it will expire
  2323.                 //$lastPaidMonth = $currentMonthNum;
  2324.                 $monthsValidArray = [];
  2325.                 for($month=1$month<=12$month++) {
  2326.                 
  2327.                     $monthStringName '';
  2328.                     switch($month) {
  2329.                     case  1$monthStringName 'JANUARY'; break;
  2330.                     case  2$monthStringName 'FEBRUARY'; break;
  2331.                     case  3$monthStringName 'MARCH'; break;
  2332.                     case  4$monthStringName 'APRIL'; break;
  2333.                     case  5$monthStringName 'MAY'; break;
  2334.                     case  6$monthStringName 'JUNE'; break;
  2335.                     case  7$monthStringName 'JULY'; break;
  2336.                     case  8$monthStringName 'AUGUST'; break;
  2337.                     case  9$monthStringName 'SEPTEMBER'; break;
  2338.                     case 10$monthStringName 'OCTOBER'; break;
  2339.                     case 11$monthStringName 'NOVEMBER'; break;
  2340.                     case 12$monthStringName 'DECEMBER'; break;
  2341.                     }
  2342.                     //$thisMonthAIPaidLicense = $this->settings['ai']['tipMonthlyLicences'][$month-1];
  2343.                     //if ($thisMonthAIPaidLicense==1) {
  2344.                     //if ($this->aiPaidLicenseThisMonth) {
  2345.                         //$lastPaidMonth = intval($month);
  2346.                         //$monthsValidArray[] = '2024-'.str_pad($month, 2, '0', STR_PAD_LEFT);
  2347.                         $monthsValidArray[] = '2024. '.
  2348.                                                $this->translator->trans('monthName.'.$monthStringName, array(), 'general');
  2349.                         //$inputArray['aiPaidLicenseThisMonth'] = true;
  2350.                         //$this->aiPaidLicenseThisMonth = true;
  2351.                         
  2352.                     //} else {
  2353.                     //    //break;
  2354.                     //}
  2355.                     
  2356.                 }
  2357.                 //dump("lastPaidMonth: $lastPaidMonth");
  2358.                 //dump(str_pad($lastPaidMonth.'', 2, '0', STR_PAD_LEFT));
  2359.                 //dump('monthsValidArray', $monthsValidArray);
  2360.                 //$lastMonthStartDate = $this->timeCalc->currentYear."-".str_pad($lastPaidMonth.'', 2, '0', STR_PAD_LEFT).'-01';
  2361.                 //dump("lastMonthStartDate: $lastMonthStartDate");
  2362.                 //$lastAIPaidDate = date("Y-m-t", strtotime($lastMonthStartDate));
  2363.                 //dump("lastAIPaidDate: $lastAIPaidDate");
  2364.                 //$inputArray['AIFreePaidNote'] = 'paid until '.$lastAIPaidDate.'';
  2365.                 $inputArray['AIFreePaidNote'] = $this->translator->trans('label.aiValidityNote.paid', array(
  2366.                                                     //'[date]' => $lastAIPaidDate,
  2367.                                                 ), 'general');
  2368.                                                 
  2369.                 $inputArray['AIFreePaidTooltip'] = $this->translator->trans('tooltip.aiValidityNote.paid', array(
  2370.                                                     '[months]' => '<br>'.implode('<br>'$monthsValidArray),
  2371.                                                 ), 'general');
  2372.                                                 
  2373.                 //dump("****", $this->translator->trans('tooltip.aiValidityNote.paid', array(), 'general'));
  2374.             } else {
  2375.             
  2376.                 $inputArray['AIFreePaidNote'] = $this->translator->trans('label.aiValidityNote.free', array(), 'general');
  2377.                 $inputArray['AIFreePaidTooltip'] = $this->translator->trans('tooltip.aiValidityNote.free', array(), 'general');
  2378.                 
  2379.             }
  2380.             
  2381.             //$specialHintMsgToShow = rand(1, 2);
  2382.             $specialHintMsgToShow 1// request from J to show only 1
  2383.         } else {
  2384.             $specialHintMsgToShow 1;
  2385.             $inputArray['AIFreePaidNote'] = $this->translator->trans('label.aiValidityNote.free', array(), 'general');
  2386.             $inputArray['AIFreePaidTooltip'] = $this->translator->trans('tooltip.aiValidityNote.free', array(), 'general');
  2387.         }
  2388.         //$inputArray['enableAI'] = false; //JNOTE-TESTING
  2389.         $inputArray['systemHintsSpecialMsg']['title'] =
  2390.             $this->translator->trans('tipSpecialMessage.title.'.$specialHintMsgToShow, array(), 'system-tips');
  2391.         $inputArray['systemHintsSpecialMsg']['message'] =
  2392.             $this->translator->trans('tipSpecialMessage.message.'.$specialHintMsgToShow, array(), 'system-tips');
  2393.         $inputArray['aiSummary'] = $this->ai->getAISummary($this->company);
  2394.         // COM-695 - chart for Bob's bragging popup
  2395.         $chartLabels = [];
  2396.         $chartValues = [];
  2397.         foreach($inputArray['aiSummary']['monthlyStats'] as $yearMonth=>$value) {
  2398.             $chartLabels[] = $yearMonth;
  2399.             $chartValues[] = $value;
  2400.         }
  2401.         $inputArray['aiSummary']['aiChartMonthArray_js'] = json_encode($chartLabels);
  2402.         $inputArray['aiSummary']['aiChartDataArray_js'] = json_encode($chartValues);
  2403.         if (0) {
  2404.             
  2405.             $inputArray['aiSummary']['aiChartMonthArray_js'] = json_encode([
  2406.                 'sep',
  2407.                 'oct',
  2408.                 'nov',
  2409.                 'dec',
  2410.             ]);
  2411.             $inputArray['aiSummary']['aiChartDataArray_js'] = json_encode([
  2412.                 400000,
  2413.                 800000,
  2414.                 700000,
  2415.                 1000000,
  2416.             ]);
  2417.         }
  2418.         // ATTACHMENTS -- COM-787
  2419.         $inputArray['attachmentsAllowed'] = '0';
  2420.         if (isset($_SERVER['APP_ATTACHMENT_COMPANY_IDS']) && $_SERVER['APP_ATTACHMENT_COMPANY_IDS']!='' && 
  2421.             $this->company!==null) {
  2422.         
  2423.             $attachmentCompanyIds explode(','$_SERVER['APP_ATTACHMENT_COMPANY_IDS']);
  2424.             //dump($attachmentCompanyIds);
  2425.             if (in_array($this->company->getId(), $attachmentCompanyIds)) {
  2426.                 $this->enableAttachments true;
  2427.             
  2428.                 $inputArray['attachmentsAllowed'] = '1';
  2429.                 //dump('IN');
  2430.             
  2431.             }
  2432.         }            
  2433.         // API -- COM-815
  2434.         $inputArray['apiAllowed'] = '0';
  2435.         if ($this->enableApi) {
  2436.                 
  2437.             $inputArray['apiAllowed'] = '1';
  2438.             //dump('IN');
  2439.         
  2440.         }
  2441.         // TACHO-SOLVE -- COM-822
  2442.         $inputArray['tachoSolveSalespersonsEnabled'] = '0';
  2443.         if (isset($_SERVER['APP_TACHO_SOLVE_SALESPERSONS_USER_IDS'])) {
  2444.             $tsSalespersonUserIdArray explode(','$_SERVER['APP_TACHO_SOLVE_SALESPERSONS_USER_IDS']);
  2445.             if (in_array($this->getUser()->getId(), $tsSalespersonUserIdArray)) {
  2446.                 $inputArray['tachoSolveSalespersonsEnabled'] = '1';
  2447.             }
  2448.         }
  2449.         
  2450.         //dump('inputArray', $inputArray);
  2451.         //die();    
  2452.     
  2453.         return $inputArray;
  2454.         
  2455.     }
  2456.     
  2457.     public function checkMessageSecurity($user,$entity,&$result) {
  2458.         if (!$entity){
  2459.             $url $this->generateUrl('messages.index.page');
  2460.             return $this->redirect($url);
  2461.         }
  2462.        
  2463.         if (@$entity && $user->getRolesUnconverted()[0] == UserRoleEnum::ROLE_SUPER_ADMIN$result true;
  2464.         if ($user->getRolesUnconverted()[0] != UserRoleEnum::ROLE_SUPER_ADMIN) {
  2465.             if ($entity->from) {
  2466.                 $from $entity->getFrom();
  2467.                 $from $from->id;
  2468.             }
  2469.             if (@$entity->to) {
  2470.                 $to $entity->getTo();
  2471.                 $to $to->id;
  2472.             }
  2473.             if ((@$from && $user->currentCompanyViewed->id != $from) || (@$to && $user->currentCompanyViewed->id != $to)) {
  2474.                 $result 'redirect';
  2475.             }else{
  2476.                 $result true;
  2477.             }
  2478.         }elseif($user->getRolesUnconverted()[0] == UserRoleEnum::ROLE_SUPER_ADMIN) {
  2479.             $result true;
  2480.         }
  2481.     }
  2482.     public function checkConsumptionSecurity($user,$company,$entity,&$result) {
  2483.         if (!$entity){
  2484.             $url $this->generateUrl('modules.consumption.index.page');
  2485.             return $this->redirect($url);
  2486.         }
  2487.         if ($entity->company == $company->id) {
  2488.             $result true;
  2489.         }
  2490.     }
  2491.     /*
  2492.     public function getNewMessage(&$result) {
  2493.         $result = false;
  2494.         $messageRepository = $this->getDoctrine()->getRepository(Message::class);
  2495.         $user = $this->getUser();
  2496.         if ($user->getRolesUnconverted()[0] == UserRoleEnum::ROLE_SUPER_ADMIN) {
  2497.             $messageRepository->checkNewMessagesForAdmin($messages);
  2498.         }else{
  2499.             if ($this->company!=null) {
  2500.                 $messageRepository->checkNewMessagesForUser($this->company,$messages);
  2501.             } else {
  2502.                 $messages = false;
  2503.             }
  2504.         }
  2505.         if ($messages) {
  2506.             $result = true;
  2507.         }
  2508.     }
  2509.     */
  2510.     public function getBalanceforCompany($company,&$result) {
  2511.         $result '';
  2512.         $anyLicense $this->licenseHelper->checkActiveLicense($company);
  2513.         if (@$anyLicense['sum']) {
  2514.             $lastOrder $this->getDoctrine()->getRepository(LicenseOrder::class)->findOneBy(['company' => $this->company,'status' => 4],['id' => 'desc']);
  2515.             if (@$lastOrder) {
  2516.                 $orderDetails json_decode($lastOrder->details,true);
  2517.                 $discount = !is_numeric($lastOrder->discount) ? $lastOrder->discount;
  2518.                 $invoiceItems = [];
  2519.                 $fullPrice 0;
  2520.                 if ($discount 0) {
  2521.                     $invoiceItems[] = ['name' => 'Kedvezmény','qty' => 1,  'price' => $discount*-1
  2522.                     ];
  2523.                 }
  2524.                 $this->licenseHelper->getPriceMultiplierHelper($company,$multiplier);
  2525.                 foreach ($orderDetails as $key=>$orderItem) {
  2526.                     $this->licenseHelper->szamlazz_item_generator($multiplier,$orderDetails['licenseType'],$key,$orderItem,$lastOrder->getId(),$this->company,$invoiceItems[]);
  2527.                 }
  2528.                 foreach ($invoiceItems as $items) {
  2529.                     if (@$items$fullPrice += $items['price'];
  2530.                 }
  2531.                 $fullPrice number_format($fullPrice,0,'',' ');
  2532.             }
  2533.             if ($anyLicense['sum']['license_type'] == 1// VEHICLE-BASED
  2534.             {
  2535.                 // vehicle based
  2536.                 $transLicenses $this->translator->trans('balance_widget.licenses', array(), 'balance');
  2537.                 $transEndof $this->translator->trans('balance_widget.endoflegislation', array(), 'balance');
  2538.                     $result "<div class=\"muted-text-small \" style='margin-top: 5px;'><span class=\"line-clamp\">{$transLicenses}{$anyLicense['sum']['vehicleLicenses']} <br/>{$transEndof}{$anyLicense['sum']['legislationEndDate']->format('Y-m-d')}</span></div>";
  2539.             }
  2540.             elseif($anyLicense['sum']['license_type'] == 2// DRIVER_BASED
  2541.             {
  2542.                 // driver based
  2543.                 $transUnused $this->translator->trans('balance_widget.unusedvehicle', array(), 'balance');
  2544.                 $transAEtr $this->translator->trans('balance_widget.aetr', array(), 'balance');
  2545.                 $transLabour $this->translator->trans('balance_widget.labour', array(), 'balance');
  2546.                 $transOrderDate $this->translator->trans('order_date', array(), 'balance');
  2547.                 $transOrderAmount $this->translator->trans('order_amount', array(), 'balance');
  2548.                 if (@$lastOrder) {
  2549.                     $result "<div class=\"muted-text-small \" style='margin-top: 0px;'><span class=\"line-clamp\">{$transUnused}: <span id='aetr_open_widget_qty'>{$anyLicense['sum']['aetr']['open']} </span>{$transAEtr} | <span id='labour_open_widget_qty'>{$anyLicense['sum']['labour']['open']} </span>{$transLabour} </span>
  2550.                             <span class=\"line-clamp\">{$transOrderDate} {$lastOrder->createdAt->format('Y-m-d')}</span></div>";
  2551.                             //<span class=\"line-clamp\">{$transOrderAmount} {$fullPrice} HUF</span>"; // COM-510: deleted
  2552.                 }
  2553.             }
  2554.             elseif($anyLicense['sum']['license_type'] == 3)  // USAGE-BASED
  2555.             {
  2556.                 $transCredit $this->translator->trans('balance_credit', array(), 'balance');
  2557.                 $credit number_format($anyLicense['sum']['credit'],0,'',' ');
  2558.                 $credit number_format($company->balance,0,'',' ');
  2559.                 $transOrderDate $this->translator->trans('order_date', array(), 'balance');
  2560.                 $transOrderAmount $this->translator->trans('order_amount', array(), 'balance');
  2561.                 if (@$lastOrder) {
  2562.                     $result "<div class=\"muted-text-small \" style='margin-top: 0px;'><span class=\"line-clamp\">{$transCredit}{$credit} HUF</span>
  2563.                             <span class=\"line-clamp\">{$transOrderDate} {$lastOrder->createdAt->format('Y-m-d')}</span>
  2564.                             <span class=\"line-clamp\">{$transOrderAmount} {$fullPrice} HUF</span>
  2565.                             </div>";
  2566.                 }
  2567.             }
  2568.         }
  2569.         
  2570.         if ($result=='') {
  2571.         
  2572.             $transBalance $this->translator->trans('no_balance_available', array(), 'balance');
  2573.             $result "<div class=\"muted-text-small \" style='margin-top: 5px;'><span class=\"line-clamp\">{$transBalance}</span></div>";
  2574.         }
  2575.     }
  2576.     protected function jsonEncoder($content) {
  2577.         $encoders = array(new JsonEncoder());
  2578.         $normalizer = new ObjectNormalizer();
  2579.         $normalizer->setCircularReferenceLimit(0);
  2580.         $normalizer->setCircularReferenceHandler(function ($object) { // Circular reference handler
  2581.             return $object->getId();
  2582.         });
  2583.         //$normalizers = array(new ObjectNormalizer());
  2584.         $normalizers = array($normalizer);
  2585.         $serializer = new Serializer($normalizers$encoders);
  2586.         $jsonEncodedContent $serializer->serialize($content'json');
  2587.         //dump($jsonContent); die();
  2588.         return $jsonEncodedContent;
  2589.     }
  2590.     protected function getPageName($module$addPrefix=true$labelIdOverride=null) {
  2591.         $pageName '';
  2592.         $labelId = ($labelIdOverride==null) ? 'page.title' $labelIdOverride;
  2593.         if ($addPrefix$pageName $this->translator->trans('application.name', array(), 'general').' - ';
  2594.         $pageName .= $this->translator->trans($labelId, array(), $module);
  2595.         return $pageName;
  2596.     }
  2597.     protected function generateUniqueFileName() {
  2598.         return md5(uniqid());
  2599.     }
  2600.     protected function checkAccess($module$action) {
  2601.         // get user
  2602.         $user $this->getUser();
  2603.         if ($user==null) return false;
  2604.         // modify module for the purpose of the logic here
  2605.         if ($module=='subproduct'$module 'subproducts';
  2606.         if ($module=='statistic'$module 'statistics';
  2607.         //dump($module, $action);
  2608.         if (isset($this->modulesAllowedForRegularUsers[$module][$action])) {
  2609.             if (isset($this->modulesAllowedForRegularUsers[$module][$action]) &&
  2610.                 $this->modulesAllowedForRegularUsers[$module][$action]==true) {
  2611.                 return true;
  2612.             }
  2613.         }
  2614.         return false;
  2615.     }
  2616.     protected function getDefaultAjaxReturnRec($error=null$msg=''$info=''$url=''$errorField='') {
  2617.     
  2618.         // if passed-in URL is a route name, generate the URL from the route
  2619.         if (substr($url02)=="R:") {
  2620.             $url $this->router->generate(substr($url2));
  2621.         }
  2622.         $result = array(
  2623.             'success' => false,
  2624.             'error'  => $error,
  2625.             'msg' => $msg,
  2626.             'shortMsg' => $msg,
  2627.             'info' => $info,
  2628.             'url' => $url,
  2629.             'errorField' => $errorField,
  2630.         );
  2631.         return $result;
  2632.     }
  2633.     
  2634.     // COM-API
  2635.     protected function getDefaultApiReturnRec($error=null$info='') {
  2636.     
  2637.         $result = array(
  2638.             'success' => false,
  2639.             'error'  => $error,
  2640.             'info' => $info,
  2641.         );
  2642.         return $result;
  2643.     }
  2644.     protected function getDefaultAjaxDatatableReturnRec($request$error=''$info=''$url='') {
  2645.         $result = array(
  2646.             'draw' => $request->request->get('draw'),
  2647.             'recordsTotal' => 0,
  2648.             'recordsFiltered' => 0,
  2649.             'data' => [],
  2650.             'error' => $error,
  2651.             'info' => $info,
  2652.             'url' => $url,
  2653.         );
  2654.         return $result;
  2655.     }
  2656.     protected function buildListViewRenderArray($sectionTitle$entity=null$params=null) {
  2657.         $datatableDefaultsArray = array(
  2658.             'module' => $this->module,
  2659.             'dataUrl' => "/{$this->module}/get",
  2660.             'addUrl' => "/{$this->module}/new",
  2661.             'editUrl' => "/{$this->module}/[id]",
  2662.             'deleteUrl' => "/{$this->module}/[id]/delete",
  2663.             'searching' => $this->listViewSettings['searching'],
  2664.             'searchLabel' => (isset($this->listViewSettings['searchLabel']) ? $this->listViewSettings['searchLabel'] : null),
  2665.             'ordering' => $this->listViewSettings['ordering'],
  2666.             'orderingDefault' => (isset($this->listViewSettings['orderingDefault']) ? $this->listViewSettings['orderingDefault'] : null),
  2667.             'columns' => [],
  2668.             'columnDefs' => [],
  2669.         );
  2670.         $datatableColumnArray = array();
  2671.         $datatableColumnDefArray = array();
  2672.         // fill in columns and columnDefs
  2673.         $colNumber 0;
  2674.         //dump($this->listViewSettings['columns']);
  2675.         foreach($this->listViewSettings['columns'] as $colName=>$colInfo) {
  2676.             // columns
  2677.             if (isset($colInfo['label'])) {
  2678.                 if (is_array($colInfo['label'])) {
  2679.                     $datatableColumnArray[] = [
  2680.                         'title' => $this->translator->trans($colInfo['label'][0], array(), $colInfo['label'][1]),
  2681.                     ];
  2682.                 } else {
  2683.                     $datatableColumnArray[] = [
  2684.                         'title' => $colInfo['label'],
  2685.                     ];
  2686.                 }
  2687.             } else if (in_array($colName, ['createdAt'])) {
  2688.                 $datatableColumnArray[] = [
  2689.                     'title' => $this->translator->trans("field.$colName", array(), 'general'),
  2690.                 ];
  2691.             } else {
  2692.                 $datatableColumnArray[] = [
  2693.                     'title' => $this->translator->trans("field.$colName", array(), $this->module),
  2694.                 ];
  2695.             }
  2696.             // columnDefs
  2697.             $thisColumnDef = [];
  2698.             if (isset($colInfo['tp'])) {
  2699.                 // type
  2700.                 if ($colInfo['tp']=='hidden' || $colInfo['tp']=='ignore') {
  2701.                     $thisColumnDef['visible'] = false;
  2702.                 } else if ($colInfo['tp']=='non-db') {
  2703.                     $thisColumnDef['visible'] = $colInfo['show'] ?? false;
  2704.                 } else if ($colInfo['tp']=='extra') {  // COM-685
  2705.                     $thisColumnDef['visible'] = $colInfo['show'] ?? false;
  2706.                 } else if ($colInfo['tp']=='expand-button') {
  2707.                     $thisColumnDef['expand-button'] = true;
  2708.                 }
  2709.             }
  2710.             // is searchable?
  2711.             if (isset($colInfo['orderable']) && $colInfo['orderable']===true) {
  2712.                 $thisColumnDef['orderable'] = true;
  2713.             } else {
  2714.                 $thisColumnDef['orderable'] = false;
  2715.             }
  2716.             if (isset($colInfo['class']) && $colInfo['class']!='') {
  2717.                 $thisColumnDef['class'] = $colInfo['class'];
  2718.             }
  2719.             if (count($thisColumnDef)>0) {
  2720.                 $thisColumnDef['targets'] = $colNumber;
  2721.                 $datatableColumnDefArray[] = $thisColumnDef;
  2722.             }
  2723.             $colNumber++;
  2724.         }
  2725.         //dump($datatableDefaultsArray, $datatableColumnArray, $datatableColumnDefArray);
  2726.         // countries
  2727.         $countriesArray $this->formsHelper->getCountries($this->currentCountry);
  2728.         // check if need to show a page other than first page
  2729.         //dump($this->session->get('list-page-info'));
  2730.         $initialPageOffset '';
  2731.         $initialPageSize '';
  2732.         /*$sessionListPageInfo = $this->session->get('list-page-info');
  2733.         if ($sessionListPageInfo!=null) {
  2734.             $sessionListPageInfoArr = explode(';', $sessionListPageInfo);
  2735.             if ($sessionListPageInfoArr[0]==$this->module) {
  2736.                 $initialPageOffset = $sessionListPageInfoArr[1];
  2737.                 $initialPageSize = $sessionListPageInfoArr[2];
  2738.                 $datatableDefaultsArray['displayStart'] = $initialPageOffset;
  2739.                 $datatableDefaultsArray['pageLength'] = $initialPageSize;
  2740.             }
  2741.         } else*/
  2742.         /*if (isset($_COOKIE[$this->module.'_list-page'])) {
  2743.             $cookieListPageInfoArr = explode(';', $_COOKIE[$this->module.'_list-page']);
  2744.             $initialPageOffset = $cookieListPageInfoArr[0];
  2745.             $initialPageSize = $cookieListPageInfoArr[1] ?? 10;
  2746.             $datatableDefaultsArray['displayStart'] = $initialPageOffset;
  2747.             $datatableDefaultsArray['pageLength'] = $initialPageSize;
  2748.             //dump("info from cookie: initialPageOffset: $initialPageOffset, initialPageSize: $initialPageSize");
  2749.         }*/
  2750.         //dump($_COOKIE);
  2751.         return $this->buildRenderArray($this->module, array(
  2752.             'section_title' => $sectionTitle,
  2753.             'settings_js' => json_encode($datatableDefaultsArray),
  2754.             'datatableColumnArray_js' => json_encode($datatableColumnArray),
  2755.             'datatableColumnDefArray_js' => json_encode($datatableColumnDefArray),
  2756.             'countriesArray_js' => json_encode($countriesArray),
  2757.             'entity' => $entity,
  2758.             //'initialPageOffset' => $initialPageOffset,
  2759.             //'initialPageSize' => $initialPageSize,
  2760.         ), null$params);
  2761.     }
  2762.     protected function getListViewData($request$customDataUpdaterFunction=null$searchParms=null$getAll=false) {
  2763.         //dump('getListViewData', $request, $searchParms);
  2764.         $result = array(
  2765.             'draw' => $request->request->get('draw'),
  2766.             'recordsTotal' => 0,
  2767.             'recordsFiltered' => 0,
  2768.             'data' => [],
  2769.             'error' => '',
  2770.         );
  2771.         /* // check permissions & handle actions common to every request
  2772.         $rc = $this->handleControllerAction($request, $this->module, 'list', $this->emptyEntity, true);
  2773.         if ($rc!==true && $this->redirectRoute!=null) { //T
  2774.             $result['info'] = 'no access';
  2775.             $result['url'] = $this->router->generate($this->redirectRoute);
  2776.             return $result;
  2777.         }*/
  2778.         $queryParms = new \stdClass();
  2779.         if ($getAll===true) {
  2780.             $queryParms->offset 0;
  2781.             $queryParms->pageSize 9999999999999999;
  2782.         } else {
  2783.             $queryParms->offset $request->request->get('start');
  2784.             $queryParms->pageSize $request->request->get('length');
  2785.             $sessionListPageInfo $this->module.';'.$queryParms->offset.';'.$queryParms->pageSize;
  2786.             $this->session->set('list-page-info'$sessionListPageInfo);
  2787.         }
  2788.         // sorting
  2789.         if (isset($this->listViewSettings['ordering']) && $this->listViewSettings['ordering']===true) {
  2790.             // get requested sort order
  2791.             $orderParams $request->request->get('order');
  2792.             if ($orderParams==null$orderParams = [1,'asc']; // generic, added for COM-695
  2793.             foreach($orderParams as $orderColumnInfo) {
  2794.                 // [ "column" => "1", "dir" => "desc" ]
  2795.                 //dump($orderColumnInfo);
  2796.                 break;
  2797.             }
  2798.             // find the field that is column $orderColumnInfo["column"]
  2799.             $colNum 0;
  2800.             foreach($this->listViewSettings['columns'] as $colName=>$colInfo) {
  2801.                 if ($colNum==intval($orderColumnInfo["column"])) {
  2802.                     $queryParms->sortBy $colName;
  2803.                     $queryParms->sortDesc = ($orderColumnInfo["dir"]=="desc");
  2804.                     break;
  2805.                 }
  2806.                 $colNum++;
  2807.             }
  2808.         }
  2809.         $querySearchInfo $request->request->get('search');
  2810.         $querySearchColumns $request->request->get('columns');
  2811.         //dump('querySearchInfo', $querySearchInfo, 'querySearchColumns', $querySearchColumns);
  2812.         $queryParms->searchParms = [];
  2813.         // if a company is not selected, then the list pages for all classes listed in self::EMPTY_COMPANY_CLASSES need to show no data
  2814.         if (in_array($this->modulePathself::EMPTY_COMPANY_CLASSES)) {
  2815.             /*if ($this->getUser()->__get('currentCompanyViewed')==null) {
  2816.                 // return empty result
  2817.                 return $result;
  2818.             }*/
  2819.         }
  2820.         // users list -
  2821.         if ($this->modulePath==User::class) {
  2822.             // check if company selected
  2823.             switch ($this->getUser()->getRolesUnconverted()) {
  2824.                 case UserRoleEnum::ROLE_SUPER_ADMIN:
  2825.                     if (isset($this->serverUsersArea) && $this->serverUsersArea===true) { // COM-843
  2826.                     
  2827.                         unset($queryParms->searchParms['account']);
  2828.                         unset($queryParms->searchParms['company']);
  2829.                         $queryParms->searchParms['roles'] = ['IN', [    
  2830.                                                                 UserRoleEnum::ROLE_USER
  2831.                                                                 UserRoleEnum::ROLE_ADMIN,
  2832.                                                                 UserRoleEnum::ROLE_ACCOUNT_OWNER,
  2833.                                                                 UserRoleEnum::ROLE_SUPER_ADMIN,
  2834.                                                                 UserRoleEnum::ROLE_UPLOAD_ONLY,
  2835.                                                                 UserRoleEnum::ROLE_UPLOAD_PROTOCOL,
  2836.                                                                 UserRoleEnum::ROLE_TRANSLATOR,
  2837.                                                             ]];
  2838.                                                             
  2839.                         $date24hAgo $this->timeCalc->alterDateTimeByMinutes($this->timeCalc->currentDateTime, -1440falsefalse);
  2840.                         $queryParms->searchParms['lastActionAt'] = $date24hAgo// applies >= filter
  2841.                     } else if ($this->getUser()->__get('currentCompanyViewed')==null) {
  2842.                         // company not selected - show ONLY superadmin users in the system
  2843.                         $queryParms->searchParms['roles'] = ['IN', [UserRoleEnum::ROLE_SUPER_ADMIN
  2844.                                                                     UserRoleEnum::ROLE_TRANSLATOR]]; // COM-794
  2845.                     } else {
  2846.                         // company selected - show ((??superadmin users AND??)) users all users at this ACCOUNT
  2847.                         $queryParms->searchParms['account'] = $this->getUser()->__get('currentCompanyViewed')->__get('account')->getId();
  2848.                         //dump($this->company);
  2849.                     }
  2850.                     break;
  2851.                 case UserRoleEnum::ROLE_ACCOUNT_OWNER:
  2852.                     // show all users for this account
  2853.                     ////dump($this->account);
  2854.                     ////$queryParms->searchParms['account'] = $this->account;
  2855.                     $queryParms->searchParms['account'] = $this->getUser()->__get('currentCompanyViewed')->__get('account')->getId();
  2856.                     break;
  2857.                 case UserRoleEnum::ROLE_ADMIN:
  2858.                     // show all ADMIN and VIEW users for this account
  2859.                     if ($this->getUser()->__get('currentCompanyViewed')==null) {
  2860.                         $queryParms->searchParms['account'] = $this->getUser()->__get('account')->getId();
  2861.                     } else {
  2862.                         $queryParms->searchParms['account'] = $this->getUser()->__get('currentCompanyViewed')->__get('account')->getId();
  2863.                     }
  2864.                     $queryParms->searchParms['roles'] = ['IN', [UserRoleEnum::ROLE_ADMINUserRoleEnum::ROLE_USER]];
  2865.                     break;
  2866.                 case UserRoleEnum::ROLE_USER:
  2867.                 default:
  2868.                     // should never come here, return empty set
  2869.                     return $result;
  2870.             }
  2871.         } else if ($this->modulePath==Company::class) {
  2872.             // COM-815.a
  2873.             $searchParms null;
  2874.             if (isset($this->account) && $this->account->getType()==AccountTypeEnum::EXTERNALLY_MANAGED) {
  2875.         
  2876.                 // externally-managed account
  2877.                 if ($this->getUser()->getRolesUnconverted()==UserRoleEnum::ROLE_SUPER_ADMIN ||
  2878.                     $this->getUser()->getRolesUnconverted()==UserRoleEnum::ROLE_ACCOUNT_OWNER) {
  2879.                     // COMPASS user and 'registered' user (account owner) - can see all the companies in the account
  2880.                     $queryParms->searchParms['account'] = $this->account;
  2881.                 } else {
  2882.                     // companies in the account don't see each other
  2883.                     // force the search to get the current company only
  2884.                     if ($this->company!=null) {
  2885.                         $queryParms->searchParms['id'] = $this->company->getId();
  2886.                     }
  2887.                 }
  2888.                 
  2889.             } else {
  2890.                 if ($this->getUser()->getRolesUnconverted()==UserRoleEnum::ROLE_SUPER_ADMIN) {
  2891.                     if ($this->getUser()->__get('currentCompanyViewed')==null) {
  2892.                         // show empty companies
  2893.                         return $result;
  2894.                     } else {
  2895.                         // admin user and company selected - get all companies belonging to this account
  2896.                         $queryParms->searchParms['account'] = $this->getUser()->__get('currentCompanyViewed')->getAccount();
  2897.                         //dump($currentCompanysAccount);
  2898.                     }
  2899.                 } else {
  2900.                     // get all companies with the current account
  2901.                     $queryParms->searchParms['account'] = $this->account;
  2902.                 }
  2903.                 
  2904.             }
  2905.         } else if (in_array($this->modulePathself::PARAMETER_CLASSES)) {
  2906.             // parameter entity
  2907.             if ($this->company!=null && $this->company->__get('localParamsChanged')==false) {
  2908.                 // we have a company, and there were no changes made to local parameters - show global parameters!
  2909.                 $queryParms->searchParms['company'] = null;
  2910.             } else {
  2911.                 // else show local parameters
  2912.                 if (property_exists($this->modulePath'account')) $queryParms->searchParms['account'] = $this->account;
  2913.                 if (property_exists($this->modulePath'company')) $queryParms->searchParms['company'] = $this->company;
  2914.             }
  2915.         } else if ($this->modulePath==CustomField::class) {
  2916.             $queryParms->language $this->currentLanguage;
  2917.         } else {
  2918.             if (property_exists($this->modulePath'account')) $queryParms->searchParms['account'] = $this->account;
  2919.             if (property_exists($this->modulePath'company')) $queryParms->searchParms['company'] = $this->company;
  2920.         }
  2921.         // if we're getting DayAssignments, and this is a Hungary-based company, show Compass-defined entities
  2922.         //dump('queryParms', $queryParms);
  2923.         if ($this->getUser()->__get('currentCompanyViewed')!=null &&
  2924.             $this->modulePath==DayAssignment::class) {
  2925.             if ($this->company->__get('country')!==null && $this->company->__get('country')=='hu') {
  2926.                 $queryParms->searchParms['company'] = null;
  2927.                 //dump('getListViewData, hun country'); 
  2928.             }
  2929.         }
  2930.         //die('3333');
  2931.         // apply search/filter
  2932.         //dump('querySearchInfo', $querySearchInfo);
  2933.         if (isset($querySearchInfo['value']) && $querySearchInfo['value']!=='') {
  2934.             // search all displayed columns by one value
  2935.             $queryParms->searchParms['*'] = $querySearchInfo['value'];
  2936.             //dump($this->listViewSettings); die();
  2937.             // special action if deleted field is included
  2938.             if (isset($this->listViewSettings['columns']['deleted'])) {
  2939.                 // find the deleted column
  2940.                 $idx 0;
  2941.                 foreach($this->listViewSettings['columns'] as $colName=>$colInfo) {
  2942.                     if ($colName=='deleted') break; // use current $idx
  2943.                     $idx++;
  2944.                 }
  2945.                 if ($querySearchColumns[$idx]['search']['value']==='ALL') {
  2946.                     $queryParms->searchParms['deleted'] = 'ALL';
  2947.                 }
  2948.             }
  2949.             
  2950.         }
  2951.         //dump('searchParms', $searchParms);
  2952.         if ($searchParms!=null) {
  2953.             foreach($searchParms as $searchField=>$searchValue) {
  2954.                 $queryParms->searchParms[$searchField] = $searchValue;
  2955.             }
  2956.         } else {
  2957.             // search specified columns only
  2958.             $colNumber 0;
  2959.             foreach($this->listViewSettings['columns'] as $colName=>$colInfo) {
  2960.                 //dump($colName, $colInfo);
  2961.                 if (isset($colInfo['filtered']) && $colInfo['filtered']===true) {
  2962.                     //dump('>>', $querySearchColumns[$colNumber]);
  2963.                     if ($querySearchColumns[$colNumber]['search']['value']!=='') {
  2964.                         $queryParms->searchParms[$colName] = $querySearchColumns[$colNumber]['search']['value'];
  2965.                         //dump('add');
  2966.                     }
  2967.                 }
  2968.                 $colNumber++;
  2969.             }
  2970.         }
  2971.         //dump('queryParms', $queryParms);
  2972.         //die();
  2973.         // do a pass through settings to see what we have
  2974.         $inThisSearch = [
  2975.             'dayTitles' => false,
  2976.         ];
  2977.         foreach($this->listViewSettings['columns'] as $colName=>$colInfo) {
  2978.             if (!isset($colInfo['tp'])) continue;
  2979.             if ($colInfo['tp']=='relationship') {
  2980.                 if ($colInfo['entity']=='DayTitle') {
  2981.                     $inThisSearch['dayTitles'] = true;
  2982.                 }
  2983.             }
  2984.         }
  2985.         //dump('queryParms', $queryParms);
  2986.         /*
  2987.         // if day titles, sorting is tricky - so get all the rows first, and then will filter out those not necessarily
  2988.         if ($this->modulePath==DayTitle::class) {
  2989.             //dump('queryParms', $queryParms);
  2990.             $queryParms->offset = 0;
  2991.             $queryParms->pageSize = 999;
  2992.         } */
  2993.         // COM-288: for waybills, the search in the page uses startDate and endDate, but in the db it is only
  2994.         // for endDate (endDate must be in the range specified by searchParms[startDate] and searchParms[endDate]
  2995.         if ($this->modulePath==Consumption::class) {
  2996.             //dump('$queryParms->searchParms', $queryParms->searchParms);
  2997.             if ($queryParms->searchParms['startDate']!='' && $queryParms->searchParms['endDate']!='') {
  2998.                 // this is actually a search by range of the endDate ONLY
  2999.                 $queryParms->searchParms['endDate'] = ['IN-RANGE', [$queryParms->searchParms['startDate'],
  3000.                                                                     $queryParms->searchParms['endDate']]];
  3001.                 unset($queryParms->searchParms['startDate']);
  3002.                 
  3003.                 //dump('$queryParms->searchParms (2)', $queryParms->searchParms);
  3004.                 
  3005.             }
  3006.         }
  3007.         // COM-400: for event log (manual activities), the search in the page uses startDate and endDate, but in the db it is
  3008.         // only for createdAt (createdAt must be in the range specified by searchParms[startDate] and searchParms[endDate])
  3009.         if ($this->modulePath==DriverManualActivity::class) {
  3010.             //dump('$queryParms->searchParms', $queryParms->searchParms);
  3011.             if (isset($queryParms->searchParms['createdAt']) && $queryParms->searchParms['createdAt']!='') {
  3012.                 $createdAtArray explode(","$queryParms->searchParms['createdAt']);
  3013.                 $queryParms->searchParms['createdAt'] = [
  3014.                     'IN-RANGE'
  3015.                     [$createdAtArray[0].' 00:00:00'$createdAtArray[1].' 23:59:59']
  3016.                 ];
  3017.                 
  3018.                 //dump('$queryParms->searchParms (2)', $queryParms->searchParms);
  3019.                 //dump('new createdAt', $queryParms->searchParms['createdAt']);
  3020.                 
  3021.             }
  3022.             // COM-409
  3023.             $queryParms->sortBy 'createdAt';
  3024.             $queryParms->sortDesc 'desc';
  3025.         }
  3026.         
  3027.         // COM-431
  3028.         if ($this->modulePath==ConsumptionsTanking::class) {
  3029.             $queryParms->sortBy 'date,kmAtTanking';
  3030.             $queryParms->sortDesc false;
  3031.             //dump('ConsumptionsTanking');
  3032.         }
  3033.         $repository $this->getDoctrine()->getRepository($this->modulePath);
  3034.         $customFieldRepository $this->getDoctrine()->getRepository(CustomField::class);
  3035.         $customFieldLabelRepository $this->getDoctrine()->getRepository(CustomFieldLabel::class);
  3036.         //dump($repository);
  3037.         // get count
  3038.         $count $repository->getCount($queryParms$this->listViewSettings['columns']);
  3039.         //dump('count', $count);
  3040.         //die();
  3041.         // prepare for the search
  3042.         $dayTitlesArray = []; // codes
  3043.         $dayTitleDescriptionsArray = []; // descriptions
  3044.         if ($inThisSearch['dayTitles']) {
  3045.             $dayTitlesArray $this->getCompanyDayTitles(truefalse);
  3046.             $dayTitleDescriptionsArray $this->getCompanyDayTitles(falsefalse);
  3047.             //dump('dayTitlesArray', $dayTitlesArray);
  3048.             //dump('dayTitleDescriptionsArray', $dayTitleDescriptionsArray);
  3049.         }
  3050.         //dump("IS RAW REPO", $repository->isRawRepository());
  3051.         // get data
  3052.         $data = [];
  3053.         $dbEntities $repository->getPaginatedData($queryParms$this->listViewSettings['columns'], $repository->isRawRepository());
  3054.         //dump('dbEntities', $dbEntities); //die();
  3055.         if ($dbEntities!=null) {
  3056.             $customFieldLabels = [];
  3057.             // get driversLicenseCardExpiry label (custom field) --> ACTUALLY, this is driverCardExpiry, but don't want to change code to fix this
  3058.             $driversLicenseCardExpiryLabel '';
  3059.             if ($_SERVER['APP_DRIVER_CARD_EXPIRY_CUSTOM_FIELD_ID']!='') {
  3060.                 $driversLicenseCardExpiry_customField $this->getDoctrine()->getRepository(CustomField::class)
  3061.                     ->findOneById($_SERVER['APP_DRIVER_CARD_EXPIRY_CUSTOM_FIELD_ID']);
  3062.                 if ($driversLicenseCardExpiry_customField!=null) {
  3063.                     $driversLicenseCardExpiry_label $this->getDoctrine()->getRepository(CustomFieldLabel::class)->findOneBy([
  3064.                         'customField' => $driversLicenseCardExpiry_customField,
  3065.                         'language' => $this->currentLanguage,
  3066.                     ]);
  3067.                     if ($driversLicenseCardExpiry_label!=null) {
  3068.                         $driversLicenseCardExpiryLabel $driversLicenseCardExpiry_label->__get('name');
  3069.                     }
  3070.                 }
  3071.             }
  3072.             //dump('driversLicenseCardExpiryLabel', $driversLicenseCardExpiryLabel);
  3073.             foreach($dbEntities as $d) {
  3074.                 // if array (as for some tables), convert array into object with regular methods
  3075.                 //if (gettype($d)=='array') {
  3076.                 if ($repository->isRawRepository()) {
  3077.                     $d = new RawDbRecord($d);
  3078.                     //dump($d);
  3079.                 }
  3080.                 //if ($d->__get('itemType')==LogItemTypeEnum::TO_DO_ITEM) continue;
  3081.                 $detailsArray = [];
  3082.                 if ($this->module=='log-entries' ||
  3083.                     $this->module=='expenses') {
  3084.                 
  3085.                     //dump($d);
  3086.                 
  3087.                     //if ($d->getId()==795) continue;
  3088.                 
  3089.                     if ($d->__get('itemType')==LogItemTypeEnum::BALANCE) continue; //JNOTE
  3090.                     if ($d->__get('detailsExist')==true) {
  3091.                         // load extra data about this row (from a separate table, holding additional details)
  3092.                         $rc $this->db->query("SELECT * FROM ".$this->listViewSettings['columns']['details']['table-name']."
  3093.                                                  WHERE id='".($d->getId())."'"false); //idx
  3094.                         if ($rc) {
  3095.                             $dbRows $this->db->fetchAll(true);
  3096.                             if (count($dbRows)>0) {
  3097.                                 $detailsArray json_decode($dbRows[0]['changes_made'], TRUE);
  3098.                             }
  3099.                         }
  3100.                         //dump('changeType: '.$d->__get('changeType').', detailsArray', $detailsArray, $this->listViewSettings['columns']);
  3101.                     
  3102.                     }
  3103.                 } else if ($this->module=='work-periods') {
  3104.                     //dd("WORK PERIOD", $d);
  3105.                     $daysInWorkPeriod $this->calcHelper->getWorkDaysInPeriod($d);
  3106.                     //dump($d->__getDateFormatted('startDate').' ... '.$d->__getDateFormatted('endDate'), $daysInWorkPeriod);
  3107.                     $d->__set('workHours',  $daysInWorkPeriod['numberOfWorkDays'] * 8);
  3108.                     $d->__set('workHours6'$daysInWorkPeriod['numberOfWorkDays'] * 6);
  3109.                     $d->__set('workHours4'$daysInWorkPeriod['numberOfWorkDays'] * 4);
  3110.                     if (0) { //JNOTE-TESTING
  3111.                         $d->__set('workHours4'"W:{$daysInWorkPeriod['numberOfWorkDays']}, R:{$daysInWorkPeriod['numberOfNonWorkDays']}");
  3112.                     }
  3113.                 }
  3114.                 $thisEntityData = [];
  3115.                 foreach($this->listViewSettings['columns'] as $colName=>$colInfo) {
  3116.                     //dump("************** $colName ****************");
  3117.                     //dump($colInfo);
  3118.                     try {
  3119.                         $done false;
  3120.                         if (isset($colInfo['tp'])) {
  3121.                             /*if ($colInfo['tp']=='ignore') {
  3122.                                 // ignore it, needed for something else (not getting data)
  3123.                                 $done = true;
  3124.                             }*/
  3125.                             if ($colInfo['tp']=='non-db') {
  3126.                                 // ignore it, needed for something else (not getting data)
  3127.                                 $thisEntityData[] = '';
  3128.                                 $done true;
  3129.                             } else if ($colInfo['tp']=='date') {
  3130.                                 $thisEntityData[] = $d->__getDateFormatted($colName) ?? '';
  3131.                                 $done true;
  3132.                             } else if ($colInfo['tp']=='datetime') {
  3133.                                 $thisEntityData[] = $d->__getDateTimeFormatted($colName) ?? '';
  3134.                                 $done true;
  3135.                             } else if ($colInfo['tp']=='time') {
  3136.                                 $thisEntityData[] = $d->__getTimeFormatted($colName) ?? '';
  3137.                                 $done true;
  3138.                             } else if ($colInfo['tp']=='time-as-float') {
  3139.                                 $thisEntityData[] = str_replace("."":"$d->__get($colName));
  3140.                                 $done true;
  3141.                             } else if ($colInfo['tp']=='boolean') {
  3142.                                 if (isset($colInfo['reverse']) && $colInfo['reverse']===true) {
  3143.                                     $thisEntityData[] =  BooleanEnum::getLabel(!$d->__get($colName), $this->translator);
  3144.                                 } else {
  3145.                                     $thisEntityData[] =  BooleanEnum::getLabel($d->__get($colName), $this->translator);
  3146.                                 }
  3147.                                 $done true;
  3148.                             } else if ($colInfo['tp']=='buttonlink') {
  3149.                                 $thisEntityData[] =  "<a target='_blank' href=\"{$d->__get($colName)}\" class='btn btn-primary'>{$this->translator->trans($colInfo['buttonlabel'][0], array(), $colInfo['buttonlabel'][1])}</a>";
  3150.                                 $done true;
  3151.                             } else if ($colInfo['tp']=='enum') {
  3152.                                 //dump('list - enum '.$colInfo['enum'].', '.$d->__get($colName));
  3153.                                 //$thisEntityData[] =  $colInfo['enum']::getLabel(intval($d->__get($colName)), $this->translator);
  3154.                                 if (isset($colInfo['specialEnum']) && $colInfo['specialEnum']==true) {
  3155.                                     //dump('specialEnum', $colInfo);
  3156.                                     $thisEntityRow $colInfo['enum']::getLabel2($d->__get($colName), $colInfo['specialConstant'], $this->translator'countries');
  3157.                                     //dump('>> specialEnum', $thisEntityRow);
  3158.                                 } else {
  3159.                                     $thisEntityRow $colInfo['enum']::getLabel($d->__get($colName), $this->translator);
  3160.                                 }
  3161.                                 if (0&&isset($_SERVER['APP_SHOW_DEBUG_IDS']) && $_SERVER['APP_SHOW_DEBUG_IDS']=='true') {
  3162.                                     $thisEntityRow .= ' ('.$d->__get($colName).')';
  3163.                                 }
  3164.                                 $thisEntityData[] = $thisEntityRow;
  3165.                                 $done true;
  3166.                             } else if ($colInfo['tp']=='relationship') {
  3167.                                 //dump('relationship');
  3168.                                 if ($repository->isRawRepository()) {
  3169.                                     //dump('relationship (repo raw)');
  3170.                                     if ($colInfo['entity']=='DayTitle') {
  3171.                                         //dump($d, $colInfo);
  3172.                                         //$dayTitleId = $d['day_title_id']; //->__get($colName)->getType();
  3173.                                         //$thisEntityData[] = $this->translator->trans( DayTitleTypeEnum::LABELS[$dayTitleType]['label'], array(),
  3174.                                         //                                                DayTitleTypeEnum::LABELS[$dayTitleType]['module'] );
  3175.                                         $dayTitleLabel '';
  3176.                                         if (isset($colInfo['showType']) && $colInfo['showType']==='description') {
  3177.                                             $dayTitleLabel $dayTitleDescriptionsArray$d->__get('day_title_id') ] ?? ''
  3178.                                         }
  3179.                                         if ($dayTitleLabel==='') {
  3180.                                             $dayTitleLabel $dayTitlesArray$d->__get('day_title_id') ] ?? ''
  3181.                                         }
  3182.                                         $thisEntityData[] = $dayTitleLabel;
  3183.                                     } else if ($colInfo['entity']=='Driver') {
  3184.                                         //dump("************** $colName ****************");
  3185.                                         //dump($d);
  3186.                                         //echo($d->driver_id."\n");
  3187.                                         if ($d->driver_id!=null) {
  3188.                                             //dump($d->driver_id);
  3189.                                             //dump(mb_detect_encoding($d->driver_id));
  3190.                                             if (0) {
  3191.                                                 //dump($d->driver_id);
  3192.                                                 $thisEntityData[] = mb_convert_encoding(trim($d->driver_id), 'UTF-8''UTF-8');
  3193.                                                 //dump($thisEntityData);
  3194.                                             } else if (0) {
  3195.                                                 $d->driver_id trim($d->driver_id);
  3196.                                                 $newName '';
  3197.                                                 for($g=0$g<=strlen($d->driver_id); $g++) {
  3198.                                                     $char substr($d->driver_id$g1);
  3199.                                                     //dump($char, ord($char), chr(ord($char)));
  3200.                                                     if (ord($char)==211) {
  3201.                                                         $newName .= 'O'//utf8_encode(0xC3);
  3202.                                                     } else {
  3203.                                                         $newName .= $char;
  3204.                                                     }
  3205.                                                 }
  3206.                                                 //dump("newName", $newName);
  3207.                                                 $thisEntityData[] = $newName// this is the driver name
  3208.                                             } else {
  3209.                                                 $thisEntityData[] = trim($d->driver_id);
  3210.                                             }
  3211.                                         }else {
  3212.                                             $thisEntityData[] = '';
  3213.                                         }
  3214.                                     } else {
  3215.                                         $thisEntityData[] = $d->__get($colName);
  3216.                                     }
  3217.                                 } else {
  3218.                                     //dump('relationship (repo not raw)');
  3219.                                     if ($colInfo['entity']=='Driver') {
  3220.                                         //dump($d);
  3221.                                         if ($d->__get($colName)!=null) {
  3222.                                             $thisEntityData[] = trim($d->__get($colName)->getLastName() . ' ' $d->__get($colName)->getFirstName());
  3223.                                             //dump($d->__get($colName)->getLastName() . ' ' . $d->__get($colName)->getFirstName());
  3224.                                         }else {
  3225.                                             $thisEntityData[] = '';
  3226.                                         }
  3227.                                     }else if ($colInfo['entity']=='Trailer') {
  3228.                                         if ($d->__get($colName)!=null) {
  3229.                                            $thisEntityData[] = $d->__get($colName)->getName() ?? '';
  3230.                                         }else {
  3231.                                             $thisEntityData[] = '';
  3232.                                         }
  3233.                                     }else if ($colInfo['entity']=='Company') {
  3234.                                         if ($d->__get($colName)!==null) {
  3235.                                            $thisEntityData[] = $d->__get($colName)->getName() ?? '';
  3236.                                         }else {
  3237.                                             $thisEntityData[] = $this->company->getName();
  3238.                                         }
  3239.                                     } else if ($colInfo['entity']=='DayTitle') {
  3240.                                         //dump("****DayTitle");
  3241.                                         //$thisEntityData[] = $d->__get($colName)->getCode() ?? '';
  3242.                                         if ($d->__get($colName)!=null) {
  3243.                                             $dayTitleType $d->__get($colName)->getType();
  3244.                                             //dump($dayTitleType, $dayTitleDescriptionsArray, $dayTitlesArray, $colInfo, $d->__get('dayTitle')->getId(), $dayTitleType);
  3245.                                             $dayTitleLabel '';
  3246.                                             if (isset($colInfo['showType']) && $colInfo['showType']==='description') {
  3247.                                                 $dayTitleLabel $dayTitleDescriptionsArray$d->__get('dayTitle')->getId() ] ?? ''
  3248.                                             }
  3249.                                             if ($dayTitleLabel==='') {
  3250.                                                 $dayTitleLabel $dayTitlesArray$d->__get('dayTitle')->getId() ] ?? ''
  3251.                                             }
  3252.                                             $thisEntityData[] = $dayTitleLabel;
  3253.                                             //$thisEntityData[] = $d->getId();
  3254.                                         } else {
  3255.                                             $thisEntityData[] = '';
  3256.                                         }
  3257.                                     } else if ($colInfo['entity']=='CustomFieldLabel') {
  3258.                                         //dump('---', $d->__get('customFieldLabels')[0] ?? ''); //, $d->__get('customFieldLabels')[1] ?? '');
  3259.                                         //dump($d, $d->__get('customFieldLabels')[0]);
  3260.                                         /*if (isset($d->__get('customFieldLabels')[0])) {
  3261.                                             $thisEntityData[] = $d->__get('customFieldLabels')[0]->getName() ?? '';
  3262.                                         } else {
  3263.                                             $thisEntityData[] = '';
  3264.                                         }*/
  3265.                                         $thisEntityData[] = $d->__get('customFieldLabels') ?? '';
  3266.                                     } else if ($colInfo['entity']=='User') {
  3267.                                         if ($d->__get($colName)!=null) {
  3268.                                             $thisEntityData[] = $d->__get($colName)->getUsername() ?? '';
  3269.                                         } else {
  3270.                                             $thisEntityData[] = '';
  3271.                                         }
  3272.                                     } else {
  3273.                                         $thisEntityData[] = $d->__get($colName)->getName() ?? '';
  3274.                                     }
  3275.                                 }
  3276.                                 $done true;
  3277.                             } else if ($colInfo['tp']=='multi-entity-name') {
  3278.                                 $thisClassPath $this->logger->itemTypeToModuleClassPath$d->__get('itemType') );
  3279.                                 $thisClassNameVariants $this->nc->getClassNameVariantsFromPath($thisClassPath);
  3280.                                 //dump("itemType: ".$d->__get('itemType').", thisClassPath: $thisClassPath, thisClassNameVariants", $thisClassNameVariants, $d);
  3281.                                 if ($d->__get('itemType')==LogItemTypeEnum::ROUTE_WAYPOINT) {
  3282.                                     $thisEntityData[] = '';
  3283.                                     $done true;
  3284.                                 } else if ($d->__get('itemType')==LogItemTypeEnum::DRIVER_ACTIVE_DAY) { // COM-806
  3285.                                     $activeDayDriver $this->getDoctrine()->getRepository(Driver::class)->findOneById$d->getItemId() );
  3286.                                     $thisEntityData[] = $activeDayDriver->getName();
  3287.                                     if (count($dayTitlesArray)==0) {
  3288.                                         $dayTitlesArray $this->getCompanyDayTitles(truefalse);
  3289.                                         //$dayTitleDescriptionsArray = $this->getCompanyDayTitles(false, false);
  3290.                                         //dump('dayTitlesArray', $dayTitlesArray);
  3291.                                     }
  3292.                                     $done true;
  3293.                                 } else if ($d->__get($colName)!=null) {
  3294.                                     // entity
  3295.                                     if ($thisClassPath==DriverSpecialEvent::class) {
  3296.                                         $specialEvent $this->getDoctrine()->getRepository($thisClassPath)->findOneById$d->__get($colName) );
  3297.                                         $driverName $specialEvent->getDriver()->getName();
  3298.                                         $thisEntityData[] = DriverSpecialEventEnum::getLabel($specialEvent->__get('type'), $this->translator).'<br>'.
  3299.                                             $specialEvent->__getDateTimeFormatted('timestamp').'<br>'.
  3300.                                             $driverName;
  3301.                                     } else if ($thisClassPath==DriverManualActivity::class) {
  3302.                                         $manualActivity $this->getDoctrine()->getRepository($thisClassPath)->findOneById$d->__get($colName) );
  3303.                                         $driverName $manualActivity->getDriver()->getName();
  3304.                                         $thisEntityData[] = DriverActivityTypeEnum::getLabel($manualActivity->__get('activityType'), $this->translator).'<br>'.
  3305.                                             $manualActivity->__getDateTimeFormatted('startDateTime').' - '.
  3306.                                             $manualActivity->__getDateTimeFormatted('endDateTime').'<br>'.
  3307.                                             $driverName;
  3308.                                     } else if ($thisClassPath==DriverWeeklyRestTimeException::class) {
  3309.                                         $weeklyRest $this->getDoctrine()->getRepository($thisClassPath)->findOneById$d->__get($colName) );
  3310.                                         $driverName $weeklyRest->getDriver()->getName();
  3311.                                         $weekEndSunday $weeklyRest->__getDateFormatted('weekBoundaryDay');
  3312.                                         /*if ($weeklyRest->__get('assignedWeek')==0) {
  3313.                                             $weekStr = $this->timeCalc->alterDateTimeByDays($weekEndSunday, -6, true).' - '.
  3314.                                                        $weekEndSunday;
  3315.                                         } else {
  3316.                                             $weekStr = $this->timeCalc->alterDateTimeByDays($weekEndSunday, 1, true).' - '.
  3317.                                                        $this->timeCalc->alterDateTimeByDays($weekEndSunday, 7, true);
  3318.                                         }*/
  3319.                                         $thisEntityData[] = 'Rest for week ending on: '.$weekEndSunday.'<br>'.
  3320.                                             //'Assigned to week: '.$weekStr.'<br>'.
  3321.                                             $driverName;
  3322.                                     } else if ($thisClassPath==ToDoItem::class) {
  3323.                                         // special handling - the entity id is actually inside of $detailsArray
  3324.                                         //dump('detailsArray!!!!', $detailsArray, $d);
  3325.                                         //dump('---', $colName, $colInfo);
  3326.                                         $entityName '';
  3327.                                         if (isset($detailsArray['toDoItemType'])) {
  3328.                                             if ($detailsArray['toDoItemType']==ToDoItemTypeEnum::STANDARD_DRIVER) {
  3329.                                         
  3330.                                                 // this is a driver, its id is stored in itemId
  3331.                                                 $item $this->getDoctrine()->getRepository(Driver::class)->findOneById$d->__get($colName) );
  3332.                                                 $entityName $item->getName().'<br>(driver)';
  3333.                                             } else if ($detailsArray['toDoItemType']==ToDoItemTypeEnum::STANDARD_VEHICLE) {
  3334.                                         
  3335.                                                 // this is a vehicle, its id is stored in itemId
  3336.                                                 $item $this->getDoctrine()->getRepository(Vehicle::class)->findOneById$d->__get($colName) );
  3337.                                                 $entityName $item->getName().'<br>(vehicle)';
  3338.                                             
  3339.                                             } else if ($detailsArray['toDoItemType']==ToDoItemTypeEnum::CUSTOM_FIELD) {
  3340.                                                 // this is a custom field, its id is stored in itemId
  3341.                                                 //dump('detailsArray!!!!', $detailsArray);
  3342.                                             
  3343.                                                 // find custom field id
  3344.                                                 $customFieldId null;
  3345.                                                 foreach($detailsArray as $keyname=>$keyinfo) {
  3346.                                                     if (substr($keyname,0,2)=='c.') {
  3347.                                                         $customFieldId substr($keyname,2);
  3348.                                                         break;
  3349.                                                     }
  3350.                                                 }
  3351.                                                 //dump('customFieldId: '.$customFieldId);
  3352.                                                 // get custom field
  3353.                                                 $customField $this->getDoctrine()->getRepository(CustomField::class)->findOneById($customFieldId); // $detailsArray['customFieldId'] );
  3354.                                                 //dump('customField', $customField);
  3355.                                             
  3356.                                                 // get custom field label
  3357.                                                 $cfLabel $this->getDoctrine()->getRepository(CustomFieldLabel::class)->findOneBy([
  3358.                                                                                                                             'customField' => $customField,
  3359.                                                                                                                             'language' => $this->currentLanguage,
  3360.                                                                                                                          ]);
  3361.                                                 //dump('cfLabel', $cfLabel);
  3362.                                                 $entityName '';
  3363.                                                 if ($customField->getCategory()==CustomFieldCategoryEnum::COMPANY) { //
  3364.                                                     $thisEntity $this->getDoctrine()->getRepository(Company::class)->findOneById$d->__get($colName) );
  3365.                                                     $entityTypeStr $this->translator->trans("loggedItemType.COMPANY", array(), 'log-entries');
  3366.                                                     $entityName $thisEntity->getName()."<br>($entityTypeStr)";
  3367.                                                 } else if ($customField->getCategory()==CustomFieldCategoryEnum::DRIVER) { //
  3368.                                                     $thisEntity $this->getDoctrine()->getRepository(Driver::class)->findOneById$d->__get($colName) );
  3369.                                                     $entityTypeStr $this->translator->trans("loggedItemType.DRIVER", array(), 'log-entries');
  3370.                                                     $entityName $thisEntity->getName()."<br>($entityTypeStr)";
  3371.                                                 } else if ($customField->getCategory()==CustomFieldCategoryEnum::VEHICLE) { //:dist, :date
  3372.                                                     $thisEntity $this->getDoctrine()->getRepository(Vehicle::class)->findOneById$d->__get($colName) );
  3373.                                                     $entityTypeStr $this->translator->trans("loggedItemType.VEHICLE", array(), 'log-entries');
  3374.                                                     $entityName $thisEntity->getName()."<br>($entityTypeStr)";
  3375.                                                 } else if ($customField->getCategory()==CustomFieldCategoryEnum::TRAILER) { //:date
  3376.                                                     $thisEntity $this->getDoctrine()->getRepository(Trailer::class)->findOneById$d->__get($colName) );
  3377.                                                     $entityTypeStr $this->translator->trans("loggedItemType.TRAILER", array(), 'log-entries');
  3378.                                                     $entityName $thisEntity->getName()."<br>($entityTypeStr)";
  3379.                                                 }
  3380.                                                 //dump('entityName ****', $entityName); die();
  3381.                                                 //die('pfff');
  3382.                                                 //$thisEntityData[] = '** cf **';
  3383.                                                 //dump($d);
  3384.                                                 //die();
  3385.                                                 
  3386.                                             }
  3387.                                             $thisEntityData[] = $entityName;
  3388.                                             
  3389.                                         } else {
  3390.                                             // normal to-do item (created on to-do page)
  3391.                                             //dump('xxxx', $d, $colName); die();
  3392.                                             $item $this->getDoctrine()->getRepository($thisClassPath)->findOneById$d->__get($colName) );
  3393.                                             $thisEntityData[] = $item->getName() ?? '';
  3394.                                         
  3395.                                         }                                        
  3396.                                     } else {
  3397.                                         //dump($colName, $colInfo, "thisClassPath: $thisClassPath, colName $colName, value:", $d->__get($colName));
  3398.                                         $item $this->getDoctrine()->getRepository($thisClassPath)->findOneById$d->__get($colName) );
  3399.                                         $thisEntityData[] = $item->getName() ?? '';
  3400.                                     }
  3401.                                 } else {
  3402.                                     // no entity (e.g. general "settings")
  3403.                                     $thisEntityData[] = '';
  3404.                                 }
  3405.                                 $done true;
  3406.                             } else if ($colInfo['tp']=='details-table') {
  3407.                                 $thisClassPath $this->logger->itemTypeToModuleClassPath$d->__get('itemType') );
  3408.                                 $thisClassNameVariants $this->nc->getClassNameVariantsFromPath($thisClassPath);
  3409.                                 //dump("itemType: ".$d->__get('itemType').", thisClassPath: $thisClassPath, thisClassNameVariants", $thisClassNameVariants);
  3410.                                 //dump('detailsArray', $detailsArray);
  3411.                                 //$detailsArray = [];
  3412.                                 if ($d->__get('detailsExist')==true &&
  3413.                                     count($detailsArray)>0) {
  3414.                                     // special handling for to-do items - update thisClassPath
  3415.                                     if ($thisClassPath==ToDoItem::class) {
  3416.                                         if ($detailsArray['toDoItemType']==ToDoItemTypeEnum::STANDARD_DRIVER) {
  3417.                                             $thisClassPath Driver::class;
  3418.                                             $thisClassNameVariants $this->nc->getClassNameVariantsFromPath($thisClassPath);
  3419.                                         } else if ($detailsArray['toDoItemType']==ToDoItemTypeEnum::STANDARD_VEHICLE) {
  3420.                                             $thisClassPath Vehicle::class;
  3421.                                             $thisClassNameVariants $this->nc->getClassNameVariantsFromPath($thisClassPath);
  3422.                                         } else if ($detailsArray['toDoItemType']==ToDoItemTypeEnum::CUSTOM_FIELD) {
  3423.                                             
  3424.                                             //$thisClassPath = Vehicle::class;
  3425.                                         
  3426.                                             //dump('detailsArray ^^^^^^2', $detailsArray);
  3427.                                             //die('pfff');
  3428.                                         }
  3429.                                         //$thisClassNameVariants = $this->nc->getClassNameVariantsFromPath($thisClassPath);
  3430.                                         //dump("NEW thisClassPath: $thisClassPath, thisClassNameVariants", $thisClassNameVariants);
  3431.                                     }
  3432.                                     // COM-822
  3433.                                     if ($thisClassNameVariants['classNameSmallPlural']=='drivers') {
  3434.                                         if (isset($detailsArray['language'])) unset($detailsArray['language']); // not a user-visible field, don't show (may show in future)
  3435.                                         if (isset($detailsArray['lastCardNumberActive'])) unset($detailsArray['lastCardNumberActive']); // not a user-visible field, don't show
  3436.                                     }
  3437.                                     foreach($detailsArray as $thisFieldName=>$details) {
  3438.                                         if ($thisFieldName=='toDoItemType') continue;
  3439.                                         if ($thisFieldName=='customFieldId') continue;
  3440.                                         if (substr($thisFieldName02)=='c.') {
  3441.                                             // custom field - load its label
  3442.                                             //dump('cf '.$thisFieldName);
  3443.                                             $customFieldId substr($thisFieldName2);
  3444.                                             if (!isset($customFieldLabels[$customFieldId])) {
  3445.                                                 $customFieldLabel $thisFieldName;
  3446.                                                 $customField $customFieldRepository->findOneById($customFieldId);
  3447.                                                 //dump("customField $customFieldId", $customField);
  3448.                                                 if ($customField!=null) {
  3449.                                                     $customField_label $customFieldLabelRepository->findOneBy([
  3450.                                                         'customField' => $customField,
  3451.                                                         'language' => $this->currentLanguage,
  3452.                                                     ]);
  3453.                                                     //dump('customField_label '.$customField_label);
  3454.                                                 }
  3455.                                                 if ($customField_label!==null) { // COM-632(2)
  3456.                                                     $customFieldLabels[$customFieldId] = $customField_label->__get('name');
  3457.                                                 } else {
  3458.                                                     $customFieldLabels[$customFieldId] = ''// COM-632(2)
  3459.                                                 }
  3460.                                             }
  3461.                                             $detailsArray[$thisFieldName]['label'] = $customFieldLabels[$customFieldId];
  3462.                                         } else {
  3463.                                             // normal field
  3464.                                             $thisFieldNameForLabel $thisFieldName;
  3465.                                             if ($thisFieldName=='plainPassword') {
  3466.                                                 $thisFieldNameForLabel 'password';
  3467.                                                 $detailsArray[$thisFieldName]['tp'] = 'password';
  3468.                                             }
  3469.                                             $thisFieldType $detailsArray[$thisFieldName]['tp'] ?? null;
  3470.                                             //dump("thisFieldName: [$thisFieldName], thisFieldType: [$thisFieldType]");
  3471.                                             if ($thisClassNameVariants['classNameSmallPlural']=='settings') {
  3472.                                                 $thisFieldType Setting::CONFIG[$thisFieldName]['type'];
  3473.                                                 if ($thisFieldType=='bool'$thisFieldType 'boolean';
  3474.                                                 $detailsArray[$thisFieldName]['label'] = $this->translator->trans("field.$thisFieldName", array(), 'settings');
  3475.                                             } else if ($thisClassNameVariants['classNameSmallPlural']=='drivers' && $thisFieldName=='driversLicenseCardExpiry') {
  3476.                                                 $detailsArray[$thisFieldName]['label'] = $driversLicenseCardExpiryLabel;
  3477.                                             } else if ($thisClassNameVariants['classNameSmallPlural']=='driver-manual-activities') {
  3478.                                                 $detailsArray[$thisFieldName]['label'] = $this->translator->trans("field.$thisFieldNameForLabel", array(), 'driver-activities');
  3479.                                             } else if ($thisClassPath==DriverWeeklyRestTimeException::class) {
  3480.                                                 $detailsArray[$thisFieldName]['label'] = $this->translator->trans("field.weeklyRestAssignedWeek", array(), 'driver-special-events');
  3481.                                             } else {
  3482.                                                 
  3483.                                                 // COM-806
  3484.                                                 if ($thisClassNameVariants['classNameSmallPlural']=='driver-active-days') {
  3485.                                                     //if ($thisFieldName=='date_id') {
  3486.                                                     //    unset($detailsArray[$thisFieldName]['o']);
  3487.                                                     //}
  3488.                                                     
  3489.                                                     //dump($detailsArray);
  3490.                                                     if ($thisFieldName=='day_title_id') {
  3491.                                                         $detailsArray[$thisFieldName]['o'] = $dayTitlesArray$detailsArray[$thisFieldName]['o'] ];
  3492.                                                         $detailsArray[$thisFieldName]['n'] = $dayTitlesArray$detailsArray[$thisFieldName]['n'] ];
  3493.                                                     }
  3494.                                                     
  3495.                                                 }
  3496.                                                 $detailsArray[$thisFieldName]['label'] = $this->translator->trans("field.$thisFieldNameForLabel", array(), $thisClassNameVariants['classNameSmallPlural']);
  3497.                                                 //dump("field.$thisFieldNameForLabel", $thisClassNameVariants['classNameSmallPlural']);
  3498.                                             }
  3499.                                             $enumFieldType $this->logger->getEnumTypeFromModuleAndField($thisClassNameVariants['classNameSmallPlural'], $thisFieldName$getLabelFcn);
  3500.                                             //dump("enumFieldType: $enumFieldType, getLabelFcn:", $getLabelFcn);
  3501.                                             if ($enumFieldType!=null || $thisFieldType=='enum') {
  3502.                                                 //(isset($detailsArray[$thisFieldName]['tp']) && $detailsArray[$thisFieldName]['tp']=='enum')) {
  3503.                                                 if ($getLabelFcn!=null) {
  3504.                                                     $detailsArray[$thisFieldName]['o'] = $enumFieldType::$getLabelFcn($detailsArray[$thisFieldName]['o'], $this->translator'');
  3505.                                                     $detailsArray[$thisFieldName]['n'] = $enumFieldType::$getLabelFcn($detailsArray[$thisFieldName]['n'], $this->translator'');
  3506.                                                 }
  3507.                                             } else if ($thisFieldType=='boolean') { //isset($detailsArray[$thisFieldName]['tp']) && $detailsArray[$thisFieldName]['tp']=='boolean') {
  3508.                                                 $oldLabel "word.yes";
  3509.                                                 if ($detailsArray[$thisFieldName]['o']=='0' || $detailsArray[$thisFieldName]['o']==false) {
  3510.                                                     $oldLabel "word.no";
  3511.                                                 }
  3512.                                                 $newLabel "word.yes";
  3513.                                                 if ($detailsArray[$thisFieldName]['n']=='0' || $detailsArray[$thisFieldName]['n']==false) {
  3514.                                                     $newLabel "word.no";
  3515.                                                 }
  3516.                                                 $detailsArray[$thisFieldName]['o'] = $this->translator->trans($oldLabel, array(), 'general');
  3517.                                                 $detailsArray[$thisFieldName]['n'] = $this->translator->trans($newLabel, array(), 'general');
  3518.                                             } else if ($thisClassPath==DriverWeeklyRestTimeException::class && $thisFieldName=='weekBoundaryDay') {
  3519.                                                 $detailsArray[$thisFieldName]['skip'] = true// not needed
  3520.                                             } else if ($thisClassPath==DriverWeeklyRestTimeException::class && $thisFieldName=='assignedWeek') {
  3521.                                                 $weekEndSunday $detailsArray['weekBoundaryDay']['n'];
  3522.                                                 //dump("weekEndSunday", $weekEndSunday);
  3523.                                                 $previousWeek $this->timeCalc->alterDateTimeByDays($weekEndSunday, -6true).' - '.
  3524.                                                     $weekEndSunday;
  3525.                                                 $nextWeek $this->timeCalc->alterDateTimeByDays($weekEndSunday1true).' - '.
  3526.                                                     $this->timeCalc->alterDateTimeByDays($weekEndSunday7true);
  3527.                                                 if ($detailsArray[$thisFieldName]['o']==|| $detailsArray[$thisFieldName]['o']=='') {
  3528.                                                     $detailsArray[$thisFieldName]['o'] = $previousWeek;
  3529.                                                 } else {
  3530.                                                     $detailsArray[$thisFieldName]['o'] = $nextWeek;
  3531.                                                 }
  3532.                                                 if ($detailsArray[$thisFieldName]['n']==0) {
  3533.                                                     $detailsArray[$thisFieldName]['n'] = $previousWeek;
  3534.                                                 } else {
  3535.                                                     $detailsArray[$thisFieldName]['n'] = $nextWeek;
  3536.                                                 }
  3537.                                             }
  3538.                                             //dump("detailsArray[$thisFieldName] ($thisClassPath)", $detailsArray[$thisFieldName]);
  3539.                                         }
  3540.                                     }
  3541.                                     //dump("detailsArray ($thisClassPath)", $detailsArray);
  3542.                                             
  3543.                                 }
  3544.                                 //dump('detailsArray 2', $detailsArray);
  3545.                                 
  3546.                                 if (isset($detailsArray['customFieldId'])) unset($detailsArray['customFieldId']);
  3547.                                 $thisEntityData[] = $detailsArray;
  3548.                                 $done true;
  3549.                             } else if ($colInfo['tp']=='details-table2') {
  3550.                                 //$thisClassPath = $this->logger->itemTypeToModuleClassPath( $d->__get('itemType') );
  3551.                                 //$thisClassNameVariants = $this->nc->getClassNameVariantsFromPath($thisClassPath);
  3552.                                 //dump("itemType: ".$d->__get('itemType').", thisClassPath: $thisClassPath, thisClassNameVariants", $thisClassNameVariants); die();
  3553.                                 
  3554.                                 $detailsToShow = [
  3555.                                     'type' => $d->__get('itemType'),
  3556.                                     'changeType' => $d->__get('changeType'),
  3557.                                     'export' => $detailsArray['export'] ?? false,
  3558.                                 ];
  3559.                                 
  3560.                                 if ($d->__get('itemType')==LogItemTypeEnum::BALANCE2) {
  3561.                                     // nothing to add
  3562.                                 } else if ($d->__get('itemType')==LogItemTypeEnum::DRIVER_TOKEN) {
  3563.                                     if (&& $d->__get('changeType')==BalanceTypeEnum::DRIVER_TOKEN_USE) {
  3564.                                         $detailsToShow['label1'] = 'dis';
  3565.                                         $detailsToShow['name1'] = 'dat';
  3566.                                         dump('detailsArray'$detailsArray);
  3567.                                     }
  3568.                                 
  3569.                                 } else if ($d->__get('itemType')==LogItemTypeEnum::DRIVER_FILE ||
  3570.                                            $d->__get('itemType')==LogItemTypeEnum::TACHO_FILE) {
  3571.                                     if (isset($detailsArray['entityId'])) {
  3572.                                     
  3573.                                         $tachoFile $this->getDoctrine()->getRepository(TachographFile::class)->findOneById($detailsArray['entityId']);
  3574.                                         if ($tachoFile!==null) {
  3575.                                             if ($d->__get('itemType')==LogItemTypeEnum::DRIVER_FILE) {
  3576.                                                 $detailsToShow['label1'] = $this->translator->trans('fileType.DRIVER_FILE', array(), 'tachograph-file-types');
  3577.                                             } else {
  3578.                                                 $detailsToShow['label1'] = $this->translator->trans('fileType.TACHOGRAPH_FILE', array(), 'tachograph-file-types');
  3579.                                             }
  3580.                                             $detailsToShow['name1'] = $tachoFile->getName(); //JNOTE: line-break?
  3581.                                         }
  3582.                                         
  3583.                                     }
  3584.                                            
  3585.                                 } else if ($d->__get('itemType')==LogItemTypeEnum::REPORT) {
  3586.                                 
  3587.                                     if (isset($detailsArray['driverId1'])) { //T
  3588.                                     
  3589.                                         if ($detailsArray['driverId1']==='all') {
  3590.                                             $detailsToShow['label1'] = $this->translator->trans('option.allDrivers', array(), 'report-general');
  3591.                                             $detailsToShow['name1'] = '-all-';
  3592.                                         } else {
  3593.                                         
  3594.                                             $driver1 $this->getDoctrine()->getRepository(Driver::class)->findOneById($detailsArray['driverId1']);
  3595.                                             if ($driver1!==null) {
  3596.                                                 $detailsToShow['label1'] = $this->translator->trans('label.driver', array(), 'report-general');
  3597.                                                 $detailsToShow['name1'] = $driver1->getName();
  3598.                                             }
  3599.                                         
  3600.                                             if (isset($detailsArray['driverId2'])) {
  3601.                                     
  3602.                                                 $driver2 $this->getDoctrine()->getRepository(Driver::class)->findOneById($detailsArray['driverId2']);
  3603.                                                 if ($driver2!==null) {
  3604.                                                     $detailsToShow['label2'] = $this->translator->trans('label.driver', array(), 'report-general').' 2';
  3605.                                                     $detailsToShow['name2'] = $driver2->getName();
  3606.                                                 }
  3607.                                         
  3608.                                             }
  3609.                                         }
  3610.                                         $detailsToShow['numDrivers'] = $detailsArray['numEntities'] ?? null;
  3611.                                     } else if (isset($detailsArray['vehicleId1'])) {
  3612.                                         if ($detailsArray['vehicleId1']==='Vall') {
  3613.                                             $detailsToShow['label1'] = $this->translator->trans('option.allVehicles', array(), 'report-general');
  3614.                                             $detailsToShow['name1'] = '-all-';
  3615.                                         } else {
  3616.                                     
  3617.                                             $vehicle1 $this->getDoctrine()->getRepository(Vehicle::class)->findOneById($detailsArray['vehicleId1']);
  3618.                                             if ($vehicle1!==null) {
  3619.                                                 $detailsToShow['label1'] = $this->translator->trans('label.vehicle', array(), 'report-general');
  3620.                                                 $detailsToShow['name1'] = $vehicle1->getName();
  3621.                                             }
  3622.                                         
  3623.                                             if (isset($detailsArray['vehicleId2'])) {
  3624.                                     
  3625.                                                 $vehicle2 $this->getDoctrine()->getRepository(Vehicle::class)->findOneById($detailsArray['vehicleId2']);
  3626.                                                 if ($vehicle2!==null) {
  3627.                                                     $detailsToShow['label2'] = $this->translator->trans('label.vehicle', array(), 'report-general').' 2';
  3628.                                                     $detailsToShow['name2'] = $vehicle2->getName();
  3629.                                                 }
  3630.                                         
  3631.                                             }
  3632.                                             
  3633.                                         }
  3634.                                         $detailsToShow['numVehicles'] = $detailsArray['numEntities'] ?? null;
  3635.                                     }
  3636.                                     
  3637.                                     $detailsToShow['reportClassLabel'] = $this->translator->trans('label.report', array(), 'report-general');
  3638.                                     //$detailsToShow['reportClassName'] = ReportClass::getLabel( $detailsArray['reportClass'], $this->translator );
  3639.                                     
  3640.                                     /*if (isset($detailsArray['balChgTp'])) {
  3641.                                         if ($detailsArray['balChgTp']==BalanceTypeEnum::USAGE_DRIVER_FAULT_LIST_WITH_PENALTY) {
  3642.                                             $detailsToShow['reportClassName'] .= " - with penalties";
  3643.                                         } else if ($detailsArray['balChgTp']==BalanceTypeEnum::USAGE_DRIVER_PROTOCOL_WITH_PENALTY) {
  3644.                                             $detailsToShow['reportClassName'] .= " - with penalties";
  3645.                                         } else if ($detailsArray['balChgTp']==BalanceTypeEnum::USAGE_VEHICLE_TACHOGRAPHFAULTLISTNOCARDDRIVING) {
  3646.                                             $detailsToShow['reportClassName'] .= " - with driving without card";
  3647.                                         } else if ($detailsArray['balChgTp']==BalanceTypeEnum::USAGE_VEHICLE_SPECIALEVENTSNOCARDDRIVING) {
  3648.                                             $detailsToShow['reportClassName'] .= " - with driving without card";
  3649.                                         }
  3650.                                     }*/
  3651.                                     //dump($detailsArray['balChgTp'], $thisEntityData);
  3652.                                     
  3653.                                 }
  3654.                                 
  3655.                                 //dump('detailsToShow for '.$d->__get('changeType'), $detailsArray, $detailsToShow);
  3656.                                 $thisEntityData[] = $detailsToShow;
  3657.                                 $done true;
  3658.                             } else if ($colInfo['tp']=='extra' /*|| $colInfo['tp']=='extra-hidden'*/) { // COM-685
  3659.                                 $thisEntityData[] = $d->__get($colInfo['field-name']);
  3660.                                 $done true;
  3661.                             } else if ($colInfo['tp']=='expand-button') {
  3662.                                 $thisEntityData[] = '';
  3663.                                 $done true;
  3664.                             }
  3665.                         }
  3666.                         if ($customDataUpdaterFunction!=null) {
  3667.                             //dump('pre-UPDATE thisEntityData:', $thisEntityData);
  3668.                             $updated $customDataUpdaterFunction($colName$colInfo$d$updatedValue);
  3669.                             //dump("rc from customDataUpdaterFunction: $updated", $updatedValue);
  3670.                             if ($updated===true) {
  3671.                                 if ($done) {
  3672.                                     // already added above, modify it
  3673.                                     $updateIdx count($thisEntityData) - 1;
  3674.                                     $thisEntityData$updateIdx ] = $updatedValue;
  3675.                                     //dump('UPDATING!, new thisEntityData:', $thisEntityData);
  3676.                                 } else {
  3677.                                     // not added above, add it here
  3678.                                     $thisEntityData[] = $updatedValue;
  3679.                                     $done true;
  3680.                                 }
  3681.                             }
  3682.                         }
  3683.                         if (!$done ) {
  3684.                             $thisEntityData[] = $d->__get($colName);
  3685.                         }
  3686.                     } catch(\Exception $e) {
  3687.                         $thisEntityData[] = '';
  3688.                         dump('exception'$e); die();
  3689.                     }
  3690.                 }
  3691.                 //dump('thisEntityData:', $thisEntityData);
  3692.                 $result['data'][] = $thisEntityData;
  3693.             }
  3694.         }
  3695.         $result['recordsTotal'] = intval($count);
  3696.         $result['recordsFiltered'] = intval($count); //count($result['data']);
  3697.         //dump('result:', $result);
  3698.         return $result;
  3699.     }
  3700.     public function getAllEntityData($entityPath$sortColumn$filterParms=null) {
  3701.     
  3702.         //dump("getAllEntityData($entityPath, $sortColumn, filterParms)", $filterParms);
  3703.         $queryParms = new \stdClass();
  3704.         $queryParms->offset 0;
  3705.         $queryParms->pageSize 9999999999999;
  3706.         $queryParms->sortBy $sortColumn;
  3707.         $queryParms->sortDesc false;
  3708.         $queryParms->searchParms = [];
  3709.         //dump($entityPath.', '.$this->company->__get('localParamsChanged').', '.$this->nc->classNameFromPath($entityPath), self::PARAMETER_CLASSES);
  3710.         if ($this->company!=null && $this->company->__get('localParamsChanged')==false &&
  3711.             in_array($entityPathself::PARAMETER_CLASSES)) {
  3712.             // parameter entity, and local params not yet created, so use the global params
  3713.             $queryParms->searchParms['company'] = null;
  3714.         } else {
  3715.             // default
  3716.             if (property_exists($entityPath'account')) $queryParms->searchParms['account'] = $this->account;
  3717.             if (property_exists($entityPath'company')) $queryParms->searchParms['company'] = $this->company;
  3718.         }
  3719.         // if we're getting DayAssignments, and this is a Hungary-based company, show Compass-defined entities
  3720.         //dump('queryParms', $queryParms);
  3721.         if ($this->getUser()->__get('currentCompanyViewed')!=null &&
  3722.             $entityPath==DayAssignment::class) {
  3723.             if ($this->company->__get('country')!==null && $this->company->__get('country')=='hu') {
  3724.                 $queryParms->searchParms['company'] = null;
  3725.                 //dump('getAllEntityData, reset day assignment');
  3726.             }
  3727.         }
  3728.         if (isset($filterParms)) {
  3729.             foreach($filterParms as $key=>$value) {
  3730.                 if ($key=='account' || $key=='company') continue;
  3731.                 $queryParms->searchParms[$key] = $value;
  3732.             }
  3733.         }
  3734.         //dump($entityPath, $queryParms);
  3735.         $repository $this->getDoctrine()->getRepository($entityPath);
  3736.         // get data
  3737.         $dbEntities $repository->getPaginatedData($queryParms);
  3738.         //dump($dbEntities); //die();
  3739.         return $dbEntities;
  3740.     }
  3741.     protected function buildEditViewRenderArray($sectionTitle$entity=null$initialValues=null) {
  3742.         $repository $this->getDoctrine()->getRepository($this->modulePath);
  3743.         if ($repository->isRawRepository()) {
  3744.             $entity = new RawDbRecord($entity);
  3745.             //dump($d);
  3746.         }
  3747.         $settingsArray = array(
  3748.             'addUrl' => "/{$this->module}/add",
  3749.             'updateUrl' => ($entity!=null) ? "/{$this->module}/".$entity->__get('id')."/save" '',
  3750.             'listUrl' => "/{$this->module}",
  3751.         );
  3752.         $entityRecord = [];
  3753.         foreach($this->editViewSettings['fields'] as $fieldName=>$fieldInfo) {
  3754.             $thisField $fieldInfo;
  3755.             $thisField['id'] = $fieldName;
  3756.             if ($entity!=null) {
  3757.                 if (isset($fieldInfo['tp'])) {
  3758.                     if ($fieldInfo['tp']=='datetime') {
  3759.                         $thisField['value'] = $entity->__getDateTimeFormatted($fieldName) ?? '';
  3760.                         //dump('datetime', $thisField['value']);
  3761.                         $added true;
  3762.                     } else if ($fieldInfo['tp']=='date') {
  3763.                         $thisField['value'] = $entity->__getDateFormatted($fieldName) ?? '';
  3764.                         $added true;
  3765.                     } else if ($fieldInfo['tp']=='time') {
  3766.                         $thisField['value'] = $entity->__getTimeFormatted($fieldName) ?? '';
  3767.                         $added true;
  3768.                     } else if ($fieldInfo['tp']=='non-db') {
  3769.                         // will be populated by the controller
  3770.                         $thisField['value'] = '';
  3771.                         $added true;
  3772.                     } else if ($fieldInfo['tp']=='relationship') {
  3773.                         if ($repository->isRawRepository()) {
  3774.                             $thisEntityData[] = $entity->__get($fieldName);
  3775.                         } else {
  3776.                             $thisField['value'] = ($entity->__get($fieldName)==null) ? '' $entity->__get($fieldName)->getId() ?? '';
  3777.                             $updated true;
  3778.                         }
  3779.                     }
  3780.                 }
  3781.                 if (!isset($thisField['value'])) {
  3782.                     $thisField['value'] = $entity->__get($fieldName);
  3783.                 }
  3784.                 if (isset($initialValues[$fieldName])) {
  3785.                     $thisField['value'] = $initialValues[$fieldName];
  3786.                 }
  3787.             }
  3788.             if (!isset($thisField['value'])) {
  3789.                 $thisField['value'] = '';
  3790.             }
  3791.             $entityRecord[] = $thisField;
  3792.         }
  3793.         // custom fields
  3794.         $customFieldsArray = [];
  3795.         if (in_array($this->module, ['companies''drivers''vehicles''trailers'])) {
  3796.             $customFieldRepository $this->getDoctrine()->getRepository(CustomField::class);
  3797.             $customFieldValueRepository $this->getDoctrine()->getRepository(CustomFieldValue::class);
  3798.             //dump('custom fields module', $this->module);
  3799.             $customFieldCategoryType CustomFieldCategoryEnum::moduleToCategoryType($this->module);
  3800.             //dump('customFieldCategoryType', $customFieldCategoryType);
  3801.             $dbCustomFieldsArray $customFieldRepository->loadByCategory($customFieldCategoryType$this->currentLanguage);
  3802.             //dump('dbCustomFieldsArray', $dbCustomFieldsArray);
  3803.             if ($dbCustomFieldsArray!=null) {
  3804.                 foreach($dbCustomFieldsArray as $r) {
  3805.                     $valueRec $customFieldValueRepository->findOneBy([
  3806.                         'customField' => $r,
  3807.                         'entityId' => $entity->getId(),
  3808.                     ]);
  3809.                     //dump('----', $r, $value);
  3810.                     $value '';
  3811.                     if ($valueRec!=null) {
  3812.                         $value $valueRec->__get('value');
  3813.                     }
  3814.                     $customFieldsArray[] = [
  3815.                         'customFieldId' => $r->getId(),
  3816.                         'type' => $r->__get('type'),
  3817.                         'tp' => ($r->__get('type')==CustomFieldTypeEnum::DATE 'date' 'integer'),
  3818.                         'label' => $r->__get('name'), //.' '.$r->getId(),
  3819.                         'value' => $value,
  3820.                         //'maxlength' => ($r->__get('type')==CustomFieldTypeEnum) ? 30 : '',
  3821.                     ];
  3822.                 }
  3823.             }
  3824.             //dump('customFieldsArray', $customFieldsArray);
  3825.         }
  3826.         // countries
  3827.         $countriesArray $this->formsHelper->getCountries($this->currentCountry);
  3828.         return $this->buildRenderArray($this->module, array(
  3829.             'section_title' => $sectionTitle,
  3830.             'settings_js' => json_encode($settingsArray),
  3831.             'entity_js' => json_encode($entityRecord),
  3832.             'entity' => $entity,
  3833.             'countriesArray' => $countriesArray,
  3834.             'countriesArray_js' => json_encode($countriesArray),
  3835.             'customFieldsArray' => $customFieldsArray,
  3836.             'customFieldsArray_js' => json_encode($customFieldsArray),
  3837.         ), $entity);
  3838.     }
  3839.     protected function saveEditViewForm($request$entity, &$result$customDataUpdaterFunction=null$requestOverrideData=null) {
  3840.         /* // check permissions & handle actions common to every request
  3841.         $rc = $this->handleControllerAction($request, $this->module, 'save', null, true);
  3842.         if ($rc!==true && $this->redirectRoute!=null) { //T
  3843.             $result['info'] = 'no access';
  3844.             $result['url'] = $this->router->generate($this->redirectRoute);
  3845.             return $result;
  3846.         }*/
  3847.         $em $this->getDoctrine()->getManager();
  3848.         // get parms
  3849.         $data $request->request->get('data');
  3850.         //dump('====', $data); //dump($entity); die();
  3851.         // override data
  3852.         if ($requestOverrideData!=null) {
  3853.             foreach($requestOverrideData as $k=>$v) {
  3854.                 if (isset($data[$k])) {
  3855.                     $data[$k] = $v;
  3856.                 }
  3857.             }
  3858.         }
  3859.         //dump($requestOverrideData, $data);
  3860.         $newEntity false;
  3861.         if ($entity===null) {
  3862.             $entity = new $this->modulePath;
  3863.             $newEntity true;
  3864.             if ($this->getUser()->getRolesUnconverted()==UserRoleEnum::ROLE_SUPER_ADMIN && $this->getUser()->__get('currentCompanyViewed')!=null) {
  3865.                 if ($this->modulePath==Company::class || $this->modulePath==User::class) {
  3866.                     // set to account currently selected (the one connected to the company currently selected)
  3867.                     $entity->__set('account'$this->getUser()->__get('currentCompanyViewed')->getAccount());
  3868.                 } else {
  3869.                     // set to company currently selected
  3870.                     $entity->__set('company'$this->getUser()->__get('currentCompanyViewed'));
  3871.                 }
  3872.             } else {
  3873.                 if (property_exists($this->modulePath'account')) $entity->__set('account'$this->account);
  3874.                 if (property_exists($this->modulePath'company')) $entity->__set('company'$this->company);
  3875.             }
  3876.         }
  3877.         $originalEntity = clone $entity;
  3878.         $changesMade = [];
  3879.         $entityUpdated false;
  3880.         foreach($data as $fieldName=>$fieldValue) {
  3881.             if ($fieldName=='id') continue;
  3882.             //dump($this->editViewSettings['fields'][$fieldName] || "$fieldName: no field!");
  3883.             if (!isset($this->editViewSettings['fields'][$fieldName])) continue; // skip
  3884.             //if ($fieldValue == '') continue; //******
  3885.             $fieldInfo $this->editViewSettings['fields'][$fieldName];
  3886.             // JNOTE: mandatory check?
  3887.             $updated false;
  3888.             $logChange true;
  3889.             $forceLogChange false;
  3890.             $oldValue '';
  3891.             $newValue '';
  3892.             if (isset($fieldInfo['tp'])) {
  3893.                 if ($fieldInfo['tp']=='date') {
  3894.                     $saveValue = ($fieldValue=='') ? null $fieldValue;
  3895.                     $entity->__setDate($fieldName$saveValue);
  3896.                     //dump("$fieldName: set date [$saveValue]");
  3897.                     $oldValue $originalEntity->__getDateFormatted($fieldName);
  3898.                     $newValue $saveValue;
  3899.                     $updated true;
  3900.                 } else if ($fieldInfo['tp']=='time') {
  3901.                     $entity->__setTime($fieldName$fieldValue);
  3902.                     //dump("$fieldName: set time", $fieldValue);
  3903.                     $oldValue $originalEntity->__getTimeFormatted($fieldName);
  3904.                     $newValue $fieldValue;
  3905.                     $updated true;
  3906.                 } else if ($fieldInfo['tp']=='datetime') {
  3907.                     $saveValue = ($fieldValue=='') ? null $fieldValue;
  3908.                     //if (!isset($fieldInfo['ignoreTz']) || $fieldInfo['ignoreTz']==false) $entity->setTimeZone();
  3909.                     $entity->__setDateTime($fieldName$saveValuefalsetrue);
  3910.                     //dump("$fieldName: set date [$saveValue]");
  3911.                     $oldValue $originalEntity->__getDateTimeFormatted($fieldName);
  3912.                     $newValue $saveValue;
  3913.                     $updated true;
  3914.                 } else if ($fieldInfo['tp']=='password') {
  3915.                     //dump("Pass: [$fieldValue]");
  3916.                     if ($fieldValue!='') {
  3917.                         $newPassword $this->passwordEncoder->encodePassword($entity$fieldValue);
  3918.                         $entity->__set('password'$newPassword);
  3919.                         //if ($originalEntity->__get($fieldName)!=$entity->__get($fieldName)) {
  3920.                         if ($fieldValue!='') {
  3921.                             $oldValue '';
  3922.                             $newValue '';
  3923.                             $forceLogChange true;
  3924.                         } else{
  3925.                             $logChange false;
  3926.                         }
  3927.                         //dump('pass', $originalEntity->__get('password'), $entity->__get('password'), $fieldValue);
  3928.                     }
  3929.                     $updated true;
  3930.                     /*} else if ($fieldInfo['tp']=='boolean') {
  3931.                         $entity->__set($fieldName, $fieldValue) );*/
  3932.                 } else if ($fieldInfo['tp']=='relationship') {
  3933.                     //dump("REL", $fieldName, $fieldInfo, $fieldValue, $originalEntity->__get($fieldName));
  3934.                     if ($fieldValue !== null && $fieldValue !== '') {
  3935.                     
  3936.                         //dump('1');
  3937.                         $relationshipEntityPath $this->nc->classPathFromName($fieldInfo['entity']);
  3938.                         $relationshipEntities $this->getDoctrine()->getRepository($relationshipEntityPath)->findById($fieldValue);
  3939.                         if (count($relationshipEntities)>0) {
  3940.                             $entity->__set($fieldName$relationshipEntities[0]);
  3941.                         }
  3942.                         //dump("$fieldName: set date");
  3943.                         $updated true;
  3944.                         $oldValue = ($originalEntity->__get($fieldName)!=null) ? $originalEntity->__get($fieldName)->getId() : null;
  3945.                         $newValue $relationshipEntities[0]->getId();
  3946.                     } else {
  3947.                         //dump('2');
  3948.                     
  3949.                         $entity->__set($fieldNamenull);
  3950.                         $oldValue = ($originalEntity->__get($fieldName)!=null) ? $originalEntity->__get($fieldName)->getId() : null;
  3951.                         $newValue null;
  3952.                         $updated true;
  3953.                         //dump($entity->__get($fieldName);
  3954.                     }
  3955.                     if ($oldValue!=$newValue) {
  3956.                         $oldValue = ($originalEntity->__get($fieldName)!=null) ? $originalEntity->__get($fieldName)->getName() : null;
  3957.                         $newValue $relationshipEntities[0]->getName();
  3958.                         $forceLogChange true;
  3959.                     } else{
  3960.                         $logChange false;
  3961.                     }
  3962.                 } else if ($fieldInfo['tp']=='enum') {
  3963.                     if (isset($fieldInfo['multiple']) && $fieldInfo['multiple']===true) {
  3964.                         // multi-select, save separated
  3965.                         $saveValue ";".implode(";"$fieldValue).";";
  3966.                         $entity->__set($fieldName$saveValue);
  3967.                         //dump("$fieldName: set multi-select [$saveValue]");
  3968.                     } else {
  3969.                         $saveValue $fieldValue;
  3970.                         $entity->__set($fieldName$fieldValue);
  3971.                         //dump("$fieldName: set single-select [$fieldValue]");
  3972.                     }
  3973.                     $oldValue $originalEntity->__get($fieldName); //T
  3974.                     $newValue $saveValue;
  3975.                     $updated true;
  3976.                 } else if ($fieldInfo['tp']=='non-db') {
  3977.                     // do nothing here
  3978.                     $updated true;
  3979.                     $logChange false;
  3980.                 }
  3981.             }
  3982.             if (!$updated) {
  3983.                 $entity->__set($fieldName$fieldValue);
  3984.                 //dump("$fieldName: set value to [$fieldValue]");
  3985.                 $oldValue $originalEntity->__get($fieldName);
  3986.                 $newValue $fieldValue;
  3987.             }
  3988.             $entityUpdated true;
  3989.             if ($logChange) {
  3990.                 /*if (isset($fieldInfo['tp']) && $fieldInfo['tp']=='relationship') {
  3991.                     // save related entity id only
  3992.                     $originalValue = ($originalEntity->__get($fieldName)!=null) ? $originalEntity->__get($fieldName)->getId() : null;
  3993.                     $newValue = ($entity->__get($fieldName)!=null) ? $entity->__get($fieldName)->getId() : null;
  3994.                     if ($originalValue!=$newValue) {
  3995.                         $changesMade[$fieldName] = [
  3996.                             'o' => $originalValue,
  3997.                             'n' => $newValue,
  3998.                             'class' => $relationshipEntityPath ?? '',
  3999.                         ];
  4000.                     }
  4001.                 } else if (isset($fieldInfo['tp']) && $fieldInfo['tp']=='password') {
  4002.                     // note that it was changed, but don't save the values
  4003.                     if ($originalEntity->__get($fieldName)!=$entity->__get($fieldName)) {
  4004.                         $changesMade[$fieldName] = [
  4005.                             'o' => '',
  4006.                             'n' => '',
  4007.                         ];
  4008.                     }
  4009.                 } else if (isset($fieldInfo['tp']) && $fieldInfo['tp']=='password') {
  4010.                 } else {*/
  4011.                 // default
  4012.                 //if ($originalEntity->__get($fieldName)!=$entity->__get($fieldName)) {
  4013.                 if ($forceLogChange || $oldValue!=$newValue) {
  4014.                     $changesMade[$fieldName] = [
  4015.                         'o' => $oldValue//$originalEntity->__get($fieldName),
  4016.                         'n' => $newValue//$entity->__get($fieldName),
  4017.                         'tp' => $fieldInfo['tp'] ?? '',
  4018.                     ];
  4019.                 }
  4020.                 //}
  4021.             }
  4022.         }
  4023.         //dump($entity);
  4024.         //dump('changesMade', $changesMade);
  4025.         if ($customDataUpdaterFunction!=null) {
  4026.             //dump('custom');
  4027.             $customUpdateRet $customDataUpdaterFunction($entity$data);
  4028.              //dump('customUpdateRet', $customUpdateRet);
  4029.             if (is_array($customUpdateRet)) {
  4030.                 if ($customUpdateRet['error']===true) {
  4031.                     $result $customUpdateRet;
  4032.                     return false;
  4033.                 }
  4034.             } else {
  4035.                 if ($customUpdateRet===true$entityUpdated true;
  4036.             }
  4037.         }
  4038.         //dump("5");
  4039.         if ($entityUpdated) {
  4040.             //dump('updated entity', $entity);
  4041.             $rc $entity->__setDateTime('updatedAt''now'); // add it, so it is shown always (penalty groups were changed, most likely) -- COM-828
  4042.             $rc $entity->save$em );
  4043.             //dump('update rc='.$rc);
  4044.             if (!$rc) {
  4045.                 $result['info'] = 'save error';
  4046.                 $result['msg'] = $this->translator->trans('message.genericError', array(), 'general');
  4047.                 return false;
  4048.             }
  4049.         } else {
  4050.         
  4051.             $rc $entity->__setDateTime('updatedAt''now'); // ditto above -- COM-828
  4052.             
  4053.             $rc $entity->save$em );
  4054.             //dump('update rc='.$rc);
  4055.             if (!$rc) {
  4056.                 $result['info'] = 'save error';
  4057.                 $result['msg'] = $this->translator->trans('message.genericError', array(), 'general');
  4058.                 return false;
  4059.             }        
  4060.         
  4061.         }
  4062.         //dump("6");
  4063.         // save new entity record, so it can be retrieved later by callers
  4064.         if ($newEntity) {
  4065.             $this->newEntity $entity;
  4066.         }
  4067.         // add/update custom fields
  4068.         if (in_array($this->module, ['companies''drivers''vehicles''trailers'])) {
  4069.             $customFieldRepository $this->getDoctrine()->getRepository(CustomField::class);
  4070.             $customFieldValueRepository $this->getDoctrine()->getRepository(CustomFieldValue::class);
  4071.             //dump('custom fields module', $this->module);
  4072.             $customFieldCategoryType CustomFieldCategoryEnum::moduleToCategoryType($this->module);
  4073.             //dump('customFieldCategoryType', $customFieldCategoryType);
  4074.             $dbCustomFieldsArray $customFieldRepository->loadByCategory($customFieldCategoryType$this->currentLanguage);
  4075.             //dump('dbCustomFieldsArray', $dbCustomFieldsArray);
  4076.             if ($dbCustomFieldsArray!=null) {
  4077.                 foreach($dbCustomFieldsArray as $r) {
  4078.                     $postFieldName "customFld_".$r->getId();
  4079.                     // if not in $data, then it wasn't updated
  4080.                     if (!isset($data[$postFieldName])) continue;
  4081.                     // check if
  4082.                     $customFieldValueRec null;
  4083.                     if ($newEntity)    {
  4084.                         // not found in new entities
  4085.                     } else {
  4086.                         // look up
  4087.                         $customFieldValueRec $customFieldValueRepository->findOneBy([
  4088.                             'customField' => $r,
  4089.                             'entityId' => $entity->getId(),
  4090.                         ]);
  4091.                     }
  4092.                     //dump('postFieldName', $postFieldName, $customFieldValueRec);
  4093.                     if ($customFieldValueRec==null) {
  4094.                         // add new value rec
  4095.                         $customFieldValueRec = new CustomFieldValue;
  4096.                         $customFieldValueRec->__set('customField'$r);
  4097.                         $customFieldValueRec->__set('entityId'$entity->getId());
  4098.                         $customFieldValueRec->__set('value'$data[$postFieldName]);
  4099.                         if ($data[$postFieldName]!='' && $data[$postFieldName]!=null) {
  4100.                             $changesMade['c.'.$r->getId()] = [
  4101.                                 'o' => null,
  4102.                                 'n' => $data[$postFieldName],
  4103.                             ];
  4104.                         }
  4105.                     } else {
  4106.                         // update existing value rec
  4107.                         if ($data[$postFieldName]!=$customFieldValueRec->__get('value')) {
  4108.                             $changesMade['c.'.$r->getId()] = [
  4109.                                 'o' => $customFieldValueRec->__get('value'),
  4110.                                 'n' => $data[$postFieldName],
  4111.                             ];
  4112.                         }
  4113.                         $customFieldValueRec->__set('value'$data[$postFieldName]);
  4114.                     }
  4115.                     //dump('customFieldValueRec 2', $customFieldValueRec);
  4116.                     $rc $customFieldValueRec->save$this->getDoctrine()->getManager() );
  4117.                     if (!$rc) {
  4118.                         die('error updating custom field value');
  4119.                     }
  4120.                 }
  4121.             }
  4122.         }
  4123.         //die('66');
  4124.         // log the change
  4125.         $changeType = ($newEntity LogChangeTypeEnum::ITEM_ADDED LogChangeTypeEnum::ITEM_UPDATED); //TT
  4126.         $this->logger->saveAction($changeType$this->modulePath$entity->getId(), $changesMade);
  4127.         // add flash message (unless disabled) - will show on next page open
  4128.         if (!$this->disableFlashMessages) {
  4129.             $this->addFlash('success'$this->translator->trans(($newEntity 'message.recordAdded' 'message.recordUpdated'), array(), 'general'));
  4130.         }
  4131.         $result['success'] = true;
  4132.         $result['newEntityId'] = $entity->getId();
  4133.         //$result['newEntity'] = $entity; // COM-815
  4134.         return true;
  4135.     }
  4136.     
  4137.     /****
  4138.     protected function finalizeOrder($update,&$result) {
  4139.         $em = $this->getDoctrine()->getManager();
  4140.         $order = $this->getDoctrine()->getRepository(LicenseOrder::class)->find($update->get(0));
  4141.         $discount = !is_numeric($update->get(1)) ? 0 : $update->get(1);
  4142.         $order->setDiscount($discount);
  4143.         $changesMade['ordernumber'] = $order->getOrderNumber();
  4144.         $changesMade['status'] = [
  4145.             'o' => $order->getStatus(),
  4146.             'n' => '2',
  4147.         ];
  4148.         $order->setStatus(2);
  4149.         $this->logger->saveAction(LogChangeTypeEnum::ORDER_FINALIZED, 7, $update->get(0),$changesMade); //T
  4150.         try {
  4151.             $orderDetails = json_decode($order->details,true);
  4152.             $buyer = [
  4153.                 'name' => $this->company->name,
  4154.                 'tax' => $this->company->taxNumber,
  4155.                 'zip' => $this->company->postalCode,
  4156.                 'city' => $this->company->city,
  4157.                 'address' => $this->company->address
  4158.             ];
  4159.             $email = $this->company->email;
  4160.             $invoiceItems = [];
  4161.             foreach ($orderDetails as $key=>$orderItem) {
  4162.                 $this->szamlazz_item_generator($orderDetails['licenseType'],$key,$orderItem,$invoiceItems[]);
  4163.             }
  4164.             if ($discount > 0) {
  4165.                 $invoiceItems[] = ['name' => 'Kedvezmény','qty' => 1,  'price' => $discount*-1
  4166.                 ];
  4167.             }
  4168.             $price = 0;
  4169.             foreach ($invoiceItems as $items) {
  4170.                 $price = $price+$items['price'];
  4171.             }
  4172.             if ($orderDetails['paymentOption'] == 'wire_transfer') {
  4173.                 /// create proforma
  4174.                 $this->szamlazz_hu_generate_invoice(2,$buyer,$email=false,$invoiceItems,$result);
  4175.                 $message = "
  4176.             Tisztelt Cég!<br/>
  4177.             Rendeléséről díjbekérőt állítottunk ki, melyet az alábbi címről tud letölteni!<br/>
  4178.             <a target='_blank' href='{$result['invData']}'>Díjbekérő Letöltés</a><br/>
  4179.             Kérjük az átutalásában hivatkozzon a díjbekérő sorszámára: {$result['documentNumber']}<br />
  4180.             Az összeg beérkezését követően fogjuk aktiválni a licenszét!<br/>
  4181.             ";
  4182.             }
  4183.             if ($orderDetails['paymentOption'] == 'bank_card') {
  4184.             $id = $order->getId();
  4185.                 $message = "
  4186.             Tisztelt Cég!<br/>
  4187.             Rendelését bankkártyás fizetéssel kívánja rendezni, ezért kérjük, hogy a fizetéshez kattintson a következő linkre. <br/>
  4188.             <a href='/balance/payment/init/{$id}'>Bankkártyás fizetés az OTP Simple rendszerében!</a><br/>
  4189.             <br />
  4190.             Az sikeres fizetést követően fogjuk aktiválni a licenszét!<br/>
  4191.             ";
  4192.                 $order->setStatus(99);
  4193.             }
  4194.             $fakeRequest = Request::createFromGlobals();
  4195.             $fakeRequest->request->set(0,$this->company);
  4196.             $fakeRequest->request->set(1,$message);
  4197.             $fakeRequest->request->set(2,'Megrendelés feldolgozva');
  4198.             // send message about license change.
  4199.             $this->sendMessageToCompany(null,$fakeRequest->request,null,$result);
  4200.             if ($orderDetails['paymentOption'] == 'wire_transfer') {
  4201.                 $orderDetails['proforma_no'] = $result['documentNumber'];
  4202.                 $order->setDetails(json_encode($orderDetails));
  4203.             }
  4204.             $em->persist($order);
  4205.             $em->flush();
  4206.         } catch(\Doctrine\DBAL\DBALException $e) {
  4207.             dump($e);
  4208.             $result['info'] = 'Order insert error';
  4209.             $result['msg'] = $this->translator->trans('message.genericError', array(), 'general');
  4210.             return false;
  4211.         }
  4212.         // add flash message - will show on next page open
  4213.         $this->addFlash('success', $this->translator->trans('message.recordUpdated', array(), 'general'));
  4214.         $result['success'] = true;
  4215.     }
  4216.     protected function changeLicenseByCompass($data,$company,&$result) {
  4217.         $em = $this->getDoctrine()->getManager();
  4218.         $newLicense = new Licenses();
  4219.         $newLicense->setCompany($company);
  4220.         $newLicense->setStatus(99);
  4221.         $newLicense->setBaseLicenseStartDate(new \DateTime("now"));
  4222.         $newLicense->setLicenceType($data->get(2));
  4223.         $qty = $data->get(1);
  4224.         $qty =  is_numeric($qty)? $qty : 0;
  4225.         $newLicense->setQty($qty);
  4226.         $this->updateAllLicensesNewStatus($company,3,$result);
  4227.         if (!$newLicense->save($em,true)){
  4228.             $result['success'] = false;
  4229.         }else{
  4230.             $result['success'] = true;
  4231.         }
  4232.         $fakeRequest = Request::createFromGlobals();
  4233.         $fakeRequest->request->set(0,$company);
  4234.         $fakeRequest->request->set(1,$data->get(0));
  4235.         $fakeRequest->request->set(2,'Sikeres licenszváltás');
  4236.         // send message about license change.
  4237.         $this->sendMessageToCompany(null,$fakeRequest->request,null,$result);
  4238.     }
  4239.     protected function updateAllLicensesNewStatus($company,$newstatus,&$result) {
  4240.         $em = $this->getDoctrine()->getManager();
  4241.         $allLicenses = $this->getDoctrine()->getRepository(Licenses::class)->findBy(['company' => $company]);
  4242.         foreach ($allLicenses as $license) {
  4243.             $license->setStatus($newstatus);
  4244.             $license->save($em,true);
  4245.         }
  4246.     }
  4247.     protected function activateLicenseOrder($id,$company_id,&$result) {
  4248.         $em = $this->getDoctrine()->getManager();
  4249.         $order = $this->getDoctrine()->getRepository(LicenseOrder::class)->find($id->get(0));
  4250.         $changesMade['status'] = [
  4251.             'o' => $order->getStatus(),
  4252.             'n' => '4',
  4253.         ];
  4254.         $changesMade['ordernumber'] = $order->getOrderNumber();
  4255.         //// CREATE OR EXTEND LICENSE
  4256.         ///
  4257.         if ($order->getStatus() != 4) {
  4258.         $this->createOrExtendLicense($order->getOrderNumber(),$company_id,$result);
  4259.         }
  4260.         if ($result['success'] = true) {
  4261.             $this->logger->saveAction(LogChangeTypeEnum::ORDER_ACTIVATE, 7, $id->get(0), $changesMade);
  4262.             $order->setStatus(4);
  4263.             try {
  4264.                 //create Invoice
  4265.                 $buyer = [
  4266.                     'name' => $this->company->name,
  4267.                     'tax' => $this->company->taxNumber,
  4268.                     'zip' => $this->company->postalCode,
  4269.                     'city' => $this->company->city,
  4270.                     'address' => $this->company->address
  4271.                 ];
  4272.                 $email = $this->company->email;
  4273.                 $orderDetails = json_decode($order->details,true);
  4274.                 if (isset($orderDetails['proforma_no'])) {
  4275.                     $buyer['proforma'] = $orderDetails['proforma_no'];
  4276.                 }
  4277.                 $invoiceItems = [];
  4278.                 foreach ($orderDetails as $key=>$orderItem) {
  4279.                     $this->szamlazz_item_generator($orderDetails['licenseType'],$key,$orderItem,$invoiceItems[]);
  4280.                 }
  4281.                 $discount = $order->discount;
  4282.                 if ($discount > 0 && is_numeric($discount)) {
  4283.                     $invoiceItems[] = ['name' => 'Kedvezmény','qty' => 1,  'price' => $discount*-1
  4284.                     ];
  4285.                 }
  4286.                 if (isset($orderDetails['proforma_no'])) {
  4287.                     $this->szamlazz_hu_generate_invoice(1,$buyer,$email,$invoiceItems,$result);
  4288.                     $message = "
  4289.             Tisztelt Cég!<br/>
  4290.             Aktiváltuk a licensz konstrukcióját! Rendeléséről számlát állítottunk ki, melyet az alábbi címről tud letölteni!<br/>
  4291.             <a target='_blank' href='{$result['invData']}'>Számla Letöltés</a><br/>
  4292.             Az Egyenleg oldalra érve már láthatja az aktivált licensz részleteit és használhatja az oldalt teljes funkcionalitásában!<br/>";
  4293.                 }
  4294.                 if (!isset($orderDetails['proforma_no']) && $orderDetails['paymentOption'] == 'bank_card') {
  4295.                     $this->szamlazz_hu_generate_invoice(1,$buyer,$email,$invoiceItems,$result);
  4296.                 }
  4297.                 if (!isset($orderDetails['proforma_no'])) {
  4298.                     $message = "
  4299.             Tisztelt Cég!<br/>
  4300.             Aktiváltuk a licensz konstrukcióját! <br/>
  4301.             Az Egyenleg oldalra érve már láthatja az aktivált licensz részleteit és használhatja az oldalt teljes funkcionalitásában!<br/>";
  4302.                 }
  4303.                 $fakeRequest = Request::createFromGlobals();
  4304.                 $fakeRequest->request->set(0,$this->company);
  4305.                 $fakeRequest->request->set(1,$message);
  4306.                 $fakeRequest->request->set(2,'Licensz aktiválás');
  4307.                 // send message about license change.
  4308.                 $this->sendMessageToCompany(null,$fakeRequest->request,null,$result);
  4309.                 $em->persist($order);
  4310.                 $em->flush();
  4311.             } catch(\Doctrine\DBAL\DBALException $e) {
  4312.                 dump($e);
  4313.                 $result['info'] = 'Order insert error';
  4314.                 $result['msg'] = $this->translator->trans('message.genericError', array(), 'general');
  4315.                 return false;
  4316.             }
  4317.             // add flash message - will show on next page open
  4318.             $this->addFlash('success', $this->translator->trans('message.recordUpdated', array(), 'general'));
  4319.             $result['success'] = true;
  4320.         }
  4321.     }
  4322.     protected function createOrExtendLicense($ordernumber,$company_id,&$result) {
  4323.         /// check if order is valid
  4324.         $checkLicense = $this->checkActiveLicense($company_id);
  4325.         if (is_array($checkLicense) && (@$checkLicense['active_order'] == 1 || @$checkLicense['license_change'] == 1)) {
  4326.             //// there is active order but no active license
  4327.             $this->processLicenseFromOrderNewLicense($company_id,$ordernumber,$result);
  4328.         }elseif(@$checkLicense[0]->id){
  4329.             $this->processLicenseFromOrderExtendedLicense($company_id,$ordernumber,$result);
  4330.             /// there is at least one active license
  4331.             /// check if it is expired?
  4332.             /// check if it an extension
  4333.         }else{
  4334.             //dump('here3');
  4335.             /// no active order no license
  4336.         }
  4337.         $result['success'] = true;
  4338.     }
  4339.     protected function processLicenseFromOrderExtendedLicense ($company_id,$ordernumber,&$result) {
  4340.         $em = $this->getDoctrine()->getManager();
  4341.         $order = $this->getDoctrine()->getRepository(LicenseOrder::class)->findOneBy(['ordernumber' => $ordernumber,'company'=> $company_id]);
  4342.         if (@$order) {
  4343.             $orderDetails = json_decode($order->__get('details'),true);
  4344.             $em = $this->getDoctrine()->getManager();
  4345.             $newLicense = new Licenses();
  4346.             $newLicense->setCompany($company_id);
  4347.             $newLicense->setStatus(2);
  4348.             $newLicense->setLicenceType($orderDetails['licenseType']);
  4349.             $legislation_start_date = new \DateTime("now");
  4350.             $newLicense->setBaseLicenseStartDate($legislation_start_date);
  4351.             $newLicense->setTypeLicenseStartDate($legislation_start_date);
  4352.             if (@$orderDetails['legislation'] || @$orderDetails['base_license'])
  4353.             {
  4354.                 if (@$orderDetails['legislation']) $orderDetails['legislation'] = intval($orderDetails['legislation']);
  4355.                 if (@$orderDetails['base_license']) $orderDetails['base_license'] = intval($orderDetails['base_license']);
  4356.             if (@$orderDetails['legislation'] && is_integer($orderDetails['legislation']))
  4357.                 {
  4358.                /// check if last legislation end date is still valid
  4359.                     /// get all licenses end dates
  4360.                     $lastLegistlationDate = $this->getLicenseLegislationEndDate($company_id);
  4361.                 if (!is_a($lastLegistlationDate,'DateTime')) {
  4362.                     /// if for some reason not datetime object extend with the given extension period from today
  4363.                     $legislation_end_date = new \DateTime("+" . $orderDetails['legislation'] . " year");
  4364.                 }else{
  4365.                     $today = new \DateTime('today');
  4366.                     /// if not valid extend from last day
  4367.                     if ($lastLegistlationDate < $today) {
  4368.                         $lastLegistlationDate->add(new \DateInterval('P'.$orderDetails['legislation']."Y" ));
  4369.                     }else{
  4370.                         $lastLegistlationDate->add(new \DateInterval('P'.$orderDetails['legislation']."Y" ));
  4371.                     }
  4372.                 }
  4373.                 $legislation_end_date = $lastLegistlationDate;
  4374.                     /// if valid extend with years ordered
  4375.                 $newLicense->setBaseLicenseEndDate($legislation_end_date);
  4376.                 $newLicense->setLegislationLicenseEndDate($legislation_end_date);
  4377.                 $newLicense->setTypeLicenseEndDate($legislation_end_date);
  4378.                 }
  4379.                 if (@$orderDetails['base_license'] && is_integer($orderDetails['base_license']))
  4380.                 {
  4381.                     /// check if last legislation end date is still valid
  4382.                     /// get all licenses end dates
  4383.                     $lastLegistlationDate = $this->getLicenseLegislationEndDate($company_id);
  4384.                     if (!is_a($lastLegistlationDate,'DateTime')) {
  4385.                         /// if for some reason not datetime object extend with the given extension period from today
  4386.                         $legislation_end_date = new \DateTime("+" . $orderDetails['base_license'] . " year");
  4387.                     }else{
  4388.                         $today = new \DateTime('today');
  4389.                         /// if not valid extend from last day
  4390.                         if ($lastLegistlationDate < $today) {
  4391.                             $lastLegistlationDate->add(new \DateInterval('P'.$orderDetails['base_license']."Y" ));
  4392.                         }else{
  4393.                             $lastLegistlationDate->add(new \DateInterval('P'.$orderDetails['base_license']."Y" ));
  4394.                         }
  4395.                     }
  4396.                     $legislation_end_date = $lastLegistlationDate;
  4397.                     /// if valid extend with years ordered
  4398.                     $newLicense->setBaseLicenseEndDate($legislation_end_date);
  4399.                     $newLicense->setLegislationLicenseEndDate($legislation_end_date);
  4400.                     $newLicense->setTypeLicenseEndDate($legislation_end_date);
  4401.                 }
  4402.             }
  4403.             $details = [];
  4404.             if ($orderDetails['licenseType'] == 1) {
  4405.                 /// vehicle license
  4406.                 /// check extendedLicenses
  4407.                 $details['extendedLicenses'] =  is_numeric($orderDetails['extendedLicenses'])? $orderDetails['extendedLicenses'] : 0;
  4408.                 /// check combo1
  4409.                 $details['combo1'] =  is_numeric($orderDetails['combo1'])? $orderDetails['combo1'] : 0;
  4410.                 /// check combo10
  4411.                 $details['combo10'] =  is_numeric($orderDetails['combo10'])? $orderDetails['combo10'] : 0;
  4412.             }
  4413.             if ($orderDetails['licenseType'] == 2) {
  4414.                 /// if aetr
  4415.                 if (@$orderDetails['aetr']) {
  4416.                     $details['aetr']['open'] =  is_numeric($orderDetails['aetr'])? $orderDetails['aetr'] : 0;
  4417.                     $details['aetr']['used'] =  0;
  4418.                 }
  4419.                 /// if labour
  4420.                 if (@$orderDetails['labour']) {
  4421.                     $details['labour']['open'] =  is_numeric($orderDetails['labour'])? $orderDetails['labour'] : 0;
  4422.                     $details['labour']['used'] =  0;
  4423.                 }
  4424.             }
  4425.             if ($orderDetails['licenseType'] == 3) {
  4426.                 $details['credit'] =  is_numeric($orderDetails['credit'])? $orderDetails['credit'] : 0;
  4427.                 $legislation_end_date = new \DateTime("+ 99 year");
  4428.             }
  4429.                 if (@$orderDetails['modules'] && is_array($orderDetails['modules'])){
  4430.                 $orderedModules = [];
  4431.                 $currentYear = date('Y');
  4432.                 foreach ($orderDetails['modules'] as $module) {
  4433.                     $orderedModules[$currentYear][] = $module;
  4434.                 }
  4435.                 $details['modules'] = $orderedModules;
  4436.             }
  4437.             $newLicense->setQty(0);
  4438.             $newLicense->setDetails(json_encode($details));
  4439.             if (!$newLicense->save($em,true)){
  4440.                 $result['success'] = false;
  4441.             }else{
  4442.                 $result['success'] = true;
  4443.             }
  4444.         }
  4445.     }
  4446.     protected function processLicenseFromOrderNewLicense ($company_id,$ordernumber,&$result) {
  4447.         $em = $this->getDoctrine()->getManager();
  4448.         $order = $this->getDoctrine()->getRepository(LicenseOrder::class)->findOneBy(['ordernumber' => $ordernumber,'company'=> $company_id]);
  4449.         if (@$order) {
  4450.             $orderDetails = json_decode($order->__get('details'),true);
  4451.             $em = $this->getDoctrine()->getManager();
  4452.             $newLicense = new Licenses();
  4453.             $newLicense->setCompany($company_id);
  4454.             $newLicense->setStatus(1);
  4455.             $newLicense->setLicenceType($orderDetails['licenseType']);
  4456.             $legislation_start_date = new \DateTime("now");
  4457.             if (isset($orderDetails['base_license']) && $orderDetails['base_license'] != 0) {
  4458.                 $legislation_end_date = new \DateTime("+".$orderDetails['base_license']." year");
  4459.             }elseif(@$orderDetails['legislation'] && $orderDetails['legislation'] != 0) {
  4460.                 $legislation_end_date = new \DateTime("+".$orderDetails['legislation']." year");
  4461.             }
  4462.             $details = [];
  4463.             if ($orderDetails['licenseType'] == 1) {
  4464.                 /// vehicle license
  4465.                 /// check extendedLicenses
  4466.                 $details['extendedLicenses'] =  is_numeric($orderDetails['extendedLicenses'])? $orderDetails['extendedLicenses'] : 0;
  4467.                 /// check combo1
  4468.                 $details['combo1'] =  is_numeric($orderDetails['combo1'])? $orderDetails['combo1'] : 0;
  4469.                 /// check combo10
  4470.                 $details['combo10'] =  is_numeric($orderDetails['combo10'])? $orderDetails['combo10'] : 0;
  4471.             }
  4472.             if ($orderDetails['licenseType'] == 2) {
  4473.                 $details['aetr']['open'] =  is_numeric($orderDetails['aetr'])? $orderDetails['aetr'] : 0;
  4474.                 $details['aetr']['used'] =  0;
  4475.                 $details['labour']['open'] =  is_numeric($orderDetails['labour'])? $orderDetails['labour'] : 0;
  4476.                 $details['labour']['used'] =  0;
  4477.             }
  4478.             if ($orderDetails['licenseType'] == 3) {
  4479.                 $details['credit'] =  is_numeric($orderDetails['credit'])? $orderDetails['credit'] : 0;
  4480.                 $legislation_end_date = new \DateTime("+ 99 year");
  4481.             }
  4482.                 if (@$orderDetails['modules'] && is_array($orderDetails['modules'])){
  4483.                 $orderedModules = [];
  4484.                 $currentYear = date('Y');
  4485.                 foreach ($orderDetails['modules'] as $module) {
  4486.                     $orderedModules[$currentYear][] = $module;
  4487.                 }
  4488.                 $details['modules'] = $orderedModules;
  4489.             }
  4490.             $newLicense->setBaseLicenseStartDate($legislation_start_date);
  4491.             $newLicense->setBaseLicenseEndDate($legislation_end_date);
  4492.             $newLicense->setLegislationLicenseEndDate($legislation_end_date);
  4493.             $newLicense->setTypeLicenseStartDate($legislation_start_date);
  4494.             $newLicense->setTypeLicenseEndDate($legislation_end_date);
  4495.             $newLicense->setQty(0);
  4496.             $newLicense->setDetails(json_encode($details));
  4497.             if (!$newLicense->save($em,true)){
  4498.                 $result['success'] = false;
  4499.             }else{
  4500.                 if ($orderDetails['licenseType'] == 2) {
  4501.                 // if driver license create entry in driverlicense for aetr and labour
  4502.                     $driverLicense = new DriverLicense();
  4503.                     $driverLicense->setStatus(1);
  4504.                     $driverLicense->setCompany($company_id);
  4505.                     $driverLicense->setBaseLicense($newLicense);
  4506.                     $driverLicense->setDetails('NEW');
  4507.                     if (!$driverLicense->save($em, true)) {
  4508.                         $result['success'] = false;
  4509.                     }else{
  4510.                         $result['success'] = true;
  4511.                     }
  4512.                 }
  4513.                 /// remove old license from license transfer
  4514.                 $removableLicense = $this->getDoctrine()->getRepository(Licenses::class)->findOneBy(['company' => $company_id, 'status' => 99]);
  4515.                 if (@$removableLicense) {
  4516.                     $em = $this->getDoctrine()->getManager();
  4517.                     $em->remove($removableLicense);
  4518.                     $em->flush();
  4519.                 }
  4520.                     $result['success'] = true;
  4521.             }
  4522.         }
  4523.     }
  4524.     protected function getLogsBalancePageForAdmin($company,&$result){
  4525.         $events = $this->getDoctrine()->getRepository(LogEntry::class)->findBy(['company' => $company, 'itemType' => 7]);
  4526.         $logEvents = [];
  4527.         foreach ($events as $event) {
  4528.             if ($event->detailsExist === true) {
  4529.                 $RAW_QUERY = "SELECT changes_made FROM util_log_entry_details where id = '{$event->id};'";
  4530.                 $statement = $this->getDoctrine()->getConnection()->prepare($RAW_QUERY);
  4531.                 $statement->execute();
  4532.                 $return = $statement->fetchAll();
  4533.                 if ($return) {
  4534.                     $details = json_decode($return[0]['changes_made'], true);
  4535.                     for ($i = 0; $i < sizeof($details); $i++) {
  4536.                         $detail = '';
  4537.                         foreach ($details as $k => $v) {
  4538.                             if (isset($v['o']) && isset($v['n'])) {
  4539.                                 $detail .= "{$k} -> Régi érték: " . $v['o'] . " / Új érték:" . $v['n'] . " | ";
  4540.                             }
  4541.                             if (!isset($v['o']) && !isset($v['n'])) {
  4542.                                 $detail .= "{$k} -> {$v} | ";
  4543.                             }
  4544.                         }
  4545.                     }
  4546.                 }
  4547.             }
  4548.             $change_message = BalanceTypeEnum::getAllLabelsWithValue('LOGEVENTS', $this->translator, 'balance');
  4549.             $result[] = [
  4550.                 'createdat' => $event->createdAt,
  4551.                 'createdby' => $event->createdBy->username,
  4552.                 'change' => $change_message[$event->changeType],
  4553.                 'details' => $detail,
  4554.             ];
  4555.         }
  4556.     }
  4557.     protected function getOrdersForCompany($company,$modules,&$result) {
  4558.         foreach ($company->getLicenseorders() as $orders) {
  4559.             $ordereditems = json_decode($orders->details);
  4560.             if ($ordereditems->licenseType == 1) {
  4561.                 $legislationDetails = $this->getDoctrine()->getRepository(LicensePricing::class)->findBy(['type' => 1, 'subtype' => 4, 'name' => $ordereditems->legislation]);
  4562.                 $price = 0;
  4563.                 $orderDetails = [];
  4564.                 if (isset($ordereditems->legislation) && is_numeric($ordereditems->legislation) && isset($legislationDetails[0]) && $legislationDetails[0]->price) {
  4565.                     $orderDetails['legislation'] = [
  4566.                         'name' => $legislationDetails[0]->name,
  4567.                         'price' => $legislationDetails[0]->price
  4568.                     ];
  4569.                     $price = $price + $orderDetails['legislation']['price'];
  4570.                 }
  4571.                 if (isset($ordereditems->extendedLicenses) && is_numeric($ordereditems->extendedLicenses)) {
  4572.                     $selectVechicleLicensePrice = $this->getDoctrine()->getRepository(LicensePricing::class)->findBy(['type' => 1, 'subtype' => 1, 'name' => $ordereditems->extendedLicenses]);
  4573.                     if (isset($ordereditems->extendedLicenses) && is_numeric($ordereditems->extendedLicenses) && isset($selectVechicleLicensePrice[0]) && $selectVechicleLicensePrice[0]->price) {
  4574.                         $orderDetails['extendedLicenses'] = [
  4575.                             'name' => $selectVechicleLicensePrice[0]->name,
  4576.                             'price' => $selectVechicleLicensePrice[0]->price
  4577.                         ];
  4578.                         $price = $price + $orderDetails['extendedLicenses']['price'];
  4579.                     }
  4580.                 }
  4581.                 if (isset($ordereditems->combo1) && is_numeric($ordereditems->combo1) && $ordereditems->combo1 != 0) {
  4582.                     $comboLicense1Price = $this->getDoctrine()->getRepository(LicensePricing::class)->findBy(['type' => 1, 'subtype' => 2, 'name' => 1]);
  4583.                     if (isset($comboLicense1Price[0]) && $comboLicense1Price[0]->price) {
  4584.                         $orderDetails['combo1'] = [
  4585.                             'name' => $comboLicense1Price[0]->name,
  4586.                             'price' => $comboLicense1Price[0]->price * $ordereditems->combo1,
  4587.                             'qty' => $ordereditems->combo1
  4588.                         ];
  4589.                         $price = $price + $comboLicense1Price[0]->price * $ordereditems->combo1;
  4590.                     }
  4591.                 }
  4592.                 if (isset($ordereditems->combo10) && is_numeric($ordereditems->combo10) && $ordereditems->combo10 != 0) {
  4593.                     $comboLicense10Price = $this->getDoctrine()->getRepository(LicensePricing::class)->findBy(['type' => 1, 'subtype' => 2, 'name' => 10]);
  4594.                     if (isset($comboLicense10Price[0]) && $comboLicense10Price[0]->price) {
  4595.                         $orderDetails['combo10'] = [
  4596.                             'name' => $comboLicense10Price[0]->name,
  4597.                             'price' => $comboLicense10Price[0]->price * $ordereditems->combo10,
  4598.                             'qty' => $ordereditems->combo10
  4599.                         ];
  4600.                         $price = $price + $comboLicense10Price[0]->price * $ordereditems->combo10;
  4601.                     }
  4602.                 }
  4603.                 if (isset($ordereditems->modules) && is_array($ordereditems->modules)) {
  4604.                     $orderedModules = [];
  4605.                     foreach ($ordereditems->modules as $key => $value) {
  4606.                         foreach ($modules as $module) {
  4607.                             if ($value == $module->id) {
  4608.                                 $orderedModules[] = [
  4609.                                     'name' => $module->name,
  4610.                                     'price' => $module->price,
  4611.                                 ];
  4612.                                 $price = $price + $module->price;
  4613.                             }
  4614.                         }
  4615.                     }
  4616.                     $orderDetails['modules'] = $orderedModules;
  4617.                 }
  4618.             } elseif ($ordereditems->licenseType == 2) {
  4619.                 $price = 0;
  4620.                 $orderDetails = [];
  4621.                 if (isset($ordereditems->base_license) && is_numeric($ordereditems->base_license)) {
  4622.                     $legislationDetails = $this->getDoctrine()->getRepository(LicensePricing::class)->findBy(['type' => 2, 'subtype' => 1, 'name' => $ordereditems->base_license]);
  4623.                     if (isset($legislationDetails[0]) && $legislationDetails[0]->price) {
  4624.                         $orderDetails['legislation'] = [
  4625.                             'name' => $legislationDetails[0]->name,
  4626.                             'price' => $legislationDetails[0]->price
  4627.                         ];
  4628.                         $price = $price + $orderDetails['legislation']['price'];
  4629.                     }
  4630.                 }
  4631.                 if (isset($ordereditems->aetr) && is_numeric($ordereditems->aetr)) {
  4632.                     $aetrPrice = $this->getDoctrine()->getRepository(LicensePricing::class)->findBy(['type' => 2, 'subtype' => 2, 'name' => 1]);
  4633.                     if (isset($ordereditems->aetr) && is_numeric($ordereditems->aetr) && isset($aetrPrice[0]) && $aetrPrice[0]->price) {
  4634.                         $orderDetails['aetr'] = [
  4635.                             'name' => $aetrPrice[0]->name,
  4636.                             'price' => $aetrPrice[0]->price* $ordereditems->aetr,
  4637.                             'qty' => $ordereditems->aetr
  4638.                         ];
  4639.                         $price = $price + $orderDetails['aetr']['price'];
  4640.                     }
  4641.                 }
  4642.                 if (isset($ordereditems->labour) && is_numeric($ordereditems->labour)) {
  4643.                     $labourPrice = $this->getDoctrine()->getRepository(LicensePricing::class)->findBy(['type' => 2, 'subtype' => 3, 'name' => 1]);
  4644.                     if (isset($ordereditems->labour) && is_numeric($ordereditems->labour) && isset($labourPrice[0]) && $labourPrice[0]->price) {
  4645.                         $orderDetails['labour'] = [
  4646.                             'name' => $labourPrice[0]->name,
  4647.                             'price' => $labourPrice[0]->price* $ordereditems->labour,
  4648.                             'qty' => $ordereditems->labour
  4649.                         ];
  4650.                         $price = $price + $orderDetails['labour']['price'];
  4651.                     }
  4652.                 }
  4653.                 if (isset($ordereditems->modules) && is_array($ordereditems->modules)) {
  4654.                     $orderedModules = [];
  4655.                     foreach ($ordereditems->modules as $key => $value) {
  4656.                         foreach ($modules as $module) {
  4657.                             if ($value == $module->id) {
  4658.                                 $orderedModules[] = [
  4659.                                     'name' => $module->name,
  4660.                                     'price' => $module->price,
  4661.                                 ];
  4662.                                 $price = $price + $module->price;
  4663.                             }
  4664.                         }
  4665.                     }
  4666.                     $orderDetails['modules'] = $orderedModules;
  4667.                 }
  4668.                 } elseif ($ordereditems->licenseType == 3) {
  4669.                 if (isset($ordereditems->credit) && is_numeric($ordereditems->credit)) {
  4670.                         $orderDetails['credit'] = [
  4671.                             'name' => 'Credit',
  4672.                             'price' => $ordereditems->credit,
  4673.                         ];
  4674.                         $price = $ordereditems->credit;
  4675.                     }
  4676.                 }
  4677.                 $status_message = BalanceTypeEnum::getAllLabelsWithValue('LICENSEORDERSTATUS', $this->translator, 'balance');
  4678.                 $decline_message = !isset($ordereditems->decline_message) ? '' : $ordereditems->decline_message;
  4679.                 //if (!isset($ordereditems->decline_message) && $ordereditems->decline_message = ''){ $decline_message = ''; }else{ $decline_message = $ordereditems->decline_message; }
  4680.                 $result[] = [
  4681.                     'id' => $orders->id,
  4682.                     'ordernumber' => $orders->ordernumber,
  4683.                     'orderDetails' => $orderDetails,
  4684.                     'price' => $price,
  4685.                     'created' => $orders->createdAt,
  4686.                     'status' => $orders->status,
  4687.                     'status_message' => $status_message[$orders->status],
  4688.                     'discount' => $orders->discount,
  4689.                     'paymentOption' => $ordereditems->paymentOption,
  4690.                     'decline_message' => $decline_message
  4691.                 ];
  4692.             }
  4693.     }
  4694.     protected function getLicenseLegislationEndDate($company) {
  4695.         $anyLicense = $this->getDoctrine()->getRepository(Licenses::class)->findBy(['company' => $company, 'status' => array('1','2')]);
  4696.         $legislationEndDate = 0;
  4697.         foreach ($anyLicense as $license) {
  4698.             if ($anyLicense[0]->license_type == 1)
  4699.             {
  4700.                 if (!is_a($legislationEndDate,'DateTime') && $legislationEndDate == 0) {
  4701.                     $legislationEndDate = $license->legislation_license_end_date;
  4702.                 }elseif(is_a($legislationEndDate,'DateTime')) {
  4703.                     if ($legislationEndDate < $license->legislation_license_end_date)  $legislationEndDate = $license->legislation_license_end_date;
  4704.                 }
  4705.             }
  4706.             elseif($anyLicense[0]->license_type == 2)
  4707.             {
  4708.                 if (!is_a($legislationEndDate,'DateTime') && $legislationEndDate == 0) {
  4709.                     $legislationEndDate = $license->legislation_license_end_date;
  4710.                 }elseif(is_a($legislationEndDate,'DateTime')) {
  4711.                     if ($legislationEndDate < $license->legislation_license_end_date)  $legislationEndDate = $license->legislation_license_end_date;
  4712.                 }
  4713.             }
  4714.             elseif($anyLicense[0]->license_type == 3)
  4715.             {
  4716.             }
  4717.         }
  4718.         return $legislationEndDate;
  4719.     }
  4720.     protected function checkActiveLicense($company_id) {
  4721.         $anyLicense = false;
  4722.         $license = $this->getDoctrine()->getRepository(Licenses::class)->findOneBy(['company' => $company_id, 'status' => array('1','99')]);
  4723.         if ($license) {
  4724.             if ($license->status == 99) {
  4725.                 /// license change new license is in system recorded
  4726.                 $anyLicense = ['action' => 'redirect', 'license_type' => $license->license_type,'license_change' => 1,'compensation' => $license->qty];
  4727.                 $licenses = [];
  4728.             }else {
  4729.                 $anyLicense = $this->getDoctrine()->getRepository(Licenses::class)->findBy(['company' => $company_id, 'status' => array('1', '2')]);
  4730.                 $currentYear = date('Y');
  4731.                 if($license->license_type == 1) {
  4732.                     foreach ($anyLicense as $license) {
  4733.                         $details = json_decode($license->details, true);
  4734.                         $licenses['base_starts'][] = $license->base_license_start_date;
  4735.                         $licenses['extendedLicenses'][] = $details['extendedLicenses'];
  4736.                         $licenses['combo1'][] = $details['combo1'];
  4737.                         $licenses['combo10'][] = $details['combo10'];
  4738.                         $licenses['legislation_license_end_date'][] = $license->legislation_license_end_date;
  4739.                         if (@$details['modules'] && isset($details['modules']) && isset($details['modules'][$currentYear])) {
  4740.                             foreach ($details['modules'] as $licmodule) {
  4741.                                 $licenses['modules'][] = $licmodule;
  4742.                             }
  4743.                         }
  4744.                         $anyLicense['summary'] = $licenses;
  4745.                         if (@$anyLicense[0]->id) {
  4746.                             $anyLicense['sum']['vehicleLicenses'] = 0;
  4747.                             $anyLicense['sum']['vehiclemodules'] = [];
  4748.                             $anyLicense['sum']['base_starts'] = 0;
  4749.                             $anyLicense['sum']['legislationEndDate'] = 0;
  4750.                             $anyLicense['sum']['license_type'] = $anyLicense[0]->license_type;
  4751.                             foreach ($anyLicense['summary']['base_starts'] as $val) {
  4752.                                 if (!is_a($anyLicense['sum']['base_starts'], 'DateTime') && $anyLicense['sum']['base_starts'] == 0) {
  4753.                                     $anyLicense['sum']['base_starts'] = $val;
  4754.                                 } elseif (is_a($anyLicense['sum']['base_starts'], 'DateTime')) {
  4755.                                     if ($val < $anyLicense['sum']['base_starts']) $anyLicense['sum']['base_starts'] = $val;
  4756.                                 }
  4757.                             }
  4758.                             foreach ($anyLicense['summary']['legislation_license_end_date'] as $val) {
  4759.                                 if (!is_a($anyLicense['sum']['legislationEndDate'], 'DateTime') && $anyLicense['sum']['legislationEndDate'] == 0) {
  4760.                                     $anyLicense['sum']['legislationEndDate'] = $val;
  4761.                                 } elseif (is_a($anyLicense['sum']['legislationEndDate'], 'DateTime')) {
  4762.                                     if ($val > $anyLicense['sum']['legislationEndDate']) $anyLicense['sum']['legislationEndDate'] = $val;
  4763.                                 }
  4764.                             }
  4765.                             foreach ($anyLicense['summary']['extendedLicenses'] as $val) {
  4766.                                 $anyLicense['sum']['vehicleLicenses'] += intval($val);
  4767.                             }
  4768.                             foreach ($anyLicense['summary']['combo1'] as $val) {
  4769.                                 $anyLicense['sum']['vehicleLicenses'] += intval($val);
  4770.                             }
  4771.                             foreach ($anyLicense['summary']['combo10'] as $val) {
  4772.                                 $anyLicense['sum']['vehicleLicenses'] += intval($val) * 10;
  4773.                             }
  4774.                         }
  4775.                     }
  4776.                     if (@$anyLicense['summary']['modules']) {
  4777.                         foreach ($anyLicense['summary']['modules'] as $key=>$val) {
  4778.                             foreach ($val as $mod) {
  4779.                                 $anyLicense['sum']['modules'][] = $mod;
  4780.                             }
  4781.                         }
  4782.                     }
  4783.                 }
  4784.                 elseif($license->license_type == 2)
  4785.                 {
  4786.                     foreach ($anyLicense as $license) {
  4787.                         $details = json_decode($license->details, true);
  4788.                         $licenses['base_starts'][] = $license->base_license_start_date;
  4789.                         $licenses['base_ends'][] = $license->base_license_end_date;
  4790.                         if (@$details['modules'] && isset($details['modules']) && isset($details['modules'][$currentYear])) {
  4791.                             foreach ($details['modules'] as $licmodule) {
  4792.                                 $licenses['modules'][] = $licmodule;
  4793.                             }
  4794.                         }
  4795.                         if (@$details['aetr'] && isset($details['aetr'])) {
  4796.                             $licenses['aetr'][] = ['open' => $details['aetr']['open'],
  4797.                                 'used' => $details['aetr']['used']
  4798.                             ];
  4799.                         }
  4800.                         if (@$details['labour'] && isset($details['labour'])) {
  4801.                             $licenses['labour'][] = ['open' => $details['labour']['open'],
  4802.                                 'used' => $details['labour']['used']
  4803.                             ];
  4804.                         }
  4805.                     }
  4806.                     $anyLicense['summary'] = $licenses;
  4807.                     if (@$anyLicense[0]->id) {
  4808.                         $anyLicense['sum']['modules'] = [];
  4809.                         $anyLicense['sum']['base_starts'] = 0;
  4810.                         $anyLicense['sum']['base_ends'] = 0;
  4811.                         $anyLicense['sum']['drivers'] = sizeof($this->company->drivers);
  4812.                         $anyLicense['sum']['license_type'] = $anyLicense[0]->license_type;
  4813.                         $anyLicense['sum']['aetr']['open'] = 0;
  4814.                         $anyLicense['sum']['aetr']['used'] = 0;
  4815.                         $anyLicense['sum']['labour']['open'] = 0;
  4816.                         $anyLicense['sum']['labour']['used'] = 0;
  4817.                         foreach ($anyLicense['summary']['base_starts'] as $val) {
  4818.                             if (!is_a($anyLicense['sum']['base_starts'], 'DateTime') && $anyLicense['sum']['base_starts'] == 0) {
  4819.                                 $anyLicense['sum']['base_starts'] = $val;
  4820.                             } elseif (is_a($anyLicense['sum']['base_starts'], 'DateTime')) {
  4821.                                 if ($val < $anyLicense['sum']['base_starts']) $anyLicense['sum']['base_starts'] = $val;
  4822.                             }
  4823.                         }
  4824.                         foreach ($anyLicense['summary']['aetr'] as $val) {
  4825.                             if ($anyLicense['sum']['aetr']['open'] == 0 && !$anyLicense['sum']['aetr']['open'] > 0 ) {
  4826.                                 $anyLicense['sum']['aetr']['open'] = intval($val['open']);
  4827.                             } elseif (is_integer($anyLicense['sum']['aetr']['open']) && $anyLicense['sum']['aetr']['open'] > 0) {
  4828.                                 $anyLicense['sum']['aetr']['open'] = $val['open']+$anyLicense['sum']['aetr']['open'];
  4829.                             }
  4830.                             if ($anyLicense['sum']['aetr']['used'] == 0 && !$anyLicense['sum']['aetr']['used'] > 0 ) {
  4831.                                 $anyLicense['sum']['aetr']['used'] = intval($val['used']);
  4832.                             } elseif (is_integer($anyLicense['sum']['aetr']['used']) && $anyLicense['sum']['aetr']['used'] > 0) {
  4833.                                 $anyLicense['sum']['aetr']['used'] += $val['used'];
  4834.                             }
  4835.                         }
  4836.                         foreach ($anyLicense['summary']['labour'] as $val) {
  4837.                             if ($anyLicense['sum']['labour']['open'] == 0 && !$anyLicense['sum']['labour']['open'] > 0 ) {
  4838.                                 $anyLicense['sum']['labour']['open'] = intval($val['open']);
  4839.                             } elseif (is_integer($anyLicense['sum']['labour']['open']) && $anyLicense['sum']['labour']['open'] > 0) {
  4840.                                 $anyLicense['sum']['labour']['open'] += $val['open'];
  4841.                             }
  4842.                             if ($anyLicense['sum']['labour']['used'] == 0 && !$anyLicense['sum']['labour']['used'] > 0 ) {
  4843.                                 $anyLicense['sum']['labour']['used'] = intval($val['used']);
  4844.                             } elseif (is_integer($anyLicense['sum']['aetr']['used']) && $anyLicense['sum']['labour']['used'] > 0) {
  4845.                                 $anyLicense['sum']['labour']['used'] += $val['used'];
  4846.                             }
  4847.                         }
  4848.                         foreach ($anyLicense['summary']['base_ends'] as $val) {
  4849.                             if (!is_a($anyLicense['sum']['base_ends'], 'DateTime') && $anyLicense['sum']['base_ends'] == 0) {
  4850.                                 $anyLicense['sum']['base_ends'] = $val;
  4851.                             } elseif (is_a($anyLicense['sum']['base_ends'], 'DateTime')) {
  4852.                                 if ($val > $anyLicense['sum']['base_ends']) $anyLicense['sum']['base_ends'] = $val;
  4853.                             }
  4854.                         }
  4855.                     }
  4856.                     if (@$anyLicense['summary']['modules']) {
  4857.                         foreach ($anyLicense['summary']['modules'] as $key=>$val) {
  4858.                             foreach ($val as $mod) {
  4859.                                 $anyLicense['sum']['modules'][] = $mod;
  4860.                             }
  4861.                         }
  4862.                     }
  4863.                 }
  4864.                 elseif($license->license_type == 3)
  4865.                 {
  4866.                     $credit = 0;
  4867.                     foreach ($anyLicense as $license) {
  4868.                         $details = json_decode($license->details, true);
  4869.                         $licenses['credit'][] = $details['credit'];
  4870.                     }
  4871.                     $anyLicense['summary'] = $licenses;
  4872.                     $anyLicense['sum']['credit'] = 0;
  4873.                     if (@$anyLicense[0]->id) {
  4874.                         $anyLicense['sum']['license_type'] = $anyLicense[0]->license_type;
  4875.                         foreach ($anyLicense['summary']['credit'] as $val) {
  4876.                             $anyLicense['sum']['credit'] += $val;
  4877.                         }
  4878.                     }
  4879.                 }
  4880.             }
  4881.         }else{
  4882.             /// null -> no license
  4883.             /// check if first license for company is set
  4884.             if (is_numeric($this->company->licenseType)) {
  4885.                 $activeOrder = $this->getDoctrine()->getRepository(LicenseOrder::class)->findOneBy(['company' => $company_id,'status' => array('1','2')]);
  4886.                 if (@$activeOrder->details) {
  4887.                     $license_Type_to_redirect = json_decode($activeOrder->details,true);
  4888.                     $license_Type_to_redirect = $license_Type_to_redirect['licenseType'];
  4889.                 }else{
  4890.                     $license_Type_to_redirect = $this->company->licenseType;
  4891.                 }
  4892.                 isset($activeOrder) ? $anyLicense = ['action' => 'redirect', 'license_type' => $license_Type_to_redirect,'active_order' => 1] : $anyLicense = ['action' => 'redirect', 'license_type' => $license_Type_to_redirect,'active_order' => 0];
  4893.                 /// license type set but no license force to buy
  4894.                 //return new RedirectResponse('balance.buy.vehicle_license');
  4895.             }else{
  4896.                 // no license set after reg what should we do?
  4897.             }
  4898.         }
  4899.         return $anyLicense;
  4900.     }
  4901.     protected function declineLicenseOrder($update,&$result, $currentUser) {
  4902.         $em = $this->getDoctrine()->getManager();
  4903.         $order = $this->getDoctrine()->getRepository(LicenseOrder::class)->find($update->get(0));
  4904.         $details = json_decode($order->getDetails(),true);
  4905.         $details['decline_message'] = $update->get(1);
  4906.         $details = json_encode($details);
  4907.         $order->setDetails($details);
  4908.         $changesMade['status'] = [
  4909.             'o' => $order->getStatus(),
  4910.             'n' => '3',
  4911.         ];
  4912.         $changesMade['ordernumber'] = $order->getOrderNumber();
  4913.         $this->logger->saveAction(LogChangeTypeEnum::ORDER_DECLINED, 7,$this->company->id, $changesMade);
  4914.         $order->setStatus(3);
  4915.         try {
  4916.             $em->persist($order);
  4917.             $em->flush();
  4918.             //$user = $this->getUser();
  4919.             if ($currentUser->getRolesUnconverted()[0] == UserRoleEnum::ROLE_SUPER_ADMIN) {
  4920.                 $fakeRequest = Request::createFromGlobals();
  4921.                 $fakeRequest->request->set(0, $order->getCompany());
  4922.                 $fakeRequest->request->set(1, "Tisztelt Cég! <br/>Az alábbi megrendelés számú {$changesMade['ordernumber']} megrendelését visszavontuk.<br /> Visszavonás oka: {$update->get(1)} <br /> Tisztelettel, Compass");
  4923.                 $fakeRequest->request->set(2, 'Rendelés visszavonva');
  4924.                 $this->sendMessageToCompany(null, $fakeRequest->request, null, $result);
  4925.             }
  4926.         } catch(\Doctrine\DBAL\DBALException $e) {
  4927.             dump($e);
  4928.             $result['info'] = 'Order insert error';
  4929.             $result['msg'] = $this->translator->trans('message.genericError', array(), 'general');
  4930.             return false;
  4931.         }
  4932.         // add flash message - will show on next page open
  4933.         $this->addFlash('success', $this->translator->trans('message.recordUpdated', array(), 'general'));
  4934.         $result['success'] = true;
  4935.     }
  4936.     protected function randomOrderNumber() {
  4937.         $rand = "COMP-".rand(100000,999666);
  4938.         do {
  4939.             $orderNumberChk = $this->getDoctrine()->getRepository(LicenseOrder::class)->findBy(['ordernumber' => $rand ]);
  4940.         } while ($orderNumberChk);
  4941.         return $rand;
  4942.     }
  4943.     ****/
  4944.     /****    
  4945.     protected function checkNewMessage($user) {
  4946.         $unReadStatus = false;
  4947.         $unReadMessage = $this->getDoctrine()->getRepository(Message::class)->findOneBy(['to' => $user, 'status' => 1]);
  4948.         if ($unReadMessage) $unReadStatus = true;
  4949.         return $unReadStatus;
  4950.     }
  4951.     public function sendMessageToCompany($company,$data,$thread = null,&$result) {
  4952.         $em = $this->getDoctrine()->getManager();
  4953.         $message = new Message();
  4954.         $message->setFrom($company);
  4955.         $to = $data->get(0);
  4956.         if (!@$to->id) $message->setTo(null); else $message->setTo($to);
  4957.         $message->setSubject($data->get(2));
  4958.         $message->setContent($data->get(1));
  4959.         if ($thread) $message->setMessageRepliedTo($thread);
  4960.         $message->setStatus(1);
  4961.         try {
  4962.             $em->persist($message);
  4963.             $em->flush();
  4964.         } catch(\Doctrine\DBAL\DBALException $e) {
  4965.             dump($e);
  4966.             $result['info'] = 'Order insert error';
  4967.             $result['msg'] = $this->translator->trans('message.genericError', array(), 'general');
  4968.             return false;
  4969.         }
  4970.         // add flash message - will show on next page open
  4971.         $this->addFlash('success', $this->translator->trans('message.recordUpdated', array(), 'general'));
  4972.         $result['success'] = true;
  4973.     }
  4974.     ****/
  4975.     /****
  4976.     protected function processOrder($company,$orderDetails,&$result) {
  4977.         $orderNumber = $this->randomOrderNumber();
  4978.         $em = $this->getDoctrine()->getManager();
  4979.         $order = new LicenseOrder();
  4980.         $order->setCompany($company);
  4981.         $order->setStatus(1);
  4982.         $order->setDiscount(0);
  4983.         $order->setOrderNumber($orderNumber);
  4984.         $order->setDetails(json_encode($orderDetails));
  4985.         $changesMade['new_order'] = [
  4986.             'o' => '-',
  4987.             'n' => $orderNumber,
  4988.         ];
  4989.         $this->logger->saveAction(LogChangeTypeEnum::ORDER_CREATED, 7, 0, $changesMade);
  4990.         try {
  4991.             $em->persist($order);
  4992.             $em->flush();
  4993.             $fakeRequest = Request::createFromGlobals();
  4994.             $fakeRequest->request->set(0,'');
  4995.             $fakeRequest->request->set(1,"Új megrendelés!!! <br/>Megrendelő: {$this->company->name}<br/>Megrendelés Szám: {$orderNumber}<br />");
  4996.             $fakeRequest->request->set(2,'Új megrendelés');
  4997.             $this->sendMessageToCompany($this->company,$fakeRequest->request,null,$result);
  4998.         } catch(\Doctrine\DBAL\DBALException $e) {
  4999.             dump($e);
  5000.             $result['info'] = 'Order insert error';
  5001.             $result['msg'] = $this->translator->trans('message.genericError', array(), 'general');
  5002.             return false;
  5003.         }
  5004.         // add flash message - will show on next page open
  5005.         $this->addFlash('success', $this->translator->trans('message.recordUpdated', array(), 'general'));
  5006.         $result['success'] = true;
  5007.     }
  5008.     protected function processLicensePriceChange($request, $entity, &$result) {
  5009.         $em = $this->getDoctrine()->getManager();
  5010.         $entityFields = ['name','type','price','subtype','invoiceremark','invoicetitle','price'];
  5011.         foreach ($entityFields as $entities) {
  5012.             if ($request->$entities != $entity->$entities) $entity->__set($entities, $request->$entities);
  5013.         }
  5014.         try {
  5015.             $em->persist($entity);
  5016.             $em->flush();
  5017.         } catch(\Doctrine\DBAL\DBALException $e) {
  5018.             dump($e);
  5019.             $result['info'] = 'licenseprice update error';
  5020.             $result['msg'] = $this->translator->trans('message.genericError', array(), 'general');
  5021.             return false;
  5022.         }
  5023.         // log the change
  5024.         $this->logger->saveAction(LogChangeTypeEnum::ITEM_UPDATED, $this->modulePath, $entity->getId()); //T
  5025.         // add flash message - will show on next page open
  5026.         $this->addFlash('success', $this->translator->trans('message.recordUpdated', array(), 'general'));
  5027.         $result['success'] = true;
  5028.         return true;
  5029.     }
  5030.     protected function processLicensePriceAdd($request, &$result) {
  5031.         $em = $this->getDoctrine()->getManager();
  5032.         $entity = new LicensePricing();
  5033.         $entityFields = ['name','type','price','subtype','invoiceremark','invoicetitle','price'];
  5034.         foreach ($entityFields as $entities) {
  5035.             $entity->__set($entities,$request->$entities);
  5036.         }
  5037.         try {
  5038.             $em->persist($entity);
  5039.             $em->flush();
  5040.         } catch(\Doctrine\DBAL\DBALException $e) {
  5041.             dump($e);
  5042.             $result['info'] = 'licenseprice update error';
  5043.             $result['msg'] = $this->translator->trans('message.genericError', array(), 'general');
  5044.             return false;
  5045.         }
  5046.         // log the change
  5047.         $this->logger->saveAction(LogChangeTypeEnum::ITEM_ADDED, $this->modulePath, $entity->getId()); //T
  5048.         // add flash message - will show on next page open
  5049.         $this->addFlash('success', $this->translator->trans('message.recordDeleted', array(), 'general'));
  5050.         $result['success'] = true;
  5051.         return true;
  5052.     }
  5053.     protected function processSaveDriverLicense($data, &$result) {
  5054.         $em = $this->getDoctrine()->getManager();
  5055.         $dlicEntity = $data->get(0);
  5056.         $driverId = $data->get(1);
  5057.         $selectedVals = $data->get(2);
  5058.         $usedaetr = 0;
  5059.         $usedLabour = 0;
  5060.         $driverEntity = $this->getDoctrine()->getRepository(DriverLicense::class)->find($data->get(0));
  5061.         if ($driverEntity->details == 'NEW') {
  5062.             /// no data present
  5063.             $selMonth = [];
  5064.             foreach ($selectedVals as $vals) {
  5065.                 $val = explode('_',$vals);
  5066.                 $selMonth[$driverId]['lic'][$val[0]][$val[1]][] = $val[2]+1;
  5067.                 if ($val[0] = 'e') {
  5068.                     $usedaetr = $usedaetr+1;
  5069.                 }
  5070.                 if ($val[0] = 'l') {
  5071.                     $usedLabour = $usedLabour+1;
  5072.                 }
  5073.             }
  5074.            $selMonth_json =  json_encode($selMonth);
  5075.             $driverEntity->setDetails($selMonth_json);
  5076.             $em->persist($driverEntity);
  5077.             $em->flush();
  5078.         }else{
  5079.             $details = json_decode($driverEntity->details,true);
  5080.             $selMonth = [];
  5081.             foreach ($selectedVals as $vals) {
  5082.                 $val = explode('_',$vals);
  5083.                 $details[$driverId]['lic'][$val[0]][$val[1]][] = $val[2]+1;
  5084.                 if ($val[0] = 'e') {
  5085.                     $usedaetr = $usedaetr+1;
  5086.                 }
  5087.                 if ($val[0] = 'l') {
  5088.                     $usedLabour = $usedLabour+1;
  5089.                 }
  5090.             }
  5091.             $details =  json_encode($details);
  5092.             $driverEntity->setDetails($details);
  5093.             $em->persist($driverEntity);
  5094.             $em->flush();
  5095.         }
  5096.                 /// DEDUCT Licenses
  5097.             $baseLicense = $this->getDoctrine()->getRepository(Licenses::class)->findBy(['license_type' => 2, 'company' => $this->company]);
  5098.             foreach ($baseLicense as $license) {
  5099.                 if ($license->status != 3) {
  5100.                     $details = json_decode($license->details,true);
  5101.                     if (@$details['aetr']['open'] && $details['aetr']['open'] > 0) {
  5102.                         if ($details['aetr']['open'] > $usedaetr && $usedaetr != 0) {
  5103.                             $details['aetr']['open'] = $details['aetr']['open']-$usedaetr;
  5104.                             $details['aetr']['used'] = $details['aetr']['used']+$usedaetr;
  5105.                             $usedaetr = $usedaetr-$details['aetr']['used'];
  5106.                         }elseif($details['aetr']['open'] < $usedaetr && $usedaetr != 0){
  5107.                             $details['aetr']['open'] = 0;
  5108.                             $usedaetr = $usedaetr-$details['aetr']['open'];
  5109.                             $details['aetr']['used'] = $details['aetr']['used']+$usedaetr;
  5110.                             $usedaetr = $usedaetr-$details['aetr']['used'];
  5111.                         }
  5112.                     }
  5113.                     if (@$details['labour']['open'] && $details['labour']['open'] > 0) {
  5114.                         if ($details['labour']['open'] > $usedLabour && $usedLabour != 0) {
  5115.                             $details['labour']['open'] = $details['labour']['open']-$usedLabour;
  5116.                             $details['labour']['used'] = $details['labour']['used']+$usedLabour;
  5117.                             $usedLabour = $usedLabour-$details['labour']['used'];
  5118.                         }elseif($details['labour']['open'] < $usedLabour && $usedLabour != 0) {
  5119.                             $details['labour']['open'] = 0;
  5120.                             $usedLabour = $usedLabour - $details['labour']['open'];
  5121.                             $details['labour']['used'] = $details['labour']['used'] + $usedLabour;
  5122.                             $usedLabour = $usedLabour-$details['labour']['used'];
  5123.                         }
  5124.                     }
  5125.                     $details = json_encode($details);
  5126.                     $license->setDetails($details);
  5127.                     $em->persist($license);
  5128.                     $em->flush();
  5129.                 }
  5130.             }
  5131.             /// if more licenses used deduct all
  5132.             $result['success'] = true;
  5133.     }
  5134.     ****/
  5135.     /****
  5136.     protected function processMessageExclude($request, $entity, &$result) {
  5137.         $em = $this->getDoctrine()->getManager();
  5138.         $excluded = json_decode($entity->excluded,true);
  5139.         $user = $this->getUser();
  5140.         if ($user->getRolesUnconverted()[0] == UserRoleEnum::ROLE_SUPER_ADMIN) {
  5141.             $excluded[]['id'] = 'admin';
  5142.         }else{
  5143.             $excluded[]['id'] = $this->company->id;
  5144.         }
  5145.         $entity->__set('excluded', json_encode($excluded));
  5146.         try {
  5147.             $em->persist($entity);
  5148.             $em->flush();
  5149.         } catch(\Doctrine\DBAL\DBALException $e) {
  5150.             dump($e);
  5151.             $result['info'] = 'delete error';
  5152.             $result['msg'] = $this->translator->trans('message.genericError', array(), 'general');
  5153.             return false;
  5154.         }
  5155.         // log the change
  5156.         //$this->logger->saveAction(LogChangeTypeEnum::ITEM_DELETED, $this->modulePath, $entity->getId()); //T
  5157.         // add flash message - will show on next page open
  5158.         //$this->addFlash('success', $this->translator->trans('message.recordDeleted', array(), 'general'));
  5159.         $result['success'] = true;
  5160.         return true;
  5161.     }
  5162.     ****/
  5163.     protected function processEntityDelete($request$entity, &$result) {
  5164.         $em $this->getDoctrine()->getManager();
  5165.         $entity->__set('deleted'1);
  5166.         try {
  5167.             $em->persist($entity);
  5168.             $em->flush();
  5169.         } catch(\Doctrine\DBAL\DBALException $e) {
  5170.             dump($e);
  5171.             $result['info'] = 'delete error';
  5172.             $result['msg'] = $this->translator->trans('message.genericError', array(), 'general');
  5173.             return false;
  5174.         }
  5175.         // log the change
  5176.         $this->logger->saveAction(LogChangeTypeEnum::ITEM_DELETED$this->modulePath$entity->getId()); //T
  5177.         // add flash message - will show on next page open
  5178.         if (!$this->disableFlashMessages) {
  5179.             $this->addFlash('success'$this->translator->trans('message.recordDeleted', array(), 'general'));
  5180.         }
  5181.         $result['success'] = true;
  5182.         return true;
  5183.     }
  5184.     protected function processEntityUnDelete($request$entity, &$result) {
  5185.         $em $this->getDoctrine()->getManager();
  5186.         $entity->__set('deleted'0);
  5187.         try {
  5188.             $em->persist($entity);
  5189.             $em->flush();
  5190.         } catch(\Doctrine\DBAL\DBALException $e) {
  5191.             dump($e);
  5192.             $result['info'] = 'undelete error';
  5193.             $result['msg'] = $this->translator->trans('message.genericError', array(), 'general');
  5194.             return false;
  5195.         }
  5196.         // log the change
  5197.         $this->logger->saveAction(LogChangeTypeEnum::ITEM_UNDELETED$this->modulePath$entity->getId()); //T
  5198.         // add flash message - will show on next page open
  5199.         $this->addFlash('success'$this->translator->trans('message.recordUnDeleted', array(), 'general'));
  5200.         $result['success'] = true;
  5201.         return true;
  5202.     }
  5203.     protected function processCompanyChange($request$user$companyId, &$result) {
  5204.         $em $this->getDoctrine()->getManager();
  5205.         if ($companyId=='null') {
  5206.             $user->__set('currentCompanyViewed'null);
  5207.         } else {
  5208.             $companies $this->getDoctrine()->getRepository(Company::class)->findById($companyId);
  5209.             $user->__set('currentCompanyViewed'$companies[0]);
  5210.         }
  5211.         try {
  5212.             $em->persist($user);
  5213.             $em->flush();
  5214.         } catch(\Doctrine\DBAL\DBALException $e) {
  5215.             dump($e);
  5216.             $result['info'] = 'company change error';
  5217.             $result['msg'] = $this->translator->trans('message.genericError', array(), 'general');
  5218.             return false;
  5219.         }
  5220.         // clear session vars
  5221.         $this->session->set('selected-driver'null);
  5222.         $this->session->set('selected-range'null);
  5223.         $this->session->set('activity-original-data'null);
  5224.         $this->addFlash('success'$this->translator->trans('message.companyChanged', array(), 'general'));
  5225.         $result['success'] = true;
  5226.         return true;
  5227.     }
  5228.     public function getEntityArray($entityPath$idField$duplicateInfoFieldData=null$filterParms=null) {
  5229.         // add driver array
  5230.         $dataArray = [];
  5231.         $uniqueNamesArray = [];
  5232.         $duplicateNamesArray = [];
  5233.         $dbArray =  $this->getAllEntityData($entityPath$idField$filterParms);
  5234.         //dump("dbArray($idField)", $dbArray);
  5235.         foreach($dbArray as $d) {
  5236.             if (strpos($idField',')>0) {
  5237.                 $idFieldArray explode(","$idField);
  5238.                 $valueArray = [];
  5239.                 foreach($idFieldArray as $thisIdField) {
  5240.                     $valueArray[] = $d->__get($thisIdField);
  5241.                 }
  5242.                 $value trim(implode(" "$valueArray));
  5243.             } else {
  5244.                 $value $d->__get($idField);
  5245.             }
  5246.             $dataArray$d->getId() ] = $value;
  5247.             if (!in_array($value$uniqueNamesArray)) {
  5248.                 $uniqueNamesArray[] = $value;
  5249.             } else {
  5250.                 $duplicateNamesArray[] = $value;
  5251.             }
  5252.         }
  5253.         //dump('dataArray', $dataArray);
  5254.         //dump('uniqueNamesArray', $uniqueNamesArray);
  5255.         //dump('duplicateNamesArray', $duplicateNamesArray);
  5256.         if ($duplicateInfoFieldData!=null) {
  5257.             foreach($dbArray as $d) {
  5258.                 if (strpos($idField',')>0) {
  5259.                     $idFieldArray explode(","$idField);
  5260.                     $valueArray = [];
  5261.                     foreach($idFieldArray as $thisIdField) {
  5262.                         $valueArray[] = $d->__get($thisIdField);
  5263.                     }
  5264.                     $valueToCheck trim(implode(" "$valueArray));
  5265.                 } else {
  5266.                     $valueToCheck $d->__get($idField);
  5267.                 }
  5268.                 //dump('valueToCheck', $valueToCheck);
  5269.                 if (in_array($valueToCheck$duplicateNamesArray)) {
  5270.                     if ($duplicateInfoFieldData['type']=='datetime') {
  5271.                         $dataArray$d->getId() ] .= ' ('.$duplicateInfoFieldData['label'].': '.$d->__getDateFormatted($duplicateInfoFieldData['name']).')';
  5272.                     }
  5273.                 }
  5274.             }
  5275.         }
  5276.         return $dataArray;
  5277.     }
  5278.     protected function getCurrentAccountCompanyArray() {
  5279.         $dataArray = [];
  5280.         if ($this->account==null) {
  5281.             // no account selected = Compass user => show all companies in the system
  5282.             //$companies = null; //    $this->getDoctrine()->getRepository(Company::class)->getAllSorted();
  5283.             if ($this->company!=null) {
  5284.                 // if a company is selected, get all companies belonging to this company's account
  5285.                 $companyAccount $this->company->getAccount();
  5286.                 $companies $companyAccount->__get('companies');
  5287.             } else {
  5288.                 // can't get any
  5289.                 $companies null;
  5290.             }
  5291.         } else {
  5292.             // account selected => get all companies of this account
  5293.             $companies $this->account->__get('companies'); // get non-deleted!!!!
  5294.         }
  5295.         if ($companies!=null) {
  5296.             foreach($companies as $company) {
  5297.                 $dataArray$company->getId() ] = $company->getName();
  5298.             }
  5299.         }
  5300.         return $dataArray;
  5301.     }
  5302.     // COM-492: added $thisIsVehiclePlate
  5303.     protected function checkLicensePlateUniqueness($licensePlate$entityIdExceptionArray=null$thisIsVehiclePlate=true)
  5304.     {
  5305.         //return true;    //JNOTE            -- COM-492:commented out
  5306.         //dump("checkLicensePlateUniqueness($licensePlate, entityIdExceptionArray, $thisIsVehiclePlate)", $entityIdExceptionArray);
  5307.         if ($licensePlate==null || $licensePlate=='') return true;
  5308.         
  5309.         // COM-492: exceptions only apply to the current entity (vehicle id excep to vehicles, trailer id excep to trailers)
  5310.         if ($thisIsVehiclePlate) {
  5311.             $vehicleIdExceptionArray $entityIdExceptionArray;
  5312.             $trailerIdExceptionArray = [];
  5313.         } else {
  5314.             $vehicleIdExceptionArray = [];
  5315.             $trailerIdExceptionArray $entityIdExceptionArray;
  5316.         }
  5317.         // check vehicles
  5318.         $vehicleRepository $this->getDoctrine()->getRepository(Vehicle::class);
  5319.         $vehicles $vehicleRepository->findByRegistrationNumber($licensePlate$vehicleIdExceptionArray$this->company);
  5320.         //dump('vehicles', $vehicles);
  5321.         if ($vehicles!=null) {
  5322.             $errorResult $this->getDefaultAjaxReturnRec(true,
  5323.                 $this->translator->trans("message.licensePlateAlreadyUsed", array(), 'vehicles'), // msg
  5324.                 'license plate used by a vehicle'// info
  5325.                 ''// url
  5326.                 "registrationNumber"); // errorField
  5327.             return $errorResult;
  5328.         }
  5329.         // check trailers
  5330.         $trailerRepository $this->getDoctrine()->getRepository(Trailer::class);
  5331.         $trailers $trailerRepository->findByRegistrationNumber($licensePlate$trailerIdExceptionArray$this->company);
  5332.         //dump('trailers', $trailers);
  5333.         if ($trailers!=null) {
  5334.             $errorResult $this->getDefaultAjaxReturnRec(true,
  5335.                 $this->translator->trans("message.licensePlateAlreadyUsed", array(), 'vehicles'), // msg
  5336.                 'license plate used by a trailer'// info
  5337.                 ''// url
  5338.                 "registrationNumber"); // errorField
  5339.             return $errorResult;
  5340.         }
  5341.         return true;
  5342.     }
  5343.     public function getCompanyDayTitles($getCode=true$getType=false) {
  5344.         // add this company's day titles
  5345.         $dayTitlesArray = [];
  5346.         $dayTitleTypesArray $this->getEntityArray(DayTitle::class, 'type');
  5347.         //dump('dayTitleTypesArray', $dayTitleTypesArray);
  5348.         foreach($dayTitleTypesArray as $id=>$dayTitleType) {
  5349.             if ($dayTitleType==0) {
  5350.                 if ($getCode) {
  5351.                     $dayTitlesArray[$id] = $this->getDoctrine()->getRepository(DayTitle::class)->findOneById($id)->getCode();
  5352.                 } else if ($getType) {
  5353.                     $dayTitlesArray[$id] = $dayTitleType;
  5354.                 } else {
  5355.                     $dayTitlesArray[$id] = $this->getDoctrine()->getRepository(DayTitle::class)->findOneById($id)->getName();
  5356.                 }
  5357.             } else {
  5358.                 if ($getCode) {
  5359.                     $dayTitlesArray[$id] = $this->translator->transDayTitleTypeEnum::SHORT_LABELS[$dayTitleType]['label'], array(),
  5360.                         DayTitleTypeEnum::SHORT_LABELS[$dayTitleType]['module'] );
  5361.                 } else if ($getType) {
  5362.                     $dayTitlesArray[$id] = $dayTitleType;
  5363.                 } else {
  5364.                     $dayTitlesArray[$id] = $this->translator->transDayTitleTypeEnum::LABELS[$dayTitleType]['label'], array(),
  5365.                         DayTitleTypeEnum::LABELS[$dayTitleType]['module'] );
  5366.                 }
  5367.                 //$dayTitleTypeIdsArray[$dayTitleType] = $id;
  5368.             }
  5369.         }
  5370.         //dump('dayTitlesArray', $dayTitlesArray);
  5371.         uasort($dayTitlesArray, function($v1$v2) {
  5372.             if ($v1==$v2) return 0;
  5373.             return ($v1 $v2) ? -1;
  5374.         });
  5375.         return $dayTitlesArray;
  5376.     }
  5377.     protected function buildReportRenderArray($params=null) {
  5378.         $perDriverReportsAvailable ReportClass::AVAILABLE_REPORT_SUBJECTS[$this->reportClass]['driver'];
  5379.         $perVehicleReportsAvailable ReportClass::AVAILABLE_REPORT_SUBJECTS[$this->reportClass]['vehicle'];
  5380.         $driverVehicleId '';
  5381.         $driverVehicleId2 '';
  5382.         $driverId '';
  5383.         $vehicleId '';
  5384.         $getAllMode false;
  5385.         $driverMode $perDriverReportsAvailable;
  5386.         // by default, select last month's period
  5387.         //$startDate = $this->timeCalc->currentDate;
  5388.         //$endDate = $this->timeCalc->gmDateFuture(3600*24*30, true);
  5389.         $lastMonthDate $this->timeCalc->alterDateTimeByMonths($this->timeCalc->currentDate, -1true);
  5390.         $startDate date('Y-m-01'strtotime($lastMonthDate));
  5391.         $endDate date('Y-m-t'strtotime($lastMonthDate));
  5392.         //dump("startDate: $startDate, endDate: $endDate");
  5393.         // read drivers, vehicles and date range from a session vars
  5394.         if ($this->session->get('selected-driver')!=null) {
  5395.             $driverId $this->session->get('selected-driver');
  5396.             if ($perDriverReportsAvailable) {
  5397.                 $driverVehicleId $driverId;
  5398.             }
  5399.         }
  5400.         if ($this->session->get('selected-vehicle')!=null) {
  5401.             $vehicleId $this->session->get('selected-vehicle');
  5402.             if ($perVehicleReportsAvailable) {
  5403.                 $driverVehicleId 'V'.$vehicleId;
  5404.             }
  5405.         }
  5406.         if ($this->session->get('selected-driver2')!=null) {
  5407.             $driverId2 $this->session->get('selected-driver2');
  5408.             if ($perDriverReportsAvailable) {
  5409.                 $driverVehicleId2 $driverId2;
  5410.             }
  5411.         }
  5412.         if ($this->session->get('selected-vehicle2')!=null) {
  5413.             $vehicleId2 $this->session->get('selected-vehicle2');
  5414.             if ($perVehicleReportsAvailable) {
  5415.                 $driverVehicleId2 'V'.$vehicleId2;
  5416.             }
  5417.         }
  5418.         if ($this->session->get('selected-range')!=null && $this->session->get('selected-range')!=';') {
  5419.             //dump($this->session->get('selected-range'));
  5420.             list($startDate$endDate) = explode(';'$this->session->get('selected-range'));
  5421.         }
  5422.         //dump("driverId:[$driverId], vehicleId:[$vehicleId], startDate:[$startDate], endDate:[$endDate], driverVehicleId2:[$driverVehicleId2]");
  5423.         $driverMode = !(substr($driverVehicleId,0,1)=='V');
  5424.         $getAllMode = ($driverVehicleId=='all' || $driverVehicleId=='Vall');
  5425.     
  5426.         // COM-UUU
  5427.         $filterParms null;
  5428.         if (isset($params['include-deleted-drivers']) || $params['include-deleted-drivers']==true) {
  5429.             $filterParms = [
  5430.                 'deleted' => 'ALL',
  5431.             ];
  5432.         }
  5433.         // load this company's drivers
  5434.         $driversArray = [];
  5435.         if ($perDriverReportsAvailable) {
  5436.             $driversArray $this->getEntityArray(Driver::class, 'lastName,firstName', [
  5437.                 'name' => 'birthdate',
  5438.                 'type' => 'datetime',
  5439.                 'label' => $this->translator->trans('label.birthdate.short', array(), 'drivers')
  5440.             ], $filterParms); // COM-UUU
  5441.         } else { // COM-601
  5442.             $driverMode false;
  5443.         }
  5444.         //dump('driversArray', $driversArray);
  5445.         // load this company's vehicles
  5446.         $vehiclesArray = [];
  5447.         if ($perVehicleReportsAvailable) {
  5448.             $vehiclesArray $this->getEntityArray(Vehicle::class, 'registrationNumber'null, ['inAnotherCompany'=>'0']); //COM-216
  5449.         } else { // COM-601
  5450.             $driverMode true;
  5451.         }
  5452.         //dump('driversArray', $driversArray);
  5453.         // load previously generated reports
  5454.         $dbPastReportsArray $this->getDoctrine()->getRepository(Report::class)->simpleRead(-1$this->company, [
  5455.             ['class''='$this->reportClass],
  5456.             ['status''=' ReportStatusType::SAVED], //GENERATED
  5457.         ], ['createdAt''DESC'], false);
  5458.         //dump('dbPastReportsArray', $dbPastReportsArray);
  5459.         $pastReportsArray = [];
  5460.         foreach($dbPastReportsArray as $r) {
  5461.             $pastReportsArray[] = [
  5462.                 $r->__get('id'),
  5463.                 $r->__get('fileName'),
  5464.                 $r->__getDateTimeFormatted('createdAt'),
  5465.                 ''// actions
  5466.             ];
  5467.             //break;
  5468.         }
  5469.         //dump('pastReportsArray', $pastReportsArray);
  5470.         // do not remove no-activity drivers for labour reports -- COM-464
  5471.         $allowDriversVehiclesWithoutActivities false;
  5472.         if (in_array($this->reportClass, [ ReportClass::LABOUR_ATTENDANCE_SHEET,
  5473.                                            ReportClass::LABOUR_MINIMUM_WAGES,
  5474.                                            ReportClass::LABOUR_FAULTS,
  5475.                                            ReportClass::LABOUR_DAY_TITLE_SUMMARY ] )) {
  5476.                                      
  5477.             $allowDriversVehiclesWithoutActivities true;
  5478.             
  5479.         }
  5480.         // do not remove no-activity drivers for daily allowance reports -- COM-499
  5481.         if (in_array($this->reportClass, [ ReportClass::DAILY_ALLOW_ATTENDANCE_SHEET,
  5482.                                            ReportClass::DAILY_ALLOW_MINIMUM_WAGES ] )) {
  5483.                                      
  5484.             $allowDriversVehiclesWithoutActivities true;
  5485.             
  5486.         }
  5487.         // do not remove no-activity drivers for wizard -- COM-478
  5488.         if (in_array($this->reportClass, [ ReportClass::STATS_DRIVER_WIZARD,
  5489.                                            ReportClass::STATS_DRIVER_VEHICLE_SUMMARY,
  5490.                                            ReportClass::STATS_PENALTIES ] )) {
  5491.                                      
  5492.             $allowDriversVehiclesWithoutActivities true;
  5493.             
  5494.         }        
  5495.         // JNOTE: only load this for driver/vehicle popup pages!!!
  5496.         // load data needed for driver popup -- COM-502
  5497.         $driversLicenseCardExpiry_customField null;
  5498.         if ($_SERVER['APP_DRIVER_CARD_EXPIRY_CUSTOM_FIELD_ID']!='') {
  5499.             $driversLicenseCardExpiry_customField $this->getDoctrine()->getRepository(CustomField::class)
  5500.                                                                         ->findOneById($_SERVER['APP_DRIVER_CARD_EXPIRY_CUSTOM_FIELD_ID']);
  5501.         }
  5502.         // load data needed for vehicle popup -- COM-502
  5503.         $vehicleTechPermitExpiry_customField null;
  5504.         if ($_SERVER['APP_VEHICLE_TECHNICAL_PERMIT_EXPIRY_CUSTOM_FIELD_ID']!='') {
  5505.             $vehicleTechPermitExpiry_customField $this->getDoctrine()->getRepository(CustomField::class)
  5506.                                                                         ->findOneById($_SERVER['APP_VEHICLE_TECHNICAL_PERMIT_EXPIRY_CUSTOM_FIELD_ID']);
  5507.         }
  5508.         // load exceptions -- COM-502
  5509.         $toDoItemExceptionLookupArray = [];
  5510.         $toDoItemExceptions $this->getDoctrine()->getRepository(ToDoItemException::class)->findBy([
  5511.                                                                                                 'company' => $this->company,
  5512.                                                                                                 'deleted' => 0,
  5513.                                                                                             ]);
  5514.         //dump('toDoItemExceptions', $toDoItemExceptions);
  5515.         
  5516.         if (count($toDoItemExceptions)>0) {
  5517.             foreach($toDoItemExceptions as $exception) {
  5518.                 if (!in_array($exception->getType(), [ToDoItemTypeEnum::STANDARD_DRIVERToDoItemTypeEnum::STANDARD_VEHICLE])) continue;
  5519.                 $toDoItemExceptionLookupArray[] = $exception->getType().'-'.$exception->__get('entityId');
  5520.             }
  5521.         }
  5522.         //dump('toDoItemExceptionLookupArray', $toDoItemExceptionLookupArray);
  5523.         //$toDoItemExceptionLookupArray = []; // JNOTE-DEBUG
  5524.         // load this company's drivers' data
  5525.         $driverActivityDatesArray = [];
  5526.         $driverIdsDelete = [];
  5527.         $driverVehicleDataArray = []; // COM-502
  5528.         if ($perDriverReportsAvailable) {
  5529.             $dbArray =  $this->getAllEntityData(Driver::class, 'id');
  5530.             foreach($dbArray as $d) {
  5531.                 if ($d->__getDateFormatted('oldestActivityDate')==null && !$allowDriversVehiclesWithoutActivities) {
  5532.                     // do not show drivers without activities
  5533.                     $driverIdsDelete[] = $d->getId();
  5534.                     /*// use defaults (next week)
  5535.                     $driverActivityDatesArray[ $d->getId() ] = [
  5536.                         'oldest' => '',
  5537.                         'newest' => '',
  5538.                         'display-oldest' => null, //$defaultStartDate,
  5539.                         'display-newest' => null, //$defaultEndDate,
  5540.                     ];*/
  5541.                 } else {
  5542.                     // use driver's data
  5543.                     $driverActivityDatesArray$d->getId() ] = [
  5544.                         'oldest' => $d->__getDateFormatted('oldestActivityDate'),
  5545.                         'newest' => $d->__getDateFormatted('newestActivityDate'),
  5546.                         'display-oldest' => null//$defaultStartDate,
  5547.                         'display-newest' => null//$defaultEndDate,
  5548.                     ];
  5549.                 }
  5550.                 // driver card expiry date -- COM-502            
  5551.                 /*$cardExpiryDate = '';
  5552.                 if ($driversLicenseCardExpiry_customField!=null) {
  5553.                     $driversLicenseCardExpiry_value = $this->getDoctrine()->getRepository(CustomFieldValue::class)->findOneBy([
  5554.                                                                                 'customField' => $driversLicenseCardExpiry_customField,
  5555.                                                                                 'entityId' => $d,                
  5556.                                                                             ]);
  5557.                     if ($driversLicenseCardExpiry_value!=null) {
  5558.                         $cardExpiryDate = $driversLicenseCardExpiry_value->__get('value');
  5559.                     }
  5560.                 }*/
  5561.                 $cardExpiryDate $this->calcHelper->getDriverCardExpiryDate($d$driversLicenseCardExpiry_customField);
  5562.                 // next card scan date (same logic as in CalculationHelper::getToDoItems() -- COM-502
  5563.                 /*
  5564.                 $lastCardScanDate = $d->__getDateFormatted('lastCardScanDate', false);
  5565.                 if ($lastCardScanDate==null) {
  5566.                     // lastCardScanDate is null, need to use employment start date instead
  5567.                     $lastCardScanDate = $d->__getDateFormatted('employmentStartDate', false);
  5568.                 }
  5569.                 
  5570.                 $nextCardScanDateDT = (new \DateTime($lastCardScanDate.' 12:00'))->modify('+'.self::APPROACHING_DATE_ITEM_DAYS_CARD_SCAN.' days');
  5571.                 $nextCardScanDate = $todayDT->diff($nextCardScanDateDT)->format('%R%a');
  5572.                 //if (in_array(ToDoItemTypeEnum::STANDARD_DRIVER.'-'.$d->getId(), $toDoItemExceptionLookupArray)) {
  5573.                 //    $nextCardScanDate = '
  5574.                 //}
  5575.                 //$remainingRec, //$this->buildRemainingRecord(CustomFieldTypeEnum::DATE, $listValue),
  5576.                 */
  5577.                 
  5578.                 $nextCardScanDateInfo $this->calcHelper->getDriverCardNextScanDate($d$toDoItemExceptionLookupArray);
  5579.                 // COM-502
  5580.                 $driverVehicleDataArray$d->getId() ] = [
  5581.                     'name' => $d->getName(),
  5582.                     'emplStartDate' => $d->__getDateFormatted('employmentStartDate'),
  5583.                     'emplEndDate' => $d->__getDateFormatted('employmentEndDate'),
  5584.                     'cards' => $d->getCardNumberArray(),
  5585.                     'cardExpiryDate' => $cardExpiryDate,
  5586.                     'nextCardScanDate' => $nextCardScanDateInfo,
  5587.                 ];
  5588.             }
  5589.             //dump('driverActivityDatesArray', $driverActivityDatesArray);
  5590.             //dump('driverDataArray', $driverDataArray);
  5591.             //dump('driverVehicleDataArray', $driverVehicleDataArray);
  5592.             
  5593.         }
  5594.         // delete drivers that don't have activities
  5595.         if (count($driverIdsDelete)>&&
  5596.             !isset($params['include-all-drivers']) || $params['include-all-drivers']==false) {
  5597.             
  5598.             foreach($driverIdsDelete as $drId) {
  5599.                 unset($driversArray[$drId]);
  5600.                 //dump("DEL DR $drId");
  5601.             }
  5602.             //dump('driversArray 2', $driversArray);
  5603.         }
  5604.         // put driversArray into a structure that will be handled by JS
  5605.         // (driversArray is in format ID=>NAME, with IDs not in order; JS sorts the IDs, thus breaking sorting)
  5606.         $driversArray2 = [];
  5607.         if (count($driversArray)>0) {
  5608.             foreach($driversArray as $drId=>$drName) {
  5609.                 $driversArray2[] = [
  5610.                     $drId,
  5611.                     $drName,
  5612.                 ];
  5613.             }
  5614.         }
  5615.         //dump('driversArray2', $driversArray2);
  5616.         // load this company's vehicles' oldest/newest activity dates
  5617.         $vehicleIdsDelete = [];
  5618.         if ($perVehicleReportsAvailable) {
  5619.             $dbArray =  $this->getAllEntityData(Vehicle::class, 'id');
  5620.             foreach($dbArray as $v) {
  5621.                 if ($v->__getDateFormatted('oldestActivityDate')==null && !$allowDriversVehiclesWithoutActivities) {
  5622.                     // do not show vehicles without activities
  5623.                     $vehicleIdsDelete[] = $v->getId();
  5624.                 } else {
  5625.                     // use driver's data
  5626.                     $driverActivityDatesArray'V'.$v->getId() ] = [
  5627.                         'oldest' => $v->__getDateFormatted('oldestActivityDate'),
  5628.                         'newest' => $v->__getDateFormatted('newestActivityDate'),
  5629.                         'display-oldest' => null//$defaultStartDate,
  5630.                         'display-newest' => null//$defaultEndDate,
  5631.                     ];
  5632.                 }
  5633.                 // get field to show for the driver/vehicle popup -- COM-502
  5634.                 $techPermitExpiryDate $this->calcHelper->getTechPermitExpiryDate($v$vehicleTechPermitExpiry_customField);
  5635.                 $nextDownloadDateInfo $this->calcHelper->getTachoDownloadNextScanDate($v$toDoItemExceptionLookupArray);
  5636.                 // get latest company lock record for this vehicle -- COM-502
  5637.                 $rc $this->db->query("SELECT * FROM `data_vehicle_locks` 
  5638.                                          WHERE vehicle_id=".$v->getId()."
  5639.                                          ORDER BY lock_in_time DESC
  5640.                                          LIMIT 1"
  5641.                                     false);
  5642.                 if (!$rc) {
  5643.                     die('error reading data_vehicle_locks');
  5644.                 }           
  5645.                 $dbVehicleLocks $this->db->fetchAll(true);
  5646.                 //if (count($dbVehicleLocks)>0) dump('dbVehicleLocks '.$v->getName(), $dbVehicleLocks);
  5647.                 
  5648.                 $vehicleLockInfo = [
  5649.                     'companyName' => '',
  5650.                     'lockDate' => '',
  5651.                 ];
  5652.                 if ($dbVehicleLocks!=null && is_array($dbVehicleLocks) && count($dbVehicleLocks)>0) {
  5653.                     $vehicleLockInfo['companyName'] = $dbVehicleLocks[0]['company_name'];
  5654.                     $vehicleLockInfo['lockDate'] = $this->timeCalc->unixTimestampToFormattedDateTime($dbVehicleLocks[0]['lock_in_time']);
  5655.                 }
  5656.                 
  5657.                 // get owner from MD if didn't find a lock record
  5658.                 if ($vehicleLockInfo['companyName']=='' && $v->__get('owner')!='') { //T
  5659.                     $vehicleLockInfo['companyName'] = $v->__get('owner');
  5660.                 } //T
  5661.                 
  5662.                 $lastOdoValue $v->__get('lastOdometerValue');
  5663.                 if ($lastOdoValue!=null) {
  5664.                     $lastOdoValue StringHelper::formatNumber($this->company->__get('country'), $lastOdoValuefalse);
  5665.                 }
  5666.                 
  5667.                 // COM-502
  5668.                 $driverVehicleDataArray'V'.$v->getId() ] = [
  5669.                     'name' => $v->getName(),
  5670.                     'techPermitExpiryDate' => $techPermitExpiryDate,
  5671.                     'nextDownloadDate' => $nextDownloadDateInfo,
  5672.                     'owner' => $vehicleLockInfo['companyName'],
  5673.                     'lockDate' => substr($vehicleLockInfo['lockDate'], 010),
  5674.                     'lastOdoValue' => $lastOdoValue,
  5675.                 ];
  5676.             }
  5677.             //dump('driverActivityDatesArray', $driverActivityDatesArray);
  5678.             
  5679.         }
  5680.         //dump('driverVehicleDataArray', $driverVehicleDataArray);
  5681.         
  5682.         $settingsArray = array(
  5683.             'driverVehicleId' => $driverVehicleId,
  5684.             'startDate' => $startDate,
  5685.             'endDate' => $endDate,
  5686.             'reportClass' => $this->reportClass,
  5687.             'ReportQuickFilterType' => [
  5688.                 'LAST_MONTH' => ReportQuickFilterType::LAST_MONTH,
  5689.                 'THIS_MONTH' => ReportQuickFilterType::THIS_MONTH,
  5690.                 'FROM_LAST_WEEKLY_REST' => ReportQuickFilterType::FROM_LAST_WEEKLY_REST,
  5691.             ],
  5692.             'perDriverReportsAvailable' => $perDriverReportsAvailable,
  5693.             'perVehicleReportsAvailable' => $perVehicleReportsAvailable,
  5694.             'driverActivityDatesArray' => $driverActivityDatesArray,
  5695.             'isSuperAdminUser' => ($this->getUser()->getRolesUnconverted()==UserRoleEnum::ROLE_SUPER_ADMIN),
  5696.             'module' => $this->module,
  5697.         );
  5698.         $renderArray $this->buildRenderArray($this->module, [
  5699.             'section_title' => $this->translator->trans('title.reports', array(), 'general'),
  5700.             'settings_js' => json_encode($settingsArray),
  5701.             'entity' => $this->emptyEntity,
  5702.             'driverVehicleId' => $driverVehicleId,
  5703.             'driverVehicleId2' => $driverVehicleId2,
  5704.             'driversArray' => $driversArray,
  5705.             'driversArray2_js' => json_encode($driversArray2),
  5706.             'driverVehicleDataArray_js' => json_encode($driverVehicleDataArray), //COM-502
  5707.             'vehiclesArray' => $vehiclesArray,
  5708.             'driverMode' => $driverMode,
  5709.             'getAllMode' => $getAllMode,
  5710.             'startDate' => $startDate,
  5711.             'endDate' => $endDate,
  5712.             'reportClass' => $this->reportClass,
  5713.             'perDriverReportsAvailable' => $perDriverReportsAvailable,
  5714.             'perVehicleReportsAvailable' => $perVehicleReportsAvailable,
  5715.             'pastReportsArray' => $pastReportsArray,
  5716.             'pastReportsArray_js' => json_encode($pastReportsArray),
  5717.             'driverActivityDatesArray_js' => json_encode($driverActivityDatesArray),
  5718.             'currentUser' => $this->getUser(),
  5719.         ]); //, new Report);
  5720.         $renderArray['page_content_title'] = $this->translator->trans($this->sectionTitleLabel[0], array(), $this->sectionTitleLabel[1]);
  5721.         //dump('renderArray', $renderArray);
  5722.         return $renderArray;
  5723.     }
  5724.     
  5725.     // generic, added for COM-695
  5726.     protected function updateDatatableRequestColumn(&$request$columnNum) {
  5727.     
  5728.         $requestColumns $request->request->get('columns');
  5729.         //dump('requestColumns', $requestColumns);
  5730.         
  5731.         // if column is 'all', then we need to reset search for all types, "all" to blank
  5732.         if ($requestColumns[$columnNum]['search']['value']==='all') {
  5733.             $replacedRequest = [
  5734.                 'draw' => $request->request->get('draw'),
  5735.                 'columns' => $request->request->get('columns'),
  5736.                 'order' => $request->request->get('order'),
  5737.                 'start' => $request->request->get('start'),
  5738.                 'length' => $request->request->get('length'),
  5739.                 'search' => $request->request->get('search'),
  5740.             ];
  5741.             //dump("replacedRequest (col $columnNum)", $replacedRequest);
  5742.             
  5743.             $replacedRequest['columns'][$columnNum]['search']['value'] = '';
  5744.             //dump("replacedRequest (col $columnNum)", $replacedRequest);
  5745.             
  5746.             $request->request->replace($replacedRequest);
  5747.         }
  5748.     
  5749.     }
  5750.     // COM-427
  5751.     protected function getActiveEuMinWageCountries() {
  5752.         if ($this->settings==null || count($this->settings)==0) {
  5753.             $this->settings $this->settingsLoader->getSettings($this->companyfalse);
  5754.         }
  5755.         //dump('settings', $this->settings);
  5756.         // get all min wage countries
  5757.         $minWageCountriesArray $this->formsHelper->getCountries(nullMinimalWageCountryEnum::COUNTRIES);
  5758.         //dump('minWageCountriesArray', $minWageCountriesArray);
  5759.         // if no active have been defined yet, assume all are active
  5760.         if (!isset($this->settings['company']['minimumWageActiveCountries']) ||
  5761.             $this->settings['company']['minimumWageActiveCountries']=='') {
  5762.             //dump('no inactive defined yet');
  5763.             return $minWageCountriesArray;
  5764.             
  5765.         }
  5766.         
  5767.         // now alter minWageCountriesArray to remove those that are inactive
  5768.         $correctedMinWageCountriesArray = [];
  5769.         $minWageActiveCountriesArray explode(';'$this->settings['company']['minimumWageActiveCountries']);
  5770.         foreach($minWageCountriesArray as $country=>$label) {
  5771.             if (!in_array($country$minWageActiveCountriesArray)) continue;
  5772.             $correctedMinWageCountriesArray[$country] = $label;
  5773.         }
  5774.         //dump('correctedMinWageCountriesArray', $minWageActiveCountriesArray);
  5775.         return $correctedMinWageCountriesArray;
  5776.     
  5777.     }
  5778.     // COM-787
  5779.     // function used in list view
  5780.     protected function loadAttachmentInfoForEntity($entityType$entityId
  5781.                                                    &$attachmentsArray, &$entityAttachmentArray, &$entityAttachmentArrayByType) {
  5782.         $attachments $this->getDoctrine()->getRepository(Attachment::class)->findBy([
  5783.                                                                                     'company' => $this->company,
  5784.                                                                                     'entityType' => $entityType,
  5785.                                                                                     'entityId' => $entityId,
  5786.                                                                                     'deleted' => 0,
  5787.                                                                                 ]);
  5788.         //dump("attachments for entity with type $entityType and id $entityId:", $attachments);
  5789.         $attachmentsArray = [];
  5790.         //$attachmentsArrayByType = [];
  5791.         if (count($attachments)>0) {
  5792.             foreach($attachments as $attachment) {
  5793.                     
  5794.                 $attId $attachment->getId();
  5795.                 $attType $attachment->__get('attachmentType');
  5796.                     
  5797.                 $fileNamePartsArray explode("."$attachment->__get('name'));
  5798.                 $extension $fileNamePartsArraycount($fileNamePartsArray)-];
  5799.                 $attachmentRecord = [
  5800.                     'id' => $attachment->getId(),
  5801.                     'fieldName' => $attachment->__get('fieldName'),
  5802.                     'attachmentType' => $attachment->__get('attachmentType'),
  5803.                     'originalFileName' => $attachment->__get('originalFileName'),
  5804.                     'customLabel' => $attachment->__get('customLabel'),
  5805.                     'extension' => $extension,
  5806.                 ];
  5807.                 $attachmentsArray$attId ] = $attachmentRecord;
  5808.                         
  5809.                 if (!isset($entityAttachmentArray$entityId ])) $entityAttachmentArray$entityId ] = [];
  5810.                 $entityAttachmentArray$entityId ][ $attId ] = $attachmentRecord;
  5811.                 if (!isset($entityAttachmentArrayByType$entityId ])) $entityAttachmentArrayByType$entityId ] = [];
  5812.                 if (!isset($entityAttachmentArrayByType$entityId ][ $attType ])) $entityAttachmentArrayByType$entityId ][ $attType ] = [];
  5813.                 $entityAttachmentArrayByType$entityId ][ $attType ][] = $attachmentRecord;
  5814.             }
  5815.         }
  5816.                        
  5817.     }
  5818.     // COM-787
  5819.     // function used on edit view
  5820.     protected function addAttachmentInfoRenderArray(&$renderArray$entity) {
  5821.         $entityId $entity->getId();
  5822.         // attachments
  5823.         if ($this->module=='drivers') {
  5824.         
  5825.             $entityType EntityTypeEnum::DRIVER;
  5826.             
  5827.             $renderArray['attachmentTypesArray'] = AttachmentTypeEnum::getDriverLabels($this->translator);
  5828.             
  5829.             $renderArray['customFieldsWithAttachments'] = [
  5830.                 $_SERVER['APP_DRIVER_HEALTH_EXAM_CUSTOM_FIELD_ID'] => AttachmentTypeEnum::DRIVER_HEALTH_EXAM,
  5831.                 $_SERVER['APP_DRIVER_PAV_PERMIT_CUSTOM_FIELD_ID'] => AttachmentTypeEnum::DRIVER_PAV_PERMIT,
  5832.                 $_SERVER['APP_DRIVER_PERS_IDENTITY_CARD_CUSTOM_FIELD_ID'] => AttachmentTypeEnum::DRIVER_PERS_IDENTITY_CARD,
  5833.                 $_SERVER['APP_DRIVER_INT_TRANSPORT_PERMIT_CUSTOM_FIELD_ID'] => AttachmentTypeEnum::DRIVER_INT_TRANSPORT_PERMIT,
  5834.                 $_SERVER['APP_DRIVER_PASSPORT_CUSTOM_FIELD_ID'] => AttachmentTypeEnum::DRIVER_PASSPORT,
  5835.                 $_SERVER['APP_DRIVER_ADR_PERMIT_CUSTOM_FIELD_ID'] => AttachmentTypeEnum::DRIVER_ADR_PERMIT,
  5836.                 $_SERVER['APP_DRIVER_JOB_MACHINE_LICENSE_CUSTOM_FIELD_ID'] => AttachmentTypeEnum::DRIVER_JOB_MACHINE_LICENSE,
  5837.             ];
  5838.             //dump('customFieldsWithAttachments', $renderArray['customFieldsWithAttachments']);
  5839.         } else {
  5840.             $entityType EntityTypeEnum::VEHICLE;
  5841.             
  5842.             $renderArray['attachmentTypesArray'] = AttachmentTypeEnum::getVehicleLabels($this->translator);
  5843.             $renderArray['customFieldsWithAttachments'] = [
  5844.                 $_SERVER['APP_NEXT_TACHOGRAPH_CALIBRATION_CUSTOM_FIELD_ID'] => AttachmentTypeEnum::VEHICLE_NEXT_TACHO_CALIBR,
  5845.                 $_SERVER['APP_VEHICLE_NEXT_TACHO_INSP_CUSTOM_FIELD_ID'] => AttachmentTypeEnum::VEHICLE_NEXT_TACHO_INSP,
  5846.                 $_SERVER['APP_VEHICLE_ADR_EXPIRY_CUSTOM_FIELD_ID'] => AttachmentTypeEnum::VEHICLE_ADR_EXPIRY,
  5847.                 $_SERVER['APP_VEHICLE_ATP_EXPIRY_CUSTOM_FIELD_ID'] => AttachmentTypeEnum::VEHICLE_ATP_EXPIRY,
  5848.                 $_SERVER['APP_VEHICLE_NEXT_CRANE_STRUCT_TEST_CUSTOM_FIELD_ID'] => AttachmentTypeEnum::VEHICLE_NEXT_CRANE_STRUCT_TEST,
  5849.                 $_SERVER['APP_VEHICLE_CRANE_MAIN_INSP_CUSTOM_FIELD_ID'] => AttachmentTypeEnum::VEHICLE_CRANE_MAIN_INSP,
  5850.                 $_SERVER['APP_VEHICLE_CRANE_SAFETY_INSP_CUSTOM_FIELD_ID'] => AttachmentTypeEnum::VEHICLE_CRANE_SAFETY_INSP,
  5851.                 $_SERVER['APP_VEHICLE_CMR_INSURANCE_CUSTOM_FIELD_ID'] => AttachmentTypeEnum::VEHICLE_CMR_INSURANCE,
  5852.                 $_SERVER['APP_VEHICLE_DOMESTIC_INSURANCE_CUSTOM_FIELD_ID'] => AttachmentTypeEnum::VEHICLE_DOMESTIC_INSURANCE,
  5853.                 $_SERVER['APP_VEHICLE_ROAD_TRANSPORT_CERT_CUSTOM_FIELD_ID'] => AttachmentTypeEnum::VEHICLE_ROAD_TRANSPORT_CERT,
  5854.             ];
  5855.         }
  5856.         
  5857.         $renderArray['attachmentTypesArray_js'] = json_encode($renderArray['attachmentTypesArray']);
  5858.         $renderArray['attachmentTypeNamesArray_js'] = json_encodeAttachmentTypeEnum::getAvailableTypes() );
  5859.         $renderArray['attachmentsArray'] = [];
  5860.         $entityAttachmentArray = [
  5861.             $entityId => [],
  5862.         ];
  5863.         $entityAttachmentArray = [];
  5864.         $entityAttachmentArrayByType = [];
  5865.         $attachments $this->getDoctrine()->getRepository(Attachment::class)->findBy([
  5866.                                                                                     'entityType' => $entityType,
  5867.                                                                                     'entityId' => $entity->getId(),
  5868.                                                                                     'deleted' => 0,
  5869.                                                                                 ]);
  5870.         //dump('attachments', $attachments);
  5871.         foreach($attachments as $attachment) {
  5872.             $attType $attachment->getAttachmentType();
  5873.             if (!isset($renderArray['attachmentsArray'][$attType])) $renderArray['attachmentsArray'][$attType] = [];
  5874.             $fileNamePartsArray explode("."$attachment->__get('name'));
  5875.             $extension $fileNamePartsArraycount($fileNamePartsArray)-];
  5876.         
  5877.             $attachmentRecord = [
  5878.                 'id' => $attachment->getId(),
  5879.                 'attachmentType' => $attType,
  5880.                 'relatedId' => $attachment->getRelatedId(),
  5881.                 'originalFileName' => $attachment->__get('originalFileName'),
  5882.                 'customLabel' => $attachment->__get('customLabel'),
  5883.                 'extension' => $extension,
  5884.             ];
  5885.             $renderArray['attachmentsArray'][$attType][] = $attachmentRecord;
  5886.             if (!isset($entityAttachmentArray$entityId ])) $entityAttachmentArray[$entity->getId()] = [];
  5887.             $entityAttachmentArray$entityId ][$attachment->getId()] = $attachmentRecord;
  5888.             if (!isset($entityAttachmentArrayByType$entityId ])) $entityAttachmentArrayByType$entityId ] = [];
  5889.             if (!isset($entityAttachmentArrayByType$entityId ][ $attType ])) $entityAttachmentArrayByType$entityId ][ $attType ] = [];
  5890.             $entityAttachmentArrayByType$entityId ][ $attType ][] = $attachmentRecord;
  5891.         }
  5892.         $renderArray['entityAttachmentArray_js'] = json_encode($entityAttachmentArray);
  5893.         $renderArray['entityAttachmentArrayByType_js'] = json_encode($entityAttachmentArrayByType);
  5894.         //dump('renderArray', $renderArray['attachmentsArray']);
  5895.     }
  5896.     /****
  5897.     function szamlazz_item_generator($licence_type,$key,$item,&$result)
  5898.     {
  5899.         if ($licence_type == 1) {
  5900.             if (@$key == 'legislation' && is_numeric($item) && $item > 0) {
  5901.                 $details = $this->getDoctrine()->getRepository(LicensePricing::class)->findBy(['type' => 1, 'subtype' => 4, 'name' => $item] );
  5902.                 $name = @$details[0]->invoicetitle ? $details[0]->invoicetitle : 'Jogszabálykövetés';
  5903.                 $result = ['name' => $name,'qty' => 1,  'price' => $details[0]->price];
  5904.             }
  5905.             if (@$key == 'extendedLicenses' && is_numeric($item) && $item > 0) {
  5906.                 $details = $this->getDoctrine()->getRepository(LicensePricing::class)->findBy(['type' => 1, 'subtype' => 1, 'name' => $item] );
  5907.                 $name = @$details[0]->invoicetitle ? $details[0]->invoicetitle : 'Járműlicensz';
  5908.                 $result = ['name' => $name,'qty' => 1,  'price' => $details[0]->price];
  5909.             }
  5910.             if (@$key == 'combo1' && is_numeric($item) && $item > 0) {
  5911.                 $details = $this->getDoctrine()->getRepository(LicensePricing::class)->findBy(['type' => 1, 'subtype' => 2, 'name' => 1] );
  5912.                 $name = @$details[0]->invoicetitle ? $details[0]->invoicetitle : 'Combo1 Licensz';
  5913.                 $result = ['name' => $name,'qty' => $item,  'price' => $details[0]->price*$item];
  5914.             }
  5915.             if (@$key == 'combo10' && is_numeric($item) && $item > 0) {
  5916.                 $details = $this->getDoctrine()->getRepository(LicensePricing::class)->findBy(['type' => 1, 'subtype' => 2, 'name' => 10] );
  5917.                 $name = @$details[0]->invoicetitle ? $details[0]->invoicetitle : 'Combo10 Licensz';
  5918.                 $result = ['name' => $name,'qty' => $item,  'price' => $details[0]->price*$item];
  5919.             }
  5920.             if ($key == 'modules') {
  5921.                 $modules = $this->getDoctrine()->getRepository(LicensePricing::class)->findAll();
  5922.                 $orderedModules = [];
  5923.                 $price = 0;
  5924.                 foreach ($item as $mod) {
  5925.                     foreach ($modules as $module) {
  5926.                         if ($mod == $module->id) {
  5927.                             $orderedModules[] = [
  5928.                                 'name' => $module->name,
  5929.                                 'price' => $module->price,
  5930.                             ];
  5931.                             $price = $price + $module->price;
  5932.                         }
  5933.                     }
  5934.                 }
  5935.                 if (isset($orderedModules)) {
  5936.                     $result = [
  5937.                         'name' => 'Modulok',
  5938.                         'price' => $price,
  5939.                         'qty' => 1
  5940.                     ];
  5941.                 }
  5942.             }
  5943.         }
  5944.         if ($licence_type == 2) {
  5945.             if (@$key == 'base_license' && is_numeric($item)) {
  5946.                 $legislationDetails = $this->getDoctrine()->getRepository(LicensePricing::class)->findBy(['type' => 2, 'subtype' => 1, 'name' => $item] );
  5947.                 $name = @$legislationDetails[0]->invoicetitle ? $legislationDetails[0]->invoicetitle : 'Licensz Ár';
  5948.                 $result = ['name' => $name,'qty' => 1,  'price' => $legislationDetails[0]->price];
  5949.             }
  5950.             if (@$key == 'aetr'  && is_numeric($item)) {
  5951.                 $aetrPrice = $this->getDoctrine()->getRepository(LicensePricing::class)->findBy(['type' => 2, 'subtype' => 2, 'name' => 1]);
  5952.                 if (isset($aetrPrice[0]) && $aetrPrice[0]->price) {
  5953.                     $name = @$aetrPrice[0]->invoicetitle ? $aetrPrice[0]->invoicetitle : 'AETR Licensz';
  5954.                     $result = [
  5955.                         'name' => $name,
  5956.                         'price' => $aetrPrice[0]->price* $item,
  5957.                         'qty' => intval($item)
  5958.                     ];
  5959.                 }
  5960.             }
  5961.             if (@$key == 'labour'  && is_numeric($item)) {
  5962.                 $labourPrice = $this->getDoctrine()->getRepository(LicensePricing::class)->findBy(['type' => 2, 'subtype' => 3, 'name' => 1]);
  5963.                 if (isset($labourPrice[0]) && $labourPrice[0]->price) {
  5964.                     $name = @$labourPrice[0]->invoicetitle ? $labourPrice[0]->invoicetitle : 'Munkaügy Licensz';
  5965.                     $result = [
  5966.                         'name' => $name,
  5967.                         'price' => $labourPrice[0]->price* $item,
  5968.                         'qty' => intval($item)
  5969.                     ];
  5970.                 }
  5971.             }
  5972.             if ($key == 'modules') {
  5973.                 $modules = $this->getDoctrine()->getRepository(LicensePricing::class)->findAll();
  5974.                 $orderedModules = [];
  5975.                 $price = 0;
  5976.                 foreach ($item as $mod) {
  5977.                     foreach ($modules as $module) {
  5978.                         if ($mod == $module->id) {
  5979.                             $orderedModules[] = [
  5980.                                 'name' => $module->name,
  5981.                                 'price' => $module->price,
  5982.                             ];
  5983.                             $price = $price + $module->price;
  5984.                         }
  5985.                     }
  5986.                 }
  5987.                 if (isset($orderedModules)) {
  5988.                     $result = [
  5989.                         'name' => 'Modulok',
  5990.                         'price' => $price,
  5991.                         'qty' => 1
  5992.                     ];
  5993.                 }
  5994.             }
  5995.         }
  5996.         if ($licence_type == 3) {
  5997.             if (@$key == 'credit'  && is_numeric($item)) {
  5998.                 $result = [
  5999.                         'name' => 'Egyenleg feltöltés',
  6000.                         'price' => $item,
  6001.                         'qty' => 1
  6002.                     ];
  6003.                 }
  6004.         }
  6005.     }
  6006.     function szamlazz_hu_generate_invoice($type,$buyer,$email=false,$items,&$result) {
  6007.         require_once(__DIR__.'/../../vendor/SzamlaAgent/phpapi/v2/examples/autoload.php');
  6008.         try {
  6009.             / **
  6010.              * Számla Agent létrehozása alapértelmezett adatokkal
  6011.              *
  6012.              * A számla sikeres kiállítása esetén a válasz (response) tartalmazni fogja
  6013.              * a létrejött bizonylatot PDF formátumban (1 példányban)
  6014.              * /
  6015.             $agent = SzamlaAgentAPI::create($_ENV['szamlazz_hu_api']);
  6016.             / **
  6017.              * Új papír alapú számla létrehozása
  6018.              *
  6019.              * Átutalással fizetendő magyar nyelvű (Ft) számla kiállítása mai keltezési és
  6020.              * teljesítési dátummal, +8 nap fizetési határidővel, üres számlaelőtaggal.
  6021.              * /
  6022.             if ($type == 2){
  6023.                 $invoice = new Proforma();
  6024.             }else{
  6025.                 $invoice = new Invoice(Invoice::INVOICE_TYPE_P_INVOICE);
  6026.                 if (isset($buyer['proforma'])) {
  6027.                     $invoice->getHeader()->setProformaNumber($buyer['proforma']);
  6028.                     $invoice->getHeader()->setPaid(true);
  6029.                 }
  6030.             }
  6031.                 $buyerData = new Buyer($buyer['name'], $buyer['zip'], $buyer['city'], $buyer['address']);
  6032.                 $buyerData->setTaxNumber($buyer['tax']);
  6033.                 if(@$email) {
  6034.                     $buyerData->setSendEmail(true);
  6035.                     $buyerData->setEmail($email);
  6036.                 }
  6037.             // Vevő adatainak hozzáadása (kötelezően kitöltendő adatokkal)
  6038.             $invoice->setBuyer($buyerData);
  6039.             foreach ($items as $item) {
  6040.                 if (@$item['name']) {
  6041.                // $unitPrice = round((($item['price']/$item['qty'])/1.27),0); // 1732,28
  6042.                 $unitPrice = ($item['price']/$item['qty']); // 1732,28
  6043.                 $netPrice = $item['price'];  // 17322
  6044.                 $grossPrice = $netPrice*1.27;
  6045.                 $vat = $grossPrice-$netPrice; // 4676,9
  6046.                 $name = $item['name'];
  6047.                 $Invoiceitem = new InvoiceItem($name, $unitPrice);
  6048.                     $Invoiceitem->setNetPrice($netPrice);
  6049.                     $Invoiceitem->setQuantity($item['qty']);
  6050.                     $Invoiceitem->setVatAmount($vat);
  6051.                     $Invoiceitem->setGrossAmount($grossPrice);
  6052.                 $invoice->addItem($Invoiceitem);
  6053.                 }
  6054.             }
  6055.             // Számla elkészítése
  6056.             if ($type == 2){
  6057.                 $result = $agent->generateProforma($invoice);
  6058.             }else{
  6059.                 $result = $agent->generateInvoice($invoice);
  6060.             }
  6061.             // Agent válasz sikerességének ellenőrzése
  6062.             if ($result->isSuccess()) {
  6063.                 $result->getDocumentNumber();
  6064.                // echo 'A számla sikeresen elkészült. Számlaszám: ' . $result->getDocumentNumber();
  6065.                 // Válasz adatai a további feldolgozáshoz
  6066.                 $return['documentNumber'] = $result->getDocumentNumber();
  6067.                 $return['invData'] = $result->getDataObj()->getUserAccountUrl();
  6068.                 $result = $return;
  6069.             }
  6070.         } catch (\Exception $e) {
  6071.             $agent->logError($e->getMessage());
  6072.             dd($e->getMessage());
  6073.         }
  6074.     }
  6075.     ****/
  6076. }