<?php
namespace App\Base;
use App\Controller\MasterBalanceController;
use App\Entity\Account;
use App\Entity\Company;
use App\Entity\Driver;
use App\Entity\DriverLicense;
use App\Entity\GasPrices;
use App\Entity\KmMultiplier;
use App\Entity\LicenseOrder;
use App\Entity\LicensePricing;
use App\Entity\Licenses;
use App\Entity\LogEntry;
use App\Entity\LogEntry2; // balance log
use App\Entity\Message;
use App\Entity\Vehicle;
use App\Entity\Trailer;
use App\Entity\User;
use App\Entity\Document;
use App\Entity\Setting;
use App\Entity\Balance; // generic, added for COM-831
use App\Entity\InvoiceStore; // generic, added for COM-831
use App\Entity\WorkPeriod;
use App\Entity\DayAssignment;
use App\Entity\DayTitle;
use App\Entity\AttendanceRegisterParams;
use App\Entity\ProtocolParams;
use App\Entity\Attachment; // COM-787
use App\Entity\TachographFile;
use App\Entity\DriverActivity;
use App\Entity\DriverManualActivity;
use App\Entity\DriverBorderCrossing;
use App\Entity\DriverActiveDay;
use App\Entity\DriverMinimumWagePeriod;
use App\Entity\DriverSpecialEvent;
use App\Entity\DriverWeeklyRestTimeException;
use App\Entity\DriverActivityProofSheet;
use App\Entity\Report;
use App\Entity\Report2;
use App\Entity\TravelRoute;
use App\Entity\ToDoItem;
use App\Entity\ToDoItemException; // COM-502
use App\Entity\Consumption;
use App\Entity\DailyAllowance;
use App\Entity\Statistic; //COM-349
use App\Entity\ConsumptionsTanking; //COM-431
//use App\Entity\EmailServerConnection; //COM-819
use App\Entity\EmailTachographFile; //COM-819
use App\Entity\TachoSolveOrder; // COM-822
use App\Entity\TachoSolveClient; // COM-822
use App\Entity\ApiConnection; //COM-API
use App\Entity\Penalty;
use App\Entity\CustomField;
use App\Entity\CustomFieldValue;
use App\Entity\CustomFieldLabel;
use App\Entity\RawDbRecord;
use App\Repository\ConsumptionRepository; //???
use App\Services\TimeCalculator;
use App\Services\SettingsLoader;
use App\Services\DataUpdater;
use App\Services\FormsHelper;
use App\Services\StringHelper;
use App\Services\EmailNotifier;
use App\Services\NameConverter;
use App\Services\DataSynchronizer;
use App\Services\DatabaseConnector;
use App\Services\RoutingHelper;
use App\Services\PenaltyHelper;
use App\Services\DocumentHelper;
use App\Services\LoggingHelper;
use App\Services\LicenseHelper;
use App\Services\MessageHelper;
use App\Services\CalculationHelper;
use App\Services\BalanceHelper;
use App\Services\AIHelper; // COM-695
use App\Services\DriverVehicleDataHelper; // COM-API
use App\Services\ApiHelper; // COM-796
use App\Services\TachoSolveManager; // COM-822
use App\Services\RateLimiter; // generic API, added for COM-822
use App\Type\BalanceTypeEnum;
use App\Type\TypeEnum;
use App\Type\BooleanEnum;
use App\Type\UserRoleEnum;
use App\Type\DriverActivityTypeEnum;
use App\Type\DriverSpecialEventEnum;
use App\Type\DayTitleTypeEnum;
use App\Type\ReportClass;
use App\Type\ReportQuickFilterType;
use App\Type\ReportStatusType;
use App\Type\CustomFieldCategoryEnum;
use App\Type\CustomFieldTypeEnum;
use App\Type\LogChangeTypeEnum;
use App\Type\LogItemTypeEnum;
use App\Type\LicenseTypeEnum;
use App\Type\ToDoItemTypeEnum;
use App\Type\CompanyConfigStatusTypeEnum;
use App\Type\MinimalWageCountryEnum;
use App\Type\BroadcastMessageReactionEnum; // COM-469
use App\Type\CompanyAdminTypeEnum; //COM-481
use App\Type\EntityTypeEnum; // generic, added for COM-787
use App\Type\AttachmentTypeEnum; // COM-787
use App\Type\ApiOriginTypeEnum; // COM-815
use App\Type\CompanySpecialTypeEnum; // COM-831
use App\Type\ApplicationTypeEnum; // COM-796
use App\Type\AccountTypeEnum; // COM-815.a
#use App\Controller\MainController;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\HttpFoundation\Session\Storage\SessionStorageInterface;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Serializer\Serializer;
#use Symfony\Component\Serializer\Encoder\XmlEncoder;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Translation\TranslatorInterface;
use Psr\Log\LoggerInterface;
use Sinergi\BrowserDetector\Browser;
use SunCat\MobileDetectBundle\DeviceDetector\MobileDetector;
class ControllerBase extends Controller
{
protected $translator;
protected $session;
protected $logger;
//protected $doctrine;
protected $router;
protected $mobileDetect;
protected $passwordEncoder;
protected $nc;
protected $db;
protected $symfonyLogger;
protected $timeCalc;
protected $statHelper;
protected $settingsLoader;
protected $settings = array();
protected $gridHelper;
protected $formsHelper;
protected $stringHelper;
protected $penaltyHelper;
protected $docHelper;
protected $licenseHelper;
protected $messageHelper;
protected $calcHelper;
protected $balanceHelper;
protected $ai; // COM-695
protected $dvHelper; // COM-796
protected $apiHelper; // COM-796
protected $tachoSolve; // COM-822
protected $emails;
protected $dataUpdater;
protected $dataImporter;
protected $dataSynchronizer;
protected $rateLimiter; // generic API, added for COM-822
protected $currentYear;
protected $currentWeekName;
protected $currentDate;
protected $readOnly = true;
protected $currentLanguage;
protected $breadcrumbs;
protected $returnURL;
public $overrideCurrentUser = null; // generic, added for COM-707
protected $showSettingsMenu;
protected $redirectRoute = null;
protected $homeRoute = 'companies.index.page';
protected $cookiesToSet = null;
protected $immediatelyAfterLogin = false;
protected $firstLoginConfigMode = false;
protected $newCompanyConfigMode = false;
protected $aiEnabled = false; // COM-709a
protected $aiPaidLicenseThisMonth = false; // COM-709a
protected $disableFlashMessages = false;
protected $keepFlashMessageOpen = false;
protected $enableAttachments = false; // COM-787
protected $enableApi = false; // COM-815
protected $languages = [
'en',
'hu',
'de',
//'sk',
//'ro',
'pl', // COM-660
'it', // COM-793
];
protected $defaultLanguage = 'hu';
protected $interEndpointComm = false;
protected $forceSessionFilter = false;
protected $account;
protected $company;
protected $currentCountry = null;
protected $currentCompanyConfigStatus = null;
protected $module = null;
protected $modulePath = null;
protected $emptyEntity = null;
protected $newEntity = null;
protected $mainCountry = 'hu';
protected $mainCity = 'Budapest';
// used by report controllers only
protected $reportClass;
//protected $perDriverReportsAvailable = false;
//protected $perVehicleReportsAvailable = false;
protected $debug = false;
protected $superAdminDebug = false;
const LOGIN_EXPIRY = 30999; // minutes
const WARNING_BEFORE_LOGOUT = 5; // minutes
const EMPTY_COMPANY_CLASSES = [
Company::class,
Driver::class,
Vehicle::class,
Trailer::class,
Document::class,
];
const PARAMETER_CLASSES = [
WorkPeriod::class,
DayAssignment::class,
DayTitle::class,
AttendanceRegisterParams::class,
ProtocolParams::class,
];
protected $validApiKeyName = [ // COM-796
'APP_API_KEY_FLOTTAWEB',
'APP_API_KEY_TECHSUPP_DEV',
'APP_API_KEY_MINI_RM', // miniRM
'APP_API_KEY_ANDROID', // droid
];
private $modulesAllowedForRegularUsers = array(
'general' => array(
//'modeChange',
'keepAlive' => ['allow'=>true],
),
'subproducts' => array(
'list' => ['allow'=>true],
'view' => ['allow'=>true],
//'create',
//'edit',
'history' => ['allow'=>true], // view/update history
),
'statistics' => array(
'list' => ['allow'=>true],
'view' => ['allow'=>true],
),
'posts' => array(
//'list',
//'view',
//'create',
//'edit',
),
'users' => array(
//'list',
//'view',
//'create',
//'edit',
'password-change' => ['allow'=>true],
),
'settings' => array(
'edit' => ['allow'=>true], // personal settings only
'view' => ['allow'=>true],
),
);
public function __construct(TranslatorInterface $translator, SessionInterface $session, LoggerInterface $symfonyLogger,
UrlGeneratorInterface $router, UserPasswordEncoderInterface $passwordEncoder,
TimeCalculator $timeCalc, SettingsLoader $settingsLoader, FormsHelper $formsHelper,
EmailNotifier $emails, DataUpdater $dataUpdater, StringHelper $stringHelper,
NameConverter $nc, DataSynchronizer $dataSynchronizer, DatabaseConnector $db,
PenaltyHelper $penaltyHelper, DocumentHelper $docHelper, LoggingHelper $logger,
LicenseHelper $licenseHelper, MessageHelper $messageHelper, CalculationHelper $calcHelper,
BalanceHelper $balanceHelper/*, OfflineActionsHelper $offlineHelper */,
AIHelper $ai, // COM-695
DriverVehicleDataHelper $dvHelper, ApiHelper $apiHelper, // COM-API
TachoSolveManager $tachoSolve, // COM-822
RateLimiter $rateLimiter) // generic API, added for COM-822
{
//dump('ControllerBase constructor');
//dump($this);
//dump('session', $session);
//dump(session_id());
//$session->set('jj-var', '12345');
$this->translator = $translator;
$this->session = $session;
$this->logger = $logger;
$this->router = $router;
$this->mobileDetect = new MobileDetector();
//$this->mobileDetect->setCookieSamesite('None');
//dump($this->mobileDetect);
//dump('isMobile', $this->mobileDetect->isMobile());
//$mobileDetector = $this->mobileDetect->get('mobile_detect.mobile_detector');
//dump('isMobile', $mobileDetector->isMobile());
//$mobileDetector->isTablet()
$this->passwordEncoder = $passwordEncoder;
$this->nc = $nc;
$this->db = $db;
$this->penaltyHelper = $penaltyHelper;
$this->docHelper = $docHelper;
$this->symfonyLogger = $symfonyLogger;
$this->timeCalc = $timeCalc;
//$this->gridHelper = $gridHelper;
$this->formsHelper = $formsHelper;
$this->stringHelper = $stringHelper;
$this->emails = $emails;
$this->dataUpdater = $dataUpdater;
$this->dataSynchronizer = $dataSynchronizer;
$this->rateLimiter = $rateLimiter; // generic API, added for COM-822
//$this->statHelper = $statHelper;
$this->settingsLoader = $settingsLoader;
$this->settingsLoader->setTimeCalc($this->timeCalc);
//$this->settings = $this->settingsLoader->getSettings();
//dump('ControllerBase', $this->settingsLoader);
$this->licenseHelper = $licenseHelper;
$this->licenseHelper->setParent($this);
$this->messageHelper = $messageHelper;
$this->messageHelper->setParent($this);
$this->calcHelper = $calcHelper;
$this->balanceHelper = $balanceHelper;
$this->balanceHelper->setParent($this);
$this->ai = $ai; // COM-695
$this->ai->setParent($this); // COM-731
$this->dvHelper = $dvHelper; // COM-796
$this->apiHelper = $apiHelper; // COM-796
$this->tachoSolve = $tachoSolve; // COM-822
//$this->offlineHelper = $offlineHelper;
//$this->licenseHelper->setBalanceHelper($this->balanceHelper);
// create empty entity of the right class (needed for e.g permissions checking)
if ($this->modulePath!=null) {
$this->emptyEntity = new $this->modulePath;
}
$this->currentLanguage = $translator->getLocale();
date_default_timezone_set('Europe/Budapest');
//$this->helper = $helper;
//$this->helper->setParent($this);
/*if (isset($_COOKIE['ACE_settings_menu'])) {
$this->showSettingsMenu = ($_COOKIE['ACE_settings_menu']==='shown');
} else {
$this->showSettingsMenu = true;
}*/
//dump($_COOKIE['ACE_settings_menu']);
//$this->logger->error('MainController opened');
//die('888');
//dump($this);
//dump('keep-flash-message-open', $this->session->get('keep-flash-message-open'));
if ($this->session->get('keep-flash-message-open')!=null) {
if ($this->session->get('keep-flash-message-open')===true) {
$this->keepFlashMessageOpen = true;
}
$this->session->set('keep-flash-message-open', null);
}
// check browser
/*dump($this->mobileDetect);
dump("isMobile: [".$this->mobileDetect->isMobile()."]");
dump("isTablet: [".$this->mobileDetect->isTablet()."]");
dump("isIphone: [".$this->mobileDetect->isIphone()."]");
dump("isIpad: [".$this->mobileDetect->isIpad()."]");
dump("isIOS: [".$this->mobileDetect->isIOS()."]");
dump("isChrome: [".$this->mobileDetect->isChrome()."]");
dump("isSafari: [".$this->mobileDetect->isSafari()."]");*/
}
/*public function setBreadcrumbs($breadcrumbs) {
$this->breadcrumbs = $breadcrumbs;
}
public function setReturnURL($returnURL) {
$this->returnURL = $returnURL;
}
public function getControllerUser() {
return $this->getUser();
}
public function getCurrentYear() {
return $this->currentYear;
}
public function getCurrentYear() {
return $this->currentYear;
}*/
public function getCompany() {
return $this->company;
}
public function getCurrentUser() {
return $this->getUser();
}
public function getCurrentLanguage() {
return $this->currentLanguage;
}
public function getCurrentCountry() {
return $this->currentCountry;
}
public function getCurrentSession() { // generic, added for COM-822
return $this->session;
}
public function getBalanceHelper() {
return $this->balanceHelper;
}
public function addFlash2($type, $text) {
$this->addFlash($type, $text);
}
public function triggerBalanceChange($changeType, $details=null, $calculateWithoutWrite=false) {
$this->balanceHelper->triggerBalanceChange($changeType, $details, $calculateWithoutWrite);
}
public function triggerDriverTokenBalanceChange($changeType, $details=null, $calculateWithoutWrite=false) {
$this->balanceHelper->triggerDriverTokenBalanceChange($changeType, $details, $calculateWithoutWrite);
}
protected function handlePageOpen(&$request, $module=null, $action=null, $entity=null) {
return $this->handleControllerAction($request, $module, $action, $entity, false);
}
protected function handleControllerAction(&$request, $module=null, $action=null, $entity=null, $ajaxCall=false, $parms=null) {
//dump("handlePageOpen(request, $module, $action, entity)");
//dump($request);
//dump($entity);
//dump("user: ", $this->getUser());
//dump('session', $this->session, session_id());
//dump(1);
//dd('--');
// login expiry
//dump(time() - $this->session->getMetadataBag()->getLastUsed(), self::LOGIN_EXPIRY * 60);
/*if (time() - $this->session->getMetadataBag()->getLastUsed() > self::LOGIN_EXPIRY * 60) {
//dump('invalid');
$this->session->invalidate();
$this->redirectRoute = 'b_logout';
return false;
}*/
//dump(2);
//echo "($module || $action)\n";
// check module
if ($request==null || $module==null || $action==null) {
$this->redirectRoute = $this->homeRoute;
return false;
}
$this->timeCalc->refreshTimeZone();
//dump(3);
$thisUserType = ($this->getUser()==null) ? null : $this->getUser()->getRolesUnconverted();
// check if we are immediately after login and in default route (companies list)
//dump($request); die();
if ($this->session->get('immediatelyAfterLogin')!==null && $this->session->get('immediatelyAfterLogin')===true) {
$this->immediatelyAfterLogin = true;
// clear it, don't need it again
$this->session->set('immediatelyAfterLogin', false);
//$this->session->set('immediatelyAfterLoginActions', [
// 'vehicleLicenseCheck'
//]);
// right after login, we can go to previous page opened, or to default companies.index.page (per the security yaml config)
// check which one it is
if ($request->attributes->get('_route')=='companies.index.page') {
// it's companies.index.page, but not every user should or can go there
// correct it here - choose the proper route, and redirect there
$newRoute = RoutingHelper::getDefaultRoute($thisUserType);
if ($newRoute!='companies.index.page') {
$this->redirectRoute = $newRoute;
return false;
}
}
}
if ($this->getUser()==null) {
$this->redirectRoute = 'b_logout';
return false;
}
//dump('3a', $module, $this->getUser()->getUsername()); ///
// set language & locale
$this->setLanguageAndLocale($request);
//dump('3a.1');
$this->calcHelper->setLanguage($this->currentLanguage);
//dump('3a.2');
// check if logged in (if in a logged-in area)
if ($module!='general' && $this->getUser()==null) {
// no user means login session expired, send to login page
$this->redirectRoute = 'b_login';
//dump('3b');
return false;
}
//dump('4');
// get account info from current user
$this->account = $this->getUser()->getAccount();
//dump('account', $this->getUser()->getAccount());
//dump('primaryCompany', $this->account->__get('primaryCompany'));
//var_dump('getCurrentCompanyViewed '.$this->getUser()->getCurrentCompanyViewed()->getName());
// COM-815 ==>
// check if company is still allowed for this user
$allowedCompanyIdsForUser = [];
foreach($this->getUser()->__get('administeredCompanies') as $dbAllowedCompany) {
$allowedCompanyIdsForUser[] = $dbAllowedCompany->getId();
}
//var_dump('allowedCompanyIdsForUser', $allowedCompanyIdsForUser);
if ($this->getUser()->getCurrentCompanyViewed()!=null &&
count($allowedCompanyIdsForUser)>0 &&
($this->getUser()->getRolesUnconverted()==UserRoleEnum::ROLE_USER || $this->getUser()->getRolesUnconverted()==UserRoleEnum::ROLE_ADMIN) && // COM-815a
!in_array($this->getUser()->getCurrentCompanyViewed()->getId(), $allowedCompanyIdsForUser)) {
//var_dump("OVERWRITE WITH ", $allowedCompanyIdsForUser[0] ?? 'x');
$firstAllowedCompany = $this->getDoctrine()->getRepository(Company::class)->findOneById($allowedCompanyIdsForUser[0]);
//var_dump('firstAllowedCompany id: ', $firstAllowedCompany->getId());
$this->getUser()->__set('currentCompanyViewed', $firstAllowedCompany);
//var_dump('user company id: ', $this->getUser()->getCurrentCompanyViewed()->getId());
$rc = $this->getUser()->save( $this->getDoctrine()->getManager(), false );
//dump('update rc='.$rc);
if (!$rc) {
die('user save error');
//return false;
}
}
// <== COM-815
$companyInDb = true;
/**** --> NO, creates other problems, better to change the user's last company
// handle the (rare/development) case when company was deleted
try {
$tmpName = $this->getUser()->getCurrentCompanyViewed()->getName();
} catch(EntityNotFoundException $e) {
$companyInDb = false;
} catch(\EntityNotFoundException $e) {
$companyInDb = false;
} catch(Exception $e) {
$companyInDb = false;
} catch(\Exception $e) {
$companyInDb = false;
}
dump('companyInDb', $companyInDb);
//dump($this->getUser()->getCurrentCompanyViewed());
//dump($this->getUser()->getCurrentCompanyViewed()->deleted);
//$verifiedCompany = $this->getDoctrine()->getRepository(Company::class)->findOneById($this->getUser()->getCurrentCompanyViewed());
****/
// COM-843 ==>
if ($module!='general' && $action!='check-session') {
$this->getUser()->__setDateTime('lastActionAt', 'now');
$this->getUser()->__set('lastModule', $module);
$this->getUser()->__set('lastActionType', $action);
$rc = $this->getUser()->save( $this->getDoctrine()->getManager(), false );
//dump('update rc='.$rc);
if (!$rc) {
die('user save error');
//return false;
}
}
// <== COM-843
//dump($this->getUser()->getCurrentCompanyViewed()); //die();
///superadmin-tacho-solve-orders/download-file/8123
// get company from current user (if exists)
if ($companyInDb &&
$this->getUser()->getCurrentCompanyViewed()!=null &&
$this->getUser()->getCurrentCompanyViewed()->__get('deleted')==false) { // COM-643
// user already chose a company - get the company from the user's last choice
$this->company = $this->getUser()->getCurrentCompanyViewed();
//var_dump('1: '.$this->company->getName());
// in case it's not loaded
if ($this->account==null) {
$this->account = $this->company->getAccount();
}
} else {
// user didn't choose a company yet
if ($this->getUser()->getRolesUnconverted()==UserRoleEnum::ROLE_SUPER_ADMIN ||
$this->getUser()->getRolesUnconverted()==UserRoleEnum::ROLE_TRANSLATOR) { // COM-794
// allowed to not have a company
//dump('2');
} else {
// find this account's main company
if ($this->account->__get('primaryCompany')!=null &&
$this->account->__get('primaryCompany')->__get('deleted')==false) { // COM-643
// use that company
//dump('using primary company');
$this->company = $this->account->__get('primaryCompany');
//dump('3');
} else {
// find any company of this account - JNOTE: earliest/assigned
$accountCompanies = $this->account->__get('companies');
//dump('4');
foreach($accountCompanies as $accountCompany) {
//dump('accountCompany', $accountCompany);
if ($accountCompany->__get('deleted')==true) continue; // COM-643
$this->company = $accountCompany;
//$this->account = $this->company->getAccount();
break;
}
}
}
}
//var_dump('this->company: '.$this->company->name);
//dump('account type', $this->account->__get('type'));
$this->currentCountry = ($this->company!=null) ? $this->company->getCountry() : null;
//dump($this);
// COM-SEC
// check the entity being accessed belongs to this company
if ($entity!=null && $entity->getId()!='') {
//dump('entity company check');
if ($module=='companies') { //T
if ($entity->getAccount() != $this->account) {
//dd('1');
$this->redirectRoute = 'noaccess.page';
return false;
}
} else if ($module=='users') { //T
if ($entity->getAccount() != $this->account) {
//dd('2');
$this->redirectRoute = 'noaccess.page';
return false;
}
} else if (property_exists($entity, 'company') &&
$entity->getCompany() != $this->company) {
if ($request->isXmlHttpRequest()==false) {
//dd('3');
$this->redirectRoute = 'noaccess.page';
return false;
} else {
}
//die('no permission');
}
//JNOTE: check AJAX?
}
/****
$requestCompanyId = $request->request->get('companyId');
//dump('requestCompanyId', $requestCompanyId);
//dump('this->company', $this->company);
//dump('module', $module);
//dump('entity', $entity);
// check if company is correct for this entity
$companyChanged = false;
if ($requestCompanyId!=null && $this->company->getId()!=$requestCompanyId) {
// we know that the company id has changed, by a post parameter in an AJAX call
$companyChanged = true;
//$newRoute = RoutingHelper::getDefaultRoute($thisUserType);
//die($newRoute);
//$this->redirectRoute = $newRoute;
//return false;
} else if ($entity!=null && $entity->getId()!=null &&
!in_array($module, ['companies', 'penalties'])) {
//JNOTE: check if companies list for different account??
// check if the company changed, by looking at current entity, etc
// this is used more for page opens (e.g. editing driver 78),
// 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)
//dump('entity', $entity);
if ($module=='users') {
//dump($entity, $this->company, $this->account);
if ($entity->getAccount()!=$this->company->getAccount()) {
$companyChanged = true;
}
} else if ($module=='messages') {
// check from or to
} else if (property_exists($entity, 'company')) {
if ($entity->getCompany()!=$this->company) {
$companyChanged = true;
}
}
}
****/
if (0&&$companyChanged) {
$newRoute = RoutingHelper::getDefaultRoute($thisUserType);
//die($newRoute);
$this->redirectRoute = $newRoute;
return false;
}
if (isset($_SERVER['APP_DEVELOPER_USER']) && $_SERVER['APP_DEVELOPER_USER']==$this->getUser()->getUsername()) {
$this->superAdminDebug = true;
}
// now that we know the company, we can load the settings
$this->settings = $this->settingsLoader->getSettings( $this->company );
//dump($this->settings);
// and prepare the logger for saving data for this company
$this->logger->setCompany( $this->company );
// and prepare the license helper, for any license/order actions
$activeLicense = null;
if ($this->company!=null) {
$this->balanceHelper->setCompany( $this->company );
$this->licenseHelper->setCompany( $this->company );
$activeLicense = $this->licenseHelper->getActiveLicense( $this->company->getId() );
$this->messageHelper->setCompany( $this->company );
//dump($activeLicense);
}
/*if (isset($activeLicense['action']) && $activeLicense['action']=='redirect') {
// JNOTE
} else if ($activeLicense['sum']['license_type']==LicenseTypeEnum::DRIVER) {
//dump('activeLicense', $activeLicense);
$this->licenseHelper->getDriverLicenseForDriver(958, $this->company, LicenseTypeEnum::DRV_LIC_AETR,
'2010-02', //$startDate,
'2011-01', //$endDate = false,
$driverLicenseAssignments);
//dump('driverLicenseAssignments', $driverLicenseAssignments);
}*/
//dd('--');
// check user permission (voters) - except for general module (login, etc.)
// MUST be here - voters check licenseHelper
if ($module!='general') {
//dd("denyAccessUnlessGranted", $action, $entity);
$this->denyAccessUnlessGranted($action, $entity);
// NOTE: control won't go here;
// - if it's a page, the user is sent to the "no access" page
// - if ajax request, an error JSON is returned
//die('XXX');
}
//dump('4');
// This session variable is used to log out the user automatically. (After self::LOGIN_EXPIRY is reached, the page will log the user out.)
// The last user action must be kept here, because just a javascript timer on the page is not enough. Reason:
// - The JS timer would have to be per page, but multiple pages can be open (different browser tabs), each with different page open time,
// and tabs out of focus (opened earlier) can log out all other tabs (opened later).
// - Hence, the timer must be on the server side.
if ($module!='general' || $action!='check-session') {
// Save the last user action time (other than automated check-session). This starts the countdown,
// which will log the user out, once self::LOGIN_EXPIRY is reached on the current page. (Due to page open, or ajax call.)
$this->session->set('last-user-action-time', time());
//dump('updating last-user-action-time', $this->session->get('last-user-action-time'));
}
// get info about current company & account
$numCompaniesInAccount = 0;
if ($this->account!=null) {
$numCompaniesInAccount = count($this->account->getCompanies());
}
// get current company config status
$this->currentCompanyConfigStatus = null;
if ($activeLicense!=null) {
$this->currentCompanyConfigStatus = $this->checkCurrentCompanyConfigStatus($activeLicense);
}
//dump("currentCompanyConfigStatus: $this->currentCompanyConfigStatus, numCompaniesInAccount: $numCompaniesInAccount"); //die();
//dump('activeLicense', $activeLicense); die();
// get current company AI status - COM-709a
if (!$this->firstLoginConfigMode) {
// check if AI enabled
if (in_array($this->getUser()->getRolesUnconverted(), [UserRoleEnum::ROLE_SUPER_ADMIN,
UserRoleEnum::ROLE_ACCOUNT_OWNER,
UserRoleEnum::ROLE_ADMIN])) {
$this->aiEnabled = true;
//dump('aiEnabled');
}
// COM-831
// AI is disabled for ToDo-only companies
if ($this->company!==null && $this->company->__get('specialType')==CompanySpecialTypeEnum::TODO_ONLY) {
$this->aiEnabled = false;
}
// get company paid AI status
if ($this->aiEnabled) {
$currentMonthNum = intval(date('m'));
$currentMonthAIPaidLicense = $this->settings['ai']['tipMonthlyLicences'][$currentMonthNum-1];
//dump('currentMonthAIPaidLicense: '.$currentMonthAIPaidLicense);
// COM-731
if (isset($_SERVER['APP_AI_ALWAYS_ALLOW_PAID_FOR_COMPANY_TYPES']) &&
$_SERVER['APP_AI_ALWAYS_ALLOW_PAID_FOR_COMPANY_TYPES']!='' &&
$this->company!==null) {
$companyTypesAllowingPaidAI = explode(',', $_SERVER['APP_AI_ALWAYS_ALLOW_PAID_FOR_COMPANY_TYPES']);
if (in_array($this->company->__get('adminType'), $companyTypesAllowingPaidAI)) {
$this->aiPaidLicenseThisMonth = true;
//dump('auto allow paid Bob, company type: '.$this->company->__get('adminType'));
//dump('.');
} else {
if ($currentMonthAIPaidLicense==1) {
$this->aiPaidLicenseThisMonth = true;
//dump('aiPaidLicenseThisMonth');
}
}
} else {
if ($currentMonthAIPaidLicense==1) {
$this->aiPaidLicenseThisMonth = true;
//dump('aiPaidLicenseThisMonth');
}
}
}
if ($this->superAdminDebug && !($request->isXmlHttpRequest())) {
//dump("aiEnabled: $this->aiEnabled, aiPaidLicenseThisMonth: $this->aiPaidLicenseThisMonth");
}
}
// API -- COM-815
$inputArray['apiAllowed'] = '0';
if ($this->getUser()->getRolesUnconverted()==UserRoleEnum::ROLE_SUPER_ADMIN ||
$this->getUser()->getRolesUnconverted()==UserRoleEnum::ROLE_ACCOUNT_OWNER) {
if (isset($_SERVER['APP_API_COMPANY_IDS']) && $_SERVER['APP_API_COMPANY_IDS']!='' &&
$this->company!==null) {
$apiCompanyIds = explode(',', $_SERVER['APP_API_COMPANY_IDS']);
//dump($apiCompanyIds);
if (in_array($this->company->getId(), $apiCompanyIds)) {
$this->enableApi = true;
$inputArray['apiAllowed'] = '1';
//dump('IN');
}
}
}
/*
const INITIAL = 0; // company created, no config yet
const CONFIG_COMPLETE = 50; // config complete, order not placed
const ORDER_PLACED = 75; // order placed, not completed
const ACTIVE = 100; // order completed/company activated
const LICENSE_EXPIRED = 110; // previously active company, license expired
if ($numCompaniesInAccount == 1) {
if ($companyConfigurationStep < 7) {
// didn't complete configuration, must be forced to edit the config popup
$this->newCompanyConfigMode = true;
} else {
// completed config, check if balance is set
// apply permissions based on user role & company configuration state
if ($this->getUser()->getRolesUnconverted()==UserRoleEnum::ROLE_ACCOUNT_OWNER) {
$companyH = ($this->company->configurationStep >= 7);
//dump("numCompaniesInAccount: $numCompaniesInAccount, companyConfigurationStep: $companyConfigurationStep");
dump('num companies in account', count($this->account->getCompanies()));
dump('configurationStep', $this->company->configurationStep);
// no user means login session expired, send to login page
$this->redirectRoute = 'b_login';
//dump('3b');
return false;
*/
// 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)
$ajaxCall = ($request->isXmlHttpRequest());
//dump("ajaxCall: $ajaxCall");
//dump("currentCompanyConfigStatus: $this->currentCompanyConfigStatus, numCompaniesInAccount: $numCompaniesInAccount"); //die();
//dump($ajaxCall, $module, $action, $parms);
// special logic to bypass further permission checks
if ($ajaxCall && $module=='general' && $action=='check-session') {
// check session, no need
return true;
} else if ($ajaxCall &&
$module=='general' && $action=='general' &&
isset($parms['lastConfigStep']) && $parms['lastConfigStep']===true) {
// if on last step of configuration popup, we can't continue (or the code below will throw 'no-access-to-company-with-no-license')
return true;
} else if ($ajaxCall && $module=='general' && $action=='message-reaction') { // COM-792
// if on broadcast mesage popup, we can't continue (or the code below will throw 'no-access-to-company-with-no-license')
return true;
} else if ($ajaxCall &&
$module=='companies' && $action=='view' &&
isset($parms['changeToCompany'])) {
// allow change to new company - this will be followed by a page reload (at new company),
// and then this logic will be re-run for the new company (allowing or disallowing access as needed)
// NOTE: if user on 'no-access-to-company-with-no-license' page, then changes company to another with a valid license,
// he will be moved to another page - see MainController::company_not_ready_page()
//$newCompany = $this->getDoctrine()->getRepository(Company::class)->findOneById($parms['changeToCompany']);
return true;
}
//// that's all needed if this is an ajax call
//if ($ajaxCall==true) return true;
//dump($this->getUser()->__get('firstLoginConfigAt'));
//// PAGE OPEN ONLY FROM HERE ON DOWN
$onNoAccessPage = ($request->getPathInfo() == '/no-access');
$onNoAccessCompanyNotReadyPage = ($request->getPathInfo() == '/company-not-ready');
$onBalancePage = (substr($request->getPathInfo(),0,8) == '/balance');
// check for which pages the user is allowed to access - based on user type, and company config stage
if ($this->getUser()->getRolesUnconverted()==UserRoleEnum::ROLE_SUPER_ADMIN) {
// Compass user - full access, no need to create popup, send to any page, or do anything else;
// just proceed
} else if ($this->getUser()->getRolesUnconverted()==UserRoleEnum::ROLE_ACCOUNT_OWNER) {
// Registered user - can configure company, order/extend licenses
// (access depends on company config status)
//dump('ROLE_ACCOUNT_OWNER', $this->currentCompanyConfigStatus, ($this->currentCompanyConfigStatus==CompanyConfigStatusTypeEnum::CONFIG_COMPLETE));
if ($this->currentCompanyConfigStatus==CompanyConfigStatusTypeEnum::INITIAL) {
// initial status, need to show company config popup (cannot be closed)
if ($this->getUser()->__get('firstLoginConfigAt')==null) {
// first login, this user can only configure the company, can't do anything else
$this->firstLoginConfigMode = true;
} else if ($this->company->__get('configurationStep') < 7) {
// new company, this user can
$this->newCompanyConfigMode = true;
}
// JNOTE: need to differentiate between firstLoginConfigMode and newCompanyConfigMode above???
} else if ($this->currentCompanyConfigStatus==CompanyConfigStatusTypeEnum::CONFIG_COMPLETE) {
// config completed, need to send the user to the Balance page, so he places the order
// place an order - and no access to other pages
//dump('CONFIG_COMPLETE');
if ($this->immediatelyAfterLogin) {
// if right after login, go to balance only
$allowedModules = [
'balance',
];
} else {
// later, allow other pages too
if ($numCompaniesInAccount==1) {
// there is only one company, allow the following
$allowedModules = [
'documents',
'balance',
'messages',
'companies',
];
} else {
// there is only one company, allow the same as above
$allowedModules = [
'documents',
'balance',
'messages',
'companies',
'users',
];
}
// JNOTE: those not available should be grayed out maybe
}
//dump('allowedModules', $allowedModules, $module, in_array($module, $allowedModules)); die();
if (!in_array($module, $allowedModules)) {
throw new AccessDeniedException('no-access-to-company-with-no-license');
}
} else if ($this->currentCompanyConfigStatus==CompanyConfigStatusTypeEnum::ORDER_PLACED) {
// order placed, now the user needs to wait for Compass to activate the license (e.g. when money comes in)
//dump('ORDER_PLACED');
if ($this->immediatelyAfterLogin) {
// if right after login, go to balance only
$allowedModules = [
'balance',
];
} else {
// later, allow other pages too
if ($numCompaniesInAccount==1) {
// there is only one company, allow the following
$allowedModules = [
'documents',
'balance',
'messages',
'companies',
];
} else {
// there is only one company, allow the same as above
$allowedModules = [
'documents',
'balance',
'messages',
'companies',
'users',
];
}
// JNOTE: those not available should be grayed out maybe
}
//dump('allowedModules', $allowedModules, $module, in_array($module, $allowedModules)); die();
if (!in_array($module, $allowedModules)) {
throw new AccessDeniedException('no-access-to-company-with-no-license');
}
} else { // ACTIVE, LICENSE_EXPIRED
// company is active, license is active (or expired): allow full access to this company
}
} else if ($this->getUser()->getRolesUnconverted()==UserRoleEnum::ROLE_ADMIN ||
$this->getUser()->getRolesUnconverted()==UserRoleEnum::ROLE_UPLOAD_ONLY || // COM-639
$this->getUser()->getRolesUnconverted()==UserRoleEnum::ROLE_UPLOAD_PROTOCOL) { // COM-639
// Admin user - can order/extend licenses, cannot create or configure new companies
// (access depends on company config status)
if ($this->currentCompanyConfigStatus==CompanyConfigStatusTypeEnum::CONFIG_COMPLETE) {
// config completed, need to send the user to the Balance page, so he places the order
// place an order - and no access to other pages
//dump('CONFIG_COMPLETE');
if ($this->immediatelyAfterLogin) {
// if right after login, go to balance only
$allowedModules = [
'balance',
];
} else {
// later, allow other pages too
if ($numCompaniesInAccount==1) {
// there is only one company, allow the following
$allowedModules = [
'documents',
'balance',
'messages',
'companies',
];
} else {
// there is only one company, allow the same as above
$allowedModules = [
'documents',
'balance',
'messages',
'companies',
'users',
];
}
// JNOTE: those not available should be grayed out maybe
}
//dump('allowedModules', $allowedModules, $module, in_array($module, $allowedModules)); die();
if (!in_array($module, $allowedModules)) {
throw new AccessDeniedException('no-access-to-company-with-no-license');
}
} else if ($this->currentCompanyConfigStatus==CompanyConfigStatusTypeEnum::ORDER_PLACED) {
// order placed, now the user needs to wait for Compass to activate the license (e.g. when money comes in)
//dump('ORDER_PLACED');
if ($this->immediatelyAfterLogin) {
// if right after login, go to balance only
$allowedModules = [
'balance',
];
} else {
// later, allow other pages too
if ($numCompaniesInAccount==1) {
// there is only one company, allow the following
$allowedModules = [
'documents',
'balance',
'messages',
'companies',
];
} else {
// there is only one company, allow the same as above
$allowedModules = [
'documents',
'balance',
'messages',
'companies',
'users',
];
}
// JNOTE: those not available should be grayed out maybe
}
//dump('allowedModules', $allowedModules, $module, in_array($module, $allowedModules)); die();
if (!in_array($module, $allowedModules)) {
throw new AccessDeniedException('no-access-to-company-with-no-license');
}
} else { // ACTIVE, LICENSE_EXPIRED
// company is active, license is active (or expired): allow full access to this company
}
} else if ($this->getUser()->getRolesUnconverted()==UserRoleEnum::ROLE_TRANSLATOR) { // COM-794
// no company permission/configuration check needed
} else { // VIEWER
// Viewer user - limited access to some pages only
// (access depends on company config status)
//dump('$this->currentCompanyConfigStatus (VIEWER types)', $this->currentCompanyConfigStatus);
if ($this->currentCompanyConfigStatus==CompanyConfigStatusTypeEnum::ACTIVE ||
$this->currentCompanyConfigStatus==CompanyConfigStatusTypeEnum::LICENSE_EXPIRED) {
// license is active or expired: allow access to this company
/*if ($onNoAccessCompanyNotReadyPage) {
$newRoute = RoutingHelper::getDefaultRoute( $this->getUser()->getRolesUnconverted() );
//return new Response(new RedirectResponse( $this->router->generate($newRoute) ));
//return new RedirectResponse($newRoute);
$this->redirectRoute = $newRoute;
return false;
dd('onNoAccessCompanyNotReadyPage', $newRoute);
}*/
} else {
// do not allow access, send to an error page
if (!$onNoAccessCompanyNotReadyPage) {
throw new AccessDeniedException('no-access-to-not-configured-company');
}
}
}
/***
// check for first login configuration
if ($this->getUser()->getRolesUnconverted()==UserRoleEnum::ROLE_ACCOUNT_OWNER) {
if ($this->getUser()->__get('firstLoginConfigAt')==null) {
// first login, this user can only configure the company, can't do anything else
$this->firstLoginConfigMode = true;
} else if ($this->company->__get('configurationStep') < 7) {
// new company, this user can
$this->newCompanyConfigMode = true;
}
// JNOTE: other user types should not be allowed to do this
}
****/
return true;
}
// COM-API
protected function handleControllerApiAction(&$request, $action=null, $apiUser=null,
$apiKey=null, $companyUuid=null, $company=null) { //miniRM
//dump("handleControllerApiAction request, $action, $apiKey, $companyUuid");
/****
// check module
if ($request==null || $module==null || $action==null) {
$this->redirectRoute = $this->homeRoute;
return false;
}
****/
//$this->timeCalc->refreshTimeZone();
// ----- CHECK RATE LIMIT (DDOS prevention) -----
// apply limiting the request frequency to prevent DDOS
/*$rc = $this->checkApiRequestRateLimit();
if ($rc!==true) {
return $rc;
}*/
if (0) {
$this->rateLimiter->applyRateLimit($request); //$clientEmail, $apiType)
die("----\n");
}
// ----- VALIDATE API KEY -----
// get API key from Request & validate it
if ($apiKey==null) { //miniRM
$apiKey = $request->request->get('apiKey');
if ($apiKey==null) {
return 'missing-key';
}
}
//echo "input apiKey: [$apiKey]\n";
$apiKeyValid = false;
//$validApiKeyNames = ApiOriginTypeEnum::getValidApiKeyNames(); //API
foreach($this->validApiKeyName as $apiKeyName) {
//echo("$apiKeyName: "); echo($_SERVER[$apiKeyName]); echo("\n");
if (isset($_SERVER[$apiKeyName])) {
if ($apiKey==$_SERVER[$apiKeyName]) {
$apiKeyValid = true;
//dump("API key $apiKeyName matched");
break;
}
}
}
//dump($this->validApiKeyName);
if (!$apiKeyValid) {
//dump('bad key');
return 'invalid-key';
}
// ----- CHECK RATE LIMIT (DDOS prevention) -----
// apply limiting the request frequency to prevent DDOS
//$this->rateLimiter->applyRateLimit($request);
$originType = null;
$originId = null;
//die($apiKey.' ?= '.$_SERVER['APP_API_KEY_ANDROID']);
$company = null;
$companyChosen = false;
// different logic based on app type (android, MiniRm)
if (isset($_SERVER['APP_API_KEY_ANDROID']) && //COM-822
$apiKey==$_SERVER['APP_API_KEY_ANDROID']) {
//dd('tacho solve');
$this->tachoSolve->setCurrentUser($apiUser);
$ret = $this->tachoSolve->processApiRequest($request);
//dump('processApiRequest ret', $ret);
//LoggingHelper::var_dump('processApiRequest::ret', $ret);
if (!isset($ret['success'])) {
// error
return $ret;
}
// the company was either created in TachoSolveManager class,
// or it was loaded from the already-existing order
if ($ret['currentCompany']!=null) {
//$this->company = null;
//$this->account = null;
$company = $ret['currentCompany'];
//$this->account = $this->company->getAccount();
$companyChosen = true;
}
$this->apiHelper->setTachoSolveMode();
$this->apiHelper->setOriginType($ret['originType']);
$this->apiHelper->setOriginId($ret['originId']);
} else if (isset($_SERVER['APP_API_KEY_MINI_RM']) && // check for mini-RM -- COM-839
$apiKey==$_SERVER['APP_API_KEY_MINI_RM']) {
//JNOTE-TEMP
$ret = [
'originType' => ApplicationTypeEnum::API_MINI_RM,
'originId' => null,
];
$company = $this->getDoctrine()->getRepository(Company::class)->findOneById(225);
$companyChosen = true;
$this->apiHelper->setMiniRmMode();
$this->apiHelper->setOriginType($ret['originType']);
$this->apiHelper->setOriginId($ret['originId']);
// this tells the code to not clear EntityManager after each file (otherwise things don't work)
$this->apiHelper->setMultiFileMode();
} else {
// default API
$this->apiHelper->setOriginType(ApplicationTypeEnum::API_CLIENT);
//$this->apiHelper->setOriginId($originId);
//JNOTE: check other API keys, etc.?
}
// COM-815
//$originInfo = ApiOriginTypeEnum::getOriginFromApiKey($apiKey);
//$this->apiHelper->setOriginType($originInfo['originType']);
//$this->apiHelper->setOriginId($originInfo['originId']); //JNOTE
if ($originType!==null) $this->apiHelper->setOriginType($originType);
if ($originId!==null) $this->apiHelper->setOriginId($originId);
// ----- VALIDATE COMPANY -----
// get company from Request & validate it (all requests need company!)
if ($companyChosen==false) {
if ($companyUuid==null && $company==null) { //miniRM
//$companyUuid = $request->query->get('company');
$companyUuid = $request->request->get('company');
//LoggingHelper::var_dump('companyUuid (query)', $companyUuid);
if ($companyUuid==null) {
return 'missing-company';
}
} else if ($company!==null) {
$companyUuid = $company->__get('uuid');
}
}
// JNOTE: check format, check for injection
// find company
if ($companyChosen==false &&
$company===null) {
$companyRepository = $this->getDoctrine()->getRepository(Company::class);
$company = $companyRepository->findOneBy([
'uuid' => $companyUuid, //'a97eb1f8-ae46-11ef-905d-0050568c',
'deleted' => 0,
]);
}
//dd(); //'company', $company);
//dump('company;', $company->getName());
if ($company==null) {
return 'invalid-company';
}
$this->company = $company;
$userRepository = $this->getDoctrine()->getRepository(User::class);
//$this->currentUser = $userRepository->findOneById($_SERVER['APP_API_USER_ID']);
//$this->setUser($this->currentUser); //???
/*
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
// main - your main firewall key
$token = new UsernamePasswordToken($user, null, 'main', $user->getRoles());
$tokenStorage->setToken($token);
*/
/****
$thisUserType = ($this->getUser()==null) ? null : $this->getUser()->getRolesUnconverted();
if ($this->getUser()==null) {
$this->redirectRoute = 'b_logout';
return false;
}
//dump('3a', $module, $this->getUser()->getUsername()); ///
// set language & locale
$this->setLanguageAndLocale($request);
//dump('3a.1');
$this->calcHelper->setLanguage($this->currentLanguage);
****/
//dump('3a.2');
$this->currentCountry = ($company!=null) ? $company->getCountry() : null;
//dump($this);
//if (isset($_SERVER['APP_DEVELOPER_USER']) && $_SERVER['APP_DEVELOPER_USER']==$this->getUser()->getUsername()) {
// $this->superAdminDebug = true;
//}
// now that we know the company, we can load the settings
$this->settings = $this->settingsLoader->getSettings( $company );
//dump($this->settings);
// and prepare the logger for saving data for this company
$this->logger->setCompany( $company );
// and prepare the license helper, for any license/order actions
$activeLicense = null;
if ($this->company!=null) {
$this->balanceHelper->setCompany( $company );
$this->licenseHelper->setCompany( $company );
$activeLicense = $this->licenseHelper->getActiveLicense( $company->getId() );
$this->messageHelper->setCompany( $company );
//dump($activeLicense);
}
//dd('--');
/****
// check user permission (voters) - except for general module (login, etc.)
// MUST be here - voters check licenseHelper
if ($module!='general') {
//dd("denyAccessUnlessGranted", $action, $entity);
$this->denyAccessUnlessGranted($action, $entity);
// NOTE: control won't go here;
// - if it's a page, the user is sent to the "no access" page
// - if ajax request, an error JSON is returned
//die('XXX');
}
****/
//dump('4');
// get info about current company & account
$numCompaniesInAccount = 0;
if ($this->account!=null) {
$numCompaniesInAccount = count($this->account->getCompanies());
}
// get current company config status
$this->currentCompanyConfigStatus = null;
if ($activeLicense!=null) {
$this->currentCompanyConfigStatus = $this->checkCurrentCompanyConfigStatus($activeLicense);
}
//dump("currentCompanyConfigStatus: $this->currentCompanyConfigStatus, numCompaniesInAccount: $numCompaniesInAccount"); //die();
//dump('activeLicense', $activeLicense); die();
// 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)
//$ajaxCall = ($request->isXmlHttpRequest());
//dump("ajaxCall: $ajaxCall");
//dump("currentCompanyConfigStatus: $this->currentCompanyConfigStatus, numCompaniesInAccount: $numCompaniesInAccount"); //die();
//dump($ajaxCall, $module, $action, $parms);
/****
// special logic to bypass further permission checks
if ($ajaxCall && $module=='general' && $action=='check-session') {
// check session, no need
return true;
} else if ($ajaxCall &&
$module=='general' && $action=='general' &&
isset($parms['lastConfigStep']) && $parms['lastConfigStep']===true) {
// if on last step of configuration popup, we can't continue (or the code below will throw 'no-access-to-company-with-no-license')
return true;
} else if ($ajaxCall && $module=='general' && $action=='message-reaction') { // COM-792
// if on broadcast mesage popup, we can't continue (or the code below will throw 'no-access-to-company-with-no-license')
return true;
} else if ($ajaxCall &&
$module=='companies' && $action=='view' &&
isset($parms['changeToCompany'])) {
// allow change to new company - this will be followed by a page reload (at new company),
// and then this logic will be re-run for the new company (allowing or disallowing access as needed)
// NOTE: if user on 'no-access-to-company-with-no-license' page, then changes company to another with a valid license,
// he will be moved to another page - see MainController::company_not_ready_page()
//$newCompany = $this->getDoctrine()->getRepository(Company::class)->findOneById($parms['changeToCompany']);
return true;
}
****/
//// that's all needed if this is an ajax call
//if ($ajaxCall==true) return true;
//dump($this->getUser()->__get('firstLoginConfigAt'));
return true;
}
private function checkApiRequestRateLimit() {
$apiConnectionRepository = $this->getDoctrine()->getRepository(ApiConnection::class);
// check how many calls from this API address, ApiConnection::API_CALLS_PERIOD_SECONDS in the past
$numRecentCalls = $apiConnectionRepository->getNumRecentApiCallsFromIpAddress(ApiConnection::API_CALLS_PERIOD_SECONDS, $_SERVER['REMOTE_ADDR']);
//var_dump($numRecentCalls);
//echo "numRecentCalls: $numRecentCalls\n";
if ($numRecentCalls <= ApiConnection::MAX_NUM_API_CALLS_PER_PERIOD) {
// rate limit not reached, add the record to db
$apiConnection = new ApiConnection;
$apiConnection->__set('ipAddress', $_SERVER['REMOTE_ADDR']);
$rc = $apiConnection->save( $this->getDoctrine()->getManager() );
if (!$rc) {
die('error creating apiConnection');
}
return true;
} else {
return 'too-many-requests';
}
}
private function checkCurrentCompanyConfigStatus($activeLicense=null) {
// if current company not selected (i.e. Compass user), return null
if ($this->company===null) return null;
//$numCompaniesInAccount = count($this->account->getCompanies());
//dump('configurationStep', $this->company->configurationStep); //, $this->company);
// check if company config completed
if ($this->company->configurationStep < 7) {
return CompanyConfigStatusTypeEnum::INITIAL;
}
// check if order placed
if ($activeLicense==null) $activeLicense = $this->licenseHelper->getActiveLicense( $this->company->getId() );
//dump('activeLicense', $activeLicense);
if (isset($activeLicense['action']) && $activeLicense['action']==='redirect') {
if (!isset($activeLicense['active_order']) || $activeLicense['active_order']===0) {
return CompanyConfigStatusTypeEnum::CONFIG_COMPLETE;
} else {
return CompanyConfigStatusTypeEnum::ORDER_PLACED;
}
}
// check if there is a license
if (isset($activeLicense['sum'])) {
$status = CompanyConfigStatusTypeEnum::ACTIVE;
// JNOTE: company license expired (LICENSE_EXPIRED) - need something here?
return $status;
}
return false;
}
protected function setLanguageAndLocale($request) {
//dump($this->session->get('language'));
// set language & locale
$language = $request->query->get('lang');
//$tmpLanguageRequest = (isset($request->query->get('lang')) && @$request->query->get('tmpLang')==1);
if ($language==null) $language = $this->session->get('language');
if ($language==null && isset($_COOKIE['lang']) && $_COOKIE['lang']!='') $language = $_COOKIE['lang'];
$newLanguage = null;
$newLocale = null;
if ($language!=null) {
if ($language=='en') {
$newLanguage = 'en';
} else if ($language=='hu') {
$newLanguage = 'hu';
$newLocale = 'hu_HU.ISO8859-2';
} else if ($language=='pl') {
$newLanguage = 'pl';
} else if ($language=='de') {
$newLanguage = 'de';
} else if ($language=='sk') {
$newLanguage = 'sk';
} else if ($language=='ro') {
$newLanguage = 'ro';
} else if ($language=='it') { // COM-793
$newLanguage = 'it';
} else {
$newLanguage = 'hu';
$newLocale = 'hu_HU.ISO8859-2';
}
} else {
$referrerWithoutExtras = '';
if (isset($_SERVER['HTTP_REFERER']) && $_SERVER['HTTP_REFERER']!='') {
$referrerWithoutExtras = str_replace('https://', '', $_SERVER['HTTP_REFERER']);
$referrerWithoutExtras = str_replace('/', '', $referrerWithoutExtras);
}
if ($referrerWithoutExtras=='compass.techsupp.hu') {
$newLanguage = 'pl';
echo "<!-- NEW LANG: pl -->";
} else if (in_array($referrerWithoutExtras, ['www.flottaweb.com', 'www.flottaweb.eu', 'fe.flottaweb.eu'])) {
$newLanguage = 'it';
echo "<!-- NEW LANG: it -->";
} else {
$newLanguage = 'hu';
$newLocale = 'hu_HU.ISO8859-2';
}
}
if ($newLanguage!=null) {
//dump($newLanguage);
$request->setLocale($newLanguage);
$this->translator->setLocale($newLanguage);
$this->currentLanguage = $newLanguage;
//if (!$tmpLanguageRequest) {
$this->session->set('language', $newLanguage);
setcookie('lang', $newLanguage, time()+3600*24*30, '/');
//}
}
if ($newLocale!=null) {
setlocale(LC_COLLATE, $newLocale);
}
//dump($request->getLocale());
}
protected function buildRenderArray($module, $inputArray, $entity=null, $params=null) {
$titleLabelId = ($entity==null) ? 'page.title' : 'page.title.singular';
// add to array
$inputArray['page_title'] = $this->getPageName($module, true, $titleLabelId); //$this->translator->trans('application.name', array(), 'general').' - '.
//$this->translator->trans('page.title', array(), $module);
$inputArray['page_content_title'] = $this->translator->trans($titleLabelId, array(), $module);
if ($this->debug) {
$inputArray['page_content_debug_info'] = ($entity==null) ? '' : 'id:'.$entity->getId();
} else {
$inputArray['page_content_debug_info'] = '';
}
$inputArray['module'] = $module;
$inputArray['previousModule'] = $this->session->get('previousModule') ?? '';
$inputArray['currentUser'] = $this->getUser();
$inputArray['currentLanguage'] = $this->currentLanguage;
$inputArray['companyId'] = ($this->company==null) ? null : $this->company->getId();
$inputArray['currentCompanyId'] = ($this->company==null) ? null : $this->company->getId(); // needed together with companyId (diff. files use diff. vars)
$inputArray['company'] = $this->company;
$inputArray['account'] = $this->account; // COM-815
$inputArray['languages'] = $this->languages;
$inputArray['isAdmin'] = $this->getUser()->isAdmin();
$inputArray['adminUserRoles'] = $this->getUser()->getAdminUserTypes();
$inputArray['currentYear'] = $this->timeCalc->currentYear;
$inputArray['currentDate'] = $this->timeCalc->currentDate; // COM-549: fixed
$inputArray['menuSection'] = (isset($_COOKIE['menuSection']) && $_COOKIE['menuSection']!='') ? $_COOKIE['menuSection'] : '';
//$inputArray['breadcrumbs'] = $this->breadcrumbs;
$inputArray['returnURL'] = $this->returnURL;
$inputArray['APP_HOME_URL'] = $_SERVER['APP_HOME_URL'];
$inputArray['LOGIN_EXPIRY'] = self::LOGIN_EXPIRY; // * 60; //time() - $this->session->getMetadataBag()->getLastUsed();
$inputArray['WARNING_BEFORE_LOGOUT'] = self::WARNING_BEFORE_LOGOUT;
$inputArray['session_id'] = session_id();
$inputArray['enableAutoLogout'] = (!isset($_SERVER['APP_DISABLE_AUTO_LOGOUT']) || $_SERVER['APP_DISABLE_AUTO_LOGOUT']!=true);
$inputArray['currentCompanyConfigStatus'] = $this->currentCompanyConfigStatus;
$inputArray['superAdminDebug'] = false; // generic, added in COM-603
$inputArray['APP_DEVELOPER_USER'] = $_SERVER['APP_DEVELOPER_USER']; // generic, added in COM-829
if ($this->company==null) {
$inputArray['currentCompanyConfigStep'] = -1;
} else {
$inputArray['currentCompanyConfigStep'] = $this->company->__get('configurationStep'); //COM-705
}
#$inputArray['APP_FORMS_JS_VERSION'] = $_SERVER['APP_FORMS_JS_VERSION'];
#$inputArray['APP_LISTS_JS_VERSION'] = $_SERVER['APP_LISTS_JS_VERSION'];
$inputArray['APP_REPORTS_JS_VERSION'] = $_SERVER['APP_REPORTS_JS_VERSION'];
#$inputArray['APP_LANGUAGE_JS_VERSION'] = $_SERVER['APP_LANGUAGE_JS_VERSION'];
// reset previous module
$this->session->set('previousModule', $module);
// account balance
if ($this->account==null) {
if ($this->company==null) {
$inputArray['accountBalance'] = '-';
} else {
$accountOfCompany = $this->company->getAccount();
$inputArray['accountBalance'] = $accountOfCompany->getBalance();
}
} else {
$inputArray['accountBalance'] = $this->account->getBalance();
}
// all companies in this account
$allAccountCompanies = [];
if ($this->getUser()->getRolesUnconverted()==UserRoleEnum::ROLE_SUPER_ADMIN) {
// COMPASS user (superadmin) - show grouped (by account) list of companies
if (isset($_SERVER['APP_DEVELOPER_USER']) && $_SERVER['APP_DEVELOPER_USER']==$this->getUser()->getUsername()) {
$this->superAdminDebug = true;
$inputArray['superAdminDebug'] = true; // generic, added in COM-603
}
$dbCompanies = $this->getDoctrine()->getRepository(Company::class)->getAllSortedByAccount();
//dump('dbCompanies', $dbCompanies, $dbCompanies[282]);
$companies = [];
foreach($dbCompanies as $company) {
//dump($company->getId().': '.($companies[$company->getAccount()->getId()] ?? '--'));
if (!isset($companies[$company->getAccount()->getId()])) {
$registeredTypeUser = $this->getDoctrine()->getRepository(User::class)->findOneBy([
'account' => $company->getAccount(),
'roles' => UserRoleEnum::ROLE_ACCOUNT_OWNER,
'deleted' => 0,
]);
//dump('registeredTypeUser', $registeredTypeUser);
if ($registeredTypeUser==null) continue;
$registeredUserName = '';
if ($company->getAccount()->getName()!='') { // COM-387
$registeredUserName = $company->getAccount()->getName(); // COM-387
} else if ($registeredTypeUser->getUsername()!=null && $registeredTypeUser->getName()!=null) {
$registeredUserName = $registeredTypeUser->getName();
if ($registeredTypeUser->getName() !== $registeredTypeUser->getUsername()) {
$registeredUserName .= ' ('.$registeredTypeUser->getUsername().')';
}
} else if ($registeredTypeUser->getName()!=null) {
$registeredUserName = $registeredTypeUser->getName();
} else if ($registeredTypeUser->getUsername()!=null) {
$registeredUserName = $registeredTypeUser->getUsername();
} else {
$registeredUserName = $company->getAccount()->getId();
}
if ($this->superAdminDebug) {
$registeredUserName .= " (".$company->getAccount()->getId().")";
} else if (isset($_SERVER['APP_SHOW_DEBUG_IDS']) && $_SERVER['APP_SHOW_DEBUG_IDS']=='true') {
$registeredUserName .= " (".$company->getAccount()->getId().")";
}
$companies[$company->getAccount()->getId()] = [
//'ownerUsername' => $registeredTypeUser->getUsername(),
'ownerName' => $registeredUserName,
'companies' => [],
];
}
$companyName = $company->getName();
if ($this->superAdminDebug) {
$companyName .= ' ('.$company->getId().')';
} else if (isset($_SERVER['APP_SHOW_DEBUG_IDS']) && $_SERVER['APP_SHOW_DEBUG_IDS']=='true') {
$companyName .= ' ('.$company->getId().')';
}
$companies[$company->getAccount()->getId()]['companies'][] = [
'id' => $company->getId(),
'name' => $companyName,
'selected' => ($this->company!=null && $company->getId()==$this->company->getId()),
];
}
//dump('companies', $companies); //die();
// sort the list by account owner name
usort($companies, function($r1, $r2) {
$v1 = $r1['ownerName'] ?? '';
$v2 = $r2['ownerName'] ?? '';
return strcasecmp($v1, $v2);
if ($v1==$v2) return 0;
return ($v1 < $v2) ? -1 : 1;
});
//dump('companies', $companies); //die();
$inputArray['allAccountCompanies'] = $companies;
} else {
// any other user - use normal logic
if ($this->account!=null) {
$companies = null;
//dump('user', $this->getUser()->getRolesUnconverted());
// COM-815: only allow access to the companies that this user is allowed to administer
if ($this->getUser()->getRolesUnconverted()==UserRoleEnum::ROLE_ACCOUNT_OWNER) {
// REGISTERED USER - can access all companies in this account
//$companies = $this->account->__get('companies'); // get non-deleted!!!!
$companies = $this->getDoctrine()->getRepository(Company::class)->getAllSortedByAccount($this->account);
//dump('all non-compass companies', $companies);
} else {
// ADMIN/VIEWER USER - can access only selected companies
$companies = $this->getUser()->__get('administeredCompanies');
//dump('selected non-compass companies', $companies);
// if none found, it means that there is no setting in the db yet - it's a migration matter;
// in this case, read ALL the companies in this account, as before (to not break anything for existing users);
// the user can be set to access only some companies later, by a registered user
if ($companies==null || count($companies)==0) { //T
$companies = $this->getDoctrine()->getRepository(Company::class)->getAllSortedByAccount($this->account);
//dump('all non-compass companies (2)', $companies);
}
}
if ($companies!=null) {
if ($this->account==null) {
// add a row for "no company"
$allAccountCompanies[] = [
'id' => 'null',
'name' => '- no company -',
'selected' => ($this->company==null),
];
}
foreach($companies as $company) {
//dump('non-compass company', $company);
if ($company->getDeleted()==1) continue;
$allAccountCompanies[] = [
'id' => $company->getId(),
'name' => $company->getName(),
'selected' => ($this->company!=null && $company->getId()==$this->company->getId()),
];
}
//dump($allAccountCompanies);
}
}
// sort the list by company name
usort($allAccountCompanies, function($r1, $r2) {
$v1 = $r1['name'] ?? '';
$v2 = $r2['name'] ?? '';
return strcasecmp($v1, $v2);
if ($v1==$v2) return 0;
return ($v1 < $v2) ? -1 : 1;
});
//dump('allAccountCompanies', $allAccountCompanies); //die();
$inputArray['allAccountCompanies'] = $allAccountCompanies;
}
// current company info
if ($this->company==null) {
$inputArray['currentCompanyName'] = '';
$inputArray['currentCompanyId'] = '';
$inputArray['companyAdminType'] = ''; // COM-481
$inputArray['companySpecialType'] = ''; // COM-831
} else {
$inputArray['currentCompanyName'] = $this->company->getName();
$inputArray['currentCompanyId'] = $this->company->getId();
// COM-481
$inputArray['companyAdminType'] = $this->company->__get('adminType');
//dump('cat', $inputArray['companyAdminType']);
if ( $inputArray['companyAdminType']===null) {
$inputArray['companyAdminType'] = 'no type';
} else {
$inputArray['companyAdminType'] = CompanyAdminTypeEnum::LABELS[ $inputArray['companyAdminType'] ];
}
// COM-831
if ($this->company->__get('specialType')!==null) {
$inputArray['companySpecialType'] = CompanySpecialTypeEnum::LABELS[ $this->company->__get('specialType') ];
} else {
$inputArray['companySpecialType'] = '';
}
}
// widgets
$inputArray['widgets'] = [
'balance' => false,
'masterdata' => false,
'dataproc' => false,
'reports' => false,
];
switch ($this->getUser()->getRolesUnconverted()) {
case UserRoleEnum::ROLE_SUPER_ADMIN:
if ($this->company==null) {
$inputArray['widgets']['masterdata'] = true;
} else {
$inputArray['widgets']['balance'] = true;
$inputArray['widgets']['masterdata'] = true;
$inputArray['widgets']['dataproc'] = true;
$inputArray['widgets']['reports'] = true;
}
break;
case UserRoleEnum::ROLE_ACCOUNT_OWNER:
$inputArray['widgets']['balance'] = true;
//$inputArray['widgets']['masterdata'] = true; // COM-695 - JNOTE??
$inputArray['widgets']['reports'] = true;
break;
case UserRoleEnum::ROLE_ADMIN:
$inputArray['widgets']['balance'] = true;
$inputArray['widgets']['masterdata'] = true;
$inputArray['widgets']['dataproc'] = true;
$inputArray['widgets']['reports'] = true;
break;
case UserRoleEnum::ROLE_USER:
$inputArray['widgets']['reports'] = true; // COM-695 - JNOTE??
break;
default:
break;
}
// COM-831
// modify widget access for special company types
if ($this->company!==null && $this->company->__get('specialType')==CompanySpecialTypeEnum::TODO_ONLY) {
$inputArray['widgets']['balance'] = false;
$inputArray['widgets']['masterdata'] = true;
$inputArray['widgets']['dataproc'] = false;
$inputArray['widgets']['reports'] = false;
}
// error/success messages (show only 1)
$initialMessage = '';
//dump($request->getSession()->getFlashBag());
if ($initialMessage=='') {
foreach ($this->session->getFlashBag()->get('error', array()) as $message) {
if ($initialMessage!='') continue;
$message = str_replace("'", "\'", $message); // COM-809
$initialMessage .= "showMsg('$message', false, 5000);\n";
}
}
if ($initialMessage=='') {
foreach ($this->session->getFlashBag()->get('success', array()) as $message) {
if ($initialMessage!='') continue;
$message = str_replace("'", "\'", $message); // COM-809
if ($this->keepFlashMessageOpen) {
$initialMessage .= "showMsg('$message', true, null);\n";
} else {
$initialMessage .= "showMsg('$message', true);\n";
}
}
}
$inputArray['initialMessage'] = $initialMessage;
// new company config popup
//dump('firstLoginConfigMode', $this->firstLoginConfigMode);
$includeCompanyConfigPopup = false;
if ($this->firstLoginConfigMode ||
$this->newCompanyConfigMode ||
(isset($params['companyListPage']) && $params['companyListPage']==true)) {
$includeCompanyConfigPopup = true;
}
$inputArray['includeCompanyConfigPopup'] = $includeCompanyConfigPopup;
// logic for specific permissions
// vehicle license check
$inputArray['enableVehicleCleanupPopup'] = false;
$vehicleLicenseCheckAction = null;
if ($this->getUser()->getRolesUnconverted()==UserRoleEnum::ROLE_SUPER_ADMIN ||
$this->getUser()->getRolesUnconverted()==UserRoleEnum::ROLE_ACCOUNT_OWNER ||
$this->getUser()->getRolesUnconverted()==UserRoleEnum::ROLE_TRANSLATOR) { // COM-794
// license check not needed for Compass users
$vehicleLicenseCheckAction = 'not-needed (superadmin/registered/viewer)';
if (0) {
$activeLicense = $this->licenseHelper->getActiveLicense( $this->company->getId() );
dump("licensed vehicles: {$activeLicense['sum']['currentNumVehicles']} / {$activeLicense['sum']['vehicleLicenses']}");
}
} else {
$activeLicense = $this->licenseHelper->getActiveLicense( $this->company->getId() );
//dump('activeLicense', $activeLicense['sum']);
if (isset($activeLicense['sum'])) {
if ($activeLicense['sum']['license_type']==LicenseTypeEnum::VEHICLE) {
// VEHICLE-based license
//dump("licensed vehicles: {$activeLicense['sum']['currentNumVehicles']} / {$activeLicense['sum']['vehicleLicenses']}");
if ($activeLicense['sum']['currentNumVehicles'] > $activeLicense['sum']['vehicleLicenses']) {
$inputArray['enableVehicleCleanupPopup'] = true;
$vehicleLicenseCheckAction = 'delete-necessary';
} else {
// # of vehicls is within the license, vehicle license check is not needed
$vehicleLicenseCheckAction = 'completed';
}
} else {
// not a vehicle-based license, vehicle license check is not needed
$vehicleLicenseCheckAction = 'not-needed (not vehicle license)';
}
} else {
// don't have a license yet, vehicle license check is not needed
$vehicleLicenseCheckAction = 'not-needed (no license selected yet)';
}
}
//dump("vehicleLicenseCheckAction: $vehicleLicenseCheckAction");
/****
// if vehicle license check above is not needed, update session variable, to tell it that after-login vehicle license check is not needed
if ($this->session->get('immediatelyAfterLoginActions')!==null &&
in_array('vehicleLicenseCheck', $this->session->get('immediatelyAfterLoginActions')) &&
( $vehicleLicenseCheckAction===null ||
substr($vehicleLicenseCheckAction,0,10)=='not-needed' ||
$vehicleLicenseCheckAction=='completed') ) {
$immediatelyAfterLoginActions = $this->session->get('immediatelyAfterLoginActions');
$newImmediatelyAfterLoginActions = [];
foreach($immediatelyAfterLoginActions as $afterLoginAction) {
if ($afterLoginAction=='vehicleLicenseCheck') continue;
$newImmediatelyAfterLoginActions[] = $afterLoginAction;
}
//dump('newImmediatelyAfterLoginActions', $newImmediatelyAfterLoginActions);
if (count($newImmediatelyAfterLoginActions)>0) {
$this->session->set('immediatelyAfterLoginActions', $newImmediatelyAfterLoginActions);
} else {
$this->session->set('immediatelyAfterLoginActions', null);
}
}
****/
$inputArray['showVehicleCleanupPopup'] = false;
$inputArray['numVehicleLicenses'] = 0;
$inputArray['numCurrentVehicles'] = 0;
$inputArray['numVehiclesToDelete'] = 0;
if ($inputArray['enableVehicleCleanupPopup']==true) {
$inputArray['numVehicleLicenses'] = $activeLicense['sum']['vehicleLicenses'];
$inputArray['numCurrentVehicles'] = $activeLicense['sum']['currentNumVehicles'];
$inputArray['numVehiclesToDelete'] = $activeLicense['sum']['currentNumVehicles'] - $activeLicense['sum']['vehicleLicenses'];
$inputArray['vehicleCleanupList'] = [];
$vehicles = $this->getDoctrine()->getRepository(Vehicle::class)->findAllSortedByDateCreated( $this->company );
//dump('vehicles', $vehicles, count($vehicles));
foreach($vehicles as $vehicle) {
if ($vehicle->__get('hasTachograph')==false) continue;
$inputArray['vehicleCleanupList'][] = [
'id' => $vehicle->getId(),
'name' => $vehicle->getName().' ('.$vehicle->getId().')',
'date' => $vehicle->__getDateFormatted('createdAt'),
];
}
$inputArray['vehicleCleanupList'] = json_encode($inputArray['vehicleCleanupList']);
// show on page open
//if ($this->session->get('immediatelyAfterLoginActions')!==null &&
// in_array('vehicleLicenseCheck', $this->session->get('immediatelyAfterLoginActions'))) {
$inputArray['showVehicleCleanupPopup'] = true;
//}
//dump($inputArray);
}
/****
if ($this->session->get('immediatelyAfterLoginActions')!==null) {
dump("immediatelyAfterLoginActions:", $this->session->get('immediatelyAfterLoginActions'));
if ($this->company!==null) dump('company: '.$this->company->getName().' - '.$this->company->getId());
$licenseChecksToComplete = [];
// vehicle license check
if (in_array('vehicleLicenseCheck', $this->session->get('immediatelyAfterLoginActions'))) {
// remove this login vehicle license check
if ($vehicleLicenseCheckAction===null ||
substr($vehicleLicenseCheckAction,0,10)=='not-needed' ||
$vehicleLicenseCheckAction=='completed') {
$licenseChecksToComplete[] = 'vehicleLicenseCheck';
}
}
if (count($licenseChecksToComplete)>0) {
$immediatelyAfterLoginActions = $this->session->get('immediatelyAfterLoginActions');
$newImmediatelyAfterLoginActions = [];
foreach($immediatelyAfterLoginActions as $afterLoginAction) {
if (in_array($afterLoginAction, $licenseChecksToComplete)) continue;
$newImmediatelyAfterLoginActions[] = $afterLoginAction;
}
dump('newImmediatelyAfterLoginActions', $newImmediatelyAfterLoginActions);
if (count($newImmediatelyAfterLoginActions)>0) {
$this->session->set('immediatelyAfterLoginActions', $newImmediatelyAfterLoginActions);
} else {
$this->session->set('immediatelyAfterLoginActions', null);
}
}
}
****/
//dump('session var (0)', $this->session->get('broadcast-msgs'));
$inputArray['broadcastMsg'] = [
'show' => false,
];
if (!$includeCompanyConfigPopup &&
$this->company!==null) { // generic, added for COM-794
// broadcast msgs -- COM-469
$brMsgPopupToShow = $this->messageHelper->checkIfBroadcastMessagePopupNeedsToBeShown($this->company, $this->getUser(),
$this->session->get('broadcast-msgs'));
//dump('brMsgPopupToShow', $brMsgPopupToShow);
if ($brMsgPopupToShow===false) {
//$inputArray['broadcastMsg'] = [
// 'show' => false,
//];
} else {
$inputArray['broadcastMsg'] = [
'show' => true,
'id' => $brMsgPopupToShow->__get('id'),
'type' => $brMsgPopupToShow->__get('type'),
'title' => $brMsgPopupToShow->__get('title'),
//'content' => str_replace("\n", "<br>", $brMsgPopupToShow->__get('content')),
'content' => $brMsgPopupToShow->__get('content'),
];
$this->messageHelper->saveBroadcastMessageReaction($brMsgPopupToShow, $this->company, $this->getUser(), BroadcastMessageReactionEnum::SHOW);
}
}
// language strings
$allMessages = $this->translator->getCatalogue()->all();
$languageStrings['general'] = $allMessages['general'];
$languageStrings['driver-vehicle-popup'] = $allMessages['driver-vehicle-popup'];
$languageStrings['videos'] = $allMessages['videos']; //COM-785
if (substr($this->module,0,7)=='report-') {
$languageStrings['report-general'] = $allMessages['report-general'];
}
if ($this->module!='' && isset($allMessages[$this->module])) {
$languageStrings[$this->module] = $allMessages[$this->module];
}
if ($this->module=='driver-activity-diagram') {
$languageStrings['driver-activities'] = $allMessages['driver-activities'];
$languageStrings['driver-special-events'] = $allMessages['driver-special-events'];
}
if ($this->module=='data-conflicts') { // COM-CONFLICTS
$languageStrings['driver-activity-diagram'] = $allMessages['driver-activity-diagram'];
$languageStrings['driver-activities'] = $allMessages['driver-activities'];
$languageStrings['driver-special-events'] = $allMessages['driver-special-events'];
}
if ($includeCompanyConfigPopup) {
$languageStrings['registration'] = $allMessages['registration']; // need registration strings
}
if (in_array($module, ['drivers', 'vehicles'])) { // attachments -- COM-787
$languageStrings['attachments'] = $allMessages['attachments'];
}
$inputArray['languageStrings_js'] = json_encode($languageStrings);
//dump('allMessages', $allMessages, $this->module);
// empty objects
$inputArray['objects'] = [
// master data
'Account' => new Account,
'Company' => new Company,
'Driver' => new Driver,
'Vehicle' => new Vehicle,
'Trailer' => new Trailer,
'User' => new User,
// master data - dashboard
'Document' => new Document,
'Message' => new Message, // generic, added for COM-831
'LicensePricing' => new LicensePricing,// generic, added for COM-831
'Balance' => new Balance, // generic, added for COM-831
'InvoiceStore' => new InvoiceStore, // generic, added for COM-831
'Setting' => new Setting, // generic, added for COM-831
// parameters
'WorkPeriod' => new WorkPeriod,
'DayAssignment' => new DayAssignment,
'DayTitle' => new DayTitle,
'AttendanceRegisterParams' => new AttendanceRegisterParams,
'ProtocolParams' => new ProtocolParams,
// data processing
'TachographFile' => new TachographFile,
'DriverActivity' => new DriverActivity,
'DriverManualActivity' => new DriverManualActivity,
'DriverBorderCrossing' => new DriverBorderCrossing,
'DriverActiveDay' => new DriverActiveDay,
'DriverMinimumWagePeriod' => new DriverMinimumWagePeriod,
'DriverSpecialEvent' => new DriverSpecialEvent,
'DriverActivityProofSheet' => new DriverActivityProofSheet,
// reports
'Report' => new Report,
'Report2' => new Report2,
'LogEntry' => new LogEntry,
'LogEntry2' => new LogEntry2,
'TravelRoute' => new TravelRoute,
'ToDoItem' => new ToDoItem,
// other
'Penalty' => new Penalty,
'CustomField' => new CustomField,
'LicensePricing' => new LicensePricing,
'Consumption' => new Consumption,
'KmMultiplier' => new KmMultiplier,
'GasPrices' => new GasPrices,
'DailyAllowance' => new DailyAllowance,
'Statistic' => new Statistic, //COM-349
//'EmailServerConnection' => new EmailServerConnection, //COM-819
'EmailTachographFile' => new EmailTachographFile, // COM-819
];
$inputArray['licensePermitsTodoModule'] = $this->licenseHelper->doesLicenseAllowModule_voterCheck('todo');
$inputArray['licensePermitsDailyAllowanceModule'] = $this->licenseHelper->doesLicenseAllowModule_voterCheck('daily-allowance');
// module access
//$inputArray['moduleAccess'] = [
// // master data
// 'Account' => new Account,
//dump($inputArray, $params);
// load help text
$inputArray['helpContents'] = $this->docHelper->loadHelpHtmlFile($this->currentLanguage, $this->module); // COM-783: added $module
//dump('helpContents', $inputArray['helpContents']);
// COM-783
$allowHelpInlineEdit = false;
if ($inputArray['helpContents']===null) {
if ($this->getUser()->getRolesUnconverted()==UserRoleEnum::ROLE_SUPER_ADMIN) {
$inputArray['helpContents'] = ''; //'Help file does not exist, contact Janusz to configure it<br><br>';
//$inputArray['helpContents'] = '('.$this->docHelper->lastFileName.')';
} else {
$inputArray['helpContents'] = '';
}
} else {
if ($this->getUser()->getRolesUnconverted()==UserRoleEnum::ROLE_SUPER_ADMIN) {
//$allowHelpInlineEdit = true;
}
}
$inputArray['allowHelpInlineEdit'] = $allowHelpInlineEdit;
// load knowledge base (simple file for now)
$inputArray['knowledgeBaseUrl'] = $this->generateUrl('documents.show-simple.action', [
'type' => 'knowledge-base',
'randomNumber' => rand(1000000000, 9000000000),
]);
// load TofU and other documents, if the user needs to accept these
if ($includeCompanyConfigPopup) {
$inputArray['includeCompanyConfigPopup'] = $includeCompanyConfigPopup;
$inputArray['firstLoginConfigMode'] = $this->firstLoginConfigMode;
$inputArray['newCompanyConfigMode'] = $this->newCompanyConfigMode;
//JNOTE: maybe need this per company?
if ($this->getUser()->getRolesUnconverted()==UserRoleEnum::ROLE_ACCOUNT_OWNER ||
$this->getUser()->getRolesUnconverted()==UserRoleEnum::ROLE_SUPER_ADMIN) {
//dump($this->settings, $this->company->getId()); die();
// full registration
$inputArray['registration']['term-of-use'] = $this->docHelper->loadHtmlFile('term-of-use', $this->currentLanguage);
$inputArray['registration']['contract'] = $this->docHelper->loadHtmlFile('contract', $this->currentLanguage);
$inputArray['registration']['gdpr'] = $this->docHelper->loadHtmlFile('gdpr', $this->currentLanguage);
$inputArray['registration']['cookies'] = $this->docHelper->loadHtmlFile('cookies', $this->currentLanguage); //COM-424
// countries
$inputArray['countriesArray'] = $this->formsHelper->getCountries($this->mainCountry);
//$inputArray['mainCountry'] = $this->mainCountry;
// cities
$inputArray['citiesArray'] = $this->formsHelper->getCities($this->mainCountry);
//$inputArray['mainCity'] = $this->mainCity;
// config settings
$configInitSettings = [
'blankContract' => '',
'mainCountry' => $this->mainCountry,
'mainCity' => $this->mainCity,
'account' => [
'name' => $this->account->getId(),
],
'company' => [
'id' => null,
'name' => '',
'country' => $this->company->country, // use current company's country as default
'city' => '',
'address' => '',
'postalCode' => '',
'email' => '',
'protocolCreator' => $this->company->protocolCreator,
'protocolApprover' => $this->company->protocolApprover,
],
'configurationStep' => 0,
'licenseTypes' => [
'vehicle' => LicenseTypeEnum::VEHICLE,
'driver' => LicenseTypeEnum::DRIVER,
'usage' => LicenseTypeEnum::USAGE,
],
'config-done' => [
'tofu-accepted' => ($this->settings['config-step']['tofu']!=''),
'contract-accepted' => ($this->settings['config-step']['contract']!=''),
'gdpr-accepted' => ($this->settings['config-step']['gdpr']!=''),
'cookies-accepted' => ($this->settings['config-step']['cookies']!=''),
'license-type-chosen' => $this->company->__get('licenseType'),
],
'settings'
];
// if first login mode, need to set initial popup fields to the already-created company
if ($this->firstLoginConfigMode) {
$configInitSettings['company'] = [
'id' => $this->company->getId(),
// contract/general
'coName' => $this->company->getName(),
'coCountry' => $this->company->__get('country'),
'coAddrCity' => $this->company->__get('city'),
'coAddr' => $this->company->__get('address'),
'coAddrPCode' => $this->company->__get('postalCode'),
'coEmail' => $this->company->__get('email'),
'coTaxNumber' => $this->company->__get('taxNumber'),
'coRegistrationNumber' => $this->company->__get('registrationNumber'),
'coEUTaxNumber' => $this->company->__get('europeanTaxNumber'),
'contractSign1' => $this->company->__get('contractSign1'),
'contractSign1Email' => $this->company->__get('contractSign1Email'),
'contractSign1Phone' => $this->company->__get('contractSign1Phone'),
'contractSign2' => $this->company->__get('contractSign2'),
'contractSign2Email' => $this->company->__get('contractSign2Email'),
'contractSign2Phone' => $this->company->__get('contractSign2Phone'),
// invoicing
//invoicingDataSameAsContract coInvoicingDataSameAsContract
'coNameForInvoicing' => $this->company->__get('invoicingCompanyName'),
'coInvoicingAddrPCode' => $this->company->__get('invoicingPostalCode'),
'coInvoicingAddrCity' => $this->company->__get('invoicingCity'),
'coInvoicingAddr' => $this->company->__get('invoicingAddress'),
'coInvoicingCountry' => $this->company->__get('invoicingCountry'),
'coInvoicingTaxNumber' => $this->company->__get('invoicingTaxNumber'),
'coInvoicingEUTaxNumber' => $this->company->__get('invoicingEuropeanTaxNumber'),
// shipping
//coShippingDataSameAsContract coShippingDataSameAsContract
'coNameForShipping' => $this->company->__get('shippingCompanyName'),
'coContactNameForShipping' => $this->company->__get('shippingContactName'),
'coShippingAddrPCode' => $this->company->__get('shippingPostalCode'),
'coShippingAddrCity' => $this->company->__get('shippingCity'),
'coShippingAddr' => $this->company->__get('shippingAddress'),
'coShippingCountry' => $this->company->__get('shippingCountry'),
'coProtocolCreator' => $this->company->__get('protocolCreator'),
'coProtocolApprover' => $this->company->__get('protocolApprover'),
];
// JNOTE: + accepted contact, etc. already - show
$configInitSettings['configurationStep'] = $this->company->__get('configurationStep');
if ($configInitSettings['configurationStep']=='' || $configInitSettings['configurationStep']=='') {
$configInitSettings['configurationStep'] = 0;
}
}
$inputArray['configInitSettings_js'] = json_encode($configInitSettings);
// need to include settings
$inputArray['settings'] = $this->settings;
$inputArray['minTimeBetweenShiftsDefault'] = Setting::CONFIG['rule.minTimeBetweenShifts']['default'];
$inputArray['defaultMinTimeBetweenShifts'] = ($inputArray['settings']['rule']['minTimeBetweenShifts']=='') ||
($inputArray['settings']['rule']['minTimeBetweenShifts']==Setting::CONFIG['rule.minTimeBetweenShifts']['default']);
$inputArray['minWrongSwitchActivityLen'] = Setting::CONFIG['rule.minWrongSwitchActivityLen']['default'];
} else {
// should not have any users
$inputArray['includeCompanyConfigPopup'] = false;
}
} else {
$inputArray['includeCompanyConfigPopup'] = false;
}
if (!isset($inputArray['configInitSettings_js'])) $inputArray['configInitSettings_js'] = json_encode([]);
/// CHECK BALANCE
$this->getBalanceforCompany($this->company,$inputArray['license_balance']);
//dump('balance: '.$this->company->getBalance());
/// check new message
$this->messageHelper->getNewMessage($inputArray['new_messages'], $this->getUser());
// COM-695 - Bob
$inputArray['enableAI'] = $this->aiEnabled; // COM-709a
//$inputArray['systemHintId'] = '';
//$inputArray['systemHintMessage'] = '';
$inputArray['systemHintsArray_js'] = json_encode([]);
$inputArray['systemHintsIdsArray_js'] = json_encode([]);
$inputArray['systemHintsAvail'] = 0;
$inputArray['aiPaidLicenseThisMonth'] = $this->aiPaidLicenseThisMonth; // COM-709a
//$inputArray['systemHintsSpecialMsg'] = [
// 'title' => '',
// 'message' => '',
//];
//protected $aiEnabled = false;
//protected $aiPaidLicenseThisMonth = false;
if (!$this->firstLoginConfigMode) {
/*
// show system tips, depending on user type
if (in_array($this->getUser()->getRolesUnconverted(), [UserRoleEnum::ROLE_SUPER_ADMIN,
UserRoleEnum::ROLE_ACCOUNT_OWNER,
UserRoleEnum::ROLE_ADMIN])) {
$inputArray['enableAI'] = true;
//dump('enableAI');
}
*/
//if ($inputArray['enableAI']) {
if ($this->aiEnabled) { // COM-709a
$systemHintsToShow = $this->ai->getSystemTipsForCompany($this->company, true, 3);
//dump('systemHintsToShow', $systemHintsToShow);
if ($systemHintsToShow!==null) {
//$inputArray['systemHintId'] = $systemHintInfoToShow['id'];
//$inputArray['systemHintMessage'] = $systemHintInfoToShow['msg'];
//$inputArray['systemHintsAvail'] = $systemHintInfoToShow['numAvail'];
//$inputArray['systemHintsArray'] = $systemHintsToShow;
$inputArray['systemHintsArray_js'] = json_encode($systemHintsToShow['tips']);
$inputArray['systemHintsAvail'] = $systemHintsToShow['numAvail'];
$systemHintsIdsArray = [];
foreach($systemHintsToShow['tips'] as $tip) {
$systemHintsIdsArray[] = $tip['id'];
}
//dump('systemHintsIdsArray', $systemHintsIdsArray);
$inputArray['systemHintsIdsArray_js'] = json_encode($systemHintsIdsArray);
}
}
// show the validity of the instant schedule aid page
//dump($this->settings);
//$currentMonthNum = intval(date('m'));
//$currentMonthAIPaidLicense = $this->settings['ai']['tipMonthlyLicences'][$currentMonthNum-1];
//dump('currentMonthAIPaidLicense: '.$currentMonthAIPaidLicense);
//if ($currentMonthAIPaidLicense==1) {
if ($this->aiPaidLicenseThisMonth) { // COM-709a
// if now is enabled, check when it will expire
//$lastPaidMonth = $currentMonthNum;
$monthsValidArray = [];
for($month=1; $month<=12; $month++) {
$monthStringName = '';
switch($month) {
case 1: $monthStringName = 'JANUARY'; break;
case 2: $monthStringName = 'FEBRUARY'; break;
case 3: $monthStringName = 'MARCH'; break;
case 4: $monthStringName = 'APRIL'; break;
case 5: $monthStringName = 'MAY'; break;
case 6: $monthStringName = 'JUNE'; break;
case 7: $monthStringName = 'JULY'; break;
case 8: $monthStringName = 'AUGUST'; break;
case 9: $monthStringName = 'SEPTEMBER'; break;
case 10: $monthStringName = 'OCTOBER'; break;
case 11: $monthStringName = 'NOVEMBER'; break;
case 12: $monthStringName = 'DECEMBER'; break;
}
//$thisMonthAIPaidLicense = $this->settings['ai']['tipMonthlyLicences'][$month-1];
//if ($thisMonthAIPaidLicense==1) {
//if ($this->aiPaidLicenseThisMonth) {
//$lastPaidMonth = intval($month);
//$monthsValidArray[] = '2024-'.str_pad($month, 2, '0', STR_PAD_LEFT);
$monthsValidArray[] = '2024. '.
$this->translator->trans('monthName.'.$monthStringName, array(), 'general');
//$inputArray['aiPaidLicenseThisMonth'] = true;
//$this->aiPaidLicenseThisMonth = true;
//} else {
// //break;
//}
}
//dump("lastPaidMonth: $lastPaidMonth");
//dump(str_pad($lastPaidMonth.'', 2, '0', STR_PAD_LEFT));
//dump('monthsValidArray', $monthsValidArray);
//$lastMonthStartDate = $this->timeCalc->currentYear."-".str_pad($lastPaidMonth.'', 2, '0', STR_PAD_LEFT).'-01';
//dump("lastMonthStartDate: $lastMonthStartDate");
//$lastAIPaidDate = date("Y-m-t", strtotime($lastMonthStartDate));
//dump("lastAIPaidDate: $lastAIPaidDate");
//$inputArray['AIFreePaidNote'] = 'paid until '.$lastAIPaidDate.'';
$inputArray['AIFreePaidNote'] = $this->translator->trans('label.aiValidityNote.paid', array(
//'[date]' => $lastAIPaidDate,
), 'general');
$inputArray['AIFreePaidTooltip'] = $this->translator->trans('tooltip.aiValidityNote.paid', array(
'[months]' => '<br>'.implode('<br>', $monthsValidArray),
), 'general');
//dump("****", $this->translator->trans('tooltip.aiValidityNote.paid', array(), 'general'));
} else {
$inputArray['AIFreePaidNote'] = $this->translator->trans('label.aiValidityNote.free', array(), 'general');
$inputArray['AIFreePaidTooltip'] = $this->translator->trans('tooltip.aiValidityNote.free', array(), 'general');
}
//$specialHintMsgToShow = rand(1, 2);
$specialHintMsgToShow = 1; // request from J to show only 1
} else {
$specialHintMsgToShow = 1;
$inputArray['AIFreePaidNote'] = $this->translator->trans('label.aiValidityNote.free', array(), 'general');
$inputArray['AIFreePaidTooltip'] = $this->translator->trans('tooltip.aiValidityNote.free', array(), 'general');
}
//$inputArray['enableAI'] = false; //JNOTE-TESTING
$inputArray['systemHintsSpecialMsg']['title'] =
$this->translator->trans('tipSpecialMessage.title.'.$specialHintMsgToShow, array(), 'system-tips');
$inputArray['systemHintsSpecialMsg']['message'] =
$this->translator->trans('tipSpecialMessage.message.'.$specialHintMsgToShow, array(), 'system-tips');
$inputArray['aiSummary'] = $this->ai->getAISummary($this->company);
// COM-695 - chart for Bob's bragging popup
$chartLabels = [];
$chartValues = [];
foreach($inputArray['aiSummary']['monthlyStats'] as $yearMonth=>$value) {
$chartLabels[] = $yearMonth;
$chartValues[] = $value;
}
$inputArray['aiSummary']['aiChartMonthArray_js'] = json_encode($chartLabels);
$inputArray['aiSummary']['aiChartDataArray_js'] = json_encode($chartValues);
if (0) {
$inputArray['aiSummary']['aiChartMonthArray_js'] = json_encode([
'sep',
'oct',
'nov',
'dec',
]);
$inputArray['aiSummary']['aiChartDataArray_js'] = json_encode([
400000,
800000,
700000,
1000000,
]);
}
// ATTACHMENTS -- COM-787
$inputArray['attachmentsAllowed'] = '0';
if (isset($_SERVER['APP_ATTACHMENT_COMPANY_IDS']) && $_SERVER['APP_ATTACHMENT_COMPANY_IDS']!='' &&
$this->company!==null) {
$attachmentCompanyIds = explode(',', $_SERVER['APP_ATTACHMENT_COMPANY_IDS']);
//dump($attachmentCompanyIds);
if (in_array($this->company->getId(), $attachmentCompanyIds)) {
$this->enableAttachments = true;
$inputArray['attachmentsAllowed'] = '1';
//dump('IN');
}
}
// API -- COM-815
$inputArray['apiAllowed'] = '0';
if ($this->enableApi) {
$inputArray['apiAllowed'] = '1';
//dump('IN');
}
// TACHO-SOLVE -- COM-822
$inputArray['tachoSolveSalespersonsEnabled'] = '0';
if (isset($_SERVER['APP_TACHO_SOLVE_SALESPERSONS_USER_IDS'])) {
$tsSalespersonUserIdArray = explode(',', $_SERVER['APP_TACHO_SOLVE_SALESPERSONS_USER_IDS']);
if (in_array($this->getUser()->getId(), $tsSalespersonUserIdArray)) {
$inputArray['tachoSolveSalespersonsEnabled'] = '1';
}
}
//dump('inputArray', $inputArray);
//die();
return $inputArray;
}
public function checkMessageSecurity($user,$entity,&$result) {
if (!$entity){
$url = $this->generateUrl('messages.index.page');
return $this->redirect($url);
}
if (@$entity && $user->getRolesUnconverted()[0] == UserRoleEnum::ROLE_SUPER_ADMIN) $result = true;
if ($user->getRolesUnconverted()[0] != UserRoleEnum::ROLE_SUPER_ADMIN) {
if ($entity->from) {
$from = $entity->getFrom();
$from = $from->id;
}
if (@$entity->to) {
$to = $entity->getTo();
$to = $to->id;
}
if ((@$from && $user->currentCompanyViewed->id != $from) || (@$to && $user->currentCompanyViewed->id != $to)) {
$result = 'redirect';
}else{
$result = true;
}
}elseif($user->getRolesUnconverted()[0] == UserRoleEnum::ROLE_SUPER_ADMIN) {
$result = true;
}
}
public function checkConsumptionSecurity($user,$company,$entity,&$result) {
if (!$entity){
$url = $this->generateUrl('modules.consumption.index.page');
return $this->redirect($url);
}
if ($entity->company == $company->id) {
$result = true;
}
}
/*
public function getNewMessage(&$result) {
$result = false;
$messageRepository = $this->getDoctrine()->getRepository(Message::class);
$user = $this->getUser();
if ($user->getRolesUnconverted()[0] == UserRoleEnum::ROLE_SUPER_ADMIN) {
$messageRepository->checkNewMessagesForAdmin($messages);
}else{
if ($this->company!=null) {
$messageRepository->checkNewMessagesForUser($this->company,$messages);
} else {
$messages = false;
}
}
if ($messages) {
$result = true;
}
}
*/
public function getBalanceforCompany($company,&$result) {
$result = '';
$anyLicense = $this->licenseHelper->checkActiveLicense($company);
if (@$anyLicense['sum']) {
$lastOrder = $this->getDoctrine()->getRepository(LicenseOrder::class)->findOneBy(['company' => $this->company,'status' => 4],['id' => 'desc']);
if (@$lastOrder) {
$orderDetails = json_decode($lastOrder->details,true);
$discount = !is_numeric($lastOrder->discount) ? 0 : $lastOrder->discount;
$invoiceItems = [];
$fullPrice = 0;
if ($discount > 0) {
$invoiceItems[] = ['name' => 'Kedvezmény','qty' => 1, 'price' => $discount*-1
];
}
$this->licenseHelper->getPriceMultiplierHelper($company,$multiplier);
foreach ($orderDetails as $key=>$orderItem) {
$this->licenseHelper->szamlazz_item_generator($multiplier,$orderDetails['licenseType'],$key,$orderItem,$lastOrder->getId(),$this->company,$invoiceItems[]);
}
foreach ($invoiceItems as $items) {
if (@$items) $fullPrice += $items['price'];
}
$fullPrice = number_format($fullPrice,0,'',' ');
}
if ($anyLicense['sum']['license_type'] == 1) // VEHICLE-BASED
{
// vehicle based
$transLicenses = $this->translator->trans('balance_widget.licenses', array(), 'balance');
$transEndof = $this->translator->trans('balance_widget.endoflegislation', array(), 'balance');
$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>";
}
elseif($anyLicense['sum']['license_type'] == 2) // DRIVER_BASED
{
// driver based
$transUnused = $this->translator->trans('balance_widget.unusedvehicle', array(), 'balance');
$transAEtr = $this->translator->trans('balance_widget.aetr', array(), 'balance');
$transLabour = $this->translator->trans('balance_widget.labour', array(), 'balance');
$transOrderDate = $this->translator->trans('order_date', array(), 'balance');
$transOrderAmount = $this->translator->trans('order_amount', array(), 'balance');
if (@$lastOrder) {
$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>
<span class=\"line-clamp\">{$transOrderDate} {$lastOrder->createdAt->format('Y-m-d')}</span></div>";
//<span class=\"line-clamp\">{$transOrderAmount} {$fullPrice} HUF</span>"; // COM-510: deleted
}
}
elseif($anyLicense['sum']['license_type'] == 3) // USAGE-BASED
{
$transCredit = $this->translator->trans('balance_credit', array(), 'balance');
$credit = number_format($anyLicense['sum']['credit'],0,'',' ');
$credit = number_format($company->balance,0,'',' ');
$transOrderDate = $this->translator->trans('order_date', array(), 'balance');
$transOrderAmount = $this->translator->trans('order_amount', array(), 'balance');
if (@$lastOrder) {
$result = "<div class=\"muted-text-small \" style='margin-top: 0px;'><span class=\"line-clamp\">{$transCredit}: {$credit} HUF</span>
<span class=\"line-clamp\">{$transOrderDate} {$lastOrder->createdAt->format('Y-m-d')}</span>
<span class=\"line-clamp\">{$transOrderAmount} {$fullPrice} HUF</span>
</div>";
}
}
}
if ($result=='') {
$transBalance = $this->translator->trans('no_balance_available', array(), 'balance');
$result = "<div class=\"muted-text-small \" style='margin-top: 5px;'><span class=\"line-clamp\">{$transBalance}</span></div>";
}
}
protected function jsonEncoder($content) {
$encoders = array(new JsonEncoder());
$normalizer = new ObjectNormalizer();
$normalizer->setCircularReferenceLimit(0);
$normalizer->setCircularReferenceHandler(function ($object) { // Circular reference handler
return $object->getId();
});
//$normalizers = array(new ObjectNormalizer());
$normalizers = array($normalizer);
$serializer = new Serializer($normalizers, $encoders);
$jsonEncodedContent = $serializer->serialize($content, 'json');
//dump($jsonContent); die();
return $jsonEncodedContent;
}
protected function getPageName($module, $addPrefix=true, $labelIdOverride=null) {
$pageName = '';
$labelId = ($labelIdOverride==null) ? 'page.title' : $labelIdOverride;
if ($addPrefix) $pageName = $this->translator->trans('application.name', array(), 'general').' - ';
$pageName .= $this->translator->trans($labelId, array(), $module);
return $pageName;
}
protected function generateUniqueFileName() {
return md5(uniqid());
}
protected function checkAccess($module, $action) {
// get user
$user = $this->getUser();
if ($user==null) return false;
// modify module for the purpose of the logic here
if ($module=='subproduct') $module = 'subproducts';
if ($module=='statistic') $module = 'statistics';
//dump($module, $action);
if (isset($this->modulesAllowedForRegularUsers[$module][$action])) {
if (isset($this->modulesAllowedForRegularUsers[$module][$action]) &&
$this->modulesAllowedForRegularUsers[$module][$action]==true) {
return true;
}
}
return false;
}
protected function getDefaultAjaxReturnRec($error=null, $msg='', $info='', $url='', $errorField='') {
// if passed-in URL is a route name, generate the URL from the route
if (substr($url, 0, 2)=="R:") {
$url = $this->router->generate(substr($url, 2));
}
$result = array(
'success' => false,
'error' => $error,
'msg' => $msg,
'shortMsg' => $msg,
'info' => $info,
'url' => $url,
'errorField' => $errorField,
);
return $result;
}
// COM-API
protected function getDefaultApiReturnRec($error=null, $info='') {
$result = array(
'success' => false,
'error' => $error,
'info' => $info,
);
return $result;
}
protected function getDefaultAjaxDatatableReturnRec($request, $error='', $info='', $url='') {
$result = array(
'draw' => $request->request->get('draw'),
'recordsTotal' => 0,
'recordsFiltered' => 0,
'data' => [],
'error' => $error,
'info' => $info,
'url' => $url,
);
return $result;
}
protected function buildListViewRenderArray($sectionTitle, $entity=null, $params=null) {
$datatableDefaultsArray = array(
'module' => $this->module,
'dataUrl' => "/{$this->module}/get",
'addUrl' => "/{$this->module}/new",
'editUrl' => "/{$this->module}/[id]",
'deleteUrl' => "/{$this->module}/[id]/delete",
'searching' => $this->listViewSettings['searching'],
'searchLabel' => (isset($this->listViewSettings['searchLabel']) ? $this->listViewSettings['searchLabel'] : null),
'ordering' => $this->listViewSettings['ordering'],
'orderingDefault' => (isset($this->listViewSettings['orderingDefault']) ? $this->listViewSettings['orderingDefault'] : null),
'columns' => [],
'columnDefs' => [],
);
$datatableColumnArray = array();
$datatableColumnDefArray = array();
// fill in columns and columnDefs
$colNumber = 0;
//dump($this->listViewSettings['columns']);
foreach($this->listViewSettings['columns'] as $colName=>$colInfo) {
// columns
if (isset($colInfo['label'])) {
if (is_array($colInfo['label'])) {
$datatableColumnArray[] = [
'title' => $this->translator->trans($colInfo['label'][0], array(), $colInfo['label'][1]),
];
} else {
$datatableColumnArray[] = [
'title' => $colInfo['label'],
];
}
} else if (in_array($colName, ['createdAt'])) {
$datatableColumnArray[] = [
'title' => $this->translator->trans("field.$colName", array(), 'general'),
];
} else {
$datatableColumnArray[] = [
'title' => $this->translator->trans("field.$colName", array(), $this->module),
];
}
// columnDefs
$thisColumnDef = [];
if (isset($colInfo['tp'])) {
// type
if ($colInfo['tp']=='hidden' || $colInfo['tp']=='ignore') {
$thisColumnDef['visible'] = false;
} else if ($colInfo['tp']=='non-db') {
$thisColumnDef['visible'] = $colInfo['show'] ?? false;
} else if ($colInfo['tp']=='extra') { // COM-685
$thisColumnDef['visible'] = $colInfo['show'] ?? false;
} else if ($colInfo['tp']=='expand-button') {
$thisColumnDef['expand-button'] = true;
}
}
// is searchable?
if (isset($colInfo['orderable']) && $colInfo['orderable']===true) {
$thisColumnDef['orderable'] = true;
} else {
$thisColumnDef['orderable'] = false;
}
if (isset($colInfo['class']) && $colInfo['class']!='') {
$thisColumnDef['class'] = $colInfo['class'];
}
if (count($thisColumnDef)>0) {
$thisColumnDef['targets'] = $colNumber;
$datatableColumnDefArray[] = $thisColumnDef;
}
$colNumber++;
}
//dump($datatableDefaultsArray, $datatableColumnArray, $datatableColumnDefArray);
// countries
$countriesArray = $this->formsHelper->getCountries($this->currentCountry);
// check if need to show a page other than first page
//dump($this->session->get('list-page-info'));
$initialPageOffset = '';
$initialPageSize = '';
/*$sessionListPageInfo = $this->session->get('list-page-info');
if ($sessionListPageInfo!=null) {
$sessionListPageInfoArr = explode(';', $sessionListPageInfo);
if ($sessionListPageInfoArr[0]==$this->module) {
$initialPageOffset = $sessionListPageInfoArr[1];
$initialPageSize = $sessionListPageInfoArr[2];
$datatableDefaultsArray['displayStart'] = $initialPageOffset;
$datatableDefaultsArray['pageLength'] = $initialPageSize;
}
} else*/
/*if (isset($_COOKIE[$this->module.'_list-page'])) {
$cookieListPageInfoArr = explode(';', $_COOKIE[$this->module.'_list-page']);
$initialPageOffset = $cookieListPageInfoArr[0];
$initialPageSize = $cookieListPageInfoArr[1] ?? 10;
$datatableDefaultsArray['displayStart'] = $initialPageOffset;
$datatableDefaultsArray['pageLength'] = $initialPageSize;
//dump("info from cookie: initialPageOffset: $initialPageOffset, initialPageSize: $initialPageSize");
}*/
//dump($_COOKIE);
return $this->buildRenderArray($this->module, array(
'section_title' => $sectionTitle,
'settings_js' => json_encode($datatableDefaultsArray),
'datatableColumnArray_js' => json_encode($datatableColumnArray),
'datatableColumnDefArray_js' => json_encode($datatableColumnDefArray),
'countriesArray_js' => json_encode($countriesArray),
'entity' => $entity,
//'initialPageOffset' => $initialPageOffset,
//'initialPageSize' => $initialPageSize,
), null, $params);
}
protected function getListViewData($request, $customDataUpdaterFunction=null, $searchParms=null, $getAll=false) {
//dump('getListViewData', $request, $searchParms);
$result = array(
'draw' => $request->request->get('draw'),
'recordsTotal' => 0,
'recordsFiltered' => 0,
'data' => [],
'error' => '',
);
/* // check permissions & handle actions common to every request
$rc = $this->handleControllerAction($request, $this->module, 'list', $this->emptyEntity, true);
if ($rc!==true && $this->redirectRoute!=null) { //T
$result['info'] = 'no access';
$result['url'] = $this->router->generate($this->redirectRoute);
return $result;
}*/
$queryParms = new \stdClass();
if ($getAll===true) {
$queryParms->offset = 0;
$queryParms->pageSize = 9999999999999999;
} else {
$queryParms->offset = $request->request->get('start');
$queryParms->pageSize = $request->request->get('length');
$sessionListPageInfo = $this->module.';'.$queryParms->offset.';'.$queryParms->pageSize;
$this->session->set('list-page-info', $sessionListPageInfo);
}
// sorting
if (isset($this->listViewSettings['ordering']) && $this->listViewSettings['ordering']===true) {
// get requested sort order
$orderParams = $request->request->get('order');
if ($orderParams==null) $orderParams = [1,'asc']; // generic, added for COM-695
foreach($orderParams as $orderColumnInfo) {
// [ "column" => "1", "dir" => "desc" ]
//dump($orderColumnInfo);
break;
}
// find the field that is column $orderColumnInfo["column"]
$colNum = 0;
foreach($this->listViewSettings['columns'] as $colName=>$colInfo) {
if ($colNum==intval($orderColumnInfo["column"])) {
$queryParms->sortBy = $colName;
$queryParms->sortDesc = ($orderColumnInfo["dir"]=="desc");
break;
}
$colNum++;
}
}
$querySearchInfo = $request->request->get('search');
$querySearchColumns = $request->request->get('columns');
//dump('querySearchInfo', $querySearchInfo, 'querySearchColumns', $querySearchColumns);
$queryParms->searchParms = [];
// if a company is not selected, then the list pages for all classes listed in self::EMPTY_COMPANY_CLASSES need to show no data
if (in_array($this->modulePath, self::EMPTY_COMPANY_CLASSES)) {
/*if ($this->getUser()->__get('currentCompanyViewed')==null) {
// return empty result
return $result;
}*/
}
// users list -
if ($this->modulePath==User::class) {
// check if company selected
switch ($this->getUser()->getRolesUnconverted()) {
case UserRoleEnum::ROLE_SUPER_ADMIN:
if (isset($this->serverUsersArea) && $this->serverUsersArea===true) { // COM-843
unset($queryParms->searchParms['account']);
unset($queryParms->searchParms['company']);
$queryParms->searchParms['roles'] = ['IN', [
UserRoleEnum::ROLE_USER,
UserRoleEnum::ROLE_ADMIN,
UserRoleEnum::ROLE_ACCOUNT_OWNER,
UserRoleEnum::ROLE_SUPER_ADMIN,
UserRoleEnum::ROLE_UPLOAD_ONLY,
UserRoleEnum::ROLE_UPLOAD_PROTOCOL,
UserRoleEnum::ROLE_TRANSLATOR,
]];
$date24hAgo = $this->timeCalc->alterDateTimeByMinutes($this->timeCalc->currentDateTime, -1440, false, false);
$queryParms->searchParms['lastActionAt'] = $date24hAgo; // applies >= filter
} else if ($this->getUser()->__get('currentCompanyViewed')==null) {
// company not selected - show ONLY superadmin users in the system
$queryParms->searchParms['roles'] = ['IN', [UserRoleEnum::ROLE_SUPER_ADMIN,
UserRoleEnum::ROLE_TRANSLATOR]]; // COM-794
} else {
// company selected - show ((??superadmin users AND??)) users all users at this ACCOUNT
$queryParms->searchParms['account'] = $this->getUser()->__get('currentCompanyViewed')->__get('account')->getId();
//dump($this->company);
}
break;
case UserRoleEnum::ROLE_ACCOUNT_OWNER:
// show all users for this account
////dump($this->account);
////$queryParms->searchParms['account'] = $this->account;
$queryParms->searchParms['account'] = $this->getUser()->__get('currentCompanyViewed')->__get('account')->getId();
break;
case UserRoleEnum::ROLE_ADMIN:
// show all ADMIN and VIEW users for this account
if ($this->getUser()->__get('currentCompanyViewed')==null) {
$queryParms->searchParms['account'] = $this->getUser()->__get('account')->getId();
} else {
$queryParms->searchParms['account'] = $this->getUser()->__get('currentCompanyViewed')->__get('account')->getId();
}
$queryParms->searchParms['roles'] = ['IN', [UserRoleEnum::ROLE_ADMIN, UserRoleEnum::ROLE_USER]];
break;
case UserRoleEnum::ROLE_USER:
default:
// should never come here, return empty set
return $result;
}
} else if ($this->modulePath==Company::class) {
// COM-815.a
$searchParms = null;
if (isset($this->account) && $this->account->getType()==AccountTypeEnum::EXTERNALLY_MANAGED) {
// externally-managed account
if ($this->getUser()->getRolesUnconverted()==UserRoleEnum::ROLE_SUPER_ADMIN ||
$this->getUser()->getRolesUnconverted()==UserRoleEnum::ROLE_ACCOUNT_OWNER) {
// COMPASS user and 'registered' user (account owner) - can see all the companies in the account
$queryParms->searchParms['account'] = $this->account;
} else {
// companies in the account don't see each other
// force the search to get the current company only
if ($this->company!=null) {
$queryParms->searchParms['id'] = $this->company->getId();
}
}
} else {
if ($this->getUser()->getRolesUnconverted()==UserRoleEnum::ROLE_SUPER_ADMIN) {
if ($this->getUser()->__get('currentCompanyViewed')==null) {
// show empty companies
return $result;
} else {
// admin user and company selected - get all companies belonging to this account
$queryParms->searchParms['account'] = $this->getUser()->__get('currentCompanyViewed')->getAccount();
//dump($currentCompanysAccount);
}
} else {
// get all companies with the current account
$queryParms->searchParms['account'] = $this->account;
}
}
} else if (in_array($this->modulePath, self::PARAMETER_CLASSES)) {
// parameter entity
if ($this->company!=null && $this->company->__get('localParamsChanged')==false) {
// we have a company, and there were no changes made to local parameters - show global parameters!
$queryParms->searchParms['company'] = null;
} else {
// else show local parameters
if (property_exists($this->modulePath, 'account')) $queryParms->searchParms['account'] = $this->account;
if (property_exists($this->modulePath, 'company')) $queryParms->searchParms['company'] = $this->company;
}
} else if ($this->modulePath==CustomField::class) {
$queryParms->language = $this->currentLanguage;
} else {
if (property_exists($this->modulePath, 'account')) $queryParms->searchParms['account'] = $this->account;
if (property_exists($this->modulePath, 'company')) $queryParms->searchParms['company'] = $this->company;
}
// if we're getting DayAssignments, and this is a Hungary-based company, show Compass-defined entities
//dump('queryParms', $queryParms);
if ($this->getUser()->__get('currentCompanyViewed')!=null &&
$this->modulePath==DayAssignment::class) {
if ($this->company->__get('country')!==null && $this->company->__get('country')=='hu') {
$queryParms->searchParms['company'] = null;
//dump('getListViewData, hun country');
}
}
//die('3333');
// apply search/filter
//dump('querySearchInfo', $querySearchInfo);
if (isset($querySearchInfo['value']) && $querySearchInfo['value']!=='') {
// search all displayed columns by one value
$queryParms->searchParms['*'] = $querySearchInfo['value'];
//dump($this->listViewSettings); die();
// special action if deleted field is included
if (isset($this->listViewSettings['columns']['deleted'])) {
// find the deleted column
$idx = 0;
foreach($this->listViewSettings['columns'] as $colName=>$colInfo) {
if ($colName=='deleted') break; // use current $idx
$idx++;
}
if ($querySearchColumns[$idx]['search']['value']==='ALL') {
$queryParms->searchParms['deleted'] = 'ALL';
}
}
}
//dump('searchParms', $searchParms);
if ($searchParms!=null) {
foreach($searchParms as $searchField=>$searchValue) {
$queryParms->searchParms[$searchField] = $searchValue;
}
} else {
// search specified columns only
$colNumber = 0;
foreach($this->listViewSettings['columns'] as $colName=>$colInfo) {
//dump($colName, $colInfo);
if (isset($colInfo['filtered']) && $colInfo['filtered']===true) {
//dump('>>', $querySearchColumns[$colNumber]);
if ($querySearchColumns[$colNumber]['search']['value']!=='') {
$queryParms->searchParms[$colName] = $querySearchColumns[$colNumber]['search']['value'];
//dump('add');
}
}
$colNumber++;
}
}
//dump('queryParms', $queryParms);
//die();
// do a pass through settings to see what we have
$inThisSearch = [
'dayTitles' => false,
];
foreach($this->listViewSettings['columns'] as $colName=>$colInfo) {
if (!isset($colInfo['tp'])) continue;
if ($colInfo['tp']=='relationship') {
if ($colInfo['entity']=='DayTitle') {
$inThisSearch['dayTitles'] = true;
}
}
}
//dump('queryParms', $queryParms);
/*
// if day titles, sorting is tricky - so get all the rows first, and then will filter out those not necessarily
if ($this->modulePath==DayTitle::class) {
//dump('queryParms', $queryParms);
$queryParms->offset = 0;
$queryParms->pageSize = 999;
} */
// COM-288: for waybills, the search in the page uses startDate and endDate, but in the db it is only
// for endDate (endDate must be in the range specified by searchParms[startDate] and searchParms[endDate]
if ($this->modulePath==Consumption::class) {
//dump('$queryParms->searchParms', $queryParms->searchParms);
if ($queryParms->searchParms['startDate']!='' && $queryParms->searchParms['endDate']!='') {
// this is actually a search by range of the endDate ONLY
$queryParms->searchParms['endDate'] = ['IN-RANGE', [$queryParms->searchParms['startDate'],
$queryParms->searchParms['endDate']]];
unset($queryParms->searchParms['startDate']);
//dump('$queryParms->searchParms (2)', $queryParms->searchParms);
}
}
// COM-400: for event log (manual activities), the search in the page uses startDate and endDate, but in the db it is
// only for createdAt (createdAt must be in the range specified by searchParms[startDate] and searchParms[endDate])
if ($this->modulePath==DriverManualActivity::class) {
//dump('$queryParms->searchParms', $queryParms->searchParms);
if (isset($queryParms->searchParms['createdAt']) && $queryParms->searchParms['createdAt']!='') {
$createdAtArray = explode(",", $queryParms->searchParms['createdAt']);
$queryParms->searchParms['createdAt'] = [
'IN-RANGE',
[$createdAtArray[0].' 00:00:00', $createdAtArray[1].' 23:59:59']
];
//dump('$queryParms->searchParms (2)', $queryParms->searchParms);
//dump('new createdAt', $queryParms->searchParms['createdAt']);
}
// COM-409
$queryParms->sortBy = 'createdAt';
$queryParms->sortDesc = 'desc';
}
// COM-431
if ($this->modulePath==ConsumptionsTanking::class) {
$queryParms->sortBy = 'date,kmAtTanking';
$queryParms->sortDesc = false;
//dump('ConsumptionsTanking');
}
$repository = $this->getDoctrine()->getRepository($this->modulePath);
$customFieldRepository = $this->getDoctrine()->getRepository(CustomField::class);
$customFieldLabelRepository = $this->getDoctrine()->getRepository(CustomFieldLabel::class);
//dump($repository);
// get count
$count = $repository->getCount($queryParms, $this->listViewSettings['columns']);
//dump('count', $count);
//die();
// prepare for the search
$dayTitlesArray = []; // codes
$dayTitleDescriptionsArray = []; // descriptions
if ($inThisSearch['dayTitles']) {
$dayTitlesArray = $this->getCompanyDayTitles(true, false);
$dayTitleDescriptionsArray = $this->getCompanyDayTitles(false, false);
//dump('dayTitlesArray', $dayTitlesArray);
//dump('dayTitleDescriptionsArray', $dayTitleDescriptionsArray);
}
//dump("IS RAW REPO", $repository->isRawRepository());
// get data
$data = [];
$dbEntities = $repository->getPaginatedData($queryParms, $this->listViewSettings['columns'], $repository->isRawRepository());
//dump('dbEntities', $dbEntities); //die();
if ($dbEntities!=null) {
$customFieldLabels = [];
// get driversLicenseCardExpiry label (custom field) --> ACTUALLY, this is driverCardExpiry, but don't want to change code to fix this
$driversLicenseCardExpiryLabel = '';
if ($_SERVER['APP_DRIVER_CARD_EXPIRY_CUSTOM_FIELD_ID']!='') {
$driversLicenseCardExpiry_customField = $this->getDoctrine()->getRepository(CustomField::class)
->findOneById($_SERVER['APP_DRIVER_CARD_EXPIRY_CUSTOM_FIELD_ID']);
if ($driversLicenseCardExpiry_customField!=null) {
$driversLicenseCardExpiry_label = $this->getDoctrine()->getRepository(CustomFieldLabel::class)->findOneBy([
'customField' => $driversLicenseCardExpiry_customField,
'language' => $this->currentLanguage,
]);
if ($driversLicenseCardExpiry_label!=null) {
$driversLicenseCardExpiryLabel = $driversLicenseCardExpiry_label->__get('name');
}
}
}
//dump('driversLicenseCardExpiryLabel', $driversLicenseCardExpiryLabel);
foreach($dbEntities as $d) {
// if array (as for some tables), convert array into object with regular methods
//if (gettype($d)=='array') {
if ($repository->isRawRepository()) {
$d = new RawDbRecord($d);
//dump($d);
}
//if ($d->__get('itemType')==LogItemTypeEnum::TO_DO_ITEM) continue;
$detailsArray = [];
if ($this->module=='log-entries' ||
$this->module=='expenses') {
//dump($d);
//if ($d->getId()==795) continue;
if ($d->__get('itemType')==LogItemTypeEnum::BALANCE) continue; //JNOTE
if ($d->__get('detailsExist')==true) {
// load extra data about this row (from a separate table, holding additional details)
$rc = $this->db->query("SELECT * FROM ".$this->listViewSettings['columns']['details']['table-name']."
WHERE id='".($d->getId())."'", false); //idx
if ($rc) {
$dbRows = $this->db->fetchAll(true);
if (count($dbRows)>0) {
$detailsArray = json_decode($dbRows[0]['changes_made'], TRUE);
}
}
//dump('changeType: '.$d->__get('changeType').', detailsArray', $detailsArray, $this->listViewSettings['columns']);
}
} else if ($this->module=='work-periods') {
//dd("WORK PERIOD", $d);
$daysInWorkPeriod = $this->calcHelper->getWorkDaysInPeriod($d);
//dump($d->__getDateFormatted('startDate').' ... '.$d->__getDateFormatted('endDate'), $daysInWorkPeriod);
$d->__set('workHours', $daysInWorkPeriod['numberOfWorkDays'] * 8);
$d->__set('workHours6', $daysInWorkPeriod['numberOfWorkDays'] * 6);
$d->__set('workHours4', $daysInWorkPeriod['numberOfWorkDays'] * 4);
if (0) { //JNOTE-TESTING
$d->__set('workHours4', "W:{$daysInWorkPeriod['numberOfWorkDays']}, R:{$daysInWorkPeriod['numberOfNonWorkDays']}");
}
}
$thisEntityData = [];
foreach($this->listViewSettings['columns'] as $colName=>$colInfo) {
//dump("************** $colName ****************");
//dump($colInfo);
try {
$done = false;
if (isset($colInfo['tp'])) {
/*if ($colInfo['tp']=='ignore') {
// ignore it, needed for something else (not getting data)
$done = true;
}*/
if ($colInfo['tp']=='non-db') {
// ignore it, needed for something else (not getting data)
$thisEntityData[] = '';
$done = true;
} else if ($colInfo['tp']=='date') {
$thisEntityData[] = $d->__getDateFormatted($colName) ?? '';
$done = true;
} else if ($colInfo['tp']=='datetime') {
$thisEntityData[] = $d->__getDateTimeFormatted($colName) ?? '';
$done = true;
} else if ($colInfo['tp']=='time') {
$thisEntityData[] = $d->__getTimeFormatted($colName) ?? '';
$done = true;
} else if ($colInfo['tp']=='time-as-float') {
$thisEntityData[] = str_replace(".", ":", $d->__get($colName));
$done = true;
} else if ($colInfo['tp']=='boolean') {
if (isset($colInfo['reverse']) && $colInfo['reverse']===true) {
$thisEntityData[] = BooleanEnum::getLabel(!$d->__get($colName), $this->translator);
} else {
$thisEntityData[] = BooleanEnum::getLabel($d->__get($colName), $this->translator);
}
$done = true;
} else if ($colInfo['tp']=='buttonlink') {
$thisEntityData[] = "<a target='_blank' href=\"{$d->__get($colName)}\" class='btn btn-primary'>{$this->translator->trans($colInfo['buttonlabel'][0], array(), $colInfo['buttonlabel'][1])}</a>";
$done = true;
} else if ($colInfo['tp']=='enum') {
//dump('list - enum '.$colInfo['enum'].', '.$d->__get($colName));
//$thisEntityData[] = $colInfo['enum']::getLabel(intval($d->__get($colName)), $this->translator);
if (isset($colInfo['specialEnum']) && $colInfo['specialEnum']==true) {
//dump('specialEnum', $colInfo);
$thisEntityRow = $colInfo['enum']::getLabel2($d->__get($colName), $colInfo['specialConstant'], $this->translator, 'countries');
//dump('>> specialEnum', $thisEntityRow);
} else {
$thisEntityRow = $colInfo['enum']::getLabel($d->__get($colName), $this->translator);
}
if (0&&isset($_SERVER['APP_SHOW_DEBUG_IDS']) && $_SERVER['APP_SHOW_DEBUG_IDS']=='true') {
$thisEntityRow .= ' ('.$d->__get($colName).')';
}
$thisEntityData[] = $thisEntityRow;
$done = true;
} else if ($colInfo['tp']=='relationship') {
//dump('relationship');
if ($repository->isRawRepository()) {
//dump('relationship (repo raw)');
if ($colInfo['entity']=='DayTitle') {
//dump($d, $colInfo);
//$dayTitleId = $d['day_title_id']; //->__get($colName)->getType();
//$thisEntityData[] = $this->translator->trans( DayTitleTypeEnum::LABELS[$dayTitleType]['label'], array(),
// DayTitleTypeEnum::LABELS[$dayTitleType]['module'] );
$dayTitleLabel = '';
if (isset($colInfo['showType']) && $colInfo['showType']==='description') {
$dayTitleLabel = $dayTitleDescriptionsArray[ $d->__get('day_title_id') ] ?? '';
}
if ($dayTitleLabel==='') {
$dayTitleLabel = $dayTitlesArray[ $d->__get('day_title_id') ] ?? '';
}
$thisEntityData[] = $dayTitleLabel;
} else if ($colInfo['entity']=='Driver') {
//dump("************** $colName ****************");
//dump($d);
//echo($d->driver_id."\n");
if ($d->driver_id!=null) {
//dump($d->driver_id);
//dump(mb_detect_encoding($d->driver_id));
if (0) {
//dump($d->driver_id);
$thisEntityData[] = mb_convert_encoding(trim($d->driver_id), 'UTF-8', 'UTF-8');
//dump($thisEntityData);
} else if (0) {
$d->driver_id = trim($d->driver_id);
$newName = '';
for($g=0; $g<=strlen($d->driver_id); $g++) {
$char = substr($d->driver_id, $g, 1);
//dump($char, ord($char), chr(ord($char)));
if (ord($char)==211) {
$newName .= 'O'; //utf8_encode(0xC3);
} else {
$newName .= $char;
}
}
//dump("newName", $newName);
$thisEntityData[] = $newName; // this is the driver name
} else {
$thisEntityData[] = trim($d->driver_id);
}
}else {
$thisEntityData[] = '';
}
} else {
$thisEntityData[] = $d->__get($colName);
}
} else {
//dump('relationship (repo not raw)');
if ($colInfo['entity']=='Driver') {
//dump($d);
if ($d->__get($colName)!=null) {
$thisEntityData[] = trim($d->__get($colName)->getLastName() . ' ' . $d->__get($colName)->getFirstName());
//dump($d->__get($colName)->getLastName() . ' ' . $d->__get($colName)->getFirstName());
}else {
$thisEntityData[] = '';
}
}else if ($colInfo['entity']=='Trailer') {
if ($d->__get($colName)!=null) {
$thisEntityData[] = $d->__get($colName)->getName() ?? '';
}else {
$thisEntityData[] = '';
}
}else if ($colInfo['entity']=='Company') {
if ($d->__get($colName)!==null) {
$thisEntityData[] = $d->__get($colName)->getName() ?? '';
}else {
$thisEntityData[] = $this->company->getName();
}
} else if ($colInfo['entity']=='DayTitle') {
//dump("****DayTitle");
//$thisEntityData[] = $d->__get($colName)->getCode() ?? '';
if ($d->__get($colName)!=null) {
$dayTitleType = $d->__get($colName)->getType();
//dump($dayTitleType, $dayTitleDescriptionsArray, $dayTitlesArray, $colInfo, $d->__get('dayTitle')->getId(), $dayTitleType);
$dayTitleLabel = '';
if (isset($colInfo['showType']) && $colInfo['showType']==='description') {
$dayTitleLabel = $dayTitleDescriptionsArray[ $d->__get('dayTitle')->getId() ] ?? '';
}
if ($dayTitleLabel==='') {
$dayTitleLabel = $dayTitlesArray[ $d->__get('dayTitle')->getId() ] ?? '';
}
$thisEntityData[] = $dayTitleLabel;
//$thisEntityData[] = $d->getId();
} else {
$thisEntityData[] = '';
}
} else if ($colInfo['entity']=='CustomFieldLabel') {
//dump('---', $d->__get('customFieldLabels')[0] ?? ''); //, $d->__get('customFieldLabels')[1] ?? '');
//dump($d, $d->__get('customFieldLabels')[0]);
/*if (isset($d->__get('customFieldLabels')[0])) {
$thisEntityData[] = $d->__get('customFieldLabels')[0]->getName() ?? '';
} else {
$thisEntityData[] = '';
}*/
$thisEntityData[] = $d->__get('customFieldLabels') ?? '';
} else if ($colInfo['entity']=='User') {
if ($d->__get($colName)!=null) {
$thisEntityData[] = $d->__get($colName)->getUsername() ?? '';
} else {
$thisEntityData[] = '';
}
} else {
$thisEntityData[] = $d->__get($colName)->getName() ?? '';
}
}
$done = true;
} else if ($colInfo['tp']=='multi-entity-name') {
$thisClassPath = $this->logger->itemTypeToModuleClassPath( $d->__get('itemType') );
$thisClassNameVariants = $this->nc->getClassNameVariantsFromPath($thisClassPath);
//dump("itemType: ".$d->__get('itemType').", thisClassPath: $thisClassPath, thisClassNameVariants", $thisClassNameVariants, $d);
if ($d->__get('itemType')==LogItemTypeEnum::ROUTE_WAYPOINT) {
$thisEntityData[] = '';
$done = true;
} else if ($d->__get('itemType')==LogItemTypeEnum::DRIVER_ACTIVE_DAY) { // COM-806
$activeDayDriver = $this->getDoctrine()->getRepository(Driver::class)->findOneById( $d->getItemId() );
$thisEntityData[] = $activeDayDriver->getName();
if (count($dayTitlesArray)==0) {
$dayTitlesArray = $this->getCompanyDayTitles(true, false);
//$dayTitleDescriptionsArray = $this->getCompanyDayTitles(false, false);
//dump('dayTitlesArray', $dayTitlesArray);
}
$done = true;
} else if ($d->__get($colName)!=null) {
// entity
if ($thisClassPath==DriverSpecialEvent::class) {
$specialEvent = $this->getDoctrine()->getRepository($thisClassPath)->findOneById( $d->__get($colName) );
$driverName = $specialEvent->getDriver()->getName();
$thisEntityData[] = DriverSpecialEventEnum::getLabel($specialEvent->__get('type'), $this->translator).'<br>'.
$specialEvent->__getDateTimeFormatted('timestamp').'<br>'.
$driverName;
} else if ($thisClassPath==DriverManualActivity::class) {
$manualActivity = $this->getDoctrine()->getRepository($thisClassPath)->findOneById( $d->__get($colName) );
$driverName = $manualActivity->getDriver()->getName();
$thisEntityData[] = DriverActivityTypeEnum::getLabel($manualActivity->__get('activityType'), $this->translator).'<br>'.
$manualActivity->__getDateTimeFormatted('startDateTime').' - '.
$manualActivity->__getDateTimeFormatted('endDateTime').'<br>'.
$driverName;
} else if ($thisClassPath==DriverWeeklyRestTimeException::class) {
$weeklyRest = $this->getDoctrine()->getRepository($thisClassPath)->findOneById( $d->__get($colName) );
$driverName = $weeklyRest->getDriver()->getName();
$weekEndSunday = $weeklyRest->__getDateFormatted('weekBoundaryDay');
/*if ($weeklyRest->__get('assignedWeek')==0) {
$weekStr = $this->timeCalc->alterDateTimeByDays($weekEndSunday, -6, true).' - '.
$weekEndSunday;
} else {
$weekStr = $this->timeCalc->alterDateTimeByDays($weekEndSunday, 1, true).' - '.
$this->timeCalc->alterDateTimeByDays($weekEndSunday, 7, true);
}*/
$thisEntityData[] = 'Rest for week ending on: '.$weekEndSunday.'<br>'.
//'Assigned to week: '.$weekStr.'<br>'.
$driverName;
} else if ($thisClassPath==ToDoItem::class) {
// special handling - the entity id is actually inside of $detailsArray
//dump('detailsArray!!!!', $detailsArray, $d);
//dump('---', $colName, $colInfo);
$entityName = '';
if (isset($detailsArray['toDoItemType'])) {
if ($detailsArray['toDoItemType']==ToDoItemTypeEnum::STANDARD_DRIVER) {
// this is a driver, its id is stored in itemId
$item = $this->getDoctrine()->getRepository(Driver::class)->findOneById( $d->__get($colName) );
$entityName = $item->getName().'<br>(driver)';
} else if ($detailsArray['toDoItemType']==ToDoItemTypeEnum::STANDARD_VEHICLE) {
// this is a vehicle, its id is stored in itemId
$item = $this->getDoctrine()->getRepository(Vehicle::class)->findOneById( $d->__get($colName) );
$entityName = $item->getName().'<br>(vehicle)';
} else if ($detailsArray['toDoItemType']==ToDoItemTypeEnum::CUSTOM_FIELD) {
// this is a custom field, its id is stored in itemId
//dump('detailsArray!!!!', $detailsArray);
// find custom field id
$customFieldId = null;
foreach($detailsArray as $keyname=>$keyinfo) {
if (substr($keyname,0,2)=='c.') {
$customFieldId = substr($keyname,2);
break;
}
}
//dump('customFieldId: '.$customFieldId);
// get custom field
$customField = $this->getDoctrine()->getRepository(CustomField::class)->findOneById($customFieldId); // $detailsArray['customFieldId'] );
//dump('customField', $customField);
// get custom field label
$cfLabel = $this->getDoctrine()->getRepository(CustomFieldLabel::class)->findOneBy([
'customField' => $customField,
'language' => $this->currentLanguage,
]);
//dump('cfLabel', $cfLabel);
$entityName = '';
if ($customField->getCategory()==CustomFieldCategoryEnum::COMPANY) { //
$thisEntity = $this->getDoctrine()->getRepository(Company::class)->findOneById( $d->__get($colName) );
$entityTypeStr = $this->translator->trans("loggedItemType.COMPANY", array(), 'log-entries');
$entityName = $thisEntity->getName()."<br>($entityTypeStr)";
} else if ($customField->getCategory()==CustomFieldCategoryEnum::DRIVER) { //
$thisEntity = $this->getDoctrine()->getRepository(Driver::class)->findOneById( $d->__get($colName) );
$entityTypeStr = $this->translator->trans("loggedItemType.DRIVER", array(), 'log-entries');
$entityName = $thisEntity->getName()."<br>($entityTypeStr)";
} else if ($customField->getCategory()==CustomFieldCategoryEnum::VEHICLE) { //:dist, :date
$thisEntity = $this->getDoctrine()->getRepository(Vehicle::class)->findOneById( $d->__get($colName) );
$entityTypeStr = $this->translator->trans("loggedItemType.VEHICLE", array(), 'log-entries');
$entityName = $thisEntity->getName()."<br>($entityTypeStr)";
} else if ($customField->getCategory()==CustomFieldCategoryEnum::TRAILER) { //:date
$thisEntity = $this->getDoctrine()->getRepository(Trailer::class)->findOneById( $d->__get($colName) );
$entityTypeStr = $this->translator->trans("loggedItemType.TRAILER", array(), 'log-entries');
$entityName = $thisEntity->getName()."<br>($entityTypeStr)";
}
//dump('entityName ****', $entityName); die();
//die('pfff');
//$thisEntityData[] = '** cf **';
//dump($d);
//die();
}
$thisEntityData[] = $entityName;
} else {
// normal to-do item (created on to-do page)
//dump('xxxx', $d, $colName); die();
$item = $this->getDoctrine()->getRepository($thisClassPath)->findOneById( $d->__get($colName) );
$thisEntityData[] = $item->getName() ?? '';
}
} else {
//dump($colName, $colInfo, "thisClassPath: $thisClassPath, colName $colName, value:", $d->__get($colName));
$item = $this->getDoctrine()->getRepository($thisClassPath)->findOneById( $d->__get($colName) );
$thisEntityData[] = $item->getName() ?? '';
}
} else {
// no entity (e.g. general "settings")
$thisEntityData[] = '';
}
$done = true;
} else if ($colInfo['tp']=='details-table') {
$thisClassPath = $this->logger->itemTypeToModuleClassPath( $d->__get('itemType') );
$thisClassNameVariants = $this->nc->getClassNameVariantsFromPath($thisClassPath);
//dump("itemType: ".$d->__get('itemType').", thisClassPath: $thisClassPath, thisClassNameVariants", $thisClassNameVariants);
//dump('detailsArray', $detailsArray);
//$detailsArray = [];
if ($d->__get('detailsExist')==true &&
count($detailsArray)>0) {
// special handling for to-do items - update thisClassPath
if ($thisClassPath==ToDoItem::class) {
if ($detailsArray['toDoItemType']==ToDoItemTypeEnum::STANDARD_DRIVER) {
$thisClassPath = Driver::class;
$thisClassNameVariants = $this->nc->getClassNameVariantsFromPath($thisClassPath);
} else if ($detailsArray['toDoItemType']==ToDoItemTypeEnum::STANDARD_VEHICLE) {
$thisClassPath = Vehicle::class;
$thisClassNameVariants = $this->nc->getClassNameVariantsFromPath($thisClassPath);
} else if ($detailsArray['toDoItemType']==ToDoItemTypeEnum::CUSTOM_FIELD) {
//$thisClassPath = Vehicle::class;
//dump('detailsArray ^^^^^^2', $detailsArray);
//die('pfff');
}
//$thisClassNameVariants = $this->nc->getClassNameVariantsFromPath($thisClassPath);
//dump("NEW thisClassPath: $thisClassPath, thisClassNameVariants", $thisClassNameVariants);
}
// COM-822
if ($thisClassNameVariants['classNameSmallPlural']=='drivers') {
if (isset($detailsArray['language'])) unset($detailsArray['language']); // not a user-visible field, don't show (may show in future)
if (isset($detailsArray['lastCardNumberActive'])) unset($detailsArray['lastCardNumberActive']); // not a user-visible field, don't show
}
foreach($detailsArray as $thisFieldName=>$details) {
if ($thisFieldName=='toDoItemType') continue;
if ($thisFieldName=='customFieldId') continue;
if (substr($thisFieldName, 0, 2)=='c.') {
// custom field - load its label
//dump('cf '.$thisFieldName);
$customFieldId = substr($thisFieldName, 2);
if (!isset($customFieldLabels[$customFieldId])) {
$customFieldLabel = $thisFieldName;
$customField = $customFieldRepository->findOneById($customFieldId);
//dump("customField $customFieldId", $customField);
if ($customField!=null) {
$customField_label = $customFieldLabelRepository->findOneBy([
'customField' => $customField,
'language' => $this->currentLanguage,
]);
//dump('customField_label '.$customField_label);
}
if ($customField_label!==null) { // COM-632(2)
$customFieldLabels[$customFieldId] = $customField_label->__get('name');
} else {
$customFieldLabels[$customFieldId] = ''; // COM-632(2)
}
}
$detailsArray[$thisFieldName]['label'] = $customFieldLabels[$customFieldId];
} else {
// normal field
$thisFieldNameForLabel = $thisFieldName;
if ($thisFieldName=='plainPassword') {
$thisFieldNameForLabel = 'password';
$detailsArray[$thisFieldName]['tp'] = 'password';
}
$thisFieldType = $detailsArray[$thisFieldName]['tp'] ?? null;
//dump("thisFieldName: [$thisFieldName], thisFieldType: [$thisFieldType]");
if ($thisClassNameVariants['classNameSmallPlural']=='settings') {
$thisFieldType = Setting::CONFIG[$thisFieldName]['type'];
if ($thisFieldType=='bool') $thisFieldType = 'boolean';
$detailsArray[$thisFieldName]['label'] = $this->translator->trans("field.$thisFieldName", array(), 'settings');
} else if ($thisClassNameVariants['classNameSmallPlural']=='drivers' && $thisFieldName=='driversLicenseCardExpiry') {
$detailsArray[$thisFieldName]['label'] = $driversLicenseCardExpiryLabel;
} else if ($thisClassNameVariants['classNameSmallPlural']=='driver-manual-activities') {
$detailsArray[$thisFieldName]['label'] = $this->translator->trans("field.$thisFieldNameForLabel", array(), 'driver-activities');
} else if ($thisClassPath==DriverWeeklyRestTimeException::class) {
$detailsArray[$thisFieldName]['label'] = $this->translator->trans("field.weeklyRestAssignedWeek", array(), 'driver-special-events');
} else {
// COM-806
if ($thisClassNameVariants['classNameSmallPlural']=='driver-active-days') {
//if ($thisFieldName=='date_id') {
// unset($detailsArray[$thisFieldName]['o']);
//}
//dump($detailsArray);
if ($thisFieldName=='day_title_id') {
$detailsArray[$thisFieldName]['o'] = $dayTitlesArray[ $detailsArray[$thisFieldName]['o'] ];
$detailsArray[$thisFieldName]['n'] = $dayTitlesArray[ $detailsArray[$thisFieldName]['n'] ];
}
}
$detailsArray[$thisFieldName]['label'] = $this->translator->trans("field.$thisFieldNameForLabel", array(), $thisClassNameVariants['classNameSmallPlural']);
//dump("field.$thisFieldNameForLabel", $thisClassNameVariants['classNameSmallPlural']);
}
$enumFieldType = $this->logger->getEnumTypeFromModuleAndField($thisClassNameVariants['classNameSmallPlural'], $thisFieldName, $getLabelFcn);
//dump("enumFieldType: $enumFieldType, getLabelFcn:", $getLabelFcn);
if ($enumFieldType!=null || $thisFieldType=='enum') {
//(isset($detailsArray[$thisFieldName]['tp']) && $detailsArray[$thisFieldName]['tp']=='enum')) {
if ($getLabelFcn!=null) {
$detailsArray[$thisFieldName]['o'] = $enumFieldType::$getLabelFcn($detailsArray[$thisFieldName]['o'], $this->translator, '');
$detailsArray[$thisFieldName]['n'] = $enumFieldType::$getLabelFcn($detailsArray[$thisFieldName]['n'], $this->translator, '');
}
} else if ($thisFieldType=='boolean') { //isset($detailsArray[$thisFieldName]['tp']) && $detailsArray[$thisFieldName]['tp']=='boolean') {
$oldLabel = "word.yes";
if ($detailsArray[$thisFieldName]['o']=='0' || $detailsArray[$thisFieldName]['o']==false) {
$oldLabel = "word.no";
}
$newLabel = "word.yes";
if ($detailsArray[$thisFieldName]['n']=='0' || $detailsArray[$thisFieldName]['n']==false) {
$newLabel = "word.no";
}
$detailsArray[$thisFieldName]['o'] = $this->translator->trans($oldLabel, array(), 'general');
$detailsArray[$thisFieldName]['n'] = $this->translator->trans($newLabel, array(), 'general');
} else if ($thisClassPath==DriverWeeklyRestTimeException::class && $thisFieldName=='weekBoundaryDay') {
$detailsArray[$thisFieldName]['skip'] = true; // not needed
} else if ($thisClassPath==DriverWeeklyRestTimeException::class && $thisFieldName=='assignedWeek') {
$weekEndSunday = $detailsArray['weekBoundaryDay']['n'];
//dump("weekEndSunday", $weekEndSunday);
$previousWeek = $this->timeCalc->alterDateTimeByDays($weekEndSunday, -6, true).' - '.
$weekEndSunday;
$nextWeek = $this->timeCalc->alterDateTimeByDays($weekEndSunday, 1, true).' - '.
$this->timeCalc->alterDateTimeByDays($weekEndSunday, 7, true);
if ($detailsArray[$thisFieldName]['o']==0 || $detailsArray[$thisFieldName]['o']=='') {
$detailsArray[$thisFieldName]['o'] = $previousWeek;
} else {
$detailsArray[$thisFieldName]['o'] = $nextWeek;
}
if ($detailsArray[$thisFieldName]['n']==0) {
$detailsArray[$thisFieldName]['n'] = $previousWeek;
} else {
$detailsArray[$thisFieldName]['n'] = $nextWeek;
}
}
//dump("detailsArray[$thisFieldName] ($thisClassPath)", $detailsArray[$thisFieldName]);
}
}
//dump("detailsArray ($thisClassPath)", $detailsArray);
}
//dump('detailsArray 2', $detailsArray);
if (isset($detailsArray['customFieldId'])) unset($detailsArray['customFieldId']);
$thisEntityData[] = $detailsArray;
$done = true;
} else if ($colInfo['tp']=='details-table2') {
//$thisClassPath = $this->logger->itemTypeToModuleClassPath( $d->__get('itemType') );
//$thisClassNameVariants = $this->nc->getClassNameVariantsFromPath($thisClassPath);
//dump("itemType: ".$d->__get('itemType').", thisClassPath: $thisClassPath, thisClassNameVariants", $thisClassNameVariants); die();
$detailsToShow = [
'type' => $d->__get('itemType'),
'changeType' => $d->__get('changeType'),
'export' => $detailsArray['export'] ?? false,
];
if ($d->__get('itemType')==LogItemTypeEnum::BALANCE2) {
// nothing to add
} else if ($d->__get('itemType')==LogItemTypeEnum::DRIVER_TOKEN) {
if (0 && $d->__get('changeType')==BalanceTypeEnum::DRIVER_TOKEN_USE) {
$detailsToShow['label1'] = 'dis';
$detailsToShow['name1'] = 'dat';
dump('detailsArray', $detailsArray);
}
} else if ($d->__get('itemType')==LogItemTypeEnum::DRIVER_FILE ||
$d->__get('itemType')==LogItemTypeEnum::TACHO_FILE) {
if (isset($detailsArray['entityId'])) {
$tachoFile = $this->getDoctrine()->getRepository(TachographFile::class)->findOneById($detailsArray['entityId']);
if ($tachoFile!==null) {
if ($d->__get('itemType')==LogItemTypeEnum::DRIVER_FILE) {
$detailsToShow['label1'] = $this->translator->trans('fileType.DRIVER_FILE', array(), 'tachograph-file-types');
} else {
$detailsToShow['label1'] = $this->translator->trans('fileType.TACHOGRAPH_FILE', array(), 'tachograph-file-types');
}
$detailsToShow['name1'] = $tachoFile->getName(); //JNOTE: line-break?
}
}
} else if ($d->__get('itemType')==LogItemTypeEnum::REPORT) {
if (isset($detailsArray['driverId1'])) { //T
if ($detailsArray['driverId1']==='all') {
$detailsToShow['label1'] = $this->translator->trans('option.allDrivers', array(), 'report-general');
$detailsToShow['name1'] = '-all-';
} else {
$driver1 = $this->getDoctrine()->getRepository(Driver::class)->findOneById($detailsArray['driverId1']);
if ($driver1!==null) {
$detailsToShow['label1'] = $this->translator->trans('label.driver', array(), 'report-general');
$detailsToShow['name1'] = $driver1->getName();
}
if (isset($detailsArray['driverId2'])) {
$driver2 = $this->getDoctrine()->getRepository(Driver::class)->findOneById($detailsArray['driverId2']);
if ($driver2!==null) {
$detailsToShow['label2'] = $this->translator->trans('label.driver', array(), 'report-general').' 2';
$detailsToShow['name2'] = $driver2->getName();
}
}
}
$detailsToShow['numDrivers'] = $detailsArray['numEntities'] ?? null;
} else if (isset($detailsArray['vehicleId1'])) {
if ($detailsArray['vehicleId1']==='Vall') {
$detailsToShow['label1'] = $this->translator->trans('option.allVehicles', array(), 'report-general');
$detailsToShow['name1'] = '-all-';
} else {
$vehicle1 = $this->getDoctrine()->getRepository(Vehicle::class)->findOneById($detailsArray['vehicleId1']);
if ($vehicle1!==null) {
$detailsToShow['label1'] = $this->translator->trans('label.vehicle', array(), 'report-general');
$detailsToShow['name1'] = $vehicle1->getName();
}
if (isset($detailsArray['vehicleId2'])) {
$vehicle2 = $this->getDoctrine()->getRepository(Vehicle::class)->findOneById($detailsArray['vehicleId2']);
if ($vehicle2!==null) {
$detailsToShow['label2'] = $this->translator->trans('label.vehicle', array(), 'report-general').' 2';
$detailsToShow['name2'] = $vehicle2->getName();
}
}
}
$detailsToShow['numVehicles'] = $detailsArray['numEntities'] ?? null;
}
$detailsToShow['reportClassLabel'] = $this->translator->trans('label.report', array(), 'report-general');
//$detailsToShow['reportClassName'] = ReportClass::getLabel( $detailsArray['reportClass'], $this->translator );
/*if (isset($detailsArray['balChgTp'])) {
if ($detailsArray['balChgTp']==BalanceTypeEnum::USAGE_DRIVER_FAULT_LIST_WITH_PENALTY) {
$detailsToShow['reportClassName'] .= " - with penalties";
} else if ($detailsArray['balChgTp']==BalanceTypeEnum::USAGE_DRIVER_PROTOCOL_WITH_PENALTY) {
$detailsToShow['reportClassName'] .= " - with penalties";
} else if ($detailsArray['balChgTp']==BalanceTypeEnum::USAGE_VEHICLE_TACHOGRAPHFAULTLISTNOCARDDRIVING) {
$detailsToShow['reportClassName'] .= " - with driving without card";
} else if ($detailsArray['balChgTp']==BalanceTypeEnum::USAGE_VEHICLE_SPECIALEVENTSNOCARDDRIVING) {
$detailsToShow['reportClassName'] .= " - with driving without card";
}
}*/
//dump($detailsArray['balChgTp'], $thisEntityData);
}
//dump('detailsToShow for '.$d->__get('changeType'), $detailsArray, $detailsToShow);
$thisEntityData[] = $detailsToShow;
$done = true;
} else if ($colInfo['tp']=='extra' /*|| $colInfo['tp']=='extra-hidden'*/) { // COM-685
$thisEntityData[] = $d->__get($colInfo['field-name']);
$done = true;
} else if ($colInfo['tp']=='expand-button') {
$thisEntityData[] = '';
$done = true;
}
}
if ($customDataUpdaterFunction!=null) {
//dump('pre-UPDATE thisEntityData:', $thisEntityData);
$updated = $customDataUpdaterFunction($colName, $colInfo, $d, $updatedValue);
//dump("rc from customDataUpdaterFunction: $updated", $updatedValue);
if ($updated===true) {
if ($done) {
// already added above, modify it
$updateIdx = count($thisEntityData) - 1;
$thisEntityData[ $updateIdx ] = $updatedValue;
//dump('UPDATING!, new thisEntityData:', $thisEntityData);
} else {
// not added above, add it here
$thisEntityData[] = $updatedValue;
$done = true;
}
}
}
if (!$done ) {
$thisEntityData[] = $d->__get($colName);
}
} catch(\Exception $e) {
$thisEntityData[] = '';
dump('exception', $e); die();
}
}
//dump('thisEntityData:', $thisEntityData);
$result['data'][] = $thisEntityData;
}
}
$result['recordsTotal'] = intval($count);
$result['recordsFiltered'] = intval($count); //count($result['data']);
//dump('result:', $result);
return $result;
}
public function getAllEntityData($entityPath, $sortColumn, $filterParms=null) {
//dump("getAllEntityData($entityPath, $sortColumn, filterParms)", $filterParms);
$queryParms = new \stdClass();
$queryParms->offset = 0;
$queryParms->pageSize = 9999999999999;
$queryParms->sortBy = $sortColumn;
$queryParms->sortDesc = false;
$queryParms->searchParms = [];
//dump($entityPath.', '.$this->company->__get('localParamsChanged').', '.$this->nc->classNameFromPath($entityPath), self::PARAMETER_CLASSES);
if ($this->company!=null && $this->company->__get('localParamsChanged')==false &&
in_array($entityPath, self::PARAMETER_CLASSES)) {
// parameter entity, and local params not yet created, so use the global params
$queryParms->searchParms['company'] = null;
} else {
// default
if (property_exists($entityPath, 'account')) $queryParms->searchParms['account'] = $this->account;
if (property_exists($entityPath, 'company')) $queryParms->searchParms['company'] = $this->company;
}
// if we're getting DayAssignments, and this is a Hungary-based company, show Compass-defined entities
//dump('queryParms', $queryParms);
if ($this->getUser()->__get('currentCompanyViewed')!=null &&
$entityPath==DayAssignment::class) {
if ($this->company->__get('country')!==null && $this->company->__get('country')=='hu') {
$queryParms->searchParms['company'] = null;
//dump('getAllEntityData, reset day assignment');
}
}
if (isset($filterParms)) {
foreach($filterParms as $key=>$value) {
if ($key=='account' || $key=='company') continue;
$queryParms->searchParms[$key] = $value;
}
}
//dump($entityPath, $queryParms);
$repository = $this->getDoctrine()->getRepository($entityPath);
// get data
$dbEntities = $repository->getPaginatedData($queryParms);
//dump($dbEntities); //die();
return $dbEntities;
}
protected function buildEditViewRenderArray($sectionTitle, $entity=null, $initialValues=null) {
$repository = $this->getDoctrine()->getRepository($this->modulePath);
if ($repository->isRawRepository()) {
$entity = new RawDbRecord($entity);
//dump($d);
}
$settingsArray = array(
'addUrl' => "/{$this->module}/add",
'updateUrl' => ($entity!=null) ? "/{$this->module}/".$entity->__get('id')."/save" : '',
'listUrl' => "/{$this->module}",
);
$entityRecord = [];
foreach($this->editViewSettings['fields'] as $fieldName=>$fieldInfo) {
$thisField = $fieldInfo;
$thisField['id'] = $fieldName;
if ($entity!=null) {
if (isset($fieldInfo['tp'])) {
if ($fieldInfo['tp']=='datetime') {
$thisField['value'] = $entity->__getDateTimeFormatted($fieldName) ?? '';
//dump('datetime', $thisField['value']);
$added = true;
} else if ($fieldInfo['tp']=='date') {
$thisField['value'] = $entity->__getDateFormatted($fieldName) ?? '';
$added = true;
} else if ($fieldInfo['tp']=='time') {
$thisField['value'] = $entity->__getTimeFormatted($fieldName) ?? '';
$added = true;
} else if ($fieldInfo['tp']=='non-db') {
// will be populated by the controller
$thisField['value'] = '';
$added = true;
} else if ($fieldInfo['tp']=='relationship') {
if ($repository->isRawRepository()) {
$thisEntityData[] = $entity->__get($fieldName);
} else {
$thisField['value'] = ($entity->__get($fieldName)==null) ? '' : $entity->__get($fieldName)->getId() ?? '';
$updated = true;
}
}
}
if (!isset($thisField['value'])) {
$thisField['value'] = $entity->__get($fieldName);
}
if (isset($initialValues[$fieldName])) {
$thisField['value'] = $initialValues[$fieldName];
}
}
if (!isset($thisField['value'])) {
$thisField['value'] = '';
}
$entityRecord[] = $thisField;
}
// custom fields
$customFieldsArray = [];
if (in_array($this->module, ['companies', 'drivers', 'vehicles', 'trailers'])) {
$customFieldRepository = $this->getDoctrine()->getRepository(CustomField::class);
$customFieldValueRepository = $this->getDoctrine()->getRepository(CustomFieldValue::class);
//dump('custom fields module', $this->module);
$customFieldCategoryType = CustomFieldCategoryEnum::moduleToCategoryType($this->module);
//dump('customFieldCategoryType', $customFieldCategoryType);
$dbCustomFieldsArray = $customFieldRepository->loadByCategory($customFieldCategoryType, $this->currentLanguage);
//dump('dbCustomFieldsArray', $dbCustomFieldsArray);
if ($dbCustomFieldsArray!=null) {
foreach($dbCustomFieldsArray as $r) {
$valueRec = $customFieldValueRepository->findOneBy([
'customField' => $r,
'entityId' => $entity->getId(),
]);
//dump('----', $r, $value);
$value = '';
if ($valueRec!=null) {
$value = $valueRec->__get('value');
}
$customFieldsArray[] = [
'customFieldId' => $r->getId(),
'type' => $r->__get('type'),
'tp' => ($r->__get('type')==CustomFieldTypeEnum::DATE ? 'date' : 'integer'),
'label' => $r->__get('name'), //.' '.$r->getId(),
'value' => $value,
//'maxlength' => ($r->__get('type')==CustomFieldTypeEnum) ? 30 : '',
];
}
}
//dump('customFieldsArray', $customFieldsArray);
}
// countries
$countriesArray = $this->formsHelper->getCountries($this->currentCountry);
return $this->buildRenderArray($this->module, array(
'section_title' => $sectionTitle,
'settings_js' => json_encode($settingsArray),
'entity_js' => json_encode($entityRecord),
'entity' => $entity,
'countriesArray' => $countriesArray,
'countriesArray_js' => json_encode($countriesArray),
'customFieldsArray' => $customFieldsArray,
'customFieldsArray_js' => json_encode($customFieldsArray),
), $entity);
}
protected function saveEditViewForm($request, $entity, &$result, $customDataUpdaterFunction=null, $requestOverrideData=null) {
/* // check permissions & handle actions common to every request
$rc = $this->handleControllerAction($request, $this->module, 'save', null, true);
if ($rc!==true && $this->redirectRoute!=null) { //T
$result['info'] = 'no access';
$result['url'] = $this->router->generate($this->redirectRoute);
return $result;
}*/
$em = $this->getDoctrine()->getManager();
// get parms
$data = $request->request->get('data');
//dump('====', $data); //dump($entity); die();
// override data
if ($requestOverrideData!=null) {
foreach($requestOverrideData as $k=>$v) {
if (isset($data[$k])) {
$data[$k] = $v;
}
}
}
//dump($requestOverrideData, $data);
$newEntity = false;
if ($entity===null) {
$entity = new $this->modulePath;
$newEntity = true;
if ($this->getUser()->getRolesUnconverted()==UserRoleEnum::ROLE_SUPER_ADMIN && $this->getUser()->__get('currentCompanyViewed')!=null) {
if ($this->modulePath==Company::class || $this->modulePath==User::class) {
// set to account currently selected (the one connected to the company currently selected)
$entity->__set('account', $this->getUser()->__get('currentCompanyViewed')->getAccount());
} else {
// set to company currently selected
$entity->__set('company', $this->getUser()->__get('currentCompanyViewed'));
}
} else {
if (property_exists($this->modulePath, 'account')) $entity->__set('account', $this->account);
if (property_exists($this->modulePath, 'company')) $entity->__set('company', $this->company);
}
}
$originalEntity = clone $entity;
$changesMade = [];
$entityUpdated = false;
foreach($data as $fieldName=>$fieldValue) {
if ($fieldName=='id') continue;
//dump($this->editViewSettings['fields'][$fieldName] || "$fieldName: no field!");
if (!isset($this->editViewSettings['fields'][$fieldName])) continue; // skip
//if ($fieldValue == '') continue; //******
$fieldInfo = $this->editViewSettings['fields'][$fieldName];
// JNOTE: mandatory check?
$updated = false;
$logChange = true;
$forceLogChange = false;
$oldValue = '';
$newValue = '';
if (isset($fieldInfo['tp'])) {
if ($fieldInfo['tp']=='date') {
$saveValue = ($fieldValue=='') ? null : $fieldValue;
$entity->__setDate($fieldName, $saveValue);
//dump("$fieldName: set date [$saveValue]");
$oldValue = $originalEntity->__getDateFormatted($fieldName);
$newValue = $saveValue;
$updated = true;
} else if ($fieldInfo['tp']=='time') {
$entity->__setTime($fieldName, $fieldValue);
//dump("$fieldName: set time", $fieldValue);
$oldValue = $originalEntity->__getTimeFormatted($fieldName);
$newValue = $fieldValue;
$updated = true;
} else if ($fieldInfo['tp']=='datetime') {
$saveValue = ($fieldValue=='') ? null : $fieldValue;
//if (!isset($fieldInfo['ignoreTz']) || $fieldInfo['ignoreTz']==false) $entity->setTimeZone();
$entity->__setDateTime($fieldName, $saveValue, false, true);
//dump("$fieldName: set date [$saveValue]");
$oldValue = $originalEntity->__getDateTimeFormatted($fieldName);
$newValue = $saveValue;
$updated = true;
} else if ($fieldInfo['tp']=='password') {
//dump("Pass: [$fieldValue]");
if ($fieldValue!='') {
$newPassword = $this->passwordEncoder->encodePassword($entity, $fieldValue);
$entity->__set('password', $newPassword);
//if ($originalEntity->__get($fieldName)!=$entity->__get($fieldName)) {
if ($fieldValue!='') {
$oldValue = '';
$newValue = '';
$forceLogChange = true;
} else{
$logChange = false;
}
//dump('pass', $originalEntity->__get('password'), $entity->__get('password'), $fieldValue);
}
$updated = true;
/*} else if ($fieldInfo['tp']=='boolean') {
$entity->__set($fieldName, $fieldValue) );*/
} else if ($fieldInfo['tp']=='relationship') {
//dump("REL", $fieldName, $fieldInfo, $fieldValue, $originalEntity->__get($fieldName));
if ($fieldValue !== null && $fieldValue !== '') {
//dump('1');
$relationshipEntityPath = $this->nc->classPathFromName($fieldInfo['entity']);
$relationshipEntities = $this->getDoctrine()->getRepository($relationshipEntityPath)->findById($fieldValue);
if (count($relationshipEntities)>0) {
$entity->__set($fieldName, $relationshipEntities[0]);
}
//dump("$fieldName: set date");
$updated = true;
$oldValue = ($originalEntity->__get($fieldName)!=null) ? $originalEntity->__get($fieldName)->getId() : null;
$newValue = $relationshipEntities[0]->getId();
} else {
//dump('2');
$entity->__set($fieldName, null);
$oldValue = ($originalEntity->__get($fieldName)!=null) ? $originalEntity->__get($fieldName)->getId() : null;
$newValue = null;
$updated = true;
//dump($entity->__get($fieldName);
}
if ($oldValue!=$newValue) {
$oldValue = ($originalEntity->__get($fieldName)!=null) ? $originalEntity->__get($fieldName)->getName() : null;
$newValue = $relationshipEntities[0]->getName();
$forceLogChange = true;
} else{
$logChange = false;
}
} else if ($fieldInfo['tp']=='enum') {
if (isset($fieldInfo['multiple']) && $fieldInfo['multiple']===true) {
// multi-select, save separated
$saveValue = ";".implode(";", $fieldValue).";";
$entity->__set($fieldName, $saveValue);
//dump("$fieldName: set multi-select [$saveValue]");
} else {
$saveValue = $fieldValue;
$entity->__set($fieldName, $fieldValue);
//dump("$fieldName: set single-select [$fieldValue]");
}
$oldValue = $originalEntity->__get($fieldName); //T
$newValue = $saveValue;
$updated = true;
} else if ($fieldInfo['tp']=='non-db') {
// do nothing here
$updated = true;
$logChange = false;
}
}
if (!$updated) {
$entity->__set($fieldName, $fieldValue);
//dump("$fieldName: set value to [$fieldValue]");
$oldValue = $originalEntity->__get($fieldName);
$newValue = $fieldValue;
}
$entityUpdated = true;
if ($logChange) {
/*if (isset($fieldInfo['tp']) && $fieldInfo['tp']=='relationship') {
// save related entity id only
$originalValue = ($originalEntity->__get($fieldName)!=null) ? $originalEntity->__get($fieldName)->getId() : null;
$newValue = ($entity->__get($fieldName)!=null) ? $entity->__get($fieldName)->getId() : null;
if ($originalValue!=$newValue) {
$changesMade[$fieldName] = [
'o' => $originalValue,
'n' => $newValue,
'class' => $relationshipEntityPath ?? '',
];
}
} else if (isset($fieldInfo['tp']) && $fieldInfo['tp']=='password') {
// note that it was changed, but don't save the values
if ($originalEntity->__get($fieldName)!=$entity->__get($fieldName)) {
$changesMade[$fieldName] = [
'o' => '',
'n' => '',
];
}
} else if (isset($fieldInfo['tp']) && $fieldInfo['tp']=='password') {
} else {*/
// default
//if ($originalEntity->__get($fieldName)!=$entity->__get($fieldName)) {
if ($forceLogChange || $oldValue!=$newValue) {
$changesMade[$fieldName] = [
'o' => $oldValue, //$originalEntity->__get($fieldName),
'n' => $newValue, //$entity->__get($fieldName),
'tp' => $fieldInfo['tp'] ?? '',
];
}
//}
}
}
//dump($entity);
//dump('changesMade', $changesMade);
if ($customDataUpdaterFunction!=null) {
//dump('custom');
$customUpdateRet = $customDataUpdaterFunction($entity, $data);
//dump('customUpdateRet', $customUpdateRet);
if (is_array($customUpdateRet)) {
if ($customUpdateRet['error']===true) {
$result = $customUpdateRet;
return false;
}
} else {
if ($customUpdateRet===true) $entityUpdated = true;
}
}
//dump("5");
if ($entityUpdated) {
//dump('updated entity', $entity);
$rc = $entity->__setDateTime('updatedAt', 'now'); // add it, so it is shown always (penalty groups were changed, most likely) -- COM-828
$rc = $entity->save( $em );
//dump('update rc='.$rc);
if (!$rc) {
$result['info'] = 'save error';
$result['msg'] = $this->translator->trans('message.genericError', array(), 'general');
return false;
}
} else {
$rc = $entity->__setDateTime('updatedAt', 'now'); // ditto above -- COM-828
$rc = $entity->save( $em );
//dump('update rc='.$rc);
if (!$rc) {
$result['info'] = 'save error';
$result['msg'] = $this->translator->trans('message.genericError', array(), 'general');
return false;
}
}
//dump("6");
// save new entity record, so it can be retrieved later by callers
if ($newEntity) {
$this->newEntity = $entity;
}
// add/update custom fields
if (in_array($this->module, ['companies', 'drivers', 'vehicles', 'trailers'])) {
$customFieldRepository = $this->getDoctrine()->getRepository(CustomField::class);
$customFieldValueRepository = $this->getDoctrine()->getRepository(CustomFieldValue::class);
//dump('custom fields module', $this->module);
$customFieldCategoryType = CustomFieldCategoryEnum::moduleToCategoryType($this->module);
//dump('customFieldCategoryType', $customFieldCategoryType);
$dbCustomFieldsArray = $customFieldRepository->loadByCategory($customFieldCategoryType, $this->currentLanguage);
//dump('dbCustomFieldsArray', $dbCustomFieldsArray);
if ($dbCustomFieldsArray!=null) {
foreach($dbCustomFieldsArray as $r) {
$postFieldName = "customFld_".$r->getId();
// if not in $data, then it wasn't updated
if (!isset($data[$postFieldName])) continue;
// check if
$customFieldValueRec = null;
if ($newEntity) {
// not found in new entities
} else {
// look up
$customFieldValueRec = $customFieldValueRepository->findOneBy([
'customField' => $r,
'entityId' => $entity->getId(),
]);
}
//dump('postFieldName', $postFieldName, $customFieldValueRec);
if ($customFieldValueRec==null) {
// add new value rec
$customFieldValueRec = new CustomFieldValue;
$customFieldValueRec->__set('customField', $r);
$customFieldValueRec->__set('entityId', $entity->getId());
$customFieldValueRec->__set('value', $data[$postFieldName]);
if ($data[$postFieldName]!='' && $data[$postFieldName]!=null) {
$changesMade['c.'.$r->getId()] = [
'o' => null,
'n' => $data[$postFieldName],
];
}
} else {
// update existing value rec
if ($data[$postFieldName]!=$customFieldValueRec->__get('value')) {
$changesMade['c.'.$r->getId()] = [
'o' => $customFieldValueRec->__get('value'),
'n' => $data[$postFieldName],
];
}
$customFieldValueRec->__set('value', $data[$postFieldName]);
}
//dump('customFieldValueRec 2', $customFieldValueRec);
$rc = $customFieldValueRec->save( $this->getDoctrine()->getManager() );
if (!$rc) {
die('error updating custom field value');
}
}
}
}
//die('66');
// log the change
$changeType = ($newEntity ? LogChangeTypeEnum::ITEM_ADDED : LogChangeTypeEnum::ITEM_UPDATED); //TT
$this->logger->saveAction($changeType, $this->modulePath, $entity->getId(), $changesMade);
// add flash message (unless disabled) - will show on next page open
if (!$this->disableFlashMessages) {
$this->addFlash('success', $this->translator->trans(($newEntity ? 'message.recordAdded' : 'message.recordUpdated'), array(), 'general'));
}
$result['success'] = true;
$result['newEntityId'] = $entity->getId();
//$result['newEntity'] = $entity; // COM-815
return true;
}
/****
protected function finalizeOrder($update,&$result) {
$em = $this->getDoctrine()->getManager();
$order = $this->getDoctrine()->getRepository(LicenseOrder::class)->find($update->get(0));
$discount = !is_numeric($update->get(1)) ? 0 : $update->get(1);
$order->setDiscount($discount);
$changesMade['ordernumber'] = $order->getOrderNumber();
$changesMade['status'] = [
'o' => $order->getStatus(),
'n' => '2',
];
$order->setStatus(2);
$this->logger->saveAction(LogChangeTypeEnum::ORDER_FINALIZED, 7, $update->get(0),$changesMade); //T
try {
$orderDetails = json_decode($order->details,true);
$buyer = [
'name' => $this->company->name,
'tax' => $this->company->taxNumber,
'zip' => $this->company->postalCode,
'city' => $this->company->city,
'address' => $this->company->address
];
$email = $this->company->email;
$invoiceItems = [];
foreach ($orderDetails as $key=>$orderItem) {
$this->szamlazz_item_generator($orderDetails['licenseType'],$key,$orderItem,$invoiceItems[]);
}
if ($discount > 0) {
$invoiceItems[] = ['name' => 'Kedvezmény','qty' => 1, 'price' => $discount*-1
];
}
$price = 0;
foreach ($invoiceItems as $items) {
$price = $price+$items['price'];
}
if ($orderDetails['paymentOption'] == 'wire_transfer') {
/// create proforma
$this->szamlazz_hu_generate_invoice(2,$buyer,$email=false,$invoiceItems,$result);
$message = "
Tisztelt Cég!<br/>
Rendeléséről díjbekérőt állítottunk ki, melyet az alábbi címről tud letölteni!<br/>
<a target='_blank' href='{$result['invData']}'>Díjbekérő Letöltés</a><br/>
Kérjük az átutalásában hivatkozzon a díjbekérő sorszámára: {$result['documentNumber']}<br />
Az összeg beérkezését követően fogjuk aktiválni a licenszét!<br/>
";
}
if ($orderDetails['paymentOption'] == 'bank_card') {
$id = $order->getId();
$message = "
Tisztelt Cég!<br/>
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/>
<a href='/balance/payment/init/{$id}'>Bankkártyás fizetés az OTP Simple rendszerében!</a><br/>
<br />
Az sikeres fizetést követően fogjuk aktiválni a licenszét!<br/>
";
$order->setStatus(99);
}
$fakeRequest = Request::createFromGlobals();
$fakeRequest->request->set(0,$this->company);
$fakeRequest->request->set(1,$message);
$fakeRequest->request->set(2,'Megrendelés feldolgozva');
// send message about license change.
$this->sendMessageToCompany(null,$fakeRequest->request,null,$result);
if ($orderDetails['paymentOption'] == 'wire_transfer') {
$orderDetails['proforma_no'] = $result['documentNumber'];
$order->setDetails(json_encode($orderDetails));
}
$em->persist($order);
$em->flush();
} catch(\Doctrine\DBAL\DBALException $e) {
dump($e);
$result['info'] = 'Order insert error';
$result['msg'] = $this->translator->trans('message.genericError', array(), 'general');
return false;
}
// add flash message - will show on next page open
$this->addFlash('success', $this->translator->trans('message.recordUpdated', array(), 'general'));
$result['success'] = true;
}
protected function changeLicenseByCompass($data,$company,&$result) {
$em = $this->getDoctrine()->getManager();
$newLicense = new Licenses();
$newLicense->setCompany($company);
$newLicense->setStatus(99);
$newLicense->setBaseLicenseStartDate(new \DateTime("now"));
$newLicense->setLicenceType($data->get(2));
$qty = $data->get(1);
$qty = is_numeric($qty)? $qty : 0;
$newLicense->setQty($qty);
$this->updateAllLicensesNewStatus($company,3,$result);
if (!$newLicense->save($em,true)){
$result['success'] = false;
}else{
$result['success'] = true;
}
$fakeRequest = Request::createFromGlobals();
$fakeRequest->request->set(0,$company);
$fakeRequest->request->set(1,$data->get(0));
$fakeRequest->request->set(2,'Sikeres licenszváltás');
// send message about license change.
$this->sendMessageToCompany(null,$fakeRequest->request,null,$result);
}
protected function updateAllLicensesNewStatus($company,$newstatus,&$result) {
$em = $this->getDoctrine()->getManager();
$allLicenses = $this->getDoctrine()->getRepository(Licenses::class)->findBy(['company' => $company]);
foreach ($allLicenses as $license) {
$license->setStatus($newstatus);
$license->save($em,true);
}
}
protected function activateLicenseOrder($id,$company_id,&$result) {
$em = $this->getDoctrine()->getManager();
$order = $this->getDoctrine()->getRepository(LicenseOrder::class)->find($id->get(0));
$changesMade['status'] = [
'o' => $order->getStatus(),
'n' => '4',
];
$changesMade['ordernumber'] = $order->getOrderNumber();
//// CREATE OR EXTEND LICENSE
///
if ($order->getStatus() != 4) {
$this->createOrExtendLicense($order->getOrderNumber(),$company_id,$result);
}
if ($result['success'] = true) {
$this->logger->saveAction(LogChangeTypeEnum::ORDER_ACTIVATE, 7, $id->get(0), $changesMade);
$order->setStatus(4);
try {
//create Invoice
$buyer = [
'name' => $this->company->name,
'tax' => $this->company->taxNumber,
'zip' => $this->company->postalCode,
'city' => $this->company->city,
'address' => $this->company->address
];
$email = $this->company->email;
$orderDetails = json_decode($order->details,true);
if (isset($orderDetails['proforma_no'])) {
$buyer['proforma'] = $orderDetails['proforma_no'];
}
$invoiceItems = [];
foreach ($orderDetails as $key=>$orderItem) {
$this->szamlazz_item_generator($orderDetails['licenseType'],$key,$orderItem,$invoiceItems[]);
}
$discount = $order->discount;
if ($discount > 0 && is_numeric($discount)) {
$invoiceItems[] = ['name' => 'Kedvezmény','qty' => 1, 'price' => $discount*-1
];
}
if (isset($orderDetails['proforma_no'])) {
$this->szamlazz_hu_generate_invoice(1,$buyer,$email,$invoiceItems,$result);
$message = "
Tisztelt Cég!<br/>
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/>
<a target='_blank' href='{$result['invData']}'>Számla Letöltés</a><br/>
Az Egyenleg oldalra érve már láthatja az aktivált licensz részleteit és használhatja az oldalt teljes funkcionalitásában!<br/>";
}
if (!isset($orderDetails['proforma_no']) && $orderDetails['paymentOption'] == 'bank_card') {
$this->szamlazz_hu_generate_invoice(1,$buyer,$email,$invoiceItems,$result);
}
if (!isset($orderDetails['proforma_no'])) {
$message = "
Tisztelt Cég!<br/>
Aktiváltuk a licensz konstrukcióját! <br/>
Az Egyenleg oldalra érve már láthatja az aktivált licensz részleteit és használhatja az oldalt teljes funkcionalitásában!<br/>";
}
$fakeRequest = Request::createFromGlobals();
$fakeRequest->request->set(0,$this->company);
$fakeRequest->request->set(1,$message);
$fakeRequest->request->set(2,'Licensz aktiválás');
// send message about license change.
$this->sendMessageToCompany(null,$fakeRequest->request,null,$result);
$em->persist($order);
$em->flush();
} catch(\Doctrine\DBAL\DBALException $e) {
dump($e);
$result['info'] = 'Order insert error';
$result['msg'] = $this->translator->trans('message.genericError', array(), 'general');
return false;
}
// add flash message - will show on next page open
$this->addFlash('success', $this->translator->trans('message.recordUpdated', array(), 'general'));
$result['success'] = true;
}
}
protected function createOrExtendLicense($ordernumber,$company_id,&$result) {
/// check if order is valid
$checkLicense = $this->checkActiveLicense($company_id);
if (is_array($checkLicense) && (@$checkLicense['active_order'] == 1 || @$checkLicense['license_change'] == 1)) {
//// there is active order but no active license
$this->processLicenseFromOrderNewLicense($company_id,$ordernumber,$result);
}elseif(@$checkLicense[0]->id){
$this->processLicenseFromOrderExtendedLicense($company_id,$ordernumber,$result);
/// there is at least one active license
/// check if it is expired?
/// check if it an extension
}else{
//dump('here3');
/// no active order no license
}
$result['success'] = true;
}
protected function processLicenseFromOrderExtendedLicense ($company_id,$ordernumber,&$result) {
$em = $this->getDoctrine()->getManager();
$order = $this->getDoctrine()->getRepository(LicenseOrder::class)->findOneBy(['ordernumber' => $ordernumber,'company'=> $company_id]);
if (@$order) {
$orderDetails = json_decode($order->__get('details'),true);
$em = $this->getDoctrine()->getManager();
$newLicense = new Licenses();
$newLicense->setCompany($company_id);
$newLicense->setStatus(2);
$newLicense->setLicenceType($orderDetails['licenseType']);
$legislation_start_date = new \DateTime("now");
$newLicense->setBaseLicenseStartDate($legislation_start_date);
$newLicense->setTypeLicenseStartDate($legislation_start_date);
if (@$orderDetails['legislation'] || @$orderDetails['base_license'])
{
if (@$orderDetails['legislation']) $orderDetails['legislation'] = intval($orderDetails['legislation']);
if (@$orderDetails['base_license']) $orderDetails['base_license'] = intval($orderDetails['base_license']);
if (@$orderDetails['legislation'] && is_integer($orderDetails['legislation']))
{
/// check if last legislation end date is still valid
/// get all licenses end dates
$lastLegistlationDate = $this->getLicenseLegislationEndDate($company_id);
if (!is_a($lastLegistlationDate,'DateTime')) {
/// if for some reason not datetime object extend with the given extension period from today
$legislation_end_date = new \DateTime("+" . $orderDetails['legislation'] . " year");
}else{
$today = new \DateTime('today');
/// if not valid extend from last day
if ($lastLegistlationDate < $today) {
$lastLegistlationDate->add(new \DateInterval('P'.$orderDetails['legislation']."Y" ));
}else{
$lastLegistlationDate->add(new \DateInterval('P'.$orderDetails['legislation']."Y" ));
}
}
$legislation_end_date = $lastLegistlationDate;
/// if valid extend with years ordered
$newLicense->setBaseLicenseEndDate($legislation_end_date);
$newLicense->setLegislationLicenseEndDate($legislation_end_date);
$newLicense->setTypeLicenseEndDate($legislation_end_date);
}
if (@$orderDetails['base_license'] && is_integer($orderDetails['base_license']))
{
/// check if last legislation end date is still valid
/// get all licenses end dates
$lastLegistlationDate = $this->getLicenseLegislationEndDate($company_id);
if (!is_a($lastLegistlationDate,'DateTime')) {
/// if for some reason not datetime object extend with the given extension period from today
$legislation_end_date = new \DateTime("+" . $orderDetails['base_license'] . " year");
}else{
$today = new \DateTime('today');
/// if not valid extend from last day
if ($lastLegistlationDate < $today) {
$lastLegistlationDate->add(new \DateInterval('P'.$orderDetails['base_license']."Y" ));
}else{
$lastLegistlationDate->add(new \DateInterval('P'.$orderDetails['base_license']."Y" ));
}
}
$legislation_end_date = $lastLegistlationDate;
/// if valid extend with years ordered
$newLicense->setBaseLicenseEndDate($legislation_end_date);
$newLicense->setLegislationLicenseEndDate($legislation_end_date);
$newLicense->setTypeLicenseEndDate($legislation_end_date);
}
}
$details = [];
if ($orderDetails['licenseType'] == 1) {
/// vehicle license
/// check extendedLicenses
$details['extendedLicenses'] = is_numeric($orderDetails['extendedLicenses'])? $orderDetails['extendedLicenses'] : 0;
/// check combo1
$details['combo1'] = is_numeric($orderDetails['combo1'])? $orderDetails['combo1'] : 0;
/// check combo10
$details['combo10'] = is_numeric($orderDetails['combo10'])? $orderDetails['combo10'] : 0;
}
if ($orderDetails['licenseType'] == 2) {
/// if aetr
if (@$orderDetails['aetr']) {
$details['aetr']['open'] = is_numeric($orderDetails['aetr'])? $orderDetails['aetr'] : 0;
$details['aetr']['used'] = 0;
}
/// if labour
if (@$orderDetails['labour']) {
$details['labour']['open'] = is_numeric($orderDetails['labour'])? $orderDetails['labour'] : 0;
$details['labour']['used'] = 0;
}
}
if ($orderDetails['licenseType'] == 3) {
$details['credit'] = is_numeric($orderDetails['credit'])? $orderDetails['credit'] : 0;
$legislation_end_date = new \DateTime("+ 99 year");
}
if (@$orderDetails['modules'] && is_array($orderDetails['modules'])){
$orderedModules = [];
$currentYear = date('Y');
foreach ($orderDetails['modules'] as $module) {
$orderedModules[$currentYear][] = $module;
}
$details['modules'] = $orderedModules;
}
$newLicense->setQty(0);
$newLicense->setDetails(json_encode($details));
if (!$newLicense->save($em,true)){
$result['success'] = false;
}else{
$result['success'] = true;
}
}
}
protected function processLicenseFromOrderNewLicense ($company_id,$ordernumber,&$result) {
$em = $this->getDoctrine()->getManager();
$order = $this->getDoctrine()->getRepository(LicenseOrder::class)->findOneBy(['ordernumber' => $ordernumber,'company'=> $company_id]);
if (@$order) {
$orderDetails = json_decode($order->__get('details'),true);
$em = $this->getDoctrine()->getManager();
$newLicense = new Licenses();
$newLicense->setCompany($company_id);
$newLicense->setStatus(1);
$newLicense->setLicenceType($orderDetails['licenseType']);
$legislation_start_date = new \DateTime("now");
if (isset($orderDetails['base_license']) && $orderDetails['base_license'] != 0) {
$legislation_end_date = new \DateTime("+".$orderDetails['base_license']." year");
}elseif(@$orderDetails['legislation'] && $orderDetails['legislation'] != 0) {
$legislation_end_date = new \DateTime("+".$orderDetails['legislation']." year");
}
$details = [];
if ($orderDetails['licenseType'] == 1) {
/// vehicle license
/// check extendedLicenses
$details['extendedLicenses'] = is_numeric($orderDetails['extendedLicenses'])? $orderDetails['extendedLicenses'] : 0;
/// check combo1
$details['combo1'] = is_numeric($orderDetails['combo1'])? $orderDetails['combo1'] : 0;
/// check combo10
$details['combo10'] = is_numeric($orderDetails['combo10'])? $orderDetails['combo10'] : 0;
}
if ($orderDetails['licenseType'] == 2) {
$details['aetr']['open'] = is_numeric($orderDetails['aetr'])? $orderDetails['aetr'] : 0;
$details['aetr']['used'] = 0;
$details['labour']['open'] = is_numeric($orderDetails['labour'])? $orderDetails['labour'] : 0;
$details['labour']['used'] = 0;
}
if ($orderDetails['licenseType'] == 3) {
$details['credit'] = is_numeric($orderDetails['credit'])? $orderDetails['credit'] : 0;
$legislation_end_date = new \DateTime("+ 99 year");
}
if (@$orderDetails['modules'] && is_array($orderDetails['modules'])){
$orderedModules = [];
$currentYear = date('Y');
foreach ($orderDetails['modules'] as $module) {
$orderedModules[$currentYear][] = $module;
}
$details['modules'] = $orderedModules;
}
$newLicense->setBaseLicenseStartDate($legislation_start_date);
$newLicense->setBaseLicenseEndDate($legislation_end_date);
$newLicense->setLegislationLicenseEndDate($legislation_end_date);
$newLicense->setTypeLicenseStartDate($legislation_start_date);
$newLicense->setTypeLicenseEndDate($legislation_end_date);
$newLicense->setQty(0);
$newLicense->setDetails(json_encode($details));
if (!$newLicense->save($em,true)){
$result['success'] = false;
}else{
if ($orderDetails['licenseType'] == 2) {
// if driver license create entry in driverlicense for aetr and labour
$driverLicense = new DriverLicense();
$driverLicense->setStatus(1);
$driverLicense->setCompany($company_id);
$driverLicense->setBaseLicense($newLicense);
$driverLicense->setDetails('NEW');
if (!$driverLicense->save($em, true)) {
$result['success'] = false;
}else{
$result['success'] = true;
}
}
/// remove old license from license transfer
$removableLicense = $this->getDoctrine()->getRepository(Licenses::class)->findOneBy(['company' => $company_id, 'status' => 99]);
if (@$removableLicense) {
$em = $this->getDoctrine()->getManager();
$em->remove($removableLicense);
$em->flush();
}
$result['success'] = true;
}
}
}
protected function getLogsBalancePageForAdmin($company,&$result){
$events = $this->getDoctrine()->getRepository(LogEntry::class)->findBy(['company' => $company, 'itemType' => 7]);
$logEvents = [];
foreach ($events as $event) {
if ($event->detailsExist === true) {
$RAW_QUERY = "SELECT changes_made FROM util_log_entry_details where id = '{$event->id};'";
$statement = $this->getDoctrine()->getConnection()->prepare($RAW_QUERY);
$statement->execute();
$return = $statement->fetchAll();
if ($return) {
$details = json_decode($return[0]['changes_made'], true);
for ($i = 0; $i < sizeof($details); $i++) {
$detail = '';
foreach ($details as $k => $v) {
if (isset($v['o']) && isset($v['n'])) {
$detail .= "{$k} -> Régi érték: " . $v['o'] . " / Új érték:" . $v['n'] . " | ";
}
if (!isset($v['o']) && !isset($v['n'])) {
$detail .= "{$k} -> {$v} | ";
}
}
}
}
}
$change_message = BalanceTypeEnum::getAllLabelsWithValue('LOGEVENTS', $this->translator, 'balance');
$result[] = [
'createdat' => $event->createdAt,
'createdby' => $event->createdBy->username,
'change' => $change_message[$event->changeType],
'details' => $detail,
];
}
}
protected function getOrdersForCompany($company,$modules,&$result) {
foreach ($company->getLicenseorders() as $orders) {
$ordereditems = json_decode($orders->details);
if ($ordereditems->licenseType == 1) {
$legislationDetails = $this->getDoctrine()->getRepository(LicensePricing::class)->findBy(['type' => 1, 'subtype' => 4, 'name' => $ordereditems->legislation]);
$price = 0;
$orderDetails = [];
if (isset($ordereditems->legislation) && is_numeric($ordereditems->legislation) && isset($legislationDetails[0]) && $legislationDetails[0]->price) {
$orderDetails['legislation'] = [
'name' => $legislationDetails[0]->name,
'price' => $legislationDetails[0]->price
];
$price = $price + $orderDetails['legislation']['price'];
}
if (isset($ordereditems->extendedLicenses) && is_numeric($ordereditems->extendedLicenses)) {
$selectVechicleLicensePrice = $this->getDoctrine()->getRepository(LicensePricing::class)->findBy(['type' => 1, 'subtype' => 1, 'name' => $ordereditems->extendedLicenses]);
if (isset($ordereditems->extendedLicenses) && is_numeric($ordereditems->extendedLicenses) && isset($selectVechicleLicensePrice[0]) && $selectVechicleLicensePrice[0]->price) {
$orderDetails['extendedLicenses'] = [
'name' => $selectVechicleLicensePrice[0]->name,
'price' => $selectVechicleLicensePrice[0]->price
];
$price = $price + $orderDetails['extendedLicenses']['price'];
}
}
if (isset($ordereditems->combo1) && is_numeric($ordereditems->combo1) && $ordereditems->combo1 != 0) {
$comboLicense1Price = $this->getDoctrine()->getRepository(LicensePricing::class)->findBy(['type' => 1, 'subtype' => 2, 'name' => 1]);
if (isset($comboLicense1Price[0]) && $comboLicense1Price[0]->price) {
$orderDetails['combo1'] = [
'name' => $comboLicense1Price[0]->name,
'price' => $comboLicense1Price[0]->price * $ordereditems->combo1,
'qty' => $ordereditems->combo1
];
$price = $price + $comboLicense1Price[0]->price * $ordereditems->combo1;
}
}
if (isset($ordereditems->combo10) && is_numeric($ordereditems->combo10) && $ordereditems->combo10 != 0) {
$comboLicense10Price = $this->getDoctrine()->getRepository(LicensePricing::class)->findBy(['type' => 1, 'subtype' => 2, 'name' => 10]);
if (isset($comboLicense10Price[0]) && $comboLicense10Price[0]->price) {
$orderDetails['combo10'] = [
'name' => $comboLicense10Price[0]->name,
'price' => $comboLicense10Price[0]->price * $ordereditems->combo10,
'qty' => $ordereditems->combo10
];
$price = $price + $comboLicense10Price[0]->price * $ordereditems->combo10;
}
}
if (isset($ordereditems->modules) && is_array($ordereditems->modules)) {
$orderedModules = [];
foreach ($ordereditems->modules as $key => $value) {
foreach ($modules as $module) {
if ($value == $module->id) {
$orderedModules[] = [
'name' => $module->name,
'price' => $module->price,
];
$price = $price + $module->price;
}
}
}
$orderDetails['modules'] = $orderedModules;
}
} elseif ($ordereditems->licenseType == 2) {
$price = 0;
$orderDetails = [];
if (isset($ordereditems->base_license) && is_numeric($ordereditems->base_license)) {
$legislationDetails = $this->getDoctrine()->getRepository(LicensePricing::class)->findBy(['type' => 2, 'subtype' => 1, 'name' => $ordereditems->base_license]);
if (isset($legislationDetails[0]) && $legislationDetails[0]->price) {
$orderDetails['legislation'] = [
'name' => $legislationDetails[0]->name,
'price' => $legislationDetails[0]->price
];
$price = $price + $orderDetails['legislation']['price'];
}
}
if (isset($ordereditems->aetr) && is_numeric($ordereditems->aetr)) {
$aetrPrice = $this->getDoctrine()->getRepository(LicensePricing::class)->findBy(['type' => 2, 'subtype' => 2, 'name' => 1]);
if (isset($ordereditems->aetr) && is_numeric($ordereditems->aetr) && isset($aetrPrice[0]) && $aetrPrice[0]->price) {
$orderDetails['aetr'] = [
'name' => $aetrPrice[0]->name,
'price' => $aetrPrice[0]->price* $ordereditems->aetr,
'qty' => $ordereditems->aetr
];
$price = $price + $orderDetails['aetr']['price'];
}
}
if (isset($ordereditems->labour) && is_numeric($ordereditems->labour)) {
$labourPrice = $this->getDoctrine()->getRepository(LicensePricing::class)->findBy(['type' => 2, 'subtype' => 3, 'name' => 1]);
if (isset($ordereditems->labour) && is_numeric($ordereditems->labour) && isset($labourPrice[0]) && $labourPrice[0]->price) {
$orderDetails['labour'] = [
'name' => $labourPrice[0]->name,
'price' => $labourPrice[0]->price* $ordereditems->labour,
'qty' => $ordereditems->labour
];
$price = $price + $orderDetails['labour']['price'];
}
}
if (isset($ordereditems->modules) && is_array($ordereditems->modules)) {
$orderedModules = [];
foreach ($ordereditems->modules as $key => $value) {
foreach ($modules as $module) {
if ($value == $module->id) {
$orderedModules[] = [
'name' => $module->name,
'price' => $module->price,
];
$price = $price + $module->price;
}
}
}
$orderDetails['modules'] = $orderedModules;
}
} elseif ($ordereditems->licenseType == 3) {
if (isset($ordereditems->credit) && is_numeric($ordereditems->credit)) {
$orderDetails['credit'] = [
'name' => 'Credit',
'price' => $ordereditems->credit,
];
$price = $ordereditems->credit;
}
}
$status_message = BalanceTypeEnum::getAllLabelsWithValue('LICENSEORDERSTATUS', $this->translator, 'balance');
$decline_message = !isset($ordereditems->decline_message) ? '' : $ordereditems->decline_message;
//if (!isset($ordereditems->decline_message) && $ordereditems->decline_message = ''){ $decline_message = ''; }else{ $decline_message = $ordereditems->decline_message; }
$result[] = [
'id' => $orders->id,
'ordernumber' => $orders->ordernumber,
'orderDetails' => $orderDetails,
'price' => $price,
'created' => $orders->createdAt,
'status' => $orders->status,
'status_message' => $status_message[$orders->status],
'discount' => $orders->discount,
'paymentOption' => $ordereditems->paymentOption,
'decline_message' => $decline_message
];
}
}
protected function getLicenseLegislationEndDate($company) {
$anyLicense = $this->getDoctrine()->getRepository(Licenses::class)->findBy(['company' => $company, 'status' => array('1','2')]);
$legislationEndDate = 0;
foreach ($anyLicense as $license) {
if ($anyLicense[0]->license_type == 1)
{
if (!is_a($legislationEndDate,'DateTime') && $legislationEndDate == 0) {
$legislationEndDate = $license->legislation_license_end_date;
}elseif(is_a($legislationEndDate,'DateTime')) {
if ($legislationEndDate < $license->legislation_license_end_date) $legislationEndDate = $license->legislation_license_end_date;
}
}
elseif($anyLicense[0]->license_type == 2)
{
if (!is_a($legislationEndDate,'DateTime') && $legislationEndDate == 0) {
$legislationEndDate = $license->legislation_license_end_date;
}elseif(is_a($legislationEndDate,'DateTime')) {
if ($legislationEndDate < $license->legislation_license_end_date) $legislationEndDate = $license->legislation_license_end_date;
}
}
elseif($anyLicense[0]->license_type == 3)
{
}
}
return $legislationEndDate;
}
protected function checkActiveLicense($company_id) {
$anyLicense = false;
$license = $this->getDoctrine()->getRepository(Licenses::class)->findOneBy(['company' => $company_id, 'status' => array('1','99')]);
if ($license) {
if ($license->status == 99) {
/// license change new license is in system recorded
$anyLicense = ['action' => 'redirect', 'license_type' => $license->license_type,'license_change' => 1,'compensation' => $license->qty];
$licenses = [];
}else {
$anyLicense = $this->getDoctrine()->getRepository(Licenses::class)->findBy(['company' => $company_id, 'status' => array('1', '2')]);
$currentYear = date('Y');
if($license->license_type == 1) {
foreach ($anyLicense as $license) {
$details = json_decode($license->details, true);
$licenses['base_starts'][] = $license->base_license_start_date;
$licenses['extendedLicenses'][] = $details['extendedLicenses'];
$licenses['combo1'][] = $details['combo1'];
$licenses['combo10'][] = $details['combo10'];
$licenses['legislation_license_end_date'][] = $license->legislation_license_end_date;
if (@$details['modules'] && isset($details['modules']) && isset($details['modules'][$currentYear])) {
foreach ($details['modules'] as $licmodule) {
$licenses['modules'][] = $licmodule;
}
}
$anyLicense['summary'] = $licenses;
if (@$anyLicense[0]->id) {
$anyLicense['sum']['vehicleLicenses'] = 0;
$anyLicense['sum']['vehiclemodules'] = [];
$anyLicense['sum']['base_starts'] = 0;
$anyLicense['sum']['legislationEndDate'] = 0;
$anyLicense['sum']['license_type'] = $anyLicense[0]->license_type;
foreach ($anyLicense['summary']['base_starts'] as $val) {
if (!is_a($anyLicense['sum']['base_starts'], 'DateTime') && $anyLicense['sum']['base_starts'] == 0) {
$anyLicense['sum']['base_starts'] = $val;
} elseif (is_a($anyLicense['sum']['base_starts'], 'DateTime')) {
if ($val < $anyLicense['sum']['base_starts']) $anyLicense['sum']['base_starts'] = $val;
}
}
foreach ($anyLicense['summary']['legislation_license_end_date'] as $val) {
if (!is_a($anyLicense['sum']['legislationEndDate'], 'DateTime') && $anyLicense['sum']['legislationEndDate'] == 0) {
$anyLicense['sum']['legislationEndDate'] = $val;
} elseif (is_a($anyLicense['sum']['legislationEndDate'], 'DateTime')) {
if ($val > $anyLicense['sum']['legislationEndDate']) $anyLicense['sum']['legislationEndDate'] = $val;
}
}
foreach ($anyLicense['summary']['extendedLicenses'] as $val) {
$anyLicense['sum']['vehicleLicenses'] += intval($val);
}
foreach ($anyLicense['summary']['combo1'] as $val) {
$anyLicense['sum']['vehicleLicenses'] += intval($val);
}
foreach ($anyLicense['summary']['combo10'] as $val) {
$anyLicense['sum']['vehicleLicenses'] += intval($val) * 10;
}
}
}
if (@$anyLicense['summary']['modules']) {
foreach ($anyLicense['summary']['modules'] as $key=>$val) {
foreach ($val as $mod) {
$anyLicense['sum']['modules'][] = $mod;
}
}
}
}
elseif($license->license_type == 2)
{
foreach ($anyLicense as $license) {
$details = json_decode($license->details, true);
$licenses['base_starts'][] = $license->base_license_start_date;
$licenses['base_ends'][] = $license->base_license_end_date;
if (@$details['modules'] && isset($details['modules']) && isset($details['modules'][$currentYear])) {
foreach ($details['modules'] as $licmodule) {
$licenses['modules'][] = $licmodule;
}
}
if (@$details['aetr'] && isset($details['aetr'])) {
$licenses['aetr'][] = ['open' => $details['aetr']['open'],
'used' => $details['aetr']['used']
];
}
if (@$details['labour'] && isset($details['labour'])) {
$licenses['labour'][] = ['open' => $details['labour']['open'],
'used' => $details['labour']['used']
];
}
}
$anyLicense['summary'] = $licenses;
if (@$anyLicense[0]->id) {
$anyLicense['sum']['modules'] = [];
$anyLicense['sum']['base_starts'] = 0;
$anyLicense['sum']['base_ends'] = 0;
$anyLicense['sum']['drivers'] = sizeof($this->company->drivers);
$anyLicense['sum']['license_type'] = $anyLicense[0]->license_type;
$anyLicense['sum']['aetr']['open'] = 0;
$anyLicense['sum']['aetr']['used'] = 0;
$anyLicense['sum']['labour']['open'] = 0;
$anyLicense['sum']['labour']['used'] = 0;
foreach ($anyLicense['summary']['base_starts'] as $val) {
if (!is_a($anyLicense['sum']['base_starts'], 'DateTime') && $anyLicense['sum']['base_starts'] == 0) {
$anyLicense['sum']['base_starts'] = $val;
} elseif (is_a($anyLicense['sum']['base_starts'], 'DateTime')) {
if ($val < $anyLicense['sum']['base_starts']) $anyLicense['sum']['base_starts'] = $val;
}
}
foreach ($anyLicense['summary']['aetr'] as $val) {
if ($anyLicense['sum']['aetr']['open'] == 0 && !$anyLicense['sum']['aetr']['open'] > 0 ) {
$anyLicense['sum']['aetr']['open'] = intval($val['open']);
} elseif (is_integer($anyLicense['sum']['aetr']['open']) && $anyLicense['sum']['aetr']['open'] > 0) {
$anyLicense['sum']['aetr']['open'] = $val['open']+$anyLicense['sum']['aetr']['open'];
}
if ($anyLicense['sum']['aetr']['used'] == 0 && !$anyLicense['sum']['aetr']['used'] > 0 ) {
$anyLicense['sum']['aetr']['used'] = intval($val['used']);
} elseif (is_integer($anyLicense['sum']['aetr']['used']) && $anyLicense['sum']['aetr']['used'] > 0) {
$anyLicense['sum']['aetr']['used'] += $val['used'];
}
}
foreach ($anyLicense['summary']['labour'] as $val) {
if ($anyLicense['sum']['labour']['open'] == 0 && !$anyLicense['sum']['labour']['open'] > 0 ) {
$anyLicense['sum']['labour']['open'] = intval($val['open']);
} elseif (is_integer($anyLicense['sum']['labour']['open']) && $anyLicense['sum']['labour']['open'] > 0) {
$anyLicense['sum']['labour']['open'] += $val['open'];
}
if ($anyLicense['sum']['labour']['used'] == 0 && !$anyLicense['sum']['labour']['used'] > 0 ) {
$anyLicense['sum']['labour']['used'] = intval($val['used']);
} elseif (is_integer($anyLicense['sum']['aetr']['used']) && $anyLicense['sum']['labour']['used'] > 0) {
$anyLicense['sum']['labour']['used'] += $val['used'];
}
}
foreach ($anyLicense['summary']['base_ends'] as $val) {
if (!is_a($anyLicense['sum']['base_ends'], 'DateTime') && $anyLicense['sum']['base_ends'] == 0) {
$anyLicense['sum']['base_ends'] = $val;
} elseif (is_a($anyLicense['sum']['base_ends'], 'DateTime')) {
if ($val > $anyLicense['sum']['base_ends']) $anyLicense['sum']['base_ends'] = $val;
}
}
}
if (@$anyLicense['summary']['modules']) {
foreach ($anyLicense['summary']['modules'] as $key=>$val) {
foreach ($val as $mod) {
$anyLicense['sum']['modules'][] = $mod;
}
}
}
}
elseif($license->license_type == 3)
{
$credit = 0;
foreach ($anyLicense as $license) {
$details = json_decode($license->details, true);
$licenses['credit'][] = $details['credit'];
}
$anyLicense['summary'] = $licenses;
$anyLicense['sum']['credit'] = 0;
if (@$anyLicense[0]->id) {
$anyLicense['sum']['license_type'] = $anyLicense[0]->license_type;
foreach ($anyLicense['summary']['credit'] as $val) {
$anyLicense['sum']['credit'] += $val;
}
}
}
}
}else{
/// null -> no license
/// check if first license for company is set
if (is_numeric($this->company->licenseType)) {
$activeOrder = $this->getDoctrine()->getRepository(LicenseOrder::class)->findOneBy(['company' => $company_id,'status' => array('1','2')]);
if (@$activeOrder->details) {
$license_Type_to_redirect = json_decode($activeOrder->details,true);
$license_Type_to_redirect = $license_Type_to_redirect['licenseType'];
}else{
$license_Type_to_redirect = $this->company->licenseType;
}
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];
/// license type set but no license force to buy
//return new RedirectResponse('balance.buy.vehicle_license');
}else{
// no license set after reg what should we do?
}
}
return $anyLicense;
}
protected function declineLicenseOrder($update,&$result, $currentUser) {
$em = $this->getDoctrine()->getManager();
$order = $this->getDoctrine()->getRepository(LicenseOrder::class)->find($update->get(0));
$details = json_decode($order->getDetails(),true);
$details['decline_message'] = $update->get(1);
$details = json_encode($details);
$order->setDetails($details);
$changesMade['status'] = [
'o' => $order->getStatus(),
'n' => '3',
];
$changesMade['ordernumber'] = $order->getOrderNumber();
$this->logger->saveAction(LogChangeTypeEnum::ORDER_DECLINED, 7,$this->company->id, $changesMade);
$order->setStatus(3);
try {
$em->persist($order);
$em->flush();
//$user = $this->getUser();
if ($currentUser->getRolesUnconverted()[0] == UserRoleEnum::ROLE_SUPER_ADMIN) {
$fakeRequest = Request::createFromGlobals();
$fakeRequest->request->set(0, $order->getCompany());
$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");
$fakeRequest->request->set(2, 'Rendelés visszavonva');
$this->sendMessageToCompany(null, $fakeRequest->request, null, $result);
}
} catch(\Doctrine\DBAL\DBALException $e) {
dump($e);
$result['info'] = 'Order insert error';
$result['msg'] = $this->translator->trans('message.genericError', array(), 'general');
return false;
}
// add flash message - will show on next page open
$this->addFlash('success', $this->translator->trans('message.recordUpdated', array(), 'general'));
$result['success'] = true;
}
protected function randomOrderNumber() {
$rand = "COMP-".rand(100000,999666);
do {
$orderNumberChk = $this->getDoctrine()->getRepository(LicenseOrder::class)->findBy(['ordernumber' => $rand ]);
} while ($orderNumberChk);
return $rand;
}
****/
/****
protected function checkNewMessage($user) {
$unReadStatus = false;
$unReadMessage = $this->getDoctrine()->getRepository(Message::class)->findOneBy(['to' => $user, 'status' => 1]);
if ($unReadMessage) $unReadStatus = true;
return $unReadStatus;
}
public function sendMessageToCompany($company,$data,$thread = null,&$result) {
$em = $this->getDoctrine()->getManager();
$message = new Message();
$message->setFrom($company);
$to = $data->get(0);
if (!@$to->id) $message->setTo(null); else $message->setTo($to);
$message->setSubject($data->get(2));
$message->setContent($data->get(1));
if ($thread) $message->setMessageRepliedTo($thread);
$message->setStatus(1);
try {
$em->persist($message);
$em->flush();
} catch(\Doctrine\DBAL\DBALException $e) {
dump($e);
$result['info'] = 'Order insert error';
$result['msg'] = $this->translator->trans('message.genericError', array(), 'general');
return false;
}
// add flash message - will show on next page open
$this->addFlash('success', $this->translator->trans('message.recordUpdated', array(), 'general'));
$result['success'] = true;
}
****/
/****
protected function processOrder($company,$orderDetails,&$result) {
$orderNumber = $this->randomOrderNumber();
$em = $this->getDoctrine()->getManager();
$order = new LicenseOrder();
$order->setCompany($company);
$order->setStatus(1);
$order->setDiscount(0);
$order->setOrderNumber($orderNumber);
$order->setDetails(json_encode($orderDetails));
$changesMade['new_order'] = [
'o' => '-',
'n' => $orderNumber,
];
$this->logger->saveAction(LogChangeTypeEnum::ORDER_CREATED, 7, 0, $changesMade);
try {
$em->persist($order);
$em->flush();
$fakeRequest = Request::createFromGlobals();
$fakeRequest->request->set(0,'');
$fakeRequest->request->set(1,"Új megrendelés!!! <br/>Megrendelő: {$this->company->name}<br/>Megrendelés Szám: {$orderNumber}<br />");
$fakeRequest->request->set(2,'Új megrendelés');
$this->sendMessageToCompany($this->company,$fakeRequest->request,null,$result);
} catch(\Doctrine\DBAL\DBALException $e) {
dump($e);
$result['info'] = 'Order insert error';
$result['msg'] = $this->translator->trans('message.genericError', array(), 'general');
return false;
}
// add flash message - will show on next page open
$this->addFlash('success', $this->translator->trans('message.recordUpdated', array(), 'general'));
$result['success'] = true;
}
protected function processLicensePriceChange($request, $entity, &$result) {
$em = $this->getDoctrine()->getManager();
$entityFields = ['name','type','price','subtype','invoiceremark','invoicetitle','price'];
foreach ($entityFields as $entities) {
if ($request->$entities != $entity->$entities) $entity->__set($entities, $request->$entities);
}
try {
$em->persist($entity);
$em->flush();
} catch(\Doctrine\DBAL\DBALException $e) {
dump($e);
$result['info'] = 'licenseprice update error';
$result['msg'] = $this->translator->trans('message.genericError', array(), 'general');
return false;
}
// log the change
$this->logger->saveAction(LogChangeTypeEnum::ITEM_UPDATED, $this->modulePath, $entity->getId()); //T
// add flash message - will show on next page open
$this->addFlash('success', $this->translator->trans('message.recordUpdated', array(), 'general'));
$result['success'] = true;
return true;
}
protected function processLicensePriceAdd($request, &$result) {
$em = $this->getDoctrine()->getManager();
$entity = new LicensePricing();
$entityFields = ['name','type','price','subtype','invoiceremark','invoicetitle','price'];
foreach ($entityFields as $entities) {
$entity->__set($entities,$request->$entities);
}
try {
$em->persist($entity);
$em->flush();
} catch(\Doctrine\DBAL\DBALException $e) {
dump($e);
$result['info'] = 'licenseprice update error';
$result['msg'] = $this->translator->trans('message.genericError', array(), 'general');
return false;
}
// log the change
$this->logger->saveAction(LogChangeTypeEnum::ITEM_ADDED, $this->modulePath, $entity->getId()); //T
// add flash message - will show on next page open
$this->addFlash('success', $this->translator->trans('message.recordDeleted', array(), 'general'));
$result['success'] = true;
return true;
}
protected function processSaveDriverLicense($data, &$result) {
$em = $this->getDoctrine()->getManager();
$dlicEntity = $data->get(0);
$driverId = $data->get(1);
$selectedVals = $data->get(2);
$usedaetr = 0;
$usedLabour = 0;
$driverEntity = $this->getDoctrine()->getRepository(DriverLicense::class)->find($data->get(0));
if ($driverEntity->details == 'NEW') {
/// no data present
$selMonth = [];
foreach ($selectedVals as $vals) {
$val = explode('_',$vals);
$selMonth[$driverId]['lic'][$val[0]][$val[1]][] = $val[2]+1;
if ($val[0] = 'e') {
$usedaetr = $usedaetr+1;
}
if ($val[0] = 'l') {
$usedLabour = $usedLabour+1;
}
}
$selMonth_json = json_encode($selMonth);
$driverEntity->setDetails($selMonth_json);
$em->persist($driverEntity);
$em->flush();
}else{
$details = json_decode($driverEntity->details,true);
$selMonth = [];
foreach ($selectedVals as $vals) {
$val = explode('_',$vals);
$details[$driverId]['lic'][$val[0]][$val[1]][] = $val[2]+1;
if ($val[0] = 'e') {
$usedaetr = $usedaetr+1;
}
if ($val[0] = 'l') {
$usedLabour = $usedLabour+1;
}
}
$details = json_encode($details);
$driverEntity->setDetails($details);
$em->persist($driverEntity);
$em->flush();
}
/// DEDUCT Licenses
$baseLicense = $this->getDoctrine()->getRepository(Licenses::class)->findBy(['license_type' => 2, 'company' => $this->company]);
foreach ($baseLicense as $license) {
if ($license->status != 3) {
$details = json_decode($license->details,true);
if (@$details['aetr']['open'] && $details['aetr']['open'] > 0) {
if ($details['aetr']['open'] > $usedaetr && $usedaetr != 0) {
$details['aetr']['open'] = $details['aetr']['open']-$usedaetr;
$details['aetr']['used'] = $details['aetr']['used']+$usedaetr;
$usedaetr = $usedaetr-$details['aetr']['used'];
}elseif($details['aetr']['open'] < $usedaetr && $usedaetr != 0){
$details['aetr']['open'] = 0;
$usedaetr = $usedaetr-$details['aetr']['open'];
$details['aetr']['used'] = $details['aetr']['used']+$usedaetr;
$usedaetr = $usedaetr-$details['aetr']['used'];
}
}
if (@$details['labour']['open'] && $details['labour']['open'] > 0) {
if ($details['labour']['open'] > $usedLabour && $usedLabour != 0) {
$details['labour']['open'] = $details['labour']['open']-$usedLabour;
$details['labour']['used'] = $details['labour']['used']+$usedLabour;
$usedLabour = $usedLabour-$details['labour']['used'];
}elseif($details['labour']['open'] < $usedLabour && $usedLabour != 0) {
$details['labour']['open'] = 0;
$usedLabour = $usedLabour - $details['labour']['open'];
$details['labour']['used'] = $details['labour']['used'] + $usedLabour;
$usedLabour = $usedLabour-$details['labour']['used'];
}
}
$details = json_encode($details);
$license->setDetails($details);
$em->persist($license);
$em->flush();
}
}
/// if more licenses used deduct all
$result['success'] = true;
}
****/
/****
protected function processMessageExclude($request, $entity, &$result) {
$em = $this->getDoctrine()->getManager();
$excluded = json_decode($entity->excluded,true);
$user = $this->getUser();
if ($user->getRolesUnconverted()[0] == UserRoleEnum::ROLE_SUPER_ADMIN) {
$excluded[]['id'] = 'admin';
}else{
$excluded[]['id'] = $this->company->id;
}
$entity->__set('excluded', json_encode($excluded));
try {
$em->persist($entity);
$em->flush();
} catch(\Doctrine\DBAL\DBALException $e) {
dump($e);
$result['info'] = 'delete error';
$result['msg'] = $this->translator->trans('message.genericError', array(), 'general');
return false;
}
// log the change
//$this->logger->saveAction(LogChangeTypeEnum::ITEM_DELETED, $this->modulePath, $entity->getId()); //T
// add flash message - will show on next page open
//$this->addFlash('success', $this->translator->trans('message.recordDeleted', array(), 'general'));
$result['success'] = true;
return true;
}
****/
protected function processEntityDelete($request, $entity, &$result) {
$em = $this->getDoctrine()->getManager();
$entity->__set('deleted', 1);
try {
$em->persist($entity);
$em->flush();
} catch(\Doctrine\DBAL\DBALException $e) {
dump($e);
$result['info'] = 'delete error';
$result['msg'] = $this->translator->trans('message.genericError', array(), 'general');
return false;
}
// log the change
$this->logger->saveAction(LogChangeTypeEnum::ITEM_DELETED, $this->modulePath, $entity->getId()); //T
// add flash message - will show on next page open
if (!$this->disableFlashMessages) {
$this->addFlash('success', $this->translator->trans('message.recordDeleted', array(), 'general'));
}
$result['success'] = true;
return true;
}
protected function processEntityUnDelete($request, $entity, &$result) {
$em = $this->getDoctrine()->getManager();
$entity->__set('deleted', 0);
try {
$em->persist($entity);
$em->flush();
} catch(\Doctrine\DBAL\DBALException $e) {
dump($e);
$result['info'] = 'undelete error';
$result['msg'] = $this->translator->trans('message.genericError', array(), 'general');
return false;
}
// log the change
$this->logger->saveAction(LogChangeTypeEnum::ITEM_UNDELETED, $this->modulePath, $entity->getId()); //T
// add flash message - will show on next page open
$this->addFlash('success', $this->translator->trans('message.recordUnDeleted', array(), 'general'));
$result['success'] = true;
return true;
}
protected function processCompanyChange($request, $user, $companyId, &$result) {
$em = $this->getDoctrine()->getManager();
if ($companyId=='null') {
$user->__set('currentCompanyViewed', null);
} else {
$companies = $this->getDoctrine()->getRepository(Company::class)->findById($companyId);
$user->__set('currentCompanyViewed', $companies[0]);
}
try {
$em->persist($user);
$em->flush();
} catch(\Doctrine\DBAL\DBALException $e) {
dump($e);
$result['info'] = 'company change error';
$result['msg'] = $this->translator->trans('message.genericError', array(), 'general');
return false;
}
// clear session vars
$this->session->set('selected-driver', null);
$this->session->set('selected-range', null);
$this->session->set('activity-original-data', null);
$this->addFlash('success', $this->translator->trans('message.companyChanged', array(), 'general'));
$result['success'] = true;
return true;
}
public function getEntityArray($entityPath, $idField, $duplicateInfoFieldData=null, $filterParms=null) {
// add driver array
$dataArray = [];
$uniqueNamesArray = [];
$duplicateNamesArray = [];
$dbArray = $this->getAllEntityData($entityPath, $idField, $filterParms);
//dump("dbArray($idField)", $dbArray);
foreach($dbArray as $d) {
if (strpos($idField, ',')>0) {
$idFieldArray = explode(",", $idField);
$valueArray = [];
foreach($idFieldArray as $thisIdField) {
$valueArray[] = $d->__get($thisIdField);
}
$value = trim(implode(" ", $valueArray));
} else {
$value = $d->__get($idField);
}
$dataArray[ $d->getId() ] = $value;
if (!in_array($value, $uniqueNamesArray)) {
$uniqueNamesArray[] = $value;
} else {
$duplicateNamesArray[] = $value;
}
}
//dump('dataArray', $dataArray);
//dump('uniqueNamesArray', $uniqueNamesArray);
//dump('duplicateNamesArray', $duplicateNamesArray);
if ($duplicateInfoFieldData!=null) {
foreach($dbArray as $d) {
if (strpos($idField, ',')>0) {
$idFieldArray = explode(",", $idField);
$valueArray = [];
foreach($idFieldArray as $thisIdField) {
$valueArray[] = $d->__get($thisIdField);
}
$valueToCheck = trim(implode(" ", $valueArray));
} else {
$valueToCheck = $d->__get($idField);
}
//dump('valueToCheck', $valueToCheck);
if (in_array($valueToCheck, $duplicateNamesArray)) {
if ($duplicateInfoFieldData['type']=='datetime') {
$dataArray[ $d->getId() ] .= ' ('.$duplicateInfoFieldData['label'].': '.$d->__getDateFormatted($duplicateInfoFieldData['name']).')';
}
}
}
}
return $dataArray;
}
protected function getCurrentAccountCompanyArray() {
$dataArray = [];
if ($this->account==null) {
// no account selected = Compass user => show all companies in the system
//$companies = null; // $this->getDoctrine()->getRepository(Company::class)->getAllSorted();
if ($this->company!=null) {
// if a company is selected, get all companies belonging to this company's account
$companyAccount = $this->company->getAccount();
$companies = $companyAccount->__get('companies');
} else {
// can't get any
$companies = null;
}
} else {
// account selected => get all companies of this account
$companies = $this->account->__get('companies'); // get non-deleted!!!!
}
if ($companies!=null) {
foreach($companies as $company) {
$dataArray[ $company->getId() ] = $company->getName();
}
}
return $dataArray;
}
// COM-492: added $thisIsVehiclePlate
protected function checkLicensePlateUniqueness($licensePlate, $entityIdExceptionArray=null, $thisIsVehiclePlate=true)
{
//return true; //JNOTE -- COM-492:commented out
//dump("checkLicensePlateUniqueness($licensePlate, entityIdExceptionArray, $thisIsVehiclePlate)", $entityIdExceptionArray);
if ($licensePlate==null || $licensePlate=='') return true;
// COM-492: exceptions only apply to the current entity (vehicle id excep to vehicles, trailer id excep to trailers)
if ($thisIsVehiclePlate) {
$vehicleIdExceptionArray = $entityIdExceptionArray;
$trailerIdExceptionArray = [];
} else {
$vehicleIdExceptionArray = [];
$trailerIdExceptionArray = $entityIdExceptionArray;
}
// check vehicles
$vehicleRepository = $this->getDoctrine()->getRepository(Vehicle::class);
$vehicles = $vehicleRepository->findByRegistrationNumber($licensePlate, $vehicleIdExceptionArray, $this->company);
//dump('vehicles', $vehicles);
if ($vehicles!=null) {
$errorResult = $this->getDefaultAjaxReturnRec(true,
$this->translator->trans("message.licensePlateAlreadyUsed", array(), 'vehicles'), // msg
'license plate used by a vehicle', // info
'', // url
"registrationNumber"); // errorField
return $errorResult;
}
// check trailers
$trailerRepository = $this->getDoctrine()->getRepository(Trailer::class);
$trailers = $trailerRepository->findByRegistrationNumber($licensePlate, $trailerIdExceptionArray, $this->company);
//dump('trailers', $trailers);
if ($trailers!=null) {
$errorResult = $this->getDefaultAjaxReturnRec(true,
$this->translator->trans("message.licensePlateAlreadyUsed", array(), 'vehicles'), // msg
'license plate used by a trailer', // info
'', // url
"registrationNumber"); // errorField
return $errorResult;
}
return true;
}
public function getCompanyDayTitles($getCode=true, $getType=false) {
// add this company's day titles
$dayTitlesArray = [];
$dayTitleTypesArray = $this->getEntityArray(DayTitle::class, 'type');
//dump('dayTitleTypesArray', $dayTitleTypesArray);
foreach($dayTitleTypesArray as $id=>$dayTitleType) {
if ($dayTitleType==0) {
if ($getCode) {
$dayTitlesArray[$id] = $this->getDoctrine()->getRepository(DayTitle::class)->findOneById($id)->getCode();
} else if ($getType) {
$dayTitlesArray[$id] = $dayTitleType;
} else {
$dayTitlesArray[$id] = $this->getDoctrine()->getRepository(DayTitle::class)->findOneById($id)->getName();
}
} else {
if ($getCode) {
$dayTitlesArray[$id] = $this->translator->trans( DayTitleTypeEnum::SHORT_LABELS[$dayTitleType]['label'], array(),
DayTitleTypeEnum::SHORT_LABELS[$dayTitleType]['module'] );
} else if ($getType) {
$dayTitlesArray[$id] = $dayTitleType;
} else {
$dayTitlesArray[$id] = $this->translator->trans( DayTitleTypeEnum::LABELS[$dayTitleType]['label'], array(),
DayTitleTypeEnum::LABELS[$dayTitleType]['module'] );
}
//$dayTitleTypeIdsArray[$dayTitleType] = $id;
}
}
//dump('dayTitlesArray', $dayTitlesArray);
uasort($dayTitlesArray, function($v1, $v2) {
if ($v1==$v2) return 0;
return ($v1 < $v2) ? -1 : 1;
});
return $dayTitlesArray;
}
protected function buildReportRenderArray($params=null) {
$perDriverReportsAvailable = ReportClass::AVAILABLE_REPORT_SUBJECTS[$this->reportClass]['driver'];
$perVehicleReportsAvailable = ReportClass::AVAILABLE_REPORT_SUBJECTS[$this->reportClass]['vehicle'];
$driverVehicleId = '';
$driverVehicleId2 = '';
$driverId = '';
$vehicleId = '';
$getAllMode = false;
$driverMode = $perDriverReportsAvailable;
// by default, select last month's period
//$startDate = $this->timeCalc->currentDate;
//$endDate = $this->timeCalc->gmDateFuture(3600*24*30, true);
$lastMonthDate = $this->timeCalc->alterDateTimeByMonths($this->timeCalc->currentDate, -1, true);
$startDate = date('Y-m-01', strtotime($lastMonthDate));
$endDate = date('Y-m-t', strtotime($lastMonthDate));
//dump("startDate: $startDate, endDate: $endDate");
// read drivers, vehicles and date range from a session vars
if ($this->session->get('selected-driver')!=null) {
$driverId = $this->session->get('selected-driver');
if ($perDriverReportsAvailable) {
$driverVehicleId = $driverId;
}
}
if ($this->session->get('selected-vehicle')!=null) {
$vehicleId = $this->session->get('selected-vehicle');
if ($perVehicleReportsAvailable) {
$driverVehicleId = 'V'.$vehicleId;
}
}
if ($this->session->get('selected-driver2')!=null) {
$driverId2 = $this->session->get('selected-driver2');
if ($perDriverReportsAvailable) {
$driverVehicleId2 = $driverId2;
}
}
if ($this->session->get('selected-vehicle2')!=null) {
$vehicleId2 = $this->session->get('selected-vehicle2');
if ($perVehicleReportsAvailable) {
$driverVehicleId2 = 'V'.$vehicleId2;
}
}
if ($this->session->get('selected-range')!=null && $this->session->get('selected-range')!=';') {
//dump($this->session->get('selected-range'));
list($startDate, $endDate) = explode(';', $this->session->get('selected-range'));
}
//dump("driverId:[$driverId], vehicleId:[$vehicleId], startDate:[$startDate], endDate:[$endDate], driverVehicleId2:[$driverVehicleId2]");
$driverMode = !(substr($driverVehicleId,0,1)=='V');
$getAllMode = ($driverVehicleId=='all' || $driverVehicleId=='Vall');
// COM-UUU
$filterParms = null;
if (isset($params['include-deleted-drivers']) || $params['include-deleted-drivers']==true) {
$filterParms = [
'deleted' => 'ALL',
];
}
// load this company's drivers
$driversArray = [];
if ($perDriverReportsAvailable) {
$driversArray = $this->getEntityArray(Driver::class, 'lastName,firstName', [
'name' => 'birthdate',
'type' => 'datetime',
'label' => $this->translator->trans('label.birthdate.short', array(), 'drivers')
], $filterParms); // COM-UUU
} else { // COM-601
$driverMode = false;
}
//dump('driversArray', $driversArray);
// load this company's vehicles
$vehiclesArray = [];
if ($perVehicleReportsAvailable) {
$vehiclesArray = $this->getEntityArray(Vehicle::class, 'registrationNumber', null, ['inAnotherCompany'=>'0']); //COM-216
} else { // COM-601
$driverMode = true;
}
//dump('driversArray', $driversArray);
// load previously generated reports
$dbPastReportsArray = $this->getDoctrine()->getRepository(Report::class)->simpleRead(-1, $this->company, [
['class', '=', $this->reportClass],
['status', '=' , ReportStatusType::SAVED], //GENERATED
], ['createdAt', 'DESC'], false);
//dump('dbPastReportsArray', $dbPastReportsArray);
$pastReportsArray = [];
foreach($dbPastReportsArray as $r) {
$pastReportsArray[] = [
$r->__get('id'),
$r->__get('fileName'),
$r->__getDateTimeFormatted('createdAt'),
'', // actions
];
//break;
}
//dump('pastReportsArray', $pastReportsArray);
// do not remove no-activity drivers for labour reports -- COM-464
$allowDriversVehiclesWithoutActivities = false;
if (in_array($this->reportClass, [ ReportClass::LABOUR_ATTENDANCE_SHEET,
ReportClass::LABOUR_MINIMUM_WAGES,
ReportClass::LABOUR_FAULTS,
ReportClass::LABOUR_DAY_TITLE_SUMMARY ] )) {
$allowDriversVehiclesWithoutActivities = true;
}
// do not remove no-activity drivers for daily allowance reports -- COM-499
if (in_array($this->reportClass, [ ReportClass::DAILY_ALLOW_ATTENDANCE_SHEET,
ReportClass::DAILY_ALLOW_MINIMUM_WAGES ] )) {
$allowDriversVehiclesWithoutActivities = true;
}
// do not remove no-activity drivers for wizard -- COM-478
if (in_array($this->reportClass, [ ReportClass::STATS_DRIVER_WIZARD,
ReportClass::STATS_DRIVER_VEHICLE_SUMMARY,
ReportClass::STATS_PENALTIES ] )) {
$allowDriversVehiclesWithoutActivities = true;
}
// JNOTE: only load this for driver/vehicle popup pages!!!
// load data needed for driver popup -- COM-502
$driversLicenseCardExpiry_customField = null;
if ($_SERVER['APP_DRIVER_CARD_EXPIRY_CUSTOM_FIELD_ID']!='') {
$driversLicenseCardExpiry_customField = $this->getDoctrine()->getRepository(CustomField::class)
->findOneById($_SERVER['APP_DRIVER_CARD_EXPIRY_CUSTOM_FIELD_ID']);
}
// load data needed for vehicle popup -- COM-502
$vehicleTechPermitExpiry_customField = null;
if ($_SERVER['APP_VEHICLE_TECHNICAL_PERMIT_EXPIRY_CUSTOM_FIELD_ID']!='') {
$vehicleTechPermitExpiry_customField = $this->getDoctrine()->getRepository(CustomField::class)
->findOneById($_SERVER['APP_VEHICLE_TECHNICAL_PERMIT_EXPIRY_CUSTOM_FIELD_ID']);
}
// load exceptions -- COM-502
$toDoItemExceptionLookupArray = [];
$toDoItemExceptions = $this->getDoctrine()->getRepository(ToDoItemException::class)->findBy([
'company' => $this->company,
'deleted' => 0,
]);
//dump('toDoItemExceptions', $toDoItemExceptions);
if (count($toDoItemExceptions)>0) {
foreach($toDoItemExceptions as $exception) {
if (!in_array($exception->getType(), [ToDoItemTypeEnum::STANDARD_DRIVER, ToDoItemTypeEnum::STANDARD_VEHICLE])) continue;
$toDoItemExceptionLookupArray[] = $exception->getType().'-'.$exception->__get('entityId');
}
}
//dump('toDoItemExceptionLookupArray', $toDoItemExceptionLookupArray);
//$toDoItemExceptionLookupArray = []; // JNOTE-DEBUG
// load this company's drivers' data
$driverActivityDatesArray = [];
$driverIdsDelete = [];
$driverVehicleDataArray = []; // COM-502
if ($perDriverReportsAvailable) {
$dbArray = $this->getAllEntityData(Driver::class, 'id');
foreach($dbArray as $d) {
if ($d->__getDateFormatted('oldestActivityDate')==null && !$allowDriversVehiclesWithoutActivities) {
// do not show drivers without activities
$driverIdsDelete[] = $d->getId();
/*// use defaults (next week)
$driverActivityDatesArray[ $d->getId() ] = [
'oldest' => '',
'newest' => '',
'display-oldest' => null, //$defaultStartDate,
'display-newest' => null, //$defaultEndDate,
];*/
} else {
// use driver's data
$driverActivityDatesArray[ $d->getId() ] = [
'oldest' => $d->__getDateFormatted('oldestActivityDate'),
'newest' => $d->__getDateFormatted('newestActivityDate'),
'display-oldest' => null, //$defaultStartDate,
'display-newest' => null, //$defaultEndDate,
];
}
// driver card expiry date -- COM-502
/*$cardExpiryDate = '';
if ($driversLicenseCardExpiry_customField!=null) {
$driversLicenseCardExpiry_value = $this->getDoctrine()->getRepository(CustomFieldValue::class)->findOneBy([
'customField' => $driversLicenseCardExpiry_customField,
'entityId' => $d,
]);
if ($driversLicenseCardExpiry_value!=null) {
$cardExpiryDate = $driversLicenseCardExpiry_value->__get('value');
}
}*/
$cardExpiryDate = $this->calcHelper->getDriverCardExpiryDate($d, $driversLicenseCardExpiry_customField);
// next card scan date (same logic as in CalculationHelper::getToDoItems() -- COM-502
/*
$lastCardScanDate = $d->__getDateFormatted('lastCardScanDate', false);
if ($lastCardScanDate==null) {
// lastCardScanDate is null, need to use employment start date instead
$lastCardScanDate = $d->__getDateFormatted('employmentStartDate', false);
}
$nextCardScanDateDT = (new \DateTime($lastCardScanDate.' 12:00'))->modify('+'.self::APPROACHING_DATE_ITEM_DAYS_CARD_SCAN.' days');
$nextCardScanDate = $todayDT->diff($nextCardScanDateDT)->format('%R%a');
//if (in_array(ToDoItemTypeEnum::STANDARD_DRIVER.'-'.$d->getId(), $toDoItemExceptionLookupArray)) {
// $nextCardScanDate = '
//}
//$remainingRec, //$this->buildRemainingRecord(CustomFieldTypeEnum::DATE, $listValue),
*/
$nextCardScanDateInfo = $this->calcHelper->getDriverCardNextScanDate($d, $toDoItemExceptionLookupArray);
// COM-502
$driverVehicleDataArray[ $d->getId() ] = [
'name' => $d->getName(),
'emplStartDate' => $d->__getDateFormatted('employmentStartDate'),
'emplEndDate' => $d->__getDateFormatted('employmentEndDate'),
'cards' => $d->getCardNumberArray(),
'cardExpiryDate' => $cardExpiryDate,
'nextCardScanDate' => $nextCardScanDateInfo,
];
}
//dump('driverActivityDatesArray', $driverActivityDatesArray);
//dump('driverDataArray', $driverDataArray);
//dump('driverVehicleDataArray', $driverVehicleDataArray);
}
// delete drivers that don't have activities
if (count($driverIdsDelete)>0 &&
!isset($params['include-all-drivers']) || $params['include-all-drivers']==false) {
foreach($driverIdsDelete as $drId) {
unset($driversArray[$drId]);
//dump("DEL DR $drId");
}
//dump('driversArray 2', $driversArray);
}
// put driversArray into a structure that will be handled by JS
// (driversArray is in format ID=>NAME, with IDs not in order; JS sorts the IDs, thus breaking sorting)
$driversArray2 = [];
if (count($driversArray)>0) {
foreach($driversArray as $drId=>$drName) {
$driversArray2[] = [
$drId,
$drName,
];
}
}
//dump('driversArray2', $driversArray2);
// load this company's vehicles' oldest/newest activity dates
$vehicleIdsDelete = [];
if ($perVehicleReportsAvailable) {
$dbArray = $this->getAllEntityData(Vehicle::class, 'id');
foreach($dbArray as $v) {
if ($v->__getDateFormatted('oldestActivityDate')==null && !$allowDriversVehiclesWithoutActivities) {
// do not show vehicles without activities
$vehicleIdsDelete[] = $v->getId();
} else {
// use driver's data
$driverActivityDatesArray[ 'V'.$v->getId() ] = [
'oldest' => $v->__getDateFormatted('oldestActivityDate'),
'newest' => $v->__getDateFormatted('newestActivityDate'),
'display-oldest' => null, //$defaultStartDate,
'display-newest' => null, //$defaultEndDate,
];
}
// get field to show for the driver/vehicle popup -- COM-502
$techPermitExpiryDate = $this->calcHelper->getTechPermitExpiryDate($v, $vehicleTechPermitExpiry_customField);
$nextDownloadDateInfo = $this->calcHelper->getTachoDownloadNextScanDate($v, $toDoItemExceptionLookupArray);
// get latest company lock record for this vehicle -- COM-502
$rc = $this->db->query("SELECT * FROM `data_vehicle_locks`
WHERE vehicle_id=".$v->getId()."
ORDER BY lock_in_time DESC
LIMIT 1",
false);
if (!$rc) {
die('error reading data_vehicle_locks');
}
$dbVehicleLocks = $this->db->fetchAll(true);
//if (count($dbVehicleLocks)>0) dump('dbVehicleLocks '.$v->getName(), $dbVehicleLocks);
$vehicleLockInfo = [
'companyName' => '',
'lockDate' => '',
];
if ($dbVehicleLocks!=null && is_array($dbVehicleLocks) && count($dbVehicleLocks)>0) {
$vehicleLockInfo['companyName'] = $dbVehicleLocks[0]['company_name'];
$vehicleLockInfo['lockDate'] = $this->timeCalc->unixTimestampToFormattedDateTime($dbVehicleLocks[0]['lock_in_time']);
}
// get owner from MD if didn't find a lock record
if ($vehicleLockInfo['companyName']=='' && $v->__get('owner')!='') { //T
$vehicleLockInfo['companyName'] = $v->__get('owner');
} //T
$lastOdoValue = $v->__get('lastOdometerValue');
if ($lastOdoValue!=null) {
$lastOdoValue = StringHelper::formatNumber($this->company->__get('country'), $lastOdoValue, false);
}
// COM-502
$driverVehicleDataArray[ 'V'.$v->getId() ] = [
'name' => $v->getName(),
'techPermitExpiryDate' => $techPermitExpiryDate,
'nextDownloadDate' => $nextDownloadDateInfo,
'owner' => $vehicleLockInfo['companyName'],
'lockDate' => substr($vehicleLockInfo['lockDate'], 0, 10),
'lastOdoValue' => $lastOdoValue,
];
}
//dump('driverActivityDatesArray', $driverActivityDatesArray);
}
//dump('driverVehicleDataArray', $driverVehicleDataArray);
$settingsArray = array(
'driverVehicleId' => $driverVehicleId,
'startDate' => $startDate,
'endDate' => $endDate,
'reportClass' => $this->reportClass,
'ReportQuickFilterType' => [
'LAST_MONTH' => ReportQuickFilterType::LAST_MONTH,
'THIS_MONTH' => ReportQuickFilterType::THIS_MONTH,
'FROM_LAST_WEEKLY_REST' => ReportQuickFilterType::FROM_LAST_WEEKLY_REST,
],
'perDriverReportsAvailable' => $perDriverReportsAvailable,
'perVehicleReportsAvailable' => $perVehicleReportsAvailable,
'driverActivityDatesArray' => $driverActivityDatesArray,
'isSuperAdminUser' => ($this->getUser()->getRolesUnconverted()==UserRoleEnum::ROLE_SUPER_ADMIN),
'module' => $this->module,
);
$renderArray = $this->buildRenderArray($this->module, [
'section_title' => $this->translator->trans('title.reports', array(), 'general'),
'settings_js' => json_encode($settingsArray),
'entity' => $this->emptyEntity,
'driverVehicleId' => $driverVehicleId,
'driverVehicleId2' => $driverVehicleId2,
'driversArray' => $driversArray,
'driversArray2_js' => json_encode($driversArray2),
'driverVehicleDataArray_js' => json_encode($driverVehicleDataArray), //COM-502
'vehiclesArray' => $vehiclesArray,
'driverMode' => $driverMode,
'getAllMode' => $getAllMode,
'startDate' => $startDate,
'endDate' => $endDate,
'reportClass' => $this->reportClass,
'perDriverReportsAvailable' => $perDriverReportsAvailable,
'perVehicleReportsAvailable' => $perVehicleReportsAvailable,
'pastReportsArray' => $pastReportsArray,
'pastReportsArray_js' => json_encode($pastReportsArray),
'driverActivityDatesArray_js' => json_encode($driverActivityDatesArray),
'currentUser' => $this->getUser(),
]); //, new Report);
$renderArray['page_content_title'] = $this->translator->trans($this->sectionTitleLabel[0], array(), $this->sectionTitleLabel[1]);
//dump('renderArray', $renderArray);
return $renderArray;
}
// generic, added for COM-695
protected function updateDatatableRequestColumn(&$request, $columnNum) {
$requestColumns = $request->request->get('columns');
//dump('requestColumns', $requestColumns);
// if column is 'all', then we need to reset search for all types, "all" to blank
if ($requestColumns[$columnNum]['search']['value']==='all') {
$replacedRequest = [
'draw' => $request->request->get('draw'),
'columns' => $request->request->get('columns'),
'order' => $request->request->get('order'),
'start' => $request->request->get('start'),
'length' => $request->request->get('length'),
'search' => $request->request->get('search'),
];
//dump("replacedRequest (col $columnNum)", $replacedRequest);
$replacedRequest['columns'][$columnNum]['search']['value'] = '';
//dump("replacedRequest (col $columnNum)", $replacedRequest);
$request->request->replace($replacedRequest);
}
}
// COM-427
protected function getActiveEuMinWageCountries() {
if ($this->settings==null || count($this->settings)==0) {
$this->settings = $this->settingsLoader->getSettings($this->company, false);
}
//dump('settings', $this->settings);
// get all min wage countries
$minWageCountriesArray = $this->formsHelper->getCountries(null, MinimalWageCountryEnum::COUNTRIES);
//dump('minWageCountriesArray', $minWageCountriesArray);
// if no active have been defined yet, assume all are active
if (!isset($this->settings['company']['minimumWageActiveCountries']) ||
$this->settings['company']['minimumWageActiveCountries']=='') {
//dump('no inactive defined yet');
return $minWageCountriesArray;
}
// now alter minWageCountriesArray to remove those that are inactive
$correctedMinWageCountriesArray = [];
$minWageActiveCountriesArray = explode(';', $this->settings['company']['minimumWageActiveCountries']);
foreach($minWageCountriesArray as $country=>$label) {
if (!in_array($country, $minWageActiveCountriesArray)) continue;
$correctedMinWageCountriesArray[$country] = $label;
}
//dump('correctedMinWageCountriesArray', $minWageActiveCountriesArray);
return $correctedMinWageCountriesArray;
}
// COM-787
// function used in list view
protected function loadAttachmentInfoForEntity($entityType, $entityId,
&$attachmentsArray, &$entityAttachmentArray, &$entityAttachmentArrayByType) {
$attachments = $this->getDoctrine()->getRepository(Attachment::class)->findBy([
'company' => $this->company,
'entityType' => $entityType,
'entityId' => $entityId,
'deleted' => 0,
]);
//dump("attachments for entity with type $entityType and id $entityId:", $attachments);
$attachmentsArray = [];
//$attachmentsArrayByType = [];
if (count($attachments)>0) {
foreach($attachments as $attachment) {
$attId = $attachment->getId();
$attType = $attachment->__get('attachmentType');
$fileNamePartsArray = explode(".", $attachment->__get('name'));
$extension = $fileNamePartsArray[ count($fileNamePartsArray)-1 ];
$attachmentRecord = [
'id' => $attachment->getId(),
'fieldName' => $attachment->__get('fieldName'),
'attachmentType' => $attachment->__get('attachmentType'),
'originalFileName' => $attachment->__get('originalFileName'),
'customLabel' => $attachment->__get('customLabel'),
'extension' => $extension,
];
$attachmentsArray[ $attId ] = $attachmentRecord;
if (!isset($entityAttachmentArray[ $entityId ])) $entityAttachmentArray[ $entityId ] = [];
$entityAttachmentArray[ $entityId ][ $attId ] = $attachmentRecord;
if (!isset($entityAttachmentArrayByType[ $entityId ])) $entityAttachmentArrayByType[ $entityId ] = [];
if (!isset($entityAttachmentArrayByType[ $entityId ][ $attType ])) $entityAttachmentArrayByType[ $entityId ][ $attType ] = [];
$entityAttachmentArrayByType[ $entityId ][ $attType ][] = $attachmentRecord;
}
}
}
// COM-787
// function used on edit view
protected function addAttachmentInfoRenderArray(&$renderArray, $entity) {
$entityId = $entity->getId();
// attachments
if ($this->module=='drivers') {
$entityType = EntityTypeEnum::DRIVER;
$renderArray['attachmentTypesArray'] = AttachmentTypeEnum::getDriverLabels($this->translator);
$renderArray['customFieldsWithAttachments'] = [
$_SERVER['APP_DRIVER_HEALTH_EXAM_CUSTOM_FIELD_ID'] => AttachmentTypeEnum::DRIVER_HEALTH_EXAM,
$_SERVER['APP_DRIVER_PAV_PERMIT_CUSTOM_FIELD_ID'] => AttachmentTypeEnum::DRIVER_PAV_PERMIT,
$_SERVER['APP_DRIVER_PERS_IDENTITY_CARD_CUSTOM_FIELD_ID'] => AttachmentTypeEnum::DRIVER_PERS_IDENTITY_CARD,
$_SERVER['APP_DRIVER_INT_TRANSPORT_PERMIT_CUSTOM_FIELD_ID'] => AttachmentTypeEnum::DRIVER_INT_TRANSPORT_PERMIT,
$_SERVER['APP_DRIVER_PASSPORT_CUSTOM_FIELD_ID'] => AttachmentTypeEnum::DRIVER_PASSPORT,
$_SERVER['APP_DRIVER_ADR_PERMIT_CUSTOM_FIELD_ID'] => AttachmentTypeEnum::DRIVER_ADR_PERMIT,
$_SERVER['APP_DRIVER_JOB_MACHINE_LICENSE_CUSTOM_FIELD_ID'] => AttachmentTypeEnum::DRIVER_JOB_MACHINE_LICENSE,
];
//dump('customFieldsWithAttachments', $renderArray['customFieldsWithAttachments']);
} else {
$entityType = EntityTypeEnum::VEHICLE;
$renderArray['attachmentTypesArray'] = AttachmentTypeEnum::getVehicleLabels($this->translator);
$renderArray['customFieldsWithAttachments'] = [
$_SERVER['APP_NEXT_TACHOGRAPH_CALIBRATION_CUSTOM_FIELD_ID'] => AttachmentTypeEnum::VEHICLE_NEXT_TACHO_CALIBR,
$_SERVER['APP_VEHICLE_NEXT_TACHO_INSP_CUSTOM_FIELD_ID'] => AttachmentTypeEnum::VEHICLE_NEXT_TACHO_INSP,
$_SERVER['APP_VEHICLE_ADR_EXPIRY_CUSTOM_FIELD_ID'] => AttachmentTypeEnum::VEHICLE_ADR_EXPIRY,
$_SERVER['APP_VEHICLE_ATP_EXPIRY_CUSTOM_FIELD_ID'] => AttachmentTypeEnum::VEHICLE_ATP_EXPIRY,
$_SERVER['APP_VEHICLE_NEXT_CRANE_STRUCT_TEST_CUSTOM_FIELD_ID'] => AttachmentTypeEnum::VEHICLE_NEXT_CRANE_STRUCT_TEST,
$_SERVER['APP_VEHICLE_CRANE_MAIN_INSP_CUSTOM_FIELD_ID'] => AttachmentTypeEnum::VEHICLE_CRANE_MAIN_INSP,
$_SERVER['APP_VEHICLE_CRANE_SAFETY_INSP_CUSTOM_FIELD_ID'] => AttachmentTypeEnum::VEHICLE_CRANE_SAFETY_INSP,
$_SERVER['APP_VEHICLE_CMR_INSURANCE_CUSTOM_FIELD_ID'] => AttachmentTypeEnum::VEHICLE_CMR_INSURANCE,
$_SERVER['APP_VEHICLE_DOMESTIC_INSURANCE_CUSTOM_FIELD_ID'] => AttachmentTypeEnum::VEHICLE_DOMESTIC_INSURANCE,
$_SERVER['APP_VEHICLE_ROAD_TRANSPORT_CERT_CUSTOM_FIELD_ID'] => AttachmentTypeEnum::VEHICLE_ROAD_TRANSPORT_CERT,
];
}
$renderArray['attachmentTypesArray_js'] = json_encode($renderArray['attachmentTypesArray']);
$renderArray['attachmentTypeNamesArray_js'] = json_encode( AttachmentTypeEnum::getAvailableTypes() );
$renderArray['attachmentsArray'] = [];
$entityAttachmentArray = [
$entityId => [],
];
$entityAttachmentArray = [];
$entityAttachmentArrayByType = [];
$attachments = $this->getDoctrine()->getRepository(Attachment::class)->findBy([
'entityType' => $entityType,
'entityId' => $entity->getId(),
'deleted' => 0,
]);
//dump('attachments', $attachments);
foreach($attachments as $attachment) {
$attType = $attachment->getAttachmentType();
if (!isset($renderArray['attachmentsArray'][$attType])) $renderArray['attachmentsArray'][$attType] = [];
$fileNamePartsArray = explode(".", $attachment->__get('name'));
$extension = $fileNamePartsArray[ count($fileNamePartsArray)-1 ];
$attachmentRecord = [
'id' => $attachment->getId(),
'attachmentType' => $attType,
'relatedId' => $attachment->getRelatedId(),
'originalFileName' => $attachment->__get('originalFileName'),
'customLabel' => $attachment->__get('customLabel'),
'extension' => $extension,
];
$renderArray['attachmentsArray'][$attType][] = $attachmentRecord;
if (!isset($entityAttachmentArray[ $entityId ])) $entityAttachmentArray[$entity->getId()] = [];
$entityAttachmentArray[ $entityId ][$attachment->getId()] = $attachmentRecord;
if (!isset($entityAttachmentArrayByType[ $entityId ])) $entityAttachmentArrayByType[ $entityId ] = [];
if (!isset($entityAttachmentArrayByType[ $entityId ][ $attType ])) $entityAttachmentArrayByType[ $entityId ][ $attType ] = [];
$entityAttachmentArrayByType[ $entityId ][ $attType ][] = $attachmentRecord;
}
$renderArray['entityAttachmentArray_js'] = json_encode($entityAttachmentArray);
$renderArray['entityAttachmentArrayByType_js'] = json_encode($entityAttachmentArrayByType);
//dump('renderArray', $renderArray['attachmentsArray']);
}
/****
function szamlazz_item_generator($licence_type,$key,$item,&$result)
{
if ($licence_type == 1) {
if (@$key == 'legislation' && is_numeric($item) && $item > 0) {
$details = $this->getDoctrine()->getRepository(LicensePricing::class)->findBy(['type' => 1, 'subtype' => 4, 'name' => $item] );
$name = @$details[0]->invoicetitle ? $details[0]->invoicetitle : 'Jogszabálykövetés';
$result = ['name' => $name,'qty' => 1, 'price' => $details[0]->price];
}
if (@$key == 'extendedLicenses' && is_numeric($item) && $item > 0) {
$details = $this->getDoctrine()->getRepository(LicensePricing::class)->findBy(['type' => 1, 'subtype' => 1, 'name' => $item] );
$name = @$details[0]->invoicetitle ? $details[0]->invoicetitle : 'Járműlicensz';
$result = ['name' => $name,'qty' => 1, 'price' => $details[0]->price];
}
if (@$key == 'combo1' && is_numeric($item) && $item > 0) {
$details = $this->getDoctrine()->getRepository(LicensePricing::class)->findBy(['type' => 1, 'subtype' => 2, 'name' => 1] );
$name = @$details[0]->invoicetitle ? $details[0]->invoicetitle : 'Combo1 Licensz';
$result = ['name' => $name,'qty' => $item, 'price' => $details[0]->price*$item];
}
if (@$key == 'combo10' && is_numeric($item) && $item > 0) {
$details = $this->getDoctrine()->getRepository(LicensePricing::class)->findBy(['type' => 1, 'subtype' => 2, 'name' => 10] );
$name = @$details[0]->invoicetitle ? $details[0]->invoicetitle : 'Combo10 Licensz';
$result = ['name' => $name,'qty' => $item, 'price' => $details[0]->price*$item];
}
if ($key == 'modules') {
$modules = $this->getDoctrine()->getRepository(LicensePricing::class)->findAll();
$orderedModules = [];
$price = 0;
foreach ($item as $mod) {
foreach ($modules as $module) {
if ($mod == $module->id) {
$orderedModules[] = [
'name' => $module->name,
'price' => $module->price,
];
$price = $price + $module->price;
}
}
}
if (isset($orderedModules)) {
$result = [
'name' => 'Modulok',
'price' => $price,
'qty' => 1
];
}
}
}
if ($licence_type == 2) {
if (@$key == 'base_license' && is_numeric($item)) {
$legislationDetails = $this->getDoctrine()->getRepository(LicensePricing::class)->findBy(['type' => 2, 'subtype' => 1, 'name' => $item] );
$name = @$legislationDetails[0]->invoicetitle ? $legislationDetails[0]->invoicetitle : 'Licensz Ár';
$result = ['name' => $name,'qty' => 1, 'price' => $legislationDetails[0]->price];
}
if (@$key == 'aetr' && is_numeric($item)) {
$aetrPrice = $this->getDoctrine()->getRepository(LicensePricing::class)->findBy(['type' => 2, 'subtype' => 2, 'name' => 1]);
if (isset($aetrPrice[0]) && $aetrPrice[0]->price) {
$name = @$aetrPrice[0]->invoicetitle ? $aetrPrice[0]->invoicetitle : 'AETR Licensz';
$result = [
'name' => $name,
'price' => $aetrPrice[0]->price* $item,
'qty' => intval($item)
];
}
}
if (@$key == 'labour' && is_numeric($item)) {
$labourPrice = $this->getDoctrine()->getRepository(LicensePricing::class)->findBy(['type' => 2, 'subtype' => 3, 'name' => 1]);
if (isset($labourPrice[0]) && $labourPrice[0]->price) {
$name = @$labourPrice[0]->invoicetitle ? $labourPrice[0]->invoicetitle : 'Munkaügy Licensz';
$result = [
'name' => $name,
'price' => $labourPrice[0]->price* $item,
'qty' => intval($item)
];
}
}
if ($key == 'modules') {
$modules = $this->getDoctrine()->getRepository(LicensePricing::class)->findAll();
$orderedModules = [];
$price = 0;
foreach ($item as $mod) {
foreach ($modules as $module) {
if ($mod == $module->id) {
$orderedModules[] = [
'name' => $module->name,
'price' => $module->price,
];
$price = $price + $module->price;
}
}
}
if (isset($orderedModules)) {
$result = [
'name' => 'Modulok',
'price' => $price,
'qty' => 1
];
}
}
}
if ($licence_type == 3) {
if (@$key == 'credit' && is_numeric($item)) {
$result = [
'name' => 'Egyenleg feltöltés',
'price' => $item,
'qty' => 1
];
}
}
}
function szamlazz_hu_generate_invoice($type,$buyer,$email=false,$items,&$result) {
require_once(__DIR__.'/../../vendor/SzamlaAgent/phpapi/v2/examples/autoload.php');
try {
/ **
* Számla Agent létrehozása alapértelmezett adatokkal
*
* A számla sikeres kiállítása esetén a válasz (response) tartalmazni fogja
* a létrejött bizonylatot PDF formátumban (1 példányban)
* /
$agent = SzamlaAgentAPI::create($_ENV['szamlazz_hu_api']);
/ **
* Új papír alapú számla létrehozása
*
* Átutalással fizetendő magyar nyelvű (Ft) számla kiállítása mai keltezési és
* teljesítési dátummal, +8 nap fizetési határidővel, üres számlaelőtaggal.
* /
if ($type == 2){
$invoice = new Proforma();
}else{
$invoice = new Invoice(Invoice::INVOICE_TYPE_P_INVOICE);
if (isset($buyer['proforma'])) {
$invoice->getHeader()->setProformaNumber($buyer['proforma']);
$invoice->getHeader()->setPaid(true);
}
}
$buyerData = new Buyer($buyer['name'], $buyer['zip'], $buyer['city'], $buyer['address']);
$buyerData->setTaxNumber($buyer['tax']);
if(@$email) {
$buyerData->setSendEmail(true);
$buyerData->setEmail($email);
}
// Vevő adatainak hozzáadása (kötelezően kitöltendő adatokkal)
$invoice->setBuyer($buyerData);
foreach ($items as $item) {
if (@$item['name']) {
// $unitPrice = round((($item['price']/$item['qty'])/1.27),0); // 1732,28
$unitPrice = ($item['price']/$item['qty']); // 1732,28
$netPrice = $item['price']; // 17322
$grossPrice = $netPrice*1.27;
$vat = $grossPrice-$netPrice; // 4676,9
$name = $item['name'];
$Invoiceitem = new InvoiceItem($name, $unitPrice);
$Invoiceitem->setNetPrice($netPrice);
$Invoiceitem->setQuantity($item['qty']);
$Invoiceitem->setVatAmount($vat);
$Invoiceitem->setGrossAmount($grossPrice);
$invoice->addItem($Invoiceitem);
}
}
// Számla elkészítése
if ($type == 2){
$result = $agent->generateProforma($invoice);
}else{
$result = $agent->generateInvoice($invoice);
}
// Agent válasz sikerességének ellenőrzése
if ($result->isSuccess()) {
$result->getDocumentNumber();
// echo 'A számla sikeresen elkészült. Számlaszám: ' . $result->getDocumentNumber();
// Válasz adatai a további feldolgozáshoz
$return['documentNumber'] = $result->getDocumentNumber();
$return['invData'] = $result->getDataObj()->getUserAccountUrl();
$result = $return;
}
} catch (\Exception $e) {
$agent->logError($e->getMessage());
dd($e->getMessage());
}
}
****/
}