src/ApplicationBundle/Modules/System/MiscActions.php line 839

Open in your IDE?
  1. <?php
  2. /**
  3.  * Created by PhpStorm.
  4.  * User: ehsan_pc
  5.  * Date: 3/14/2016
  6.  * Time: 4:22 PM
  7.  */
  8. namespace ApplicationBundle\Modules\System;
  9. use ApplicationBundle\Constants\ApprovalConstant;
  10. use ApplicationBundle\Constants\BuddybeeConstant;
  11. use ApplicationBundle\Constants\GeneralConstant;
  12. use ApplicationBundle\Constants\HumanResourceConstant;
  13. use ApplicationBundle\Entity\CashFlowProjection;
  14. use ApplicationBundle\Entity\Employee;
  15. use ApplicationBundle\Entity\EmployeeAttendance;
  16. use ApplicationBundle\Helper\Generic;
  17. use ApplicationBundle\Modules\Authentication\Constants\UserConstants; use ApplicationBundle\Modules\Api\Constants\ApiConstants;
  18. use ApplicationBundle\Modules\Consultancy\Consultancy;
  19. use ApplicationBundle\Modules\HumanResource\HumanResource;
  20. use ApplicationBundle\Modules\User\Users;
  21. use CompanyGroupBundle\Entity\BeeCode;
  22. use CompanyGroupBundle\Entity\ConsultancyAvailability;
  23. use CompanyGroupBundle\Entity\EntityApplicantDetails;
  24. use CompanyGroupBundle\Entity\EntityLoginLog;
  25. use CompanyGroupBundle\Entity\EntityPerformanceIndex;
  26. use CompanyGroupBundle\Entity\EntityScheduledNotification;
  27. use CompanyGroupBundle\Entity\EntityTemporaryBooking;
  28. use CompanyGroupBundle\Entity\EntityTicket;
  29. use CompanyGroupBundle\Entity\EntityTokenStorage;
  30. use Symfony\Component\HttpFoundation\JsonResponse;
  31. class MiscActions
  32. {
  33.     public static function verifyRecaptchaEnterprise(
  34.         string $token,
  35.         string $expectedAction,
  36.         string $siteKey,
  37.         string $projectId,
  38.         string $apiKey,
  39.         float  $minScore 0.5
  40.     )
  41.     {
  42.         if ($token === '') {
  43.             return ['ok' => false'reason' => 'missing_token'];
  44.         }
  45.         $url "https://recaptchaenterprise.googleapis.com/v1/projects/"
  46.             rawurlencode($projectId)
  47.             . "/assessments?key="
  48.             rawurlencode($apiKey);
  49.         $payload = [
  50.             'event' => [
  51.                 'token' => $token,
  52.                 'expectedAction' => $expectedAction,
  53.                 'siteKey' => $siteKey,
  54.             ],
  55.         ];
  56.         $ch curl_init($url);
  57.         curl_setopt_array($ch, [
  58.             CURLOPT_RETURNTRANSFER => true,
  59.             CURLOPT_POST => true,
  60.             CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
  61.             CURLOPT_POSTFIELDS => json_encode($payload),
  62.             CURLOPT_TIMEOUT => 6,
  63.         ]);
  64.         $raw curl_exec($ch);
  65.         $httpCode = (int)curl_getinfo($chCURLINFO_HTTP_CODE);
  66.         $err curl_error($ch);
  67.         curl_close($ch);
  68.         if ($raw === false || $raw === '' || $httpCode 200 || $httpCode >= 300) {
  69.             return ['ok' => false'reason' => 'http_error''http' => $httpCode'curl' => $err'raw' => $raw];
  70.         }
  71.         $data json_decode($rawtrue);
  72.         if (!is_array($data)) {
  73.             return ['ok' => false'reason' => 'invalid_json''raw' => $raw];
  74.         }
  75.         // --- Important fields in Enterprise response ---
  76.         // tokenProperties: { valid, action, hostname, invalidReason }
  77.         // riskAnalysis: { score, reasons[] }
  78.         $tokenProps $data['tokenProperties'] ?? [];
  79.         $risk $data['riskAnalysis'] ?? [];
  80.         $valid = (bool)($tokenProps['valid'] ?? false);
  81.         if (!$valid) {
  82.             return [
  83.                 'ok' => false,
  84.                 'reason' => 'token_invalid',
  85.                 'invalidReason' => $tokenProps['invalidReason'] ?? null,
  86.                 'data' => $data
  87.             ];
  88.         }
  89.         $action = (string)($tokenProps['action'] ?? '');
  90.         if ($action !== $expectedAction) {
  91.             return ['ok' => false'reason' => 'action_mismatch''action' => $action'data' => $data];
  92.         }
  93.         $score = (float)($risk['score'] ?? 0.0);
  94.         if ($score $minScore) {
  95.             return [
  96.                 'ok' => false,
  97.                 'reason' => 'low_score',
  98.                 'score' => $score,
  99.                 'reasons' => $risk['reasons'] ?? [],
  100.                 'data' => $data
  101.             ];
  102.         }
  103.         return ['ok' => true'score' => $score'reasons' => $risk['reasons'] ?? [], 'data' => $data];
  104.     }
  105.     public static function stripGetSetKeys($data)
  106.     {
  107.         // If object, convert to array first
  108.         if (is_object($data)) {
  109.             $data = (array)$data;
  110.         }
  111.         // If not array, return as-is
  112.         if (!is_array($data)) {
  113.             return $data;
  114.         }
  115.         $result = [];
  116.         foreach ($data as $key => $value) {
  117.             // Normalize key: remove get/set prefix
  118.             if (is_string($key) && preg_match('/^(get|set)(.+)$/'$key$matches)) {
  119.                 $newKey lcfirst($matches[2]);
  120.             } else {
  121.                 $newKey $key;
  122.             }
  123.             // Recursively process nested arrays / objects
  124.             $result[$newKey] = self::stripGetSetKeys($value);
  125.         }
  126.         return $result;
  127.     }
  128.     public static function autoAttendanceGeneral($em$empId$userId$appId$dtTs$options = [], $requestFromMobile 0$markerId HumanResourceConstant::ATTENDANCE_MARKER_START_WORKING_FORCED)
  129.     {
  130.         $timeZoneStr '+0000';
  131.         $sysUserId $userId;
  132.         if ($sysUserId == 0)
  133.             $sysUserId $em->getRepository(Employee::class)
  134.                 ->findOneBy(['employeeId' => $empId])->getUserId();
  135.         if ($dtTs == 0) {
  136.             $currTsTime = new \DateTime();
  137.             $dtTs $currTsTime->format('U');
  138.         } else {
  139.             $currTsTime = new \DateTime('@' $dtTs);
  140.         }
  141.         $today = new \DateTime(date('y-m-d'));
  142.         $currTsTime->setTimezone(new \DateTimeZone('UTC'));
  143.         $attDate = new \DateTime($currTsTime->format('Y-m-d') . ' 00:00:00' $timeZoneStr);
  144.         $EmployeeAttendance $em
  145.             ->getRepository(EmployeeAttendance::class)
  146.             ->findOneBy(array('employeeId' => $empId'date' => $attDate));
  147.         if (!$EmployeeAttendance)
  148.             $EmployeeAttendance = new EmployeeAttendance;
  149.         $attendanceInfo HumanResource::StoreAttendance($em$empId$sysUserId, ['requestFromMobile' => $requestFromMobile], $EmployeeAttendance$attDate$dtTs$timeZoneStr$markerId);
  150.         if (!isset($dataByAttId[$attendanceInfo->getId()]))
  151.             $dataByAttId[$attendanceInfo->getId()] = array(
  152.                 'attendanceInfo' => $attendanceInfo,
  153.                 'empId' => $empId,
  154.                 'lat' => 0,
  155.                 'lng' => 0,
  156.                 'address' => 0,
  157.                 'sysUserId' => $sysUserId,
  158.                 'companyId' => 1,
  159.                 'appId' => $appId,
  160.                 'positionArray' => []
  161.             );
  162.         $posData = array(
  163.             'ts' => $dtTs,
  164.             'lat' => 0,
  165.             'lng' => 0,
  166.             'marker' => $markerId,
  167.             'src' => 1,
  168.         );
  169.         $dataByAttId[$attendanceInfo->getId()]['markerId'] = $markerId;
  170.         //this markerId will be calclulted and modified to check if user is in our out of office/workplace later
  171.         $dataByAttId[$attendanceInfo->getId()]['attendanceInfo'] = $attendanceInfo;
  172.         $dataByAttId[$attendanceInfo->getId()]['positionArray'][] = $posData;
  173.         $dataByAttId[$attendanceInfo->getId()]['lat'] = 0;  //for last lat lng etc
  174.         $dataByAttId[$attendanceInfo->getId()]['lng'] = 0;  //for last lat lng etc
  175.         if (isset($d['address']))
  176.             $dataByAttId[$attendanceInfo->getId()]['address'] = '';  //for last lat lng etc
  177.         $response = array(
  178.             'success' => true
  179.         );
  180.         foreach ($dataByAttId as $attInfoId => $d) {
  181.             $response HumanResource::setAttendanceLogFlutterApp($em,
  182.                 $d['empId'],
  183.                 $d['sysUserId'],
  184.                 $d['companyId'],
  185.                 $d['appId'],
  186.                 ['requestFromMobile' => $requestFromMobile],
  187.                 $d['attendanceInfo'],
  188.                 $options,
  189.                 $d['positionArray'],
  190.                 $d['lat'],
  191.                 $d['lng'],
  192.                 $d['address'],
  193.                 $d['markerId']
  194.             );
  195.         }
  196.         return $response;
  197.     }
  198.     public static function updateCompanyToErpServer($em$appId$kernel_root_dir)
  199.     {
  200.         $goc $em
  201.             ->getRepository("CompanyGroupBundle\\Entity\\CompanyGroup")
  202.             ->findOneBy(array(
  203.                 'appId' => $appId
  204.             ));
  205.         $returnData = array(
  206.             'success' => false,
  207.             'message' => "Company Could not be Initialized or Updated",
  208.             'data' => [],
  209.             'initiated' => 0,
  210.         );
  211.         if ($goc->getInitiateFlag() == || $goc->getInitiateFlag() == 1//pending Initiation and paid
  212.         {
  213.             ///NOw pushing to server
  214.             $output '';
  215.             $file $kernel_root_dir '/../web' $goc->getImage(); //<-- Path could be relative
  216.             if (file_exists($file)) {
  217. //                        $file = new \CURLFile($this->container->getParameter('kernel.root_dir') . '/../web/uploads/CompanyImage/' . $company->getImage()); //<-- Path could be relative
  218.                 $mime mime_content_type($file);
  219.                 $info pathinfo($file);
  220.                 $name $info['basename'];
  221.                 if (strpos($mime'image') !== false) {
  222.                     $output = new \CURLFile($file$mime$name);
  223.                 }
  224.             }
  225.             $validUptoDt = new \DateTime('@' $goc->getUsageValidUptoDateTs());
  226.             $post_fields = array(
  227.                 'company_id' => 1,
  228.                 'goc_id' => $goc->getId(),
  229.                 'app_id' => $goc->getAppId(),
  230.                 'dark_vibrant' => '',
  231.                 'light_vibrant' => '',
  232.                 'vibrant' => '',
  233.                 'company_type' => $goc->getCompanyType(),
  234.                 'company_name' => $goc->getName(),
  235.                 'address' => $goc->getAddress(),
  236.                 's_address' => $goc->getShippingAddress(),
  237.                 'b_address' => $goc->getBillingAddress(),
  238.                 'company_image' => $goc->getImage(),
  239.                 'motto' => $goc->getMotto(),
  240.                 'i_footer' => $goc->getInvoiceFooter(),
  241.                 'g_footer' => $goc->getGeneralFooter(),
  242.                 'company_tin' => $goc->getCompanyTin(),
  243.                 'company_bin' => $goc->getCompanyBin(),
  244.                 'company_reg' => $goc->getCompanyReg(),
  245.                 'company_tl' => $goc->getCompanyTl(),
  246.                 'usage_valid_upto_dt_str' => '@' $goc->getUsageValidUptoDateTs(),
  247.                 'usage_valid_upto_ts' => $goc->getUsageValidUptoDateTs(),
  248. //                    'sms_enabled' => $goc->getSmsNotificationEnabled(),
  249. //                    'sms_settings' => $goc->getSmsSettings(),
  250.                 'companyGroupHash' => $goc->getCompanyGroupHash(),
  251.                 'number_of_admin_user' => $goc->getAdminUserAllowed(),
  252.                 'number_of_user' => $goc->getUserAllowed(),
  253.                 'db_name' => $goc->getDbName(),
  254.                 'db_user' => $goc->getDbUser(),
  255.                 'db_pass' => $goc->getDbPass(),
  256.                 'db_host' => $goc->getDbHost(),
  257.                 'companyGroupServerId' => $goc->getCompanyGroupServerId(),
  258.                 'companyGroupServerAddress' => $goc->getCompanyGroupServerAddress(),
  259.                 'companyGroupServerHash' => $goc->getCompanyGroupServerHash(),
  260.                 'companyGroupServerPort' => $goc->getCompanyGroupServerPort(),
  261.                 'file' => $output
  262.             );
  263.             $urlToCall $goc->getCompanyGroupServerAddress() . '/UpdateCompanyGroupDataToRelevantServer';
  264.             $curl curl_init();
  265.             curl_setopt_array($curl, array(
  266.                 CURLOPT_RETURNTRANSFER => 1,
  267.                 CURLOPT_POST => 1,
  268.                 CURLOPT_URL => $urlToCall,
  269.                 CURLOPT_CONNECTTIMEOUT => 10,
  270.                 CURLOPT_SSL_VERIFYPEER => false,
  271.                 CURLOPT_SSL_VERIFYHOST => false,
  272.                 CURLOPT_HTTPHEADER => array(),
  273.                 CURLOPT_POSTFIELDS => $post_fields
  274.             ));
  275.             $retData curl_exec($curl);
  276.             $errData curl_error($curl);
  277.             curl_close($curl);
  278.             if ($errData) {
  279. //                $returnData['message']='';
  280.             } else {
  281.                 $response json_decode($retDatatrue);
  282.                 if (isset($response['success']) && $response['success'] === true) {
  283.                     $returnData['success'] = true;
  284.                     $returnData['initiated'] = true;
  285.                     $returnData['message'] = 'Successfully Initialized The Company';
  286.                     $goc->setInitiateFlag(1);// initiated
  287.                     $em->flush();
  288.                 } else {
  289.                 }
  290.             }
  291.         }
  292.         return $returnData;
  293.     }
  294.     public static function relayResponseFromCentral()
  295.     {
  296. //        $urlToCall = $goc->getCompanyGroupServerAddress() . '/UpdateCompanyGroupDataToRelevantServer';
  297. //
  298. //        $curl = curl_init();
  299. //        curl_setopt_array($curl, array(
  300. //            CURLOPT_RETURNTRANSFER => 1,
  301. //            CURLOPT_POST => 1,
  302. //            CURLOPT_URL => $urlToCall,
  303. //            CURLOPT_CONNECTTIMEOUT => 10,
  304. //            CURLOPT_SSL_VERIFYPEER => false,
  305. //            CURLOPT_SSL_VERIFYHOST => false,
  306. //            CURLOPT_HTTPHEADER => array(),
  307. //            CURLOPT_POSTFIELDS => $post_fields
  308. //        ));
  309. //
  310. //        $retData = curl_exec($curl);
  311. //        $errData = curl_error($curl);
  312. //        curl_close($curl);
  313.     }
  314.     public static function ProcessQrData($em_goc$em$data = [])
  315.     {
  316.     }
  317.     public static function encryptTrans($em$transIds '_ALL_'$hbeeOnly 0)
  318.     {
  319.         $hash '_DEFAULT_';
  320. //        $hbeeOnly=0;
  321.         $comp $em
  322.             ->getRepository('ApplicationBundle\\Entity\\Company')
  323.             ->findOneby(array(//                                    'projectId'=>$projectId
  324.             ));
  325.         if ($comp) {
  326.             $hash $comp->getCompanyHash();
  327.             if ($hbeeOnly == 1)
  328.                 if ($comp->getAppId() != 1)
  329.                     return 0;
  330.         }
  331.         if ($hash == null || $hash == '')
  332.             $hash '_DEFAULT_';
  333.         if ($transIds == '_ALL_')
  334.             $trans $em
  335.                 ->getRepository('ApplicationBundle\\Entity\\AccTransactionDetails')
  336.                 ->findby(array(//                                    'projectId'=>$projectId
  337.                 ));
  338.         else
  339.             $trans $em
  340.                 ->getRepository('ApplicationBundle\\Entity\\AccTransactionDetails')
  341.                 ->findby(array(
  342.                     'transactionId' => $transIds
  343.                 ));
  344.         foreach ($trans as $t) {
  345.             $amount $t->getAmount();
  346.             $note $t->getNote();
  347.             $iv '1234567812345678';
  348.             $pass $hash;
  349.             $suffix '_enpaac_';
  350.             if ($amount != null) {
  351.                 $str $amount;
  352.                 $data openssl_encrypt($str"AES-128-CBC"$passOPENSSL_RAW_DATA$iv);
  353.                 $data base64_encode($data) . '' $suffix;
  354.                 $t->setAmountEncoded($data);
  355.                 $t->setAmount(null);
  356.                 $str $note;
  357.                 $data openssl_encrypt($str"AES-128-CBC"$passOPENSSL_RAW_DATA$iv);
  358.                 $data base64_encode($data) . '' $suffix;
  359.                 $t->setNote($data);
  360.             }
  361. //                            $decrypted = openssl_decrypt(base64_decode(base64_encode($data)), "AES-128-CBC", $hash, OPENSSL_RAW_DATA, $iv);
  362.             $em->flush();
  363. //                            $iv = '1234567812345678';
  364. //                            $decrypted = openssl_decrypt(base64_decode($dt), "AES-128-CBC", $approveHash, OPENSSL_RAW_DATA, $iv);
  365. //
  366. //                            if ($decrypted != false) {
  367. //
  368. //                                if (!strpos($decrypted, 'YmLRocksLikeABoss'))
  369. //                                    return 0;
  370. //
  371. //                                return 1;
  372. //
  373. //                            }
  374.         }
  375.     }
  376.     public static function decryptTrans($em$transIds '_ALL_'$hbeeOnly 0)
  377.     {
  378.         $hash '_DEFAULT_';
  379. //        $hbeeOnly=0;
  380.         $comp $em
  381.             ->getRepository('ApplicationBundle\\Entity\\Company')
  382.             ->findOneby(array(//                                    'projectId'=>$projectId
  383.             ));
  384.         if ($comp) {
  385.             $hash $comp->getCompanyHash();
  386.             if ($hbeeOnly == 1)
  387.                 if ($comp->getAppId() != 1)
  388.                     return 0;
  389.         }
  390.         if ($hash == null || $hash == '')
  391.             $hash '_DEFAULT_';
  392.         if ($transIds == '_ALL_')
  393.             $trans $em
  394.                 ->getRepository('ApplicationBundle\\Entity\\AccTransactionDetails')
  395.                 ->findby(array(//                                    'projectId'=>$projectId
  396.                 ));
  397.         else
  398.             $trans $em
  399.                 ->getRepository('ApplicationBundle\\Entity\\AccTransactionDetails')
  400.                 ->findby(array(
  401.                     'transactionId' => $transIds
  402.                 ));
  403.         foreach ($trans as $t) {
  404.             $amount $t->getAmountEncoded();
  405.             $note $t->getNote();
  406.             $iv '1234567812345678';
  407.             $pass $hash;
  408.             $suffix '_enpaac_';
  409.             if ($amount != null) {
  410.                 $dt $amount;
  411.                 $dt str_replace($suffix''$dt);
  412.                 $decrypted openssl_decrypt(base64_decode($dt), "AES-128-CBC"$hashOPENSSL_RAW_DATA$iv);
  413.                 if ($decrypted != false) {
  414.                     $t->setAmount($decrypted);
  415.                     $t->setAmountEncoded(null);
  416.                 }
  417.                 $dt $note;
  418.                 $dt str_replace($suffix''$dt);
  419.                 $decrypted openssl_decrypt(base64_decode($dt), "AES-128-CBC"$hashOPENSSL_RAW_DATA$iv);
  420.                 if ($decrypted != false$t->setNote($decrypted);
  421.             }
  422.             $em->flush();
  423.         }
  424.     }
  425.     public static function getStorageIdentifier($options = [
  426.         'productId' => 0,
  427.         'warehouseId' => 0,
  428.         'actionTagId' => 0,
  429.         'color' => 0,
  430.         'size' => 0,
  431.         'batchNo' => '',
  432.         'projectId' => 0,
  433.         'soId' => 0,
  434.     ])
  435.     {
  436.         $str '_UNSET_';
  437.         if (isset($options['productId'])) {
  438.             if ($options['productId'] != 0) {
  439.                 $str "_P#" $options['productId'] . "_";//_S#2__C#0__B#889_
  440.                 if (isset($options['warehouseId'])) {
  441.                     if ($options['warehouseId'] != && $options['warehouseId'] != '' && $options['warehouseId'] != null)
  442.                         $str = ($str "_W#" $options['warehouseId'] . "_");//_S#2__C#0__B#889_
  443.                     else
  444.                         $str = ($str "_W#0_");
  445.                 }
  446.                 if (isset($options['actionTagId'])) {
  447.                     if ($options['actionTagId'] != && $options['actionTagId'] != '' && $options['actionTagId'] != null)
  448.                         $str = ($str "_V#" $options['actionTagId'] . "_");//_S#2__C#0__B#889_
  449.                     else
  450.                         $str = ($str "_V#0_");
  451.                 }
  452.                 if (isset($options['color'])) {
  453.                     if ($options['color'] != && $options['color'] != '' && $options['color'] != null)
  454.                         $str = ($str "_C#" $options['color'] . "_");//_S#2__C#0__B#889_
  455.                     else
  456.                         $str = ($str "_C#0_");
  457.                 }
  458.                 if (isset($options['size'])) {
  459.                     if ($options['size'] != && $options['size'] != '' && $options['size'] != null)
  460.                         $str = ($str "_S#" $options['size'] . "_");//_S#2__C#0__B#889_
  461.                     else
  462.                         $str = ($str "_S#0_");
  463.                 }
  464.                 if (isset($options['batchNo'])) {
  465.                     if ($options['batchNo'] != && $options['batchNo'] != '' && $options['batchNo'] != null)
  466.                         $str = ($str "_B#" $options['batchNo'] . "_");//_S#2__C#0__B#889_
  467.                     else
  468.                         $str = ($str "_B#0_");
  469.                 }
  470.                 if (isset($options['projectId'])) {
  471.                     if ($options['projectId'] != && $options['projectId'] != '' && $options['projectId'] != null)
  472.                         $str = ($str "_PRJ#" $options['projectId'] . "_");//_S#2__C#0__B#889_
  473.                     else
  474.                         $str = ($str "_PRJ#0_");
  475.                 }
  476.                 if (isset($options['soId'])) {
  477.                     if ($options['soId'] != && $options['soId'] != '' && $options['soId'] != null)
  478.                         $str = ($str "_SO#" $options['soId'] . "_");//_S#2__C#0__B#889_
  479.                     else
  480.                         $str = ($str "_SO#0_");
  481.                 }
  482.             }
  483.         } else {
  484.         }
  485.         return $str;
  486.     }
  487.     public static function getExpandedDataFromGlobalId($globalIdStr)
  488.     {
  489.         $id 0;
  490.         $appId 0;
  491.         $entity 0;
  492.         $entityId 0;
  493.         $idType 'D'// or _USER_ or _CUSTOMER_ or _SUPPLIER_ or _EMPLOYEE_
  494.         $idTypeMarker '_DOCUMENT_'// or _USER_ or _CUSTOMER_ or _SUPPLIER_ or _EMPLOYEE_
  495.         $idTypeByMarker = array(
  496.             '_DOCUMENT_' => 'D',
  497.             '_USER_' => 'U',
  498.             '_CUSTOMER_' => 'C',
  499.             '_SUPPLIER_' => 'S',
  500.             '_EMPLOYEE_' => 'E'
  501.         );
  502.         $idTypeByIdType array_flip($idTypeByMarker);
  503.         $idType substr("$globalIdStr"01);
  504.         $appId substr("$globalIdStr"15);
  505.         $entity substr("$globalIdStr"62);
  506.         $id substr("$globalIdStr"88);
  507.         $entityId $id;
  508.         $idTypeMarker = isset($idTypeByIdType[$idType]) ? $idTypeByIdType[$idType] : '';
  509.         return array(
  510.             'id' => $id,
  511.             'appId' => $appId,
  512.             'idType' => $idType,
  513.             'idTypeMarker' => $idTypeMarker,
  514.             'entity' => $entity,
  515.             'entityId' => $entityId,
  516.         );
  517.     }
  518.     public static function getGlobalIdForRecognition($id 0,
  519.                                                      $appId 0,
  520.                                                      $entity 0,
  521.                                                      $entityId 0,
  522.                                                      $idType '_DOCUMENT_')
  523.     {
  524.         $idTypeByMarker = array(
  525.             '_DOCUMENT_' => 'D',
  526.             '_USER_' => 'U',
  527.             '_CUSTOMER_' => 'C',
  528.             '_SUPPLIER_' => 'S',
  529.             '_EMPLOYEE_' => 'E'
  530.         );
  531.         $globalIdStr '';
  532.         $globalIdStr = (($idTypeByMarker[$idType]) . (str_pad($appId5'0'STR_PAD_LEFT)) . (str_pad($entity2'0'STR_PAD_LEFT))
  533.             . (str_pad($id8'0'STR_PAD_LEFT)));
  534.         return $globalIdStr;
  535.     }
  536.     public static function GenerateRandomCrypto($serialP$minLength 0)
  537.     {
  538.         $cryptoDt = [
  539.             => 'A',
  540.             => '9',
  541.             => '7',
  542.             => '2',
  543.             => '4',
  544.             => '1',
  545.             => '8',
  546.             => '5',
  547.             => '6',
  548.             => 'C',
  549.         ];
  550.         $serialP .= ('' strval(rand(11209999)));
  551.         $serial '';
  552.         $serialBrokenIntoArray str_split($serialP);
  553.         foreach ($serialBrokenIntoArray as $ser) {
  554.             if (isset($cryptoDt[$ser]))
  555.                 $serial .= $cryptoDt[$ser];
  556.             else
  557.                 $serial .= $ser;
  558.         }
  559.         $serial substr($serial610);
  560. //            $serial .= strval(rand(112, 999));
  561. //
  562. //            $serial = substr($serial, 6, 10);
  563.         return $serial;
  564.     }
  565.     public static function addEntityScheduledNotification($em$data)
  566.     {
  567.         $cdata = [
  568.             'senderHash' => isset($data['senderHash']) ? $data['senderHash'] : '_CUSTOM_',
  569.             'bodyTemplate' => isset($data['bodyTemplate']) ? $data['bodyTemplate'] : 'ApplicationBundle:email/scheduled_mail:meeting_schedule_reminder.html.twig',
  570.             'bodyData' => isset($data['bodyData']) ? $data['bodyData'] : [],
  571.             'subject' => isset($data['subject']) ? $data['subject'] : '',
  572.             'emailIds' => isset($data['emailIds']) ? $data['emailIds'] : (isset($data['forwardToMailAddress']) ? [$data['forwardToMailAddress']] : ['eco.buet@gmail.com']),
  573.             'companyImagePath' => isset($data['companyImagePath']) ? $data['companyImagePath'] : '',
  574.             'forwardToMailAddress' => isset($data['forwardToMailAddress']) ? $data['forwardToMailAddress'] : 'eco.buet@gmail.com',
  575.             'encryptionMethod' => 'ssl',
  576.             'fromAddress' => isset($data['fromAddress']) ? $data['fromAddress'] : 'no-reply@buddybee.eu',
  577.             'userName' => isset($data['userName']) ? $data['userName'] : 'no-reply@buddybee.eu',
  578.             'password' => isset($data['password']) ? $data['password'] : 'Honeybee@0112',
  579.             'smtpServer' => 'smtp.hostinger.com',
  580.             'smtpPort' => 465
  581.         ];
  582. //        $mailModule=new Email($em,)
  583.         $currTime = new \DateTime();
  584.         $currTs $currTime->format('U');
  585.         $new = new EntityScheduledNotification();
  586.         $new->setData(json_encode($cdata));
  587.         $new->setRecurringMin(isset($data['recurringMin']) ? $data['recurringMin'] : 0);
  588.         $new->setStartTimeTs(isset($data['startTimeTs']) ? $data['startTimeTs'] : $currTs);
  589.         $new->setNextTimeTs(isset($data['nextTimeTs']) ? $data['nextTimeTs'] : $currTs);
  590.         $new->setLastTimeTs(isset($data['lastTimeTs']) ? $data['lastTimeTs'] : $currTs);
  591.         $new->setCompanyId(isset($data['companyId']) ? $data['companyId'] : 0);
  592.         $new->setEnabled(1);
  593.         $new->setActionTaken(isset($data['actionTaken']) ? $data['actionTaken'] : 0);
  594.         $new->setExpiresTs(isset($data['expiresTs']) ? $data['expiresTs'] : (isset($data['lastTimeTs']) ? $data['lastTimeTs'] : $currTs));
  595.         $new->setNotificationType(isset($data['notificationType']) ? $data['notificationType'] : GeneralConstant::NOTIFICATION_TYPE_EMAIL);
  596.         $new->setShowAsNotification(isset($data['showAsNotification']) ? $data['showAsNotification'] : 0);
  597.         $new->setTitle(isset($data['title']) ? $data['title'] : 0);
  598.         $new->setBody(isset($data['body']) ? $data['body'] : 0);
  599.         $new->setTargetId(isset($data['targetId']) ? $data['targetId'] : 0);
  600.         $new->setEntityMeetingSessionId(isset($data['meetingId']) ? $data['meetingId'] : 0);
  601.         $new->setTargetType(isset($data['targetType']) ? $data['targetType'] : 0);
  602.         $new->setUserIds(json_encode(isset($data['userIds']) ? $data['userIds'] : []));
  603.         $em->persist($new);
  604.         $em->flush();
  605.         return $new;
  606.     }
  607.     public static function updateEntityPerformanceIndex($em$data$currTime null)
  608.     {
  609.         if ($currTime == null)
  610.             $currTime = new \DateTime();
  611.         $dayMarker 'D' $currTime->format('Ymd');
  612.         $weekMarker 'W' $currTime->format('W');
  613.         $monthMarker 'M' $currTime->format('Ym');
  614.         $yearMarker 'Y' $currTime->format('Y');
  615.         $markers = [$dayMarker$weekMarker$monthMarker$yearMarker];
  616.         $markerTypes = [1234];
  617.         foreach ($markers as $ind => $marker) {
  618.             $markerType $markerTypes[$ind];
  619.             $pi $em->getRepository('CompanyGroupBundle\\Entity\\EntityPerformanceIndex')->findOneBy(
  620.                 array(
  621.                     'targetId' => $data['targetId'],
  622.                     'targetType' => isset($data['targetType']) ? $data['targetType'] : 3,
  623.                     'indexType' => $markerType,
  624.                     'indexMarker' => $marker,
  625.                 )
  626.             );
  627.             if (!$pi) {
  628.                 $pi = new EntityPerformanceIndex();
  629.                 $pi->setTargetId($data['targetId']);
  630.                 $pi->setIndexType($markerType);
  631.                 $pi->setIndexMarker($marker);
  632.                 $pi->setTargetType(isset($data['targetType']) ? $data['targetType'] : 3);
  633.             }
  634.             if (isset($data['communicationData'])) {
  635.                 $pi->setCommunicationCount($pi->getCommunicationCount() + $data['communicationData']['count']);
  636.                 $pi->setCommunicationScore($pi->getCommunicationScore() + $data['communicationData']['score']);
  637.             }
  638.             if (isset($data['followupData'])) {
  639.                 $pi->setCommunicationCount($pi->getFollowupCount() + $data['followupData']['count']);
  640.                 $pi->setCommunicationScore($pi->getFollowupScore() + $data['followupData']['score']);
  641.             }
  642.             if (isset($data['conversionData'])) {
  643.                 $pi->setConversionCount($pi->getConversionCount() + $data['conversionData']['count']);
  644.                 $pi->setConversionScore($pi->getConversionScore() + $data['conversionData']['score']);
  645.             }
  646.             if (isset($data['referData'])) {
  647.                 $pi->setReferCount($pi->getReferCount() + $data['referData']['count']);
  648.                 $pi->setReferScore($pi->getReferScore() + $data['referData']['score']);
  649.             }
  650.             $em->persist($pi);
  651.             $em->flush();
  652.         }
  653.         return 1;
  654.     }
  655.     public static function uniqueCombination($in$minLength 1$max 2000)
  656.     {
  657.         $count count($in);
  658.         $members pow(2$count);
  659.         $return = array();
  660.         for ($i 0$i $members$i++) {
  661.             $b sprintf("%0" $count "b"$i);
  662.             $out = array();
  663.             for ($j 0$j $count$j++) {
  664.                 $b{$j} == '1' and $out[] = $in[$j];
  665.             }
  666.             count($out) >= $minLength && count($out) <= $max and $return[] = $out;
  667.         }
  668.         return $return;
  669.     }
  670.     public static function GenerateOtp($expireSecond 180)
  671.     {
  672.         $data = [];
  673.         $success true;
  674.         $expireSecond 180;
  675.         $currTime = new \DateTime();
  676.         $expireTime $currTime->modify('+' $expireSecond ' second');
  677.         $serial '';
  678.         $cryptoDt = [
  679.             => 'A',
  680.             => '9',
  681.             => '7',
  682.             => '2',
  683.             => '4',
  684.             => '1',
  685.             => '8',
  686.             => '5',
  687.             => '6',
  688.             => 'C',
  689.         ];
  690. //                $serialP=floor(microtime(true) * 1000);
  691. //
  692. //                $serial='';
  693. //                $serialBrokenIntoArray=str_split($serialP);
  694. //                foreach($serialBrokenIntoArray as $ser)
  695. //                {
  696. //                    if(isset($cryptoDt[$ser]))
  697. //                        $serial.=$cryptoDt[$ser];
  698. //                }
  699.         $serial .= strval(rand(11209999));
  700. //                $serial=substr($serial,6,10);
  701.         return array(
  702.             'success' => $success,
  703.             'otp' => $serial,
  704.             'expireTs' => $expireTime->format('U'),
  705. //            'expireHRT'=>$expireTime->format('d F'),
  706.         );
  707.     }
  708.     public static function GenerateEntityTicket($em$options$request)
  709.     {
  710.         $data = [];
  711.         $success true;
  712.         $expDt = new \DateTime();
  713.         $currDt = new \DateTime();
  714.         $expDt->modify('+1 year');
  715.         $expTs $expDt->format('U');
  716.         $ticket = new EntityTicket();
  717.         if (empty($options))
  718.             $options = array(
  719.                 'title' => $request->request->get('title''<no title>'),
  720.                 'ticketBody' => $request->request->get('ticketBody''<no body>'),
  721.                 'replyTo' => $request->request->get('replyTo'null),
  722.                 'ticketMarkerHash' => $request->request->get('ticketMarkerHash'''),
  723.                 'email' => $request->request->get('email'''),
  724.                 'phone' => $request->request->get('phone'''),
  725.                 'name' => $request->request->get('name'''),
  726.                 'preferredContactMethod' => $request->request->get('preferredContactMethod'1),
  727.                 'ticketAssignedDate' => $request->request->get('ticketAssignedDate'''),
  728.                 'userId' => $request->request->get('userId'0),
  729.                 'type' => $request->request->get('type'90),
  730.                 'entity' => $request->request->get('entity'''),
  731.                 'entityId' => $request->request->get('entityId'''),
  732.                 'meetingId' => $request->request->get('meetingId'0),
  733.                 'applicantId' => $request->request->get('applicantId'0),
  734.                 'expired' => $request->request->get('expired'0),
  735.                 'urgency' => $request->request->get('urgency'1),
  736.                 'attachments' => $request->request->get('attachments', []),
  737.             );
  738.         $ticket->setTitle($options['title']);
  739.         $ticket->setTicketBody($options['ticketBody']);
  740.         $ticket->setReplyTo($options['replyTo']);
  741.         $ticket->setTicketMarkerHash($options['ticketMarkerHash']);
  742.         $ticket->setEmail($options['email']);
  743.         $ticket->setPhone($options['phone']);
  744.         $ticket->setName($options['name']);
  745.         $ticket->setPreferredContactMethod($options['preferredContactMethod']);
  746.         $ticket->setUserId($options['userId']);
  747.         $ticket->setType($options['type']);
  748.         $ticket->setEntity($options['entity']);
  749.         $ticket->setEntityId($options['entityId']);
  750.         $ticket->setApplicantId($options['applicantId']);
  751.         $ticket->setExpired($options['expired']);
  752.         $ticket->setUrgency($options['urgency']);
  753.         $ticket->setMeetingId($options['meetingId']);
  754.         $ticket->setAttachments(json_encode($options['attachments']));
  755.         $ticket->setTicketAssignedDate(new \DateTime($options['ticketAssignedDate']));
  756.         $em->persist($ticket);
  757.         $em->flush();
  758.         $data = array(
  759.             'id' => $ticket->getId(),
  760.             'ticketEntityObj' => $ticket,
  761.         );
  762.         return array(
  763.             'success' => $success,
  764.             'data' => $data,
  765.         );
  766.     }
  767.     public static function GenerateBeeCode($em$options)
  768.     {
  769.         $data = [];
  770.         $success true;
  771.         $extDt = new \DateTime();
  772.         $extDt->modify('+1 year');
  773.         $expTs $extDt->format('U');
  774.         for ($c 0$c $options['cardCount']; $c++) {
  775.             $serial $options['serial'];
  776.             $pin $options['pin'];
  777.             $useCount $options['useCount'];
  778.             $cryptoDt = [
  779.                 => 'A',
  780.                 => '9',
  781.                 => '7',
  782.                 => '2',
  783.                 => '4',
  784.                 => '1',
  785.                 => '8',
  786.                 => '5',
  787.                 => '6',
  788.                 => 'C',
  789.             ];
  790.             if ($serial == '_AUTO_') {
  791.                 $serialDt = new \DateTime();
  792. //                $serialP=$serialDt->format('U');
  793.                 $serialP floor(microtime(true) * 1000);
  794.                 $serial '';
  795.                 $serialBrokenIntoArray str_split($serialP);
  796.                 foreach ($serialBrokenIntoArray as $ser) {
  797.                     if (isset($cryptoDt[$ser]))
  798.                         $serial .= $cryptoDt[$ser];
  799.                 }
  800.                 $serial .= strval(rand(112999));
  801.                 $serial substr($serial610);
  802.             }
  803.             if ($pin == '_AUTO_') {
  804.                 $pin rand(1234599999);
  805.                 $pin strval($pin);
  806.             }
  807.             $card = new BeeCode();
  808.             $card->setPrinted(0);
  809.             $card->setAmount($options['amount']);
  810.             $card->setCoinCount($options['coinCount']);
  811.             $card->setIsForHardCopy(isset($options['isForHardCopy']) ? $options['isForHardCopy'] : 0);
  812.             $card->setRetailerId($options['retailerId']);
  813.             $card->setPin($pin);
  814.             $card->setSerial($serial);
  815.             $card->setIsClaimed(0);
  816.             $card->setIsClaimed(0);
  817.             $card->setExpireTs($expTs);
  818.             $card->setUseCount($useCount);
  819.             $em->persist($card);
  820.             $em->flush();
  821.             $data[] = array(
  822.                 'id' => $card->getId(),
  823.                 'cardEntityObj' => $card,
  824.                 'printed' => $card->getPrinted(),
  825.                 'amount' => $card->getAmount(),
  826.                 'coinCount' => $card->getCoinCount(),
  827.                 'pin' => $card->getPin(),
  828.                 'serial' => $card->getSerial(),
  829.             );
  830.         }
  831.         return array(
  832.             'success' => $success,
  833.             'data' => $data,
  834.         );
  835.     }
  836.     public static function ClaimBeeCode($em$options)
  837.     {
  838.         $data = [
  839.             'claimableCoin' => 0,
  840.             'claimableAmount' => 0,
  841.             'claimedAmount' => 0,
  842.             'claimedCoin' => 0,
  843.             'cardId' => 0,
  844.             'overrideBySystem' => 0,
  845.         ];
  846.         $success false;
  847.         $isClaimable false;
  848.         $claimSuccess false;
  849.         $claimFlag = isset($options['claimFlag']) ? $options['claimFlag'] : 0;
  850.         $userId = isset($options['userId']) ? $options['userId'] : 0;
  851.         $cardId = isset($options['cardId']) ? $options['cardId'] : 0;
  852.         $overrideBySystem = isset($options['overrideBySystem']) ? $options['overrideBySystem'] : 0;
  853.         //check 1st
  854.         $serial = isset($options['serial']) ? $options['serial'] : '_NONE_';
  855.         $pin = isset($options['pin']) ? $options['pin'] : '_NONE_';
  856.         if ($overrideBySystem) {
  857.             $queryCondition = array(
  858.                 'id' => $cardId,
  859.             );
  860.         } else {
  861.             if (strlen($pin) == 10) {
  862.                 $startInd 2;
  863.                 $pin substr($pin$startInd5);
  864.             }
  865.             if ($cardId != 0) {
  866.                 $queryCondition = array(
  867.                     'id' => $cardId,
  868.                 );
  869.             } else {
  870.                 $queryCondition = array(
  871.                     'serial' => $serial,
  872.                     'pin' => $pin,
  873.                 );
  874.             }
  875.         }
  876.         $card $em->getRepository('CompanyGroupBundle\\Entity\\BeeCode')
  877.             ->findOneBy(
  878.                 $queryCondition
  879.             );
  880.         if ($card) {
  881.             $cardId $card->getId();
  882.             if ($card->getIsClaimed() != 1) {
  883.                 $isClaimable true;
  884.                 if ($success == false$success true;
  885.                 $data['claimableAmount'] = $card->getAmount();
  886.                 $data['claimableCoin'] = $card->getCoinCount();
  887.                 if ($claimFlag == && $userId != 0) {
  888.                     Buddybee::AddBalanceGeneral(
  889.                         $em,
  890.                         $userId///id
  891.                         $card->getAmount(), //amount
  892.                         $card->getCoinCount()
  893.                     );
  894.                     if ($card->getUseCount() <= 1) {
  895.                         $card->setIsClaimed(1);
  896.                     }
  897.                     $card->setUseCount($card->getUseCount() - 1);
  898.                     $em->flush();
  899.                     $data['claimedAmount'] = $card->getAmount();
  900.                     $data['claimedCoin'] = $card->getCoinCount();
  901.                     $claimSuccess true;
  902.                     if ($success == false$success true;
  903.                 }
  904.             }
  905.         }
  906.         return array(
  907.             'success' => $claimFlag == $claimSuccess $isClaimable,
  908.             'exists' => $card true false,
  909.             'isClaimable' => $isClaimable,
  910.             'claimSuccess' => $claimSuccess,
  911.             'data' => $data,
  912.             'cardId' => $cardId,
  913.             'claimFlag' => $claimFlag,
  914.             'serial' => $serial,
  915.             'pin' => $pin,
  916.         );
  917.     }
  918.     public static function ClaimPromoCode($em$options)
  919.     {
  920.         $data = [
  921.             'success' => false,
  922.             'message' => 'Invalid Code',
  923.             'claimableCoin' => 0,
  924.             'isClaimable' => 0,
  925.             'currency' => 'eur',
  926.             'claimableAmount' => 0,
  927.             'claimedAmount' => 0,
  928.             'claimedCoin' => 0,
  929.             'promoCodeId' => 0,
  930.             'overrideBySystem' => 0,
  931.         ];
  932.         $success false;
  933.         $isClaimable false;
  934.         $claimSuccess false;
  935.         $claimFlag = isset($options['claimFlag']) ? $options['claimFlag'] : 0;
  936.         $currency = isset($options['currency']) ? $options['currency'] : 'eur';
  937.         $currencyMult BuddybeeConstant::$convMultFromTo[$currency]['eur'];
  938.         $userId = isset($options['userId']) ? $options['userId'] : 0;
  939.         $cardId = isset($options['cardId']) ? $options['cardId'] : 0;
  940.         $promoCodeId = isset($options['cardId']) ? $options['promoCodeId'] : 0;
  941.         $overrideBySystem = isset($options['overrideBySystem']) ? $options['overrideBySystem'] : 0;
  942.         //check 1st
  943.         $serial = isset($options['serial']) ? $options['serial'] : '_NONE_';
  944.         $pin = isset($options['pin']) ? $options['pin'] : '_NONE_';
  945.         $promoCodeStr = isset($options['promoCode']) ? $options['promoCode'] : '_NONE_';
  946.         $orderValue $currencyMult * (isset($options['orderValue']) ? $options['orderValue'] : 0);
  947.         $orderCoins = isset($options['orderCoin']) ? $options['orderCoin'] : 0;
  948.         $isReferral = isset($options['isReferral']) ? $options['isReferral'] : 0;
  949.         $thisUserThisPromoUseCount 0;
  950.         $currDt = new \DateTime();
  951.         $currDtTs * ($currDt->format('U'));
  952.         $claimedAmount 0;
  953.         $claimableAmount 0;
  954.         $claimedCoin 0;
  955.         $claimableCoin 0;
  956.         $claimFailMessage '';
  957.         if ($isReferral == 1) {
  958.             $userData $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
  959.                 array('applicantId' => $userId)
  960.             );
  961.             $referrerData $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
  962.                 array('codeAsReferer' => $promoCodeStr)
  963.             );
  964.             $promoCode $em->getRepository('CompanyGroupBundle\\Entity\\PromoCode')
  965.                 ->findOneBy(
  966.                     array(
  967.                         'code' => '_GEN_REFER_'
  968.                     )
  969.                 );
  970.             if ($promoCode) {
  971.                 $data = array(
  972.                     'success' => true,
  973.                     'message' => '',
  974.                     'id' => $promoCode->getId(),
  975.                     'code' => $promoCode->getCode(),
  976.                     'promoType' => $promoCode->getPromoType(),
  977.                     'promoValue' => $promoCode->getPromoValue(),
  978.                     'maxDiscountAmount' => $promoCode->getMaxDiscountAmount(),
  979.                     'maxCoinAddition' => $promoCode->getMaxCoinAddition(),
  980.                     'minAmountForApplication' => $promoCode->getMinAmountForApplication(),
  981.                     'minCoinForApplication' => $promoCode->getMinCoinForApplication(),
  982.                     'nextApplicationEachCoinCount' => $promoCode->getNextApplicationEachCoinCount(),
  983.                     'maxUseCount' => $promoCode->getMaxUseCount(),
  984.                     'maxUseCountPerUser' => $promoCode->getMaxUseCountPerUser(),
  985.                     'useCountBalance' => $promoCode->getUseCountBalance(),
  986.                     'useCountBalanceUser' => 0,
  987.                     'startsAtTs' => $promoCode->getStartsAtTs(),
  988.                     'expiresAtTs' => $promoCode->getExpiresAtTs(),
  989.                     'perpetual' => $promoCode->getPerpetual(),
  990.                 );
  991.             }
  992.             //get the applicant Data
  993.             if ($promoCode) {
  994.                 $promoCodeId $promoCode->getId();
  995.                 $isClaimable false;
  996.                 if ($success == false$success true;
  997.                 if ($userData)
  998.                     $claimedPromoCodeIds json_decode($userData->getClaimedPromoCodeIds(), true);
  999.                 else
  1000.                     $claimedPromoCodeIds = [];
  1001.                 if ($claimedPromoCodeIds == null$claimedPromoCodeIds = [];
  1002.                 $claimedPromoCodeCountByIds array_count_values($claimedPromoCodeIds);
  1003.                 if (isset($claimedPromoCodeCountByIds[$promoCodeId]))
  1004.                     $thisUserThisPromoUseCount $claimedPromoCodeCountByIds[$promoCodeId];
  1005.                 //check one by one if any claim condition doesnot match
  1006.                 if ($promoCode->getUseCountBalance() != -&& $promoCode->getUseCountBalance() <= 0) {
  1007.                     $claimFailMessage "This code can no longer be used!";
  1008.                 }
  1009.                 if ($promoCode->getMaxUseCountPerUser() != -&& $promoCode->getMaxUseCountPerUser() <= $thisUserThisPromoUseCount) {
  1010.                     $claimFailMessage "This code can no longer be used for this user!";
  1011.                 } else if ($promoCode->getPerpetual() != && $promoCode->getExpiresAtTs() < $currDtTs) {
  1012.                     $claimFailMessage "This code has Expired!";
  1013.                 } else if ($promoCode->getStartsAtTs() > $currDtTs) {
  1014.                     $claimFailMessage "This code is not yet usable!";
  1015.                 } else {
  1016.                     if ($promoCode->getPromoType() == 1//amount discount
  1017.                     {
  1018.                         if ($promoCode->getMinAmountForApplication() != -&& $promoCode->getMinAmountForApplication() > $orderValue) {
  1019.                             $claimFailMessage "Minimum order for this code is " $promoCode->getMinAmountForApplication();
  1020.                         } else if ($promoCode->getMinCoinForApplication() != -&& $promoCode->getMinCoinForApplication() > $orderCoins) {
  1021.                             $claimFailMessage "You must Purchase at least " $promoCode->getMinCoinForApplication() . " points/coins";
  1022.                         } else {
  1023.                             $claimableAmount $promoCode->getPromoValue();
  1024.                             if ($promoCode->getNextApplicationEachCoinCount() != -&& $promoCode->getNextApplicationEachCoinCount() != && $orderCoins != 0) {
  1025.                                 $extraCoins $orderCoins $promoCode->getMinCoinForApplication();
  1026.                                 $it $extraCoins / ($promoCode->getNextApplicationEachCoinCount());
  1027.                                 $claimableAmount += ($it $promoCode->getPromoValue());
  1028.                             }
  1029.                             if ($promoCode->getMaxDiscountAmount() != -&& $claimableAmount $promoCode->getMaxDiscountAmount()) {
  1030.                                 $claimableAmount $promoCode->getMaxDiscountAmount();
  1031.                             }
  1032.                             $isClaimable true;
  1033.                         }
  1034.                     }
  1035.                     if ($promoCode->getPromoType() == 2//percentage discount
  1036.                     {
  1037.                         if ($promoCode->getMinAmountForApplication() != -&& $promoCode->getMinAmountForApplication() > $orderValue) {
  1038.                             $claimFailMessage "Minimum order for this code is " $promoCode->getMinAmountForApplication();
  1039.                         } else if ($promoCode->getMinCoinForApplication() != -&& $promoCode->getMinCoinForApplication() > $orderCoins) {
  1040.                             $claimFailMessage "You must Purchase at least " $promoCode->getMinCoinForApplication() . " points/coins";
  1041.                         } else {
  1042.                             $claimableAmount $orderValue $promoCode->getPromoValue() / 100;
  1043.                             if ($promoCode->getNextApplicationEachCoinCount() != -&& $promoCode->getNextApplicationEachCoinCount() != && $orderCoins != 0) {
  1044.                                 $extraCoins $orderCoins $promoCode->getMinCoinForApplication();
  1045.                                 $it $extraCoins / ($promoCode->getNextApplicationEachCoinCount());
  1046.                                 $claimableAmount += ($it $orderValue $promoCode->getPromoValue() / 100);
  1047.                             }
  1048.                             if ($promoCode->getMaxDiscountAmount() != -&& $claimableAmount $promoCode->getMaxDiscountAmount()) {
  1049.                                 $claimableAmount $promoCode->getMaxDiscountAmount();
  1050.                             }
  1051.                             $isClaimable true;
  1052.                         }
  1053.                     }
  1054.                 }
  1055.                 //if this stage has come then the
  1056.                 $data['claimableAmount'] = strval($claimableAmount);
  1057.                 $data['claimableCoin'] = $claimableCoin;
  1058.                 if ($claimFlag == && $userId != 0) {
  1059.                     $claimedPromoCodeIds[] = $promoCodeId;
  1060.                     $userData->setClaimedPromoCodeIds(json_encode($claimedPromoCodeIds));
  1061.                     $promoCode->setUseCountBalance($promoCode->setUseCountBalance() - 1);
  1062.                     $em->flush();
  1063.                     if ($promoCode->getMaxReferralCommissionCount() != -&& $promoCode->getReferralCommissionCountBalance() > 0) {
  1064.                         $claimFailMessage "Minimum order for this code is " $promoCode->getMinAmountForApplication();
  1065.                     } else {
  1066.                         $referrerData $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
  1067.                             array('applicantId' => $promoCode->getReferralApplicantId())
  1068.                         );
  1069.                         if ($referrerData) {
  1070.                             $referralAmount 0;
  1071.                             $referralCoin 0;
  1072.                             if ($promoCode->getReferralCommissionType() == 1)//amount addition
  1073.                             {
  1074.                                 $referralAmount $promoCode->getReferralAmount();
  1075. //                            $referralAmount=$orderValue*$promoCode->getReferralAmount()->getPromoValue()/100;
  1076.                             } else if ($promoCode->getReferralCommissionType() == 2)//percent addition
  1077.                             {
  1078. //                                $referralAmount = $promoCode->getReferralAmount();
  1079.                                 $referralAmount $orderValue $promoCode->getReferralAmount() / 100;
  1080.                             }
  1081.                             if ($promoCode->getMaxReferralCommissionAmount() != -&& $referralAmount $promoCode->getMaxReferralCommissionAmount()) {
  1082.                                 $referralAmount $promoCode->getMaxReferralCommissionAmount();
  1083.                             }
  1084.                             $referrerData->setReferredAmountEarned($referrerData->setReferredAmountEarned() + $referralAmount);
  1085.                             $promoCode->setReferralCommissionCountBalance($promoCode->setReferralCommissionCountBalance() - 1);
  1086.                             $em->flush();
  1087.                         }
  1088.                     }
  1089.                     $claimedAmount $claimableAmount;
  1090.                     $claimedCoin $claimableCoin;
  1091.                     $em->flush();
  1092.                     $data['claimedAmount'] = $claimedAmount;
  1093.                     $data['claimedCoin'] = $claimedCoin;
  1094.                     $claimSuccess true;
  1095.                     if ($success == false$success true;
  1096.                 }
  1097.             }
  1098.             return array(
  1099.                 'success' => $claimFlag == $claimSuccess $isClaimable,
  1100.                 'exists' => $promoCode true false,
  1101.                 'isClaimable' => $isClaimable,
  1102.                 'claimFailMessage' => $claimFailMessage,
  1103.                 'claimSuccess' => $claimSuccess,
  1104.                 'data' => $data,
  1105.                 'promoCodeId' => $promoCodeId,
  1106.                 'claimFlag' => $claimFlag,
  1107.             );
  1108.         } else {
  1109.             //1st searching for direct code
  1110.             $promoCode $em->getRepository('CompanyGroupBundle\\Entity\\PromoCode')
  1111.                 ->findOneBy(
  1112.                     array(
  1113.                         'code' => $promoCodeStr
  1114.                     )
  1115.                 );
  1116.             if ($promoCode) {
  1117.                 $data = array(
  1118.                     'success' => true,
  1119.                     'message' => '',
  1120.                     'id' => $promoCode->getId(),
  1121.                     'code' => $promoCode->getCode(),
  1122.                     'promoType' => $promoCode->getPromoType(),
  1123.                     'promoValue' => $promoCode->getPromoValue(),
  1124.                     'maxDiscountAmount' => $promoCode->getMaxDiscountAmount(),
  1125.                     'maxCoinAddition' => $promoCode->getMaxCoinAddition(),
  1126.                     'minAmountForApplication' => $promoCode->getMinAmountForApplication(),
  1127.                     'minCoinForApplication' => $promoCode->getMinCoinForApplication(),
  1128.                     'nextApplicationEachCoinCount' => $promoCode->getNextApplicationEachCoinCount(),
  1129.                     'maxUseCount' => $promoCode->getMaxUseCount(),
  1130.                     'maxUseCountPerUser' => $promoCode->getMaxUseCountPerUser(),
  1131.                     'useCountBalance' => $promoCode->getUseCountBalance(),
  1132.                     'useCountBalanceUser' => 0,
  1133.                     'startsAtTs' => $promoCode->getStartsAtTs(),
  1134.                     'expiresAtTs' => $promoCode->getExpiresAtTs(),
  1135.                     'perpetual' => $promoCode->getPerpetual(),
  1136.                 );
  1137.             }
  1138.             //get the applicant Data
  1139.             $userData $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
  1140.                 array('applicantId' => $userId)
  1141.             );
  1142.             if ($promoCode) {
  1143.                 $promoCodeId $promoCode->getId();
  1144.                 $isClaimable false;
  1145.                 if ($success == false$success true;
  1146.                 if ($userData)
  1147.                     $claimedPromoCodeIds json_decode($userData->getClaimedPromoCodeIds(), true);
  1148.                 else
  1149.                     $claimedPromoCodeIds = [];
  1150.                 if ($claimedPromoCodeIds == null$claimedPromoCodeIds = [];
  1151.                 $claimedPromoCodeCountByIds array_count_values($claimedPromoCodeIds);
  1152.                 if (isset($claimedPromoCodeCountByIds[$promoCodeId]))
  1153.                     $thisUserThisPromoUseCount $claimedPromoCodeCountByIds[$promoCodeId];
  1154.                 //check one by one if any claim condition doesnot match
  1155.                 if ($promoCode->getUseCountBalance() != -&& $promoCode->getUseCountBalance() <= 0) {
  1156.                     $claimFailMessage "This code can no longer be used!";
  1157.                 }
  1158.                 if ($promoCode->getMaxUseCountPerUser() != -&& $promoCode->getMaxUseCountPerUser() <= $thisUserThisPromoUseCount) {
  1159.                     $claimFailMessage "This code can no longer be used for this user!";
  1160.                 } else if ($promoCode->getPerpetual() != && $promoCode->getExpiresAtTs() < $currDtTs) {
  1161.                     $claimFailMessage "This code has Expired!";
  1162.                 } else if ($promoCode->getStartsAtTs() > $currDtTs) {
  1163.                     $claimFailMessage "This code is not yet usable!";
  1164.                 } else {
  1165.                     if ($promoCode->getPromoType() == 1//amount discount
  1166.                     {
  1167.                         if ($promoCode->getMinAmountForApplication() != -&& $promoCode->getMinAmountForApplication() > $orderValue) {
  1168.                             $claimFailMessage "Minimum order for this code is " $promoCode->getMinAmountForApplication();
  1169.                         } else if ($promoCode->getMinCoinForApplication() != -&& $promoCode->getMinCoinForApplication() > $orderCoins) {
  1170.                             $claimFailMessage "You must Purchase at least " $promoCode->getMinCoinForApplication() . " points/coins";
  1171.                         } else {
  1172.                             $claimableAmount $promoCode->getPromoValue();
  1173.                             if ($promoCode->getNextApplicationEachCoinCount() != -&& $promoCode->getNextApplicationEachCoinCount() != && $orderCoins != 0) {
  1174.                                 $extraCoins $orderCoins $promoCode->getMinCoinForApplication();
  1175.                                 $it $extraCoins / ($promoCode->getNextApplicationEachCoinCount());
  1176.                                 $claimableAmount += ($it $promoCode->getPromoValue());
  1177.                             }
  1178.                             if ($promoCode->getMaxDiscountAmount() != -&& $claimableAmount $promoCode->getMaxDiscountAmount()) {
  1179.                                 $claimableAmount $promoCode->getMaxDiscountAmount();
  1180.                             }
  1181.                             $isClaimable true;
  1182.                         }
  1183.                     }
  1184.                     if ($promoCode->getPromoType() == 2//percentage discount
  1185.                     {
  1186.                         if ($promoCode->getMinAmountForApplication() != -&& $promoCode->getMinAmountForApplication() > $orderValue) {
  1187.                             $claimFailMessage "Minimum order for this code is " $promoCode->getMinAmountForApplication();
  1188.                         } else if ($promoCode->getMinCoinForApplication() != -&& $promoCode->getMinCoinForApplication() > $orderCoins) {
  1189.                             $claimFailMessage "You must Purchase at least " $promoCode->getMinCoinForApplication() . " points/coins";
  1190.                         } else {
  1191.                             $claimableAmount $orderValue $promoCode->getPromoValue() / 100;
  1192.                             if ($promoCode->getNextApplicationEachCoinCount() != -&& $promoCode->getNextApplicationEachCoinCount() != && $orderCoins != 0) {
  1193.                                 $extraCoins $orderCoins $promoCode->getMinCoinForApplication();
  1194.                                 $it $extraCoins / ($promoCode->getNextApplicationEachCoinCount());
  1195.                                 $claimableAmount += ($it $orderValue $promoCode->getPromoValue() / 100);
  1196.                             }
  1197.                             if ($promoCode->getMaxDiscountAmount() != -&& $claimableAmount $promoCode->getMaxDiscountAmount()) {
  1198.                                 $claimableAmount $promoCode->getMaxDiscountAmount();
  1199.                             }
  1200.                             $isClaimable true;
  1201.                         }
  1202.                     }
  1203.                 }
  1204.                 //if this stage has come then the
  1205.                 $data['claimableAmount'] = strval($claimableAmount);
  1206.                 $data['claimableCoin'] = $claimableCoin;
  1207.                 if ($claimFlag == && $userId != 0) {
  1208.                     $claimedPromoCodeIds[] = $promoCodeId;
  1209.                     $userData->setClaimedPromoCodeIds(json_encode($claimedPromoCodeIds));
  1210.                     $promoCode->setUseCountBalance($promoCode->getUseCountBalance() - 1);
  1211.                     $em->flush();
  1212.                     if ($promoCode->getMaxReferralCommissionCount() != -&& $promoCode->getReferralCommissionCountBalance() > 0) {
  1213.                         $claimFailMessage "Minimum order for this code is " $promoCode->getMinAmountForApplication();
  1214.                     } else {
  1215.                         $referrerData $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
  1216.                             array('applicantId' => $promoCode->getReferralApplicantId())
  1217.                         );
  1218.                         if ($referrerData) {
  1219.                             $referralAmount 0;
  1220.                             $referralCoin 0;
  1221.                             if ($promoCode->getReferralCommissionType() == 1)//amount addition
  1222.                             {
  1223.                                 $referralAmount $promoCode->getReferralAmount();
  1224. //                            $referralAmount=$orderValue*$promoCode->getReferralAmount()->getPromoValue()/100;
  1225.                             } else if ($promoCode->getReferralCommissionType() == 2)//percent addition
  1226.                             {
  1227. //                                $referralAmount = $promoCode->getReferralAmount();
  1228.                                 $referralAmount $orderValue $promoCode->getReferralAmount() / 100;
  1229.                             }
  1230.                             if ($promoCode->getMaxReferralCommissionAmount() != -&& $referralAmount $promoCode->getMaxReferralCommissionAmount()) {
  1231.                                 $referralAmount $promoCode->getMaxReferralCommissionAmount();
  1232.                             }
  1233.                             $referrerData->setReferredAmountEarned($referrerData->getReferredAmountEarned() + $referralAmount);
  1234.                             $promoCode->setReferralCommissionCountBalance($promoCode->getReferralCommissionCountBalance() - 1);
  1235.                             $em->flush();
  1236.                         }
  1237.                     }
  1238.                     $claimedAmount $claimableAmount;
  1239.                     $claimedCoin $claimableCoin;
  1240.                     $em->flush();
  1241.                     $data['claimedAmount'] = $claimedAmount;
  1242.                     $data['claimedCoin'] = $claimedCoin;
  1243.                     $claimSuccess true;
  1244.                     if ($success == false$success true;
  1245.                 }
  1246. //                $data['success']=$claimFlag == 1 ? $claimSuccess : $isClaimable;
  1247.                 $data['message'] = $claimFailMessage;
  1248.                 $data['isClaimable'] = $isClaimable;
  1249.                 $data['claimSuccess'] = $claimSuccess;
  1250.             }
  1251.             return array(
  1252.                 'success' => $claimFlag == $claimSuccess $isClaimable,
  1253.                 'exists' => $promoCode true false,
  1254.                 'isClaimable' => $isClaimable,
  1255.                 'claimFailMessage' => $claimFailMessage,
  1256.                 'claimSuccess' => $claimSuccess,
  1257.                 'data' => $data,
  1258.                 'promoCodeId' => $promoCodeId,
  1259.                 'claimFlag' => $claimFlag,
  1260.             );
  1261.         }
  1262.     }
  1263.     public static function toListArray($obj)
  1264.     {
  1265.         $array = array();
  1266.         foreach ($obj as $ob)
  1267.             $array[] = $ob;
  1268.         return $array;
  1269.     }
  1270.     public static function filterPackageList($options = [])
  1271.     {
  1272.         $requiredPurchaseSessionCount = isset($options['requiredPurchaseSessionCount']) ? $options['requiredPurchaseSessionCount'] : 0;
  1273.         $packageNames BuddybeeConstant::$packageNames;
  1274.         $packageDetails BuddybeeConstant::$packageDetails;
  1275.         $array = array(
  1276.             'packageNames' => [],
  1277.             'packageDetails' => [],
  1278.             'selectionValue' => BuddybeeConstant::COIN_GENERAL_MULT,
  1279.             'selectionPackageId' => 0,
  1280.         );
  1281.         foreach ($packageDetails as $key => $obj) {
  1282.             if ($obj['sessionMaxCount'] < $requiredPurchaseSessionCount)
  1283.                 continue;
  1284.             $array['selectionPackageId'] = $key;
  1285.             if ($obj['sessionMinCount'] > $requiredPurchaseSessionCount)
  1286.                 $array['selectionValue'] = $obj['sessionMinCount'];
  1287.             else {
  1288.                 $obj['sessionMinCount'] = $requiredPurchaseSessionCount;
  1289.                 $array['selectionValue'] = $requiredPurchaseSessionCount;
  1290.             }
  1291.             $obj['packageId'] = $key;
  1292.             $array['packageNames'][] = $obj['packageName'];
  1293.             $array['packageDetails'][] = $obj;
  1294.         }
  1295.         return $array;
  1296.     }
  1297.     public static function ConvertRegionalTimeToServerTime($currentRegionalTimeStr$toConvertRegionalTimeStr)
  1298.     {
  1299.         $currSvrTime = new \DateTime();
  1300.         $toConvertTime = new \DateTime($toConvertRegionalTimeStr);
  1301.         $currClientTime = new \DateTime($currentRegionalTimeStr);
  1302.         $interval $currClientTime->diff($currSvrTime);
  1303.         if ($currClientTime $currSvrTime)
  1304.             $toConvertTime->add($interval);
  1305.         else
  1306.             $toConvertTime->sub($interval);
  1307.         return $toConvertTime;
  1308.     }
  1309.     public static function RemoveFileById($em$id$afterRemoveConfig)
  1310.     {
  1311.         //remove expired availability 1st
  1312. //        return true; //for now
  1313.         $currDateNow = new \DateTime();
  1314.         //remove restrictions over 1 year old
  1315.         $currDateNow->modify('-365 Day');
  1316.         $get_kids_sql "select * FROM `entity_files` WHERE id = " $id;
  1317.         $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  1318.         $query_output $stmt;
  1319.         foreach ($query_output as $q) {
  1320.             if (file_exists($q['path'])) {
  1321.                 chmod($q['path'], 0755);
  1322.                 unlink($q['path']);
  1323.             }
  1324.             if ($q['marker'] == '_ENTITY_APPLICANT_DOCUMENT_') {
  1325.                 $consultantDetails $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
  1326.                     array(
  1327.                         'applicantId' => $q['entity_id']
  1328.                     )
  1329.                 );;
  1330.                 $currDocList json_decode($consultantDetails->getDocumentList(), true);
  1331.                 $doc_index_here $q['doc_id_for_applicant'];
  1332.                 if ($currDocList == null)
  1333.                     $currDocList = [];
  1334.                 if (isset($currDocList[$doc_index_here])) {
  1335.                     $currDocList[$doc_index_here]['docImage'] = '';
  1336.                     $currDocList[$doc_index_here]['docExpiryDate'] = '';
  1337.                     $consultantDetails->setDocumentList(json_encode($currDocList));
  1338.                     $em->flush();
  1339.                 }
  1340.             } else if ($q['entity_bundle'] != '' && $q['entity_name'] != '' && $q['entity_id_field'] != '') {
  1341.                 $entityDoc $em->getRepository($q['entity_bundle'] . ':' $q['entity_name'])->findOneBy(
  1342.                     array(
  1343.                         $q['entity_id_field'] => $q['entity_id']
  1344.                     )
  1345.                 );
  1346.                 if ($entityDoc) {
  1347.                     $entityDoc->{$q['modify_field_setter']}('');
  1348.                     $em->flush();
  1349.                 }
  1350.                 $consultantDetails $em->getRepository(EntityApplicantDetails::class)->find($q['entity_id']);
  1351.                 $currDocList json_decode($consultantDetails->getDocumentList(), true);
  1352.                 $doc_index_here $q['doc_id_for_applicant'];
  1353.                 if ($currDocList == null)
  1354.                     $currDocList = [];
  1355.                 if (isset($currDocList[$doc_index_here])) {
  1356.                     $currDocList[$doc_index_here]['docImage'] = '';
  1357.                     $currDocList[$doc_index_here]['docExpiryDate'] = '';
  1358.                     $consultantDetails->setDocumentList(json_encode($currDocList));
  1359.                     $em->flush();
  1360.                 }
  1361.             }
  1362.         }
  1363.         $get_kids_sql "DELETE FROM `entity_files` WHERE id = " $id;
  1364.         $stmt $em->getConnection()->executeStatement($get_kids_sql);
  1365.         return true;
  1366.     }
  1367.     public static function RemoveFileByCondition($em$conditionOptions = [])
  1368.     {
  1369.         //remove expired availability 1st
  1370. //        return true; //for now
  1371.         $currDateNow = new \DateTime();
  1372.         //remove restrictions over 1 year old
  1373.         $currDateNow->modify('-365 Day');
  1374.         $EntityFile $em->getRepository('CompanyGroupBundle\\Entity\\EntityFile')->findOneBy(
  1375.             $conditionOptions
  1376.         );
  1377.         if ($EntityFile) {
  1378.             $q = array(
  1379.                 'path' => $EntityFile->getPath(),
  1380.                 'entity_name' => $EntityFile->getEntityName(),
  1381.                 'entity_id_field' => $EntityFile->getEntityIdField(),
  1382.                 'entity_id' => $EntityFile->getEntityId(),
  1383.                 'entity_bundle' => $EntityFile->getEntityBundle(),
  1384.                 'marker' => $EntityFile->getMarker(),
  1385.                 'doc_id_for_applicant' => $EntityFile->getDocIdForApplicant(),
  1386.                 'modify_field_setter' => $EntityFile->getModifyFieldSetter(),
  1387.             );
  1388.             if (file_exists($q['path'])) {
  1389.                 chmod($q['path'], 0755);
  1390.                 unlink($q['path']);
  1391.             }
  1392.             if ($q['marker'] == '_ENTITY_APPLICANT_DOCUMENT_') {
  1393.                 $consultantDetails $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
  1394.                     array(
  1395.                         'applicantId' => $q['entity_id']
  1396.                     )
  1397.                 );;
  1398.                 $currDocList json_decode($consultantDetails->getDocumentList(), true);
  1399.                 $doc_index_here $q['doc_id_for_applicant'];
  1400.                 if ($currDocList == null)
  1401.                     $currDocList = [];
  1402.                 if (isset($currDocList[$doc_index_here])) {
  1403.                     $currDocList[$doc_index_here]['docImage'] = '';
  1404.                     $currDocList[$doc_index_here]['docExpiryDate'] = '';
  1405.                     $consultantDetails->setDocumentList(json_encode($currDocList));
  1406.                     $em->flush();
  1407.                 }
  1408.             } else if ($q['entity_bundle'] != '' && $q['entity_name'] != '' && $q['entity_id_field'] != '') {
  1409.                 $entityDoc $em->getRepository($q['entity_bundle'] . ':' $q['entity_name'])->findOneBy(
  1410.                     array(
  1411.                         $q['entity_id_field'] => $q['entity_id']
  1412.                     )
  1413.                 );
  1414.                 if ($entityDoc) {
  1415.                     $entityDoc->{$q['modify_field_setter']}('');
  1416.                     $em->flush();
  1417.                 }
  1418.                 $consultantDetails $em->getRepository(EntityApplicantDetails::class)->find($q['entity_id']);
  1419.                 $currDocList json_decode($consultantDetails->getDocumentList(), true);
  1420.                 $doc_index_here $q['doc_id_for_applicant'];
  1421.                 if ($currDocList == null)
  1422.                     $currDocList = [];
  1423.                 if (isset($currDocList[$doc_index_here])) {
  1424.                     $currDocList[$doc_index_here]['docImage'] = '';
  1425.                     $currDocList[$doc_index_here]['docExpiryDate'] = '';
  1426.                     $consultantDetails->setDocumentList(json_encode($currDocList));
  1427.                     $em->flush();
  1428.                 }
  1429.             }
  1430.             $em->remove($EntityFile);
  1431.             $em->flush();
  1432.         }
  1433. //
  1434. //        $get_kids_sql = "DELETE FROM `entity_files` WHERE path like '% " . $pathStr."%'";
  1435. //        $stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
  1436. //        
  1437. //        
  1438.         return true;
  1439.     }
  1440.     public static function RemoveFileByPath($em$pathStr$afterRemoveConfig = [])
  1441.     {
  1442.         //remove expired availability 1st
  1443. //        return true; //for now
  1444.         $currDateNow = new \DateTime();
  1445.         //remove restrictions over 1 year old
  1446.         $currDateNow->modify('-365 Day');
  1447.         $get_kids_sql "select * FROM `entity_files` WHERE path like '%" $pathStr "%'";
  1448.         $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  1449.         $query_output $stmt;
  1450.         foreach ($query_output as $q) {
  1451.             if (file_exists($q['path'])) {
  1452.                 chmod($q['path'], 0755);
  1453.                 unlink($q['path']);
  1454.             }
  1455.             if ($q['marker'] == '_ENTITY_APPLICANT_DOCUMENT_') {
  1456.                 $consultantDetails $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
  1457.                     array(
  1458.                         'applicantId' => $q['entity_id']
  1459.                     )
  1460.                 );;
  1461.                 $currDocList json_decode($consultantDetails->getDocumentList(), true);
  1462.                 $doc_index_here $q['doc_id_for_applicant'];
  1463.                 if ($currDocList == null)
  1464.                     $currDocList = [];
  1465.                 if (isset($currDocList[$doc_index_here])) {
  1466.                     $currDocList[$doc_index_here]['docImage'] = '';
  1467.                     $currDocList[$doc_index_here]['docExpiryDate'] = '';
  1468.                     $consultantDetails->setDocumentList(json_encode($currDocList));
  1469.                     $em->flush();
  1470.                 }
  1471.             } else if ($q['entity_bundle'] != '' && $q['entity_name'] != '' && $q['entity_id_field'] != '') {
  1472.                 $entityDoc $em->getRepository($q['entity_bundle'] . ':' $q['entity_name'])->findOneBy(
  1473.                     array(
  1474.                         $q['entity_id_field'] => $q['entity_id']
  1475.                     )
  1476.                 );
  1477.                 if ($entityDoc) {
  1478.                     $entityDoc->{$q['modify_field_setter']}('');
  1479.                     $em->flush();
  1480.                 }
  1481.                 $consultantDetails $em->getRepository(EntityApplicantDetails::class)->find($q['entity_id']);
  1482.                 $currDocList json_decode($consultantDetails->getDocumentList(), true);
  1483.                 $doc_index_here $q['doc_id_for_applicant'];
  1484.                 if ($currDocList == null)
  1485.                     $currDocList = [];
  1486.                 if (isset($currDocList[$doc_index_here])) {
  1487.                     $currDocList[$doc_index_here]['docImage'] = '';
  1488.                     $currDocList[$doc_index_here]['docExpiryDate'] = '';
  1489.                     $consultantDetails->setDocumentList(json_encode($currDocList));
  1490.                     $em->flush();
  1491.                 }
  1492.             }
  1493.         }
  1494.         $get_kids_sql "DELETE FROM `entity_files` WHERE path like '% " $pathStr "%'";
  1495.         $stmt $em->getConnection()->executeStatement($get_kids_sql);
  1496.         return true;
  1497.     }
  1498.     public static function RemoveFilesForEntityDoc($em$entityName ''$entityId 0)
  1499.     {
  1500.         //remove expired availability 1st
  1501. //        return true; //for now
  1502.         $currDateNow = new \DateTime();
  1503.         //remove restrictions over 1 year old
  1504.         $currDateNow->modify('-365 Day');
  1505.         $get_kids_sql "select * FROM `entity_files` WHERE entity_name='" $entityName "' and entity_id =" $entityId;
  1506.         $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  1507.         $query_output $stmt;
  1508.         foreach ($query_output as $q) {
  1509.             if (file_exists($q['path'])) {
  1510.                 chmod($q['path'], 0755);
  1511.                 unlink($q['path']);
  1512.             }
  1513.         }
  1514.         return true;
  1515.     }
  1516.     public static function RemoveExpiredDocs($em)
  1517.     {
  1518.         //remove expired availability 1st
  1519. //        return true; //for now
  1520.         $currDateNow = new \DateTime();
  1521.         //remove restrictions over 1 year old
  1522.         $currDateNow->modify('-10 Day');
  1523. //        foreach (GeneralConstant::$Entity_list as $entity=>$entityName) {
  1524. //
  1525. //            $query = $em->getRepository('ApplicationBundle\\Entity\\' . $entityName)
  1526. //                ->createQueryBuilder('p')
  1527. //                ->where("p.timeStampOfForm is NOT NULL ")
  1528. //                ->andWhere("p.approved is NULL ")
  1529. //                ->andWhere("p.timeStampOfForm <= " . $currDateNow->format('U'));
  1530. //            $results = $query->getQuery()->getResult();
  1531. //
  1532. //            foreach ($results as $r) {
  1533. //                $em->remove($r);
  1534. //                $em->flush();
  1535. //            }
  1536. //        }
  1537.         return true;
  1538.     }
  1539.     public static function RemoveExpiredFiles($em)
  1540.     {
  1541.         //remove expired availability 1st
  1542. //        return true; //for now
  1543.         $currDateNow = new \DateTime();
  1544.         $currDateNow->modify('-120 Day');
  1545.         $get_kids_sql "select * FROM `entity_files` WHERE expire_ts!=0 and expire_ts < " $currDateNow->format('U');
  1546.         $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  1547.         $query_output $stmt;
  1548.         $query_output = [];
  1549.         foreach ($query_output as $q) {
  1550.             if ($q['marker'] == '_ENTITY_APPLICANT_DOCUMENT_') {
  1551.                 $consultantDetails $em->getRepository(EntityApplicantDetails::class)->find($q['entity_id']);
  1552.                 if ($consultantDetails) {
  1553.                     $currDocList json_decode($consultantDetails->getDocumentList(), true);
  1554.                     $doc_index_here $q['doc_id_for_applicant'];
  1555.                     if ($currDocList == null)
  1556.                         $currDocList = [];
  1557.                     if (isset($currDocList[$doc_index_here])) {
  1558.                         $currDocList[$doc_index_here]['docImage'] = '';
  1559.                         $currDocList[$doc_index_here]['docExpiryDate'] = '';
  1560.                         $consultantDetails->setDocumentList(json_encode($currDocList));
  1561.                         $em->flush();
  1562.                     }
  1563.                 }
  1564.             } else if ($q['entity_bundle'] != '' && $q['entity_name'] != '' && $q['entity_id_field'] != '') {
  1565.                 $entity_id array_flip(GeneralConstant::$Entity_list)[$q['entity_name']]; //change
  1566.                 $entityDoc $em->getRepository(isset(GeneralConstant::$Entity_fqcn_by_id[$entity_id]) ? GeneralConstant::$Entity_fqcn_by_id[$entity_id] : ($q['entity_bundle'] . '\\Entity\\' $q['entity_name']))->findOneBy(
  1567.                     array(
  1568.                         $q['entity_id_field'] => $q['entity_id']
  1569.                     )
  1570.                 );
  1571.                 if ($entityDoc) {
  1572.                     if (method_exists($entityDoc'getApproved'))
  1573.                         if ($entityDoc->getApproved() == 1) {
  1574.                             $get_kids_sql "UPDATE `entity_files` SET expire_ts=0  WHERE id= " $q['id'];
  1575.                             $stmt $em->getConnection()->executeStatement($get_kids_sql);
  1576.                             continue;
  1577.                         }
  1578.                     $entityDoc->{$q['modify_field_setter']}('');
  1579.                     $em->flush();
  1580.                 }
  1581.             }
  1582.             if (file_exists($q['path'])) {
  1583.                 chmod($q['path'], 0755);
  1584.                 unlink($q['path']);
  1585.             }
  1586.         }
  1587.         $get_kids_sql "DELETE FROM `entity_files`  WHERE expire_ts!=0 and expire_ts < " $currDateNow->format('U');
  1588.         $stmt $em->getConnection()->executeStatement($get_kids_sql);
  1589.         return true;
  1590.     }
  1591.     public static function RemoveExpiredScheduleRestrictions($em$applicantId = [])
  1592.     {
  1593.         //remove expired availability 1st
  1594. //        return true; //for now
  1595.         $currDateNow = new \DateTime();
  1596.         //remove restrictions over 1 year old
  1597.         $currDateNow->modify('-365 Day');
  1598.         $get_kids_sql "DELETE FROM `consultancy_availability` WHERE expires_ts < " $currDateNow->format('U');
  1599.         $stmt $em->getConnection()->executeStatement($get_kids_sql);
  1600.         return true;
  1601.     }
  1602.     public static function AddScheduleRestrictions($em$applicantId 0$periodMarker '')
  1603.     {
  1604.         //remove expired schedules 1st
  1605.         $returnData = [];
  1606.         $consultant $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
  1607.             array(
  1608.                 'applicantId' => $applicantId
  1609.             )
  1610.         );
  1611.         if (!$consultant)
  1612.             return null;
  1613.         $new = new ConsultancyAvailability();
  1614.         $Y intdiv($periodMarker100);
  1615.         $M $periodMarker 100;
  1616.         $new->setType(2);
  1617.         $new->setYear($Y);
  1618.         $new->setMonth($M);
  1619.         $startAt = new \DateTime($Y '-' str_pad($M2'0'STR_PAD_LEFT) . '-01 00:00:00 +0000');
  1620.         $M $M 1;
  1621.         if ($M == 13) {
  1622.             $M 1;
  1623.             $Y++;
  1624.         }
  1625.         $expiresAt = new \DateTime($Y '-' str_pad($M2'0'STR_PAD_LEFT) . '-01 00:00:00 +0000');
  1626.         $new->setConsultantId($consultant->getApplicantId());
  1627.         $new->setPeriodMarker($periodMarker);;
  1628.         $new->setStartTs($startAt->format('U'));
  1629.         $new->setExpiresTs($expiresAt->format('U'));
  1630.         $countryRestrictionData $em->getRepository('CompanyGroupBundle\\Entity\\EntityCountryConsultantRequirements')->findOneBy(
  1631.             array(
  1632.                 'countryId' => $consultant->getCurrentCountryId()
  1633.             )
  1634.         );
  1635.         if ($countryRestrictionData) {
  1636.             if ($countryRestrictionData->getAllowedWorkingHoursPerMonth() != -1)
  1637.                 $new->setAllowedHours($countryRestrictionData->getAllowedWorkingHoursPerMonth());
  1638.             else
  1639.                 $new->setAllowedHours(160);
  1640.         } else
  1641.             $new->setAllowedHours(160);
  1642.         $new->setAvailableHours($new->getAllowedHours());
  1643.         $new->setBookedHours(0);
  1644.         $new->setTemporaryBookedHours(0);
  1645.         $em->persist($new);
  1646.         $em->flush();
  1647.         return $new//for now
  1648.     }
  1649.     public static function SchedulingAvailabilityByRestrictions($em$scheduleMarker$startDateStr$consultantId$duration)
  1650.     {
  1651.         MiscActions::RemoveExpiredScheduleRestrictions($em);
  1652.         $nextAvailableTs 0;
  1653.         $allowed 0;
  1654.         $availableMin 0;
  1655.         $startDate = new \DateTime($startDateStr);
  1656.         $startDate->setTimezone(new \DateTimeZone('+0000'));
  1657.         $endDate = new \DateTime($startDateStr);
  1658.         $applicableMarkers = [];
  1659.         $availableMinByPeriodMarker = [];
  1660.         $allowedMinByPeriodMarker = [];
  1661.         $restrictionDataByPeriodMarker = [];
  1662.         if ($scheduleMarker == '_NEXT_60_DAYS_') {
  1663.             $endDate->modify('+60 Day');
  1664.         }
  1665.         $toTestStartDate = clone($startDate);
  1666.         $toTestEndDate = clone($endDate);
  1667.         $consultancyAvailabilityDataArray = [];
  1668.         while ($toTestStartDate <= $toTestEndDate) {
  1669.             $toTestStartDate->modify('+1 Day');
  1670.             $markerForThis $toTestStartDate->format('Ym');
  1671.             if (!in_array($markerForThis$applicableMarkers))
  1672.                 $applicableMarkers[] = $markerForThis;
  1673.         }
  1674.         $query $em->getRepository('CompanyGroupBundle\\Entity\\ConsultancyAvailability')
  1675.             ->createQueryBuilder('p')
  1676.             ->where('p.periodMarker in (:pm)')
  1677.             ->andWhere('p.consultantId = :aid')
  1678.             ->andWhere('p.type = :typ')
  1679. //            ->andWhere('p.startTs < :sd')
  1680. //            ->andWhere('p.expiresTs < :ed')
  1681.             ->setParameter('typ'2)
  1682.             ->setParameter('aid'$consultantId)
  1683. //            ->setParameter('sd', $startDate->format('U'))
  1684. //            ->setParameter('ed', $endDate->format('U'))
  1685.             ->setParameter('pm'$applicableMarkers);
  1686. //        $query->setMaxResults(1);
  1687.         $consultantAvailabilityData $query->getQuery()->getResult();
  1688.         foreach ($consultantAvailabilityData as $d) {
  1689.             $consultancyAvailabilityDataArray[$d->getPeriodMarker()] = $d;
  1690.         }
  1691.         foreach ($applicableMarkers as $pm) {
  1692.             if (!isset($consultancyAvailabilityDataArray[$pm])) {
  1693.                 $d MiscActions::AddScheduleRestrictions($em$consultantId$pm);
  1694.             } else {
  1695.                 $d $consultancyAvailabilityDataArray[$pm];
  1696.             }
  1697.             $availableMin 60 * (($d->getAvailableHours()) - ($d->getTemporaryBookedHours()));
  1698.             $availableMinByPeriodMarker[$pm] = $availableMin;
  1699.             $allowedMinByPeriodMarker[$pm] = (60 $d->getAllowedHours());
  1700.             $restrictionDataByPeriodMarker[$pm] = array(
  1701.                 'startTs' => $d->getStartTs(),
  1702.                 'allowedHours' => $d->getAllowedHours(),
  1703.                 'availableHours' => $d->getAvailableHours(),
  1704.                 'expiresTs' => $d->getExpiresTs(),
  1705.             );
  1706.             if ($availableMin 0) {
  1707.                 $allowed 1;
  1708.                 $nextAvailableTs $d->getStartTs();
  1709.             }
  1710.         }
  1711. //        return array(
  1712. //            'allowed' => 1,
  1713. //            'availableMin' => 450,
  1714. //            'nextAvailableTs' => $nextAvailableTs,
  1715. //            'restrictionDataByPeriodMarker' => [],
  1716. //            'applicableMarkers' => $applicableMarkers,
  1717. //            'availableMinByPeriodMarker' => [],
  1718. //            'allowedMinByPeriodMarker' => [],
  1719. //        );
  1720.         return array(
  1721.             'allowed' => $allowed,
  1722.             'availableMin' => $availableMin,
  1723.             'nextAvailableTs' => $nextAvailableTs,
  1724.             'restrictionDataByPeriodMarker' => $restrictionDataByPeriodMarker,
  1725.             'applicableMarkers' => $applicableMarkers,
  1726.             'availableMinByPeriodMarker' => $availableMinByPeriodMarker,
  1727. //            'availableMinByPeriodMarker' => [],
  1728.             'allowedMinByPeriodMarker' => $allowedMinByPeriodMarker,
  1729.         );
  1730.     }
  1731.     public static function UpdateSchedulingRestrictions($em$applicantId$periodMarker$toAddBookedHours 0$toAddTemporaryBookedHours 0)
  1732.     {
  1733.         MiscActions::RemoveExpiredScheduleRestrictions($em);
  1734.         $returnData = [];
  1735.         $consultant $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
  1736.             array(
  1737.                 'applicantId' => $applicantId
  1738.             )
  1739.         );
  1740.         $new $em->getRepository('CompanyGroupBundle\\Entity\\ConsultancyAvailability')->findOneBy(
  1741.             array(
  1742.                 'periodMarker' => $periodMarker,
  1743.                 'consultantId' => $applicantId
  1744.             )
  1745.         );
  1746.         if (!$new) {
  1747.             $new = new ConsultancyAvailability();
  1748.             $Y intdiv($periodMarker100);
  1749.             $M $periodMarker 100;
  1750.             $new->setType(2);
  1751.             $new->setYear($Y);
  1752.             $new->setMonth($M);
  1753.             $startAt = new \DateTime($Y '-' str_pad($M2'0'STR_PAD_LEFT) . '-01 00:00:00 +0000');
  1754.             $M $M 1;
  1755.             if ($M == 13) {
  1756.                 $M 1;
  1757.                 $Y++;
  1758.             }
  1759.             $expiresAt = new \DateTime($Y '-' str_pad($M2'0'STR_PAD_LEFT) . '-01 00:00:00 +0000');
  1760.             $new->setConsultantId($consultant->getApplicantId());
  1761.             $new->setPeriodMarker($periodMarker);;
  1762.             $new->setStartTs($startAt->format('U'));
  1763.             $new->setExpiresTs($expiresAt->format('U'));
  1764.             $countryRestrictionData $em->getRepository('CompanyGroupBundle\\Entity\\EntityCountryConsultantRequirements')->findOneBy(
  1765.                 array(
  1766.                     'countryId' => $consultant->getCurrentCountryId()
  1767.                 )
  1768.             );
  1769.             if ($countryRestrictionData) {
  1770.                 if ($countryRestrictionData->getAllowedWorkingHoursPerMonth() != -1)
  1771.                     $new->setAllowedHours($countryRestrictionData->getAllowedWorkingHoursPerMonth());
  1772.                 else
  1773.                     $new->setAllowedHours(160);
  1774.             } else
  1775.                 $new->setAllowedHours(160);
  1776.             $new->setAvailableHours($new->getAllowedHours());
  1777.             $new->setBookedHours(0);
  1778.             $new->setTemporaryBookedHours(0);
  1779.             $em->persist($new);
  1780.         }
  1781.         $new->setBookedHours(($new->getBookedHours()) + ($toAddBookedHours));
  1782.         $new->setAvailableHours(($new->getAvailableHours()) - ($toAddBookedHours));
  1783.         $new->setTemporaryBookedHours(($new->getTemporaryBookedHours()) + ($toAddTemporaryBookedHours));
  1784.         $em->flush();
  1785.         return $new//for now
  1786.     }
  1787.     public static function GetConsultantExistingSchedules($em$consultantId$startDateStr ''$endDateStr ''$durationMin 90$options = [])
  1788.     {
  1789.         //start end dates and respose dats are all with time zones or UTC and ideally the UTC time stamps
  1790.         $startDate = new \DateTime($startDateStr);
  1791.         if ($endDateStr == '') {
  1792.             $endDate = clone($startDate);
  1793. //            if (isset($options['_THIS_DAY_']))
  1794. //                $endDate->modify('+1439 Minute');
  1795. //            else if (isset($options['_NEXT_60_DAYS_']))
  1796. //                $endDate->modify('+60 Day');
  1797. //            else if (isset($options['_NEXT_DAYS_']))
  1798. //                $endDate->modify('+' . $options['_NEXT_DAYS_'] . ' Day');
  1799. //            else
  1800.             $endDate->modify('+1439 Minute');
  1801.         } else
  1802.             $endDate = new \DateTime($endDateStr);
  1803.         $schedulesList = [];
  1804.         $debugData = [];
  1805.         $closestDateTs 0;
  1806.         //now get schedules
  1807.         $consultantScheduleData $em->getRepository('CompanyGroupBundle\\Entity\\EntityConsultantSchedule')->findBy(array(
  1808.             'consultantId' => $consultantId
  1809.         ));
  1810.         $consultantTimeZone '';
  1811.         $consultantSchedules = [];
  1812.         if ($consultantScheduleData) {
  1813.             $consultantSchedules = [];
  1814.             foreach ($consultantScheduleData as $key => $val) {
  1815.                 $indTimeSche = array(
  1816.                     'date' => $val->getStartDate() ? $val->getStartDate()->format('Y-m-d') : '',
  1817.                     'dateUpto' => $val->getEndDate() ? $val->getEndDate()->format('Y-m-d') : '',
  1818.                     'type' => ($val->getType() != null && $val->getType() != '') ? $val->getType() : 2,  // 0=specific date 1=every mentioned day of month 2=every mentioned day of week
  1819. //                    'dom' => $request->get('dom')[$key],  // based on type
  1820.                     'dow' => ($val->getDow() != null && $val->getDow() != '') ? json_decode($val->getDow(), true) : [],  // based on type
  1821.                     'startTime' => $val->getStartTime(),
  1822.                     'endTime' => $val->getEndTime(),
  1823.                     'timeZone' => $val->getTimeZoneStr(),
  1824.                 );
  1825.                 $consultantSchedules[] = $indTimeSche;
  1826.             }
  1827.             foreach ($consultantSchedules as $consultantSchedule) {
  1828.                 $consultantTimeZone $consultantSchedule['timeZone'];
  1829.             }
  1830.             $existingBookedSchedules $em->getRepository('CompanyGroupBundle\\Entity\\EntityMeetingSession')
  1831.                 ->createQueryBuilder('m')
  1832.                 ->where("m.consultantId = :consultantId")
  1833.                 ->andWhere("m.isExpired != 1")
  1834.                 ->andWhere("m.scheduledTimeTs >= :startAt")
  1835.                 ->andWhere("m.sessionExpireDateTs <= :endAt")
  1836.                 ->setParameter('consultantId'$consultantId)
  1837.                 ->setParameter('startAt'$startDate->format('U'))
  1838. //                ->setParameter('startAt', $startDate->format('Y-m-d h:i:s'))
  1839.                 ->setParameter('endAt'$endDate->format('U '))
  1840. //                ->setParameter('endAt', $endDate->format('Y-m-d h:i:s'))
  1841.                 ->getQuery()
  1842.                 ->getResult();
  1843.             $skipDateTimeStart = [];
  1844.             $skipDateTimeEnd = [];
  1845.             foreach ($existingBookedSchedules as $existingBookedSchedule) {
  1846.                 $scheduledStartTime = new \DateTime('@' $existingBookedSchedule->getScheduledTimeTs());;
  1847. //                $scheduledStartTime->setTimezone(new \DateTimeZone('UTC'));
  1848. //                $scheduledStartTime->setTimezone(new \DateTimeZone('+0000'));
  1849.                 $skipDateTimeStart[] = $scheduledStartTime;
  1850.                 $skipDateTimeEnd[] = new \DateTime('@' $existingBookedSchedule->getSessionExpireDateTs());
  1851.             }
  1852.             foreach ($consultantSchedules as $consultantSchedule) {
  1853.                 $scheduleType $consultantSchedule['type'];
  1854.                 $consultantScheduleStartAtTime = new \DateTime($consultantSchedule['date'] . ' ' $consultantSchedule['startTime'] . ':00 ' $consultantTimeZone);
  1855.                 $consultantScheduleEndAtTime = new \DateTime($consultantSchedule['date'] . ' ' $consultantSchedule['endTime'] . ':00 ' $consultantTimeZone);
  1856.                 $consultantScheduleUpToDate = new \DateTime($consultantSchedule['dateUpto'] . ' ' $consultantSchedule['endTime'] . ':00 ' $consultantTimeZone);
  1857.                 $dateAllowed 0;
  1858.                 $allowedStartTime 0;
  1859.                 $allowedEndTime 0;
  1860.                 if ($scheduleType == 1)//specific date
  1861.                 {
  1862.                     $startDateForCheck = clone($startDate);
  1863.                     $safetyLoopBreaker 3000;
  1864.                     if ($startDateForCheck >= $consultantScheduleEndAtTime) {
  1865.                         $consultantScheduleStartAtTime = new \DateTime($startDateForCheck->format('Y-m-d') . ' ' $consultantSchedule['startTime'] . ':00 ' $consultantTimeZone);
  1866.                         $consultantScheduleEndAtTime = new \DateTime($startDateForCheck->format('Y-m-d') . ' ' $consultantSchedule['endTime'] . ':00 ' $consultantTimeZone);
  1867.                         $consultantScheduleStartAtTime->modify('+1 Day');
  1868.                         $consultantScheduleEndAtTime->modify('+1 Day');
  1869. //                        $startDateForCheck=new \DateTime($startDateForCheck->format('Y-m-d '.' '.$consultantSchedule['startTime'].':00 '.$consultantTimeZone));
  1870. //                        $startDateForCheck->modify('+1 Day');
  1871.                     }
  1872.                     while ($startDateForCheck $endDate && $safetyLoopBreaker >= 0) {
  1873.                         $safetyLoopBreaker--;
  1874.                         foreach ($skipDateTimeStart as $key_DTS => $skidDTS) {
  1875.                             if ($startDateForCheck >= $skipDateTimeStart && $startDateForCheck <= $skipDateTimeEnd[$key_DTS]) {
  1876.                                 $startDateForCheck = clone($skipDateTimeEnd[$key_DTS]);
  1877.                             }
  1878.                         }
  1879.                         if ($startDateForCheck >= $consultantScheduleUpToDate) {
  1880.                             $safetyLoopBreaker 0;
  1881.                             break;
  1882.                         }
  1883.                         if ($startDateForCheck >= $consultantScheduleStartAtTime && $startDateForCheck <= $consultantScheduleEndAtTime) {
  1884.                             $timeUnix $startDateForCheck->format('U');
  1885.                             $availableSchedule = [
  1886.                                 'time' => $startDateForCheck->format('Y-m-d h:i:s'),
  1887.                                 'timeUnix' => $timeUnix,
  1888.                                 'timeRfc' => $startDateForCheck->format(DATE_RFC822),
  1889.                             ];
  1890.                             $schedulesList[] = $availableSchedule;
  1891.                             if ($closestDateTs $timeUnix || $closestDateTs == 0)
  1892.                                 $closestDateTs $timeUnix;
  1893.                         }
  1894.                         if ($startDateForCheck >= $consultantScheduleEndAtTime) {
  1895.                             $consultantScheduleStartAtTime->modify('+1 Day');
  1896.                             $consultantScheduleEndAtTime->modify('+1 Day');
  1897.                             $startDateForCheck = new \DateTime($startDateForCheck->format('Y-m-d ' ' ' $consultantSchedule['startTime'] . ':00 ' $consultantTimeZone));
  1898.                             $startDateForCheck->modify('+1 Day');
  1899.                         } else
  1900.                             $startDateForCheck->modify('+' $durationMin ' Minute');
  1901.                     }
  1902.                     $debugData['sLoopBreakerSpDate'] = $safetyLoopBreaker;
  1903.                 } else if ($scheduleType == 2)//days of week
  1904.                 {
  1905.                     $dow $consultantSchedule['dow'];
  1906.                     $startDateForCheck = clone($startDate);
  1907.                     $safetyLoopBreaker 3000;
  1908.                     if ($startDateForCheck >= $consultantScheduleEndAtTime) {
  1909.                         $consultantScheduleStartAtTime = new \DateTime($startDateForCheck->format('Y-m-d') . ' ' $consultantSchedule['startTime'] . ':00 ' $consultantTimeZone);
  1910.                         $consultantScheduleEndAtTime = new \DateTime($startDateForCheck->format('Y-m-d') . ' ' $consultantSchedule['endTime'] . ':00 ' $consultantTimeZone);
  1911.                         $consultantScheduleStartAtTime->modify('+1 Day');
  1912.                         $consultantScheduleEndAtTime->modify('+1 Day');
  1913. //                        $startDateForCheck=new \DateTime($startDateForCheck->format('Y-m-d '.' '.$consultantSchedule['startTime'].':00 '.$consultantTimeZone));
  1914. //                        $startDateForCheck->modify('+1 Day');
  1915.                     }
  1916.                     while ($startDateForCheck $endDate && $safetyLoopBreaker >= 0) {
  1917. //                        $debugData[]=[
  1918. //                            'loopDate'=>$startDateForCheck->format('Y-m-d H:i:s'),
  1919. //                            'weekDate'=>$startDateForCheck->format('N'),
  1920. //                            'dow'=>$dow,
  1921. //                            'consultantScheduleStartAtTime'=>$consultantScheduleStartAtTime->format('Y-m-d H:i:s'),
  1922. //                            'consultantScheduleEndAtTime'=>$consultantScheduleEndAtTime->format('Y-m-d H:i:s'),
  1923. //                            'consultantScheduleUpToDate'=>$consultantScheduleUpToDate->format('Y-m-d H:i:s'),
  1924. //                            'in'=>in_array($startDateForCheck->format('N'),$dow)
  1925. //                        ];
  1926.                         $safetyLoopBreaker--;
  1927.                         foreach ($skipDateTimeStart as $key_DTS => $skidDTS) {
  1928.                             $debugData[] = [
  1929.                                 'loopDate' => $startDateForCheck->format('Y-m-d H:i:sP'),
  1930. //                                'weekDate' => $startDateForCheck->format('N'),
  1931. //                                'dow' => $dow,
  1932.                                 'skipDateTimeStart' => $skidDTS->format('Y-m-d H:i:sP'),
  1933.                                 'skipDateTimeEnd' => $skipDateTimeEnd[$key_DTS]->format('Y-m-d H:i:sP'),
  1934. //                                'consultantScheduleStartAtTime' => $consultantScheduleStartAtTime->format('Y-m-d H:i:s'),
  1935. //                                'consultantScheduleEndAtTime' => $consultantScheduleEndAtTime->format('Y-m-d H:i:s'),
  1936. //                                'consultantScheduleUpToDate' => $consultantScheduleUpToDate->format('Y-m-d H:i:s'),
  1937. //                                'in' => in_array($startDateForCheck->format('N'), $dow)
  1938.                             ];
  1939.                             if ($startDateForCheck >= $skidDTS && $startDateForCheck <= $skipDateTimeEnd[$key_DTS]) {
  1940.                                 $startDateForCheck = clone($skipDateTimeEnd[$key_DTS]);
  1941.                             }
  1942.                         }
  1943.                         if ($startDateForCheck >= $consultantScheduleUpToDate) {
  1944.                             $safetyLoopBreaker 0;
  1945.                             break;
  1946.                         }
  1947.                         if (!in_array($startDateForCheck->format('N'), $dow)) {
  1948.                             $consultantScheduleStartAtTime->modify('+1 Day');
  1949.                             $consultantScheduleEndAtTime->modify('+1 Day');
  1950.                             $startDateForCheck = new \DateTime($startDateForCheck->format('Y-m-d ' ' ' $consultantSchedule['startTime'] . ':00 ' $consultantTimeZone));
  1951.                             $startDateForCheck->modify('+1 Day');
  1952.                             continue;
  1953.                         }
  1954.                         if ($startDateForCheck >= $consultantScheduleStartAtTime && $startDateForCheck <= $consultantScheduleEndAtTime) {
  1955.                             $timeUnix $startDateForCheck->format('U');
  1956.                             $availableSchedule = [
  1957.                                 'time' => $startDateForCheck->format('Y-m-d h:i:s'),
  1958.                                 'timeUnix' => $timeUnix,
  1959.                                 'timeRfc' => $startDateForCheck->format(DATE_RFC822),
  1960.                             ];
  1961.                             $schedulesList[] = $availableSchedule;
  1962.                             if ($closestDateTs $timeUnix || $closestDateTs == 0)
  1963.                                 $closestDateTs $timeUnix;
  1964.                         }
  1965.                         if ($startDateForCheck >= $consultantScheduleEndAtTime) {
  1966.                             $consultantScheduleStartAtTime->modify('+1 Day');
  1967.                             $consultantScheduleEndAtTime->modify('+1 Day');
  1968.                             $startDateForCheck = new \DateTime($consultantScheduleStartAtTime->format('Y-m-d ' ' ' $consultantSchedule['startTime'] . ':00 ' $consultantTimeZone));
  1969.                             $startDateForCheck->modify('+1 Day');
  1970.                         } else
  1971.                             $startDateForCheck->modify('+' $durationMin ' Minute');
  1972.                     }
  1973.                     $debugData['sLoopBreakerDow'] = $safetyLoopBreaker;
  1974.                 } else if ($scheduleType == 3)//Exclude date
  1975.                 {
  1976.                     $startDateForCheck = clone($startDate);
  1977.                     $safetyLoopBreaker 3000;
  1978.                     while ($startDateForCheck $endDate && $safetyLoopBreaker >= 0) {
  1979.                         $safetyLoopBreaker--;
  1980.                         foreach ($skipDateTimeStart as $key_DTS => $skidDTS) {
  1981.                             if ($startDateForCheck >= $skipDateTimeStart && $startDateForCheck <= $skipDateTimeEnd[$key_DTS]) {
  1982.                                 $startDateForCheck = clone($skipDateTimeEnd[$key_DTS]);
  1983.                             }
  1984.                         }
  1985.                         if ($startDateForCheck >= $consultantScheduleUpToDate) {
  1986.                             $safetyLoopBreaker 0;
  1987.                             break;
  1988.                         }
  1989.                         if ($startDateForCheck >= $consultantScheduleStartAtTime && $startDateForCheck <= $consultantScheduleEndAtTime) {
  1990.                             $availableSchedule = [
  1991.                                 'time' => $startDateForCheck->format('Y-m-d h:i:s'),
  1992.                                 'timeUnix' => $startDateForCheck->format('U'),
  1993.                                 'timeRfc' => $startDateForCheck->format(DATE_RFC822),
  1994.                             ];
  1995.                             $schedulesList[] = $availableSchedule;
  1996.                         }
  1997.                         if ($startDateForCheck >= $consultantScheduleEndAtTime) {
  1998.                             $consultantScheduleStartAtTime->modify('+1 Day');
  1999.                             $consultantScheduleEndAtTime->modify('+1 Day');
  2000.                             $startDateForCheck = new \DateTime($startDateForCheck->format('Y-m-d ' ' ' $consultantSchedule['startTime'] . ':00 ' $consultantTimeZone));
  2001.                             $startDateForCheck->modify('+1 Day');
  2002.                         } else
  2003.                             $startDateForCheck->modify('+' $durationMin ' Minute');
  2004.                     }
  2005.                 }
  2006.                 if ($dateAllowed == 1) {
  2007.                 }
  2008.             }
  2009.             $em->flush();
  2010.         }
  2011. //        return [$schedulesList,$consultantSchedules,$debugData];
  2012.         return [
  2013.             'scheduleList' => $schedulesList,
  2014.             'closestDateTs' => $closestDateTs,
  2015.             'debugData' => $debugData,
  2016.         ];
  2017.     }
  2018.     public static function RemoveExpiredTemporaryBookingsOnBeeCard($em)
  2019.     {
  2020.         //remove expired schedules 1st
  2021.         //now that we go the data we can empty the closing table
  2022.         $currDateNow = new \DateTime();
  2023.         $get_kids_sql "UPDATE  `bee_code` set is_temporary_booked=0, booked_by=0  WHERE booking_expire_ts < " $currDateNow->format('U');
  2024.         $stmt $em->getConnection()->executeStatement($get_kids_sql);
  2025.         return true;
  2026.     }
  2027.     public static function RemoveExpiredTemporaryBookings($em)
  2028.     {
  2029.         //remove expired schedules 1st
  2030.         //now that we go the data we can empty the closing table
  2031.         $currDateNow = new \DateTime();
  2032.         $get_kids_sql "select * FROM `entity_temporary_booking` WHERE booking_expires_ts < " $currDateNow->format('U');
  2033.         $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  2034.         $query_output $stmt;
  2035.         foreach ($query_output as $q) {
  2036.             $dt = new \DateTime('@' $q['scheduled_time_ts']);
  2037.             $periodMarker $dt->format('Ym');
  2038.             MiscActions::UpdateSchedulingRestrictions($em$q['consultant_id'], $periodMarker0, -(($q['duration_allowed_min']) / 60));
  2039.         }
  2040.         $get_kids_sql "DELETE FROM `entity_temporary_booking` WHERE booking_expires_ts < " $currDateNow->format('U');
  2041.         $stmt $em->getConnection()->executeStatement($get_kids_sql);
  2042.         return true;
  2043.     }
  2044.     public static function getSessionDurationObject($em '')
  2045.     {
  2046. //        $consultantScheduleData = $em->getRepository('CompanyGroupBundle\\Entity\\EntityConsultantSchedule')->findOneBy(
  2047. //            array(
  2048. //                'consultantId' => $consultantId
  2049. //            )
  2050. //        );
  2051.         return array('object' => BuddybeeConstant::$sessionDurationObject'array' => BuddybeeConstant::$sessionDurationArray);
  2052.     }
  2053.     public static function GetConsultantSchedules($em$consultantId$startDateStr ''$endDateStr ''$durationMin 90$options = [])
  2054.     {
  2055.         //start end dates and respose dats are all with time zones or UTC and ideally the UTC time stamps
  2056.         $startDate = new \DateTime($startDateStr); ///add @ on the string if you provide timeunix
  2057.         $startDate->setTimezone(new \DateTimeZone('+0000'));
  2058.         $currDateNow = new \DateTime();
  2059.         if (is_string($options)) {
  2060.             $options json_decode($optionstrue);
  2061.             if ($options == null)
  2062.                 $options = [];
  2063.         }
  2064.         $sessionDurationData MiscActions::getSessionDurationObject($em);
  2065.         $defaultselection BuddybeeConstant::COIN_GENERAL_MULT;
  2066.         $currentSelection $defaultselection;
  2067.         if ($durationMin == '_UNSET_') {
  2068.             $durationMin $sessionDurationData['object'][$defaultselection]['durationMin'];
  2069.             $currentSelection $defaultselection;
  2070.         } else {
  2071.             foreach ($sessionDurationData['object'] as $t => $p) {
  2072.                 if ($p['durationMin'] == $durationMin)
  2073.                     $currentSelection $t;
  2074.             }
  2075.         }
  2076.         if ($endDateStr == '') {
  2077.             $endDate = clone($startDate);
  2078.             if (isset($options['_THIS_DAY_']))
  2079.                 $endDate->modify('+1439 Minute');
  2080.             else if (isset($options['_NEXT_60_DAYS_']))
  2081.                 $endDate->modify('+60 Day');
  2082.             else if (isset($options['_NEXT_DAYS_']))  ///'_NEXT_DAYS_':59
  2083.                 $endDate->modify('+' $options['_NEXT_DAYS_'] . ' Day');
  2084.             else
  2085.                 $endDate->modify('+1439 Minute');
  2086.         } else
  2087.             $endDate = new \DateTime($endDateStr);
  2088.         $schedulesList = [];
  2089.         $debugData = [];
  2090.         $closestDateTs 0;
  2091.         $singleFlag = isset($options['singleFlag']) ? $options['singleFlag'] : 0;
  2092.         $extensionFlag = isset($options['forExtension']) ? $options['forExtension'] : 0;
  2093.         $availableMinByPeriodMarker MiscActions::SchedulingAvailabilityByRestrictions($em'_NEXT_60_DAYS_'$startDateStr$consultantId$durationMin)['availableMinByPeriodMarker'];
  2094.         //now get schedules
  2095.         $consultantScheduleData $em->getRepository('CompanyGroupBundle\\Entity\\EntityConsultantSchedule')->findBy(
  2096.             array(
  2097.                 'consultantId' => $consultantId
  2098.             )
  2099.         );
  2100.         $consultantTimeZone '';
  2101.         $consultantSchedules = [];
  2102.         if (!empty($consultantScheduleData)) {
  2103.             foreach ($consultantScheduleData as $key => $val) {
  2104.                 $indTimeSche = array(
  2105.                     'date' => $val->getStartDate() ? $val->getStartDate()->format('Y-m-d') : '',
  2106.                     'dateUpto' => $val->getEndDate() ? $val->getEndDate()->format('Y-m-d') : '',
  2107.                     'type' => ($val->getType() != null && $val->getType() != '') ? $val->getType() : 2,  // 0=specific date 1=every mentioned day of month 2=every mentioned day of week
  2108. //                    'dom' => $request->get('dom')[$key],  // based on type
  2109.                     'dow' => ($val->getDow() != null && $val->getDow() != '') ? json_decode($val->getDow(), true) : [],  // based on type
  2110.                     'startTime' => $val->getStartTime(),
  2111.                     'endTime' => $val->getEndTime(),
  2112.                     'timeZone' => $val->getTimeZoneStr(),
  2113.                 );
  2114.                 $consultantSchedules[] = $indTimeSche;
  2115.             }
  2116.             foreach ($consultantSchedules as $consultantSchedule) {
  2117.                 $consultantTimeZone $consultantSchedule['timeZone'];
  2118.             }
  2119.             $existingBookedSchedules $em->getRepository('CompanyGroupBundle\\Entity\\EntityMeetingSession')
  2120.                 ->createQueryBuilder('m')
  2121.                 ->where("m.consultantId = :consultantId")
  2122.                 ->andWhere("m.isExpired != 1")
  2123.                 ->andWhere("m.scheduledTimeTs >= :startAt")
  2124.                 ->andWhere("m.sessionExpireDateTs <= :endAt")
  2125.                 ->setParameter('consultantId'$consultantId)
  2126.                 ->setParameter('startAt'$startDate->format('U'))
  2127. //                ->setParameter('startAt', $startDate->format('Y-m-d h:i:s'))
  2128.                 ->setParameter('endAt'$endDate->format('U '))
  2129. //                ->setParameter('endAt', $endDate->format('Y-m-d h:i:s'))
  2130.                 ->getQuery()
  2131.                 ->getResult();
  2132.             $skipDateTimeStart = [];
  2133.             $skipDateTimeEnd = [];
  2134.             foreach ($existingBookedSchedules as $existingBookedSchedule) {
  2135.                 $scheduledStartTime = new \DateTime('@' $existingBookedSchedule->getScheduledTimeTs());;
  2136. //                $scheduledStartTime->setTimezone(new \DateTimeZone('UTC'));
  2137. //                $scheduledStartTime->setTimezone(new \DateTimeZone('+0000'));
  2138.                 $skipDateTimeStart[] = $scheduledStartTime;
  2139.                 $skipDateTimeEnd[] = new \DateTime('@' $existingBookedSchedule->getSessionExpireDateTs());
  2140.             }
  2141.             //remove expired schedules 1st
  2142.             //now that we go the data we can empty the closing table
  2143.             MiscActions::RemoveExpiredTemporaryBookings($em);
  2144.             $existingBookedSchedules $em->getRepository('CompanyGroupBundle\\Entity\\EntityTemporaryBooking')
  2145.                 ->createQueryBuilder('m')
  2146.                 ->where("m.consultantId = :consultantId")
  2147.                 ->andWhere("m.scheduledTimeTs >= :startAt")
  2148.                 ->andWhere("m.sessionExpireDateTs <= :endAt")
  2149.                 ->setParameter('consultantId'$consultantId)
  2150.                 ->setParameter('startAt'$startDate->format('U'))
  2151. //                ->setParameter('startAt', $startDate->format('Y-m-d h:i:s'))
  2152.                 ->setParameter('endAt'$endDate->format('U '))
  2153. //                ->setParameter('endAt', $endDate->format('Y-m-d h:i:s'))
  2154.                 ->getQuery()
  2155.                 ->getResult();
  2156.             foreach ($existingBookedSchedules as $existingBookedSchedule) {
  2157.                 $scheduledStartTime = new \DateTime('@' $existingBookedSchedule->getScheduledTimeTs());;
  2158. //                $scheduledStartTime->setTimezone(new \DateTimeZone('UTC'));
  2159. //                $scheduledStartTime->setTimezone(new \DateTimeZone('+0000'));
  2160.                 $skipDateTimeStart[] = $scheduledStartTime;
  2161.                 $skipDateTimeEnd[] = new \DateTime('@' $existingBookedSchedule->getSessionExpireDateTs());
  2162.             }
  2163.             foreach ($consultantSchedules as $consultantSchedule) {
  2164.                 $scheduleType $consultantSchedule['type'];
  2165.                 $consultantTimeZone $consultantSchedule['timeZone'];
  2166.                 $consultantScheduleStartAtTime = new \DateTime($consultantSchedule['date'] . ' ' $consultantSchedule['startTime'] . ':00 ' $consultantTimeZone);
  2167.                 $consultantScheduleEndAtTime = new \DateTime($consultantSchedule['date'] . ' ' $consultantSchedule['endTime'] . ':00 ' $consultantTimeZone);
  2168.                 $consultantScheduleUpToDate = new \DateTime($consultantSchedule['dateUpto'] . ' ' $consultantSchedule['endTime'] . ':00 ' $consultantTimeZone);
  2169.                 $dateAllowed 0;
  2170.                 $allowedStartTime 0;
  2171.                 $allowedEndTime 0;
  2172.                 $hasAtleastOneSchedule 0;
  2173.                 $debugData['strt_' $consultantSchedule['date']] = array();
  2174.                 $debugData['end_' $consultantSchedule['date']] = array();
  2175.                 $debugData['slb_' $consultantSchedule['date']] = array();
  2176.                 if ($scheduleType == 1)//specific date
  2177.                 {
  2178.                     $startDateForCheck = clone($startDate);
  2179.                     $safetyLoopBreaker 3000;
  2180.                     if ($startDateForCheck >= $consultantScheduleEndAtTime) {
  2181.                         $consultantScheduleStartAtTime = new \DateTime($startDateForCheck->format('Y-m-d') . ' ' $consultantSchedule['startTime'] . ':00 ' $consultantTimeZone);
  2182.                         $consultantScheduleEndAtTime = new \DateTime($startDateForCheck->format('Y-m-d') . ' ' $consultantSchedule['endTime'] . ':00 ' $consultantTimeZone);
  2183.                         $consultantScheduleStartAtTime->modify('+1 Day');
  2184.                         $consultantScheduleEndAtTime->modify('+1 Day');
  2185.                         $startDateForCheck = new \DateTime($startDateForCheck->format('Y-m-d ' ' ' $consultantSchedule['startTime'] . ':00 ' $consultantTimeZone));
  2186.                         $startDateForCheck->modify('+1 Day');
  2187. //                        $startDateForCheck=new \DateTime($startDateForCheck->format('Y-m-d '.' '.$consultantSchedule['startTime'].':00 '.$consultantTimeZone));
  2188. //                        $startDateForCheck->modify('+1 Day');
  2189.                     }
  2190.                     while ($startDateForCheck $endDate && $safetyLoopBreaker >= 0) {
  2191.                         $debugData['strt_' $consultantSchedule['date']][] = $startDateForCheck->format(DATE_RFC822);
  2192.                         $debugData['end_' $consultantSchedule['date']][] = $endDate->format(DATE_RFC822);
  2193.                         $periodMarker $startDateForCheck->format('Ym');
  2194.                         if (isset($availableMinByPeriodMarker[$periodMarker])) {
  2195.                             if ($availableMinByPeriodMarker[$periodMarker] < $durationMin) {
  2196.                                 $Y intdiv($periodMarker100);
  2197.                                 $M $periodMarker 100;
  2198.                                 $M $M 1;
  2199.                                 if ($M == 13) {
  2200.                                     $M 1;
  2201.                                     $Y++;
  2202.                                 }
  2203.                                 $startDateForCheck = new \DateTime($Y '-' str_pad($M2'0'STR_PAD_LEFT) . '-01 ' $consultantSchedule['startTime'] . ':00 +0000');
  2204.                                 continue;
  2205.                             }
  2206.                         }
  2207.                         $safetyLoopBreaker--;
  2208.                         $checkingNextSlot 0;
  2209.                         foreach ($skipDateTimeStart as $key_DTS => $skidDTS) {
  2210. //                            if ($startDateForCheck >= $skipDateTimeStart && $startDateForCheck <= $skipDateTimeEnd[$key_DTS]) {
  2211. //                                $startDateForCheck = clone($skipDateTimeEnd[$key_DTS]);
  2212. //                                $startDateForCheck->modify('+'.BuddybeeConstant::BETWEEN_SESSION_MINUTE.' Minute');
  2213. //                            }
  2214.                             $dbg = [
  2215.                                 'loopDate' => $startDateForCheck->format('Y-m-d H:i:sP'),
  2216.                                 'loopDateTs' => $startDateForCheck->format('U'),
  2217.                                 'weekDate' => $startDateForCheck->format('N'),
  2218. //                                'dow' => $dow,
  2219.                                 'skipDateTimeStart' => $skidDTS->format('Y-m-d H:i:sP'),
  2220.                                 'skipDateTimeStartTs' => $skidDTS->format('U'),
  2221.                                 'skipDateTimeEnd' => $skipDateTimeEnd[$key_DTS]->format('Y-m-d H:i:sP'),
  2222.                                 'skipDateTimeEndTs' => $skipDateTimeEnd[$key_DTS]->format('U'),
  2223. //                                'skipDateTimeEndTs' => $skipDateTimeEnd[$key_DTS]->format('U'),
  2224.                                 'consultantScheduleStartAtTime' => $consultantScheduleStartAtTime->format('Y-m-d H:i:sP'),
  2225. //                                'consultantScheduleEndAtTime' => $consultantScheduleEndAtTime->format('Y-m-d H:i:s'),
  2226. //                                'consultantScheduleUpToDate' => $consultantScheduleUpToDate->format('Y-m-d H:i:s'),
  2227. //                                'in' => in_array($startDateForCheck->format('N'), $dow)
  2228.                             ];
  2229.                             if ($startDateForCheck >= $skidDTS && $startDateForCheck <= $skipDateTimeEnd[$key_DTS]) {
  2230.                                 $dbg['found'] = 1;
  2231.                                 $startDateForCheck = clone($skipDateTimeEnd[$key_DTS]);
  2232.                                 $startDateForCheck->modify('+' BuddybeeConstant::BETWEEN_SESSION_MINUTE ' Minute');
  2233.                                 $startDateForCheck->setTimezone(new \DateTimeZone($consultantTimeZone));
  2234.                                 $dbg['modifiedStart'] = $startDateForCheck->format('Y-m-d H:i:sP');
  2235.                                 $debugData[] = $dbg;
  2236.                                 $hasAtleastOneSchedule 1;
  2237.                                 $checkingNextSlot 1;
  2238. //                                break;
  2239.                             } else {
  2240.                                 if ($checkingNextSlot == 1)
  2241.                                     break;
  2242.                             }
  2243. //                            $debugData[] =$dbg;
  2244.                         }
  2245.                         if ($startDateForCheck >= $consultantScheduleUpToDate) {
  2246.                             $safetyLoopBreaker 0;
  2247.                             break;
  2248.                         }
  2249.                         $supposedEndDt = clone($startDateForCheck);
  2250.                         $supposedEndDt->modify('+' BuddybeeConstant::BETWEEN_SESSION_MINUTE ' Minute');
  2251.                         $supposedEndDt->modify('+' $durationMin ' Minute');
  2252. //                        if ($startDateForCheck >= $consultantScheduleStartAtTime && $startDateForCheck < $consultantScheduleEndAtTime  )
  2253.                         if ($startDateForCheck >= $consultantScheduleStartAtTime && $supposedEndDt <= $consultantScheduleEndAtTime) {
  2254.                             if ($hasAtleastOneSchedule == 0) {
  2255.                                 $startDateForCheckNew = clone($consultantScheduleStartAtTime);
  2256.                                 $supposedEndDt = clone($startDateForCheckNew);
  2257.                                 $supposedEndDt->modify('+' BuddybeeConstant::BETWEEN_SESSION_MINUTE ' Minute');
  2258.                                 $supposedEndDt->modify('+' $durationMin ' Minute');
  2259.                                 if ($startDateForCheckNew >= $startDate && $supposedEndDt <= $consultantScheduleEndAtTime) {
  2260.                                     $startDateForCheck $startDateForCheckNew;
  2261.                                     $timeUnix $startDateForCheck->format('U');
  2262.                                     $availableSchedule = [
  2263.                                         'time' => $startDateForCheck->format('Y-m-d h:i:s'),
  2264.                                         'timeUnix' => $timeUnix,
  2265.                                         'mon' => $startDateForCheck->format('m'),
  2266.                                         'timeRfc' => $startDateForCheck->format(DATE_RFC822),
  2267.                                     ];
  2268.                                     $schedulesList[] = $availableSchedule;
  2269.                                     $hasAtleastOneSchedule 1;
  2270.                                     if ($singleFlag == 1) {
  2271.                                         $safetyLoopBreaker 0;
  2272.                                         break;
  2273.                                     }
  2274.                                     if ($closestDateTs $timeUnix || $closestDateTs == 0)
  2275.                                         $closestDateTs $timeUnix;
  2276.                                 }
  2277.                             } else {
  2278.                                 $timeUnix $startDateForCheck->format('U');
  2279.                                 $availableSchedule = [
  2280.                                     'time' => $startDateForCheck->format('Y-m-d h:i:s'),
  2281.                                     'timeUnix' => $timeUnix,
  2282.                                     'mon' => $startDateForCheck->format('m'),
  2283.                                     'timeRfc' => $startDateForCheck->format(DATE_RFC822),
  2284.                                 ];
  2285.                                 $schedulesList[] = $availableSchedule;
  2286.                                 $hasAtleastOneSchedule 1;
  2287.                                 if ($singleFlag == 1) {
  2288.                                     $safetyLoopBreaker 0;
  2289.                                     break;
  2290.                                 }
  2291.                                 if ($closestDateTs $timeUnix || $closestDateTs == 0)
  2292.                                     $closestDateTs $timeUnix;
  2293.                             }
  2294.                         }
  2295.                         if ($startDateForCheck >= $consultantScheduleEndAtTime) {
  2296.                             $consultantScheduleStartAtTime->modify('+1 Day');
  2297.                             $consultantScheduleEndAtTime->modify('+1 Day');
  2298.                             $startDateForCheck = new \DateTime($startDateForCheck->format('Y-m-d ' ' ' $consultantSchedule['startTime'] . ':00 ' $consultantTimeZone));
  2299.                             $startDateForCheck->modify('+1 Day');
  2300.                         } else {
  2301.                             $startDateForCheck->modify('+' BuddybeeConstant::BETWEEN_SESSION_MINUTE ' Minute');
  2302.                             $startDateForCheck->modify('+' $durationMin ' Minute');
  2303.                         }
  2304. //                            $startDateForCheck->modify('+' . $durationMin . ' Minute');
  2305.                     }
  2306.                     $debugData['sLoopBreakerSpD'] = $safetyLoopBreaker;
  2307.                     $debugData['slb_' $consultantSchedule['date']][] = $safetyLoopBreaker;
  2308.                 } else if ($scheduleType == 2)//days of week
  2309.                 {
  2310.                     $dow $consultantSchedule['dow'];
  2311.                     $startDateForCheck = clone($startDate);
  2312.                     $safetyLoopBreaker 3000;
  2313.                     $hasAtleastOneSchedule 0;
  2314. //                    $debugData['strt_'.$consultantSchedule['date']] = $startDateForCheck->format(DATE_RFC822);
  2315. //                    $debugData['end_'.$consultantSchedule['date']] = $endDate->format(DATE_RFC822);
  2316.                     if ($startDateForCheck >= $consultantScheduleEndAtTime) {
  2317.                         $consultantScheduleStartAtTime = new \DateTime($startDateForCheck->format('Y-m-d') . ' ' $consultantSchedule['startTime'] . ':00 ' $consultantTimeZone);
  2318.                         $consultantScheduleEndAtTime = new \DateTime($startDateForCheck->format('Y-m-d') . ' ' $consultantSchedule['endTime'] . ':00 ' $consultantTimeZone);
  2319.                         $consultantScheduleStartAtTime->modify('+1 Day');
  2320.                         $consultantScheduleEndAtTime->modify('+1 Day');
  2321.                         $startDateForCheck = new \DateTime($startDateForCheck->format('Y-m-d ' ' ' $consultantSchedule['startTime'] . ':00 ' $consultantTimeZone));
  2322.                         $startDateForCheck->modify('+1 Day');
  2323. //                        $startDateForCheck=new \DateTime($startDateForCheck->format('Y-m-d '.' '.$consultantSchedule['startTime'].':00 '.$consultantTimeZone));
  2324. //                        $startDateForCheck->modify('+1 Day');
  2325.                     }
  2326.                     while ($startDateForCheck $endDate && $safetyLoopBreaker >= 0) {
  2327.                         $debugData['strt_' $consultantSchedule['date']][] = $startDateForCheck->format(DATE_RFC822);
  2328.                         $debugData['end_' $consultantSchedule['date']][] = $endDate->format(DATE_RFC822);
  2329.                         $periodMarker $startDateForCheck->format('Ym');
  2330.                         if (isset($availableMinByPeriodMarker[$periodMarker])) {
  2331.                             if ($availableMinByPeriodMarker[$periodMarker] < $durationMin) {
  2332.                                 $Y intdiv($periodMarker100);
  2333.                                 $M $periodMarker 100;
  2334.                                 $M $M 1;
  2335.                                 if ($M == 13) {
  2336.                                     $M 1;
  2337.                                     $Y++;
  2338.                                 }
  2339.                                 $startDateForCheck = new \DateTime($Y '-' str_pad($M2'0'STR_PAD_LEFT) . '-01 ' $consultantSchedule['startTime'] . ':00 +0000');
  2340.                                 continue;
  2341.                             }
  2342.                         }
  2343. //                        $debugData[]=[
  2344. //                            'loopDate'=>$startDateForCheck->format('Y-m-d H:i:s'),
  2345. //                            'weekDate'=>$startDateForCheck->format('N'),
  2346. //                            'dow'=>$dow,
  2347. //                            'consultantScheduleStartAtTime'=>$consultantScheduleStartAtTime->format('Y-m-d H:i:s'),
  2348. //                            'consultantScheduleEndAtTime'=>$consultantScheduleEndAtTime->format('Y-m-d H:i:s'),
  2349. //                            'consultantScheduleUpToDate'=>$consultantScheduleUpToDate->format('Y-m-d H:i:s'),
  2350. //                            'in'=>in_array($startDateForCheck->format('N'),$dow)
  2351. //                        ];
  2352.                         $safetyLoopBreaker--;
  2353.                         $checkingNextSlot 0;
  2354.                         foreach ($skipDateTimeStart as $key_DTS => $skidDTS) {
  2355.                             $dbg = [
  2356.                                 'loopDate' => $startDateForCheck->format('Y-m-d H:i:sP'),
  2357.                                 'loopDateTs' => $startDateForCheck->format('U'),
  2358.                                 'weekDate' => $startDateForCheck->format('N'),
  2359. //                                'dow' => $dow,
  2360.                                 'skipDateTimeStart' => $skidDTS->format('Y-m-d H:i:sP'),
  2361.                                 'skipDateTimeStartTs' => $skidDTS->format('U'),
  2362.                                 'skipDateTimeEnd' => $skipDateTimeEnd[$key_DTS]->format('Y-m-d H:i:sP'),
  2363.                                 'skipDateTimeEndTs' => $skipDateTimeEnd[$key_DTS]->format('U'),
  2364. //                                'skipDateTimeEndTs' => $skipDateTimeEnd[$key_DTS]->format('U'),
  2365.                                 'consultantScheduleStartAtTime' => $consultantScheduleStartAtTime->format('Y-m-d H:i:sP'),
  2366. //                                'consultantScheduleEndAtTime' => $consultantScheduleEndAtTime->format('Y-m-d H:i:s'),
  2367. //                                'consultantScheduleUpToDate' => $consultantScheduleUpToDate->format('Y-m-d H:i:s'),
  2368. //                                'in' => in_array($startDateForCheck->format('N'), $dow)
  2369.                             ];
  2370.                             if ($startDateForCheck >= $skidDTS && $startDateForCheck <= $skipDateTimeEnd[$key_DTS]) {
  2371.                                 $dbg['found'] = 1;
  2372.                                 $startDateForCheck = clone($skipDateTimeEnd[$key_DTS]);
  2373.                                 $startDateForCheck->modify('+' BuddybeeConstant::BETWEEN_SESSION_MINUTE ' Minute');
  2374.                                 $startDateForCheck->setTimezone(new \DateTimeZone($consultantTimeZone));
  2375.                                 $dbg['modifiedStart'] = $startDateForCheck->format('Y-m-d H:i:sP');
  2376.                                 $dbg['safetyLoopBreaker'] = $safetyLoopBreaker;
  2377.                                 $debugData[] = $dbg;
  2378.                                 $hasAtleastOneSchedule 1;
  2379.                                 $checkingNextSlot 1;
  2380. //                                break;
  2381.                             } else {
  2382.                                 if ($checkingNextSlot == 1)
  2383.                                     break;
  2384.                             }
  2385. //                            $debugData[] =$dbg;
  2386.                         }
  2387.                         if ($startDateForCheck >= $consultantScheduleUpToDate) {
  2388.                             $safetyLoopBreaker 0;
  2389.                             break;
  2390.                         }
  2391.                         if (!in_array($startDateForCheck->format('N'), $dow)) {
  2392.                             $consultantScheduleStartAtTime->modify('+1 Day');
  2393.                             $consultantScheduleEndAtTime->modify('+1 Day');
  2394.                             $startDateForCheck = new \DateTime($consultantScheduleStartAtTime->format('Y-m-d ' ' ' $consultantSchedule['startTime'] . ':00 ' $consultantTimeZone));
  2395. //                            $startDateForCheck->modify('+1 Day');
  2396.                             continue;
  2397.                         }
  2398.                         $supposedEndDt = clone($startDateForCheck);
  2399.                         $supposedEndDt->modify('+' BuddybeeConstant::BETWEEN_SESSION_MINUTE ' Minute');
  2400.                         $supposedEndDt->modify('+' $durationMin ' Minute');
  2401. //                        if ($startDateForCheck >= $consultantScheduleStartAtTime && $startDateForCheck < $consultantScheduleEndAtTime  )
  2402.                         if ($startDateForCheck >= $consultantScheduleStartAtTime && $supposedEndDt <= $consultantScheduleEndAtTime) {
  2403.                             if ($hasAtleastOneSchedule == 0) {
  2404.                                 $startDateForCheckNew = clone($consultantScheduleStartAtTime);
  2405.                                 $supposedEndDt = clone($startDateForCheckNew);
  2406.                                 $supposedEndDt->modify('+' BuddybeeConstant::BETWEEN_SESSION_MINUTE ' Minute');
  2407.                                 $supposedEndDt->modify('+' $durationMin ' Minute');
  2408.                                 if ($startDateForCheckNew >= $startDate && $supposedEndDt <= $consultantScheduleEndAtTime) {
  2409.                                     $startDateForCheck $startDateForCheckNew;
  2410.                                     $timeUnix $startDateForCheck->format('U');
  2411.                                     $availableSchedule = [
  2412.                                         'time' => $startDateForCheck->format('Y-m-d h:i:s'),
  2413.                                         'safetyLoopBreaker' => $safetyLoopBreaker,
  2414.                                         'timeUnix' => $timeUnix,
  2415.                                         'mon' => $startDateForCheck->format('m'),
  2416.                                         'timeRfc' => $startDateForCheck->format(DATE_RFC822),
  2417.                                     ];
  2418.                                     $schedulesList[] = $availableSchedule;
  2419.                                     $hasAtleastOneSchedule 1;
  2420.                                     if ($singleFlag == 1) {
  2421.                                         $safetyLoopBreaker 0;
  2422.                                         break;
  2423.                                     }
  2424.                                     if ($closestDateTs $timeUnix || $closestDateTs == 0)
  2425.                                         $closestDateTs $timeUnix;
  2426.                                 }
  2427.                             } else {
  2428.                                 $timeUnix $startDateForCheck->format('U');
  2429.                                 $availableSchedule = [
  2430.                                     'time' => $startDateForCheck->format('Y-m-d h:i:s'),
  2431.                                     'timeUnix' => $timeUnix,
  2432.                                     'mon' => $startDateForCheck->format('m'),
  2433.                                     'timeRfc' => $startDateForCheck->format(DATE_RFC822),
  2434.                                 ];
  2435.                                 $schedulesList[] = $availableSchedule;
  2436.                                 $hasAtleastOneSchedule 1;
  2437.                                 if ($singleFlag == 1) {
  2438.                                     $safetyLoopBreaker 0;
  2439.                                     break;
  2440.                                 }
  2441.                                 if ($closestDateTs $timeUnix || $closestDateTs == 0)
  2442.                                     $closestDateTs $timeUnix;
  2443.                             }
  2444.                         }
  2445.                         if ($startDateForCheck >= $consultantScheduleEndAtTime) {
  2446.                             $consultantScheduleStartAtTime->modify('+1 Day');
  2447.                             $consultantScheduleEndAtTime->modify('+1 Day');
  2448.                             $startDateForCheck = new \DateTime($startDateForCheck->format('Y-m-d ' ' ' $consultantSchedule['startTime'] . ':00 ' $consultantTimeZone));
  2449.                             $startDateForCheck->modify('+1 Day');
  2450.                         } else {
  2451.                             $startDateForCheck->modify('+' BuddybeeConstant::BETWEEN_SESSION_MINUTE ' Minute');
  2452.                             $startDateForCheck->modify('+' $durationMin ' Minute');
  2453.                         }
  2454.                     }
  2455.                     $debugData['sLoopBreaker'] = $safetyLoopBreaker;
  2456.                     $debugData['slb_' $consultantSchedule['date']][] = $safetyLoopBreaker;
  2457.                 } else if ($scheduleType == 3)//Exclude date
  2458.                 {
  2459.                     $startDateForCheck = clone($startDate);
  2460.                     $safetyLoopBreaker 3000;
  2461.                     while ($startDateForCheck $endDate && $safetyLoopBreaker >= 0) {
  2462.                         $safetyLoopBreaker--;
  2463.                         foreach ($skipDateTimeStart as $key_DTS => $skidDTS) {
  2464.                             if ($startDateForCheck >= $skipDateTimeStart && $startDateForCheck <= $skipDateTimeEnd[$key_DTS]) {
  2465.                                 $startDateForCheck = clone($skipDateTimeEnd[$key_DTS]);
  2466.                             }
  2467.                         }
  2468.                         if ($startDateForCheck >= $consultantScheduleUpToDate) {
  2469.                             $safetyLoopBreaker 0;
  2470.                             break;
  2471.                         }
  2472.                         if ($startDateForCheck >= $consultantScheduleStartAtTime && $startDateForCheck <= $consultantScheduleEndAtTime) {
  2473.                             $availableSchedule = [
  2474.                                 'time' => $startDateForCheck->format('Y-m-d h:i:s'),
  2475.                                 'timeUnix' => $startDateForCheck->format('U'),
  2476.                                 'timeRfc' => $startDateForCheck->format(DATE_RFC822),
  2477.                             ];
  2478.                             $schedulesList[] = $availableSchedule;
  2479.                             if ($singleFlag == 1) {
  2480.                                 $safetyLoopBreaker 0;
  2481.                                 break;
  2482.                             }
  2483.                         }
  2484.                         if ($startDateForCheck >= $consultantScheduleEndAtTime) {
  2485.                             $consultantScheduleStartAtTime->modify('+1 Day');
  2486.                             $consultantScheduleEndAtTime->modify('+1 Day');
  2487.                             $startDateForCheck = new \DateTime($startDateForCheck->format('Y-m-d ' ' ' $consultantSchedule['startTime'] . ':00 ' $consultantTimeZone));
  2488.                             $startDateForCheck->modify('+1 Day');
  2489.                         } else
  2490.                             $startDateForCheck->modify('+' $durationMin ' Minute');
  2491.                     }
  2492.                 }
  2493.                 if ($dateAllowed == 1) {
  2494.                 }
  2495.             }
  2496.             $em->flush();
  2497.         }
  2498. //        return [$schedulesList,$consultantSchedules,$debugData];
  2499.         return [
  2500.             'scheduleList' => $schedulesList,
  2501.             'closestDateTs' => $closestDateTs,
  2502.             'defaultselection' => $defaultselection,
  2503.             'durationMin' => $durationMin,
  2504.             'startDate' => $startDate->format(DATE_RFC822),
  2505.             'availableMinByPeriodMarker' => $availableMinByPeriodMarker,
  2506.             'currentSelectionId' => $currentSelection,
  2507.             'sessionDurationData' => $sessionDurationData,
  2508.             'debugData' => $debugData,
  2509.             'consultantSchedules' => $consultantSchedules,
  2510.         ];
  2511.     }
  2512.     public static function ConfirmConsultancySchedule($em$confirmStatus 0$meetingId 0$newConsultantId 0$newStudentId 0$confirmType '_CONSULTANT_'$redeemAction 0)
  2513.     {
  2514. //        $options['extendOnly'] = 1;
  2515. //        $options['sessionCount'] = 1;
  2516.         $new $em->getRepository('CompanyGroupBundle\\Entity\\EntityMeetingSession')->findOneBy(array(
  2517.             'sessionId' => $meetingId
  2518.         ));
  2519.         $studentId $newStudentId == $new->getStudentId() : $newStudentId;
  2520.         $newSessionCount $new->getEquivalentSessionCount();
  2521.         $redeemableSessionCount $new->getRedeemSessionCount();
  2522.         if ($confirmType == '_STUDENT_')
  2523.             $new->setScheduleConfirmedByStudent($confirmStatus);
  2524.         else if ($confirmType == '_CONSULTANT_')
  2525.             $new->setScheduleConfirmedByConsultant($confirmStatus);
  2526.         else {
  2527.             $new->setScheduleConfirmedByStudent($confirmStatus);
  2528.             $new->setScheduleConfirmedByConsultant($confirmStatus);
  2529.         }
  2530.         $em->persist($new);
  2531.         $em->flush();
  2532.         $meetingSessionId $new->getSessionId();
  2533.         if ($confirmStatus == 1) {
  2534.             if ($redeemAction == 1) {
  2535.                 Buddybee::AddBalanceGeneral(
  2536.                     $em,
  2537.                     $studentId///id
  2538.                     0//amount
  2539.                     $redeemableSessionCount
  2540.                 );
  2541.                 $em->remove($new);
  2542.                 $em->flush();
  2543.                 return array(
  2544.                     'success' => true,
  2545.                     'errorCode' => '_SUCCESS_REDEEM_',
  2546.                     'redeemedSessionCount' => $redeemableSessionCount,
  2547.                     'newConsumedSessionCount' => 0,
  2548.                     'message' => 'Action Completed.',
  2549.                     'scheduledTimeTs' => $new->getScheduledTimeTs(),
  2550.                 );
  2551.             }
  2552.         } else {
  2553. //                    $scheduledStartTime->setTimezone(new \DateTimeZone('UTC'));
  2554. //                    $scheduledEndTime->setTimezone(new \DateTimeZone('UTC'));
  2555.             //$new->setScheduledTime($request->request->get('setScheduledTime'));
  2556.             return array(
  2557.                 'success' => true,
  2558.                 'errorCode' => '_SUCCESS_RESCHEDULE_',
  2559.                 'redeemedSessionCount' => $redeemableSessionCount,
  2560.                 'newConsumedSessionCount' => $newSessionCount,
  2561.                 'message' => 'Action Completed.',
  2562.                 'scheduledTimeTs' => $new->getScheduledTimeTs(),
  2563.             );
  2564.         }
  2565.     }
  2566.     public static function CheckIfScheduleCanBeConfirmed($em$consultantId$studentId$scheduledTimeTs ''$durationMin 90$deleteThisTempBooking 0)
  2567.     {
  2568.         //start end dates and respose dats are all with time zones or UTC and ideally the UTC time stamps
  2569. //        $scheduledTimeTs = $startDate->format('U');
  2570.         MiscActions::RemoveExpiredTemporaryBookings($em);
  2571.         $existingBookedSchedules $em->getRepository('CompanyGroupBundle\\Entity\\EntityTemporaryBooking')
  2572.             ->createQueryBuilder('m')
  2573.             ->where("m.consultantId = :consultantId")
  2574.             ->andwhere("(m.studentId = :studentId or m.studentId=0)")
  2575.             ->andWhere("m.scheduledTimeTs = :startAt")
  2576.             ->andWhere("m.durationAllowedMin <= :durationAllowedMin")
  2577.             ->setParameter('consultantId'$consultantId)
  2578.             ->setParameter('studentId'$studentId)
  2579.             ->setParameter('startAt'$scheduledTimeTs)
  2580. //                ->setParameter('startAt', $startDate->format('Y-m-d h:i:s'))
  2581.             ->setParameter('durationAllowedMin'$durationMin)
  2582. //                ->setParameter('endAt', $endDate->format('Y-m-d h:i:s'))
  2583.             ->getQuery()
  2584.             ->getResult();
  2585.         $result false;
  2586.         if (empty($existingBookedSchedules))
  2587.             return false;
  2588.         else {
  2589.             $result true;
  2590.             if ($deleteThisTempBooking == 1) {
  2591.                 foreach ($existingBookedSchedules as $existingBookedSchedule)
  2592.                     $em->remove($existingBookedSchedule);
  2593.                 $em->flush();
  2594.             }
  2595.         }
  2596.         return $result;
  2597.     }
  2598.     public static function AddBeeCardTemporaryBooking($em$cardIds = [], $cardOptionsByCoinCount = [], $retailerId 0$applicantIdId 0$createIfNeeded 0)
  2599.     {
  2600.         MiscActions::RemoveExpiredTemporaryBookingsOnBeeCard($em);
  2601.         $currDate = new \DateTime();
  2602.         $bookingExpireDate = new \DateTime();
  2603.         $bookingExpireDate->modify('+15 minute');
  2604.         $bookingExpireTs $bookingExpireDate->format('U');
  2605.         $bookingAllowed 0;
  2606.         $data = array(
  2607.             'success' => false,
  2608.         );
  2609.         $cardEntityByCoinCount = array();
  2610.         $cardDataByCoinCount = array();
  2611.         $bookedCardIdsByCoinCount = array();
  2612.         $bookedCardCountByCoinCount = array();
  2613.         $queriedCardCountByCoinCount = array();
  2614.         $missingCardFlagByCoinCount = array();
  2615.         $bookedCardIds = array();
  2616.         if (!empty($cardIds)) {
  2617.             $bookingAllowed 1;
  2618.             $cards $em->getRepository('CompanyGroupBundle\\Entity\\BeeCode')
  2619.                 ->createQueryBuilder('m')
  2620.                 ->where("m.retailerId = :retailerId")
  2621.                 ->andwhere("(m.id in (:ids)")
  2622.                 ->andWhere("(m.isTemporaryBooked = 0  or m.isTemporaryBooked is null)")
  2623.                 ->andWhere("(m.isClaimed = 0  or m.isClaimed is null)")
  2624.                 ->andWhere("m.expireTs < :currTs")
  2625.                 ->setParameter('retailerId'$retailerId)
  2626.                 ->setParameter('ids'implode(','$cardIds))
  2627. //                ->setParameter('startAt', $startDate->format('Y-m-d h:i:s'))
  2628.                 ->setParameter('currTs'$currDate->format('U'))
  2629. //                ->setParameter('endAt', $endDate->format('Y-m-d h:i:s'))
  2630.                 ->getQuery()
  2631.                 ->getResult();
  2632.             foreach ($cards as $card) {
  2633.                 if (!isset($cardEntityByCoinCount[$card->getCoinCount()]))
  2634.                     $cardEntityByCoinCount[$card->getCoinCount()] = array();
  2635.                 if (!isset($queriedCardCountByCoinCount[$card->getCoinCount()]))
  2636.                     $queriedCardCountByCoinCount[$card->getCoinCount()] = 0;
  2637.                 $cardEntityByCoinCount[$card->getCoinCount()][] = $card;
  2638.                 $queriedCardCountByCoinCount[$card->getCoinCount()] = ($queriedCardCountByCoinCount[$card->getCoinCount()]) + 1;
  2639.             }
  2640.             if (count($cardIds) != count($cards)) {
  2641.                 $bookingAllowed 0;
  2642.                 $data['success'] = false;
  2643.             }
  2644.             if ($bookingAllowed == 1) {
  2645.                 $data['success'] = true;
  2646.                 foreach ($cardEntityByCoinCount as $coinCount => $entityList) {
  2647.                     if (!isset($bookedCardIdsByCoinCount[$coinCount]))
  2648.                         $bookedCardIdsByCoinCount[$coinCount] = array();
  2649.                     if (!isset($bookedCardCountByCoinCount[$coinCount]))
  2650.                         $bookedCardCountByCoinCount[$coinCount] = count($entityList);
  2651.                     foreach ($entityList as $crd) {
  2652.                         $crd->setBookingExpireTs($bookingExpireTs);
  2653.                         $crd->setIsTemporaryBooked(1);
  2654.                         $crd->setBookedBy(1);
  2655.                         $bookedCardIdsByCoinCount = array();
  2656.                         $bookedCardCountByCoinCount = array();
  2657.                     }
  2658.                 }
  2659.                 $em->flush();
  2660.             }
  2661.         } else {
  2662.             $bookingAllowed 1;
  2663.             foreach ($cardOptionsByCoinCount as $cpd) {
  2664.                 $cards $em->getRepository('CompanyGroupBundle\\Entity\\BeeCode')
  2665.                     ->createQueryBuilder('m')
  2666.                     ->where("m.retailerId = :retailerId")
  2667.                     ->andwhere("(m.coinCount = :coinCount)")
  2668.                     ->andWhere("(m.isTemporaryBooked = 0  or m.isTemporaryBooked is null)")
  2669.                     ->andWhere("(m.isClaimed = 0  or m.isClaimed is null)")
  2670.                     ->andWhere("(m.expireTs < :currTs or m.expireTs is null)")
  2671.                     ->setParameter('retailerId'$retailerId)
  2672.                     ->setParameter('coinCount'$cpd['coinCount'])
  2673. //                ->setParameter('startAt', $startDate->format('Y-m-d h:i:s'))
  2674.                     ->setParameter('currTs'$currDate->format('U'))
  2675. //                ->setParameter('endAt', $endDate->format('Y-m-d h:i:s'))
  2676.                     ->setMaxResults($cpd['qty'])
  2677.                     ->getQuery()
  2678.                     ->getResult();
  2679.                 foreach ($cards as $card) {
  2680.                     if (!isset($cardEntityByCoinCount[$card->getCoinCount()]))
  2681.                         $cardEntityByCoinCount[$card->getCoinCount()] = array();
  2682.                     if (!isset($queriedCardCountByCoinCount[$card->getCoinCount()]))
  2683.                         $queriedCardCountByCoinCount[$card->getCoinCount()] = 0;
  2684.                     $cardEntityByCoinCount[$card->getCoinCount()][] = $card;
  2685.                     $queriedCardCountByCoinCount[$card->getCoinCount()] = ($queriedCardCountByCoinCount[$card->getCoinCount()]) + 1;
  2686.                 }
  2687.                 if (($cpd['qty']) > count($cards)) {
  2688.                     if ($createIfNeeded == 1) {
  2689.                         $generateOptions = [
  2690.                             'amount' => isset($cpd['amount']) ? $cpd['amount'] : 0,
  2691.                             'coinCount' => $cpd['coinCount'],
  2692.                             'cardCount' => (($cpd['qty']) > count($cards)),
  2693.                             'serial' => '_AUTO_',
  2694.                             'pin' => '_AUTO_',
  2695.                             'useCount' => 1,
  2696.                             'retailerId' => $retailerId,
  2697.                         ];
  2698.                         $generatedData MiscActions::GenerateBeeCode($em$generateOptions);
  2699.                         foreach ($generatedData['data'] as $cardDt) {
  2700.                             $card $cardDt['cardEntityObj'];
  2701.                             if (!isset($cardEntityByCoinCount[$card->getCoinCount()]))
  2702.                                 $cardEntityByCoinCount[$card->getCoinCount()] = array();
  2703.                             if (!isset($queriedCardCountByCoinCount[$card->getCoinCount()]))
  2704.                                 $queriedCardCountByCoinCount[$card->getCoinCount()] = 0;
  2705.                             $cardEntityByCoinCount[$card->getCoinCount()][] = $card;
  2706.                             $cards[] = $card;
  2707.                             $queriedCardCountByCoinCount[$card->getCoinCount()] = ($queriedCardCountByCoinCount[$card->getCoinCount()]) + 1;
  2708.                         }
  2709.                     }
  2710.                 }
  2711.                 if (($cpd['qty']) > count($cards)) {
  2712.                     $bookingAllowed 0;
  2713.                     $data['success'] = false;
  2714.                 }
  2715.             }
  2716.             if ($bookingAllowed == 1) {
  2717.                 $data['success'] = true;
  2718.                 foreach ($cardEntityByCoinCount as $coinCount => $entityList) {
  2719.                     if (!isset($bookedCardIdsByCoinCount[$coinCount]))
  2720.                         $bookedCardIdsByCoinCount[$coinCount] = array();
  2721.                     if (!isset($bookedCardCountByCoinCount[$coinCount]))
  2722.                         $bookedCardCountByCoinCount[$coinCount] = count($entityList);
  2723.                     foreach ($entityList as $crd) {
  2724.                         $crd->setBookingExpireTs($bookingExpireTs);
  2725.                         $crd->setIsTemporaryBooked(1);
  2726.                         $crd->setBookedBy(1);
  2727.                         $bookedCardIdsByCoinCount[$coinCount][] = $crd->getId();
  2728.                         $bookedCardIds[] = $crd->getId();
  2729.                     }
  2730.                 }
  2731.                 $em->flush();
  2732.             }
  2733.         }
  2734.         $data['bookedCardIdsByCoinCount'] = $bookedCardIdsByCoinCount;
  2735.         $data['bookedCardCountByCoinCount'] = $bookedCardCountByCoinCount;
  2736.         $data['bookedCardIds'] = $bookedCardIds;
  2737.         return $data;
  2738.     }
  2739.     public static function AddTemporaryBooking($em$topicId$scheduledStartTimeTs$consultantId$studentId$duration$forcedSchdeuleDt '')
  2740.     {
  2741.         MiscActions::RemoveExpiredTemporaryBookings($em);
  2742.         $new = new EntityTemporaryBooking();
  2743.         $new->setTopicId($topicId);
  2744.         $new->setConsultantId($consultantId);
  2745.         $new->setStudentId($studentId);
  2746.         if ($scheduledStartTimeTs == || $scheduledStartTimeTs == '') {
  2747.             if ($forcedSchdeuleDt != '') {
  2748.                 $forcedSchdeuleDtime = new \DateTime($forcedSchdeuleDt);
  2749.                 $scheduledStartTimeTs $forcedSchdeuleDtime->format('U');
  2750.             }
  2751.         }
  2752.         $scheduledStartTime = new \DateTime('@' $scheduledStartTimeTs);
  2753.         $scheduledEndTime = new \DateTime('@' $scheduledStartTimeTs);
  2754.         $scheduledEndTime $scheduledEndTime->modify('+' $duration ' minute');
  2755.         $new->setScheduledTime($scheduledStartTime);
  2756.         $new->setDurationAllowedMin($duration);
  2757.         $new->setSessionExpireDate($scheduledEndTime);
  2758.         $new->setSessionExpireDateTs($scheduledEndTime->format('U'));
  2759.         $new->setScheduledTime($scheduledStartTime);
  2760.         $new->setScheduledTimeTs($scheduledStartTime->format('U'));
  2761.         $currentUnixTime = new \DateTime();
  2762.         if ($studentId == 0)
  2763.             $currentUnixTime->modify('+5 Minute');
  2764.         else
  2765.             $currentUnixTime->modify('+10 Minute');
  2766.         $bookingExpiresTs $currentUnixTime->format('U');
  2767.         $new->setBookingExpiresTs($bookingExpiresTs);
  2768.         $em->persist($new);
  2769.         $em->flush();
  2770.         $periodMarker $scheduledStartTime->format('Ym');
  2771.         MiscActions::UpdateSchedulingRestrictions($em$consultantId$periodMarker0, (($duration) / 60));
  2772. //        return $new->getBookingId();
  2773.         return array(
  2774.             'bookingId' => $new->getBookingId(),
  2775.             'ts' => $new->getScheduledTimeTs(),
  2776.         );
  2777.     }
  2778.     public static function GetDashboardDataForApplicant($em$applicantId$markerHash '_STUDENT_')
  2779.     {
  2780.         $data = [];
  2781.         $applicantDetails $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
  2782.             array
  2783.             (
  2784.                 'applicantId' => $applicantId
  2785.             )
  2786.         );
  2787.         if ($markerHash == '_CONSULTANT_') {
  2788.             ///earned this month
  2789.             $currDateNow = new \DateTime();
  2790.             $thisMonthFirstDateStr $currDateNow->format('Y-m-') . '01 00:00:00';
  2791.             $nextMmonthFirstDate = new \DateTime();
  2792.             $nextMmonthFirstDate->modify('first day of next month');
  2793.             $nextMonthFirstDateStr $nextMmonthFirstDate->format('Y-m-d') . ' 00:00:00';
  2794. //            $currDateNow = new \DateTime();
  2795. //            $currDateNow->modify('-365 Day');
  2796.             $stmt $em->getConnection()->fetchAllAssociative("select sum(amount) total_amount FROM `entity_invoice` WHERE applicant_id = $applicantId and invoice_type=5 and amount_type in (0,1)
  2797. and created_at <'$nextMonthFirstDateStr' and created_at>='$thisMonthFirstDateStr'");
  2798.             $query_output $stmt;
  2799.             $data['earnedThisMonth'] = isset($query_output[0]) ? $query_output[0]['total_amount'] : 0;
  2800.         }
  2801.         return $data;
  2802.     }
  2803.     public static function GetDocumentDataForBuddybeeApplicant($em$applicantId$topicId 0$semesterIdsData = [], $sort '_DEFAULT_'$outputAs 'object')
  2804.     {
  2805.         $data = array(
  2806.             'hasMissingDoc' => 0,
  2807.             'hasExpiredDoc' => 0,
  2808.             'documentList' => [],
  2809.             'documentListByStatus' => [],
  2810.             'documentListObj' => null,
  2811.             'documentDataByTopicId' => [],
  2812.         );
  2813.         $documentList = [];
  2814.         $documentListObj = [];
  2815.         $hasMissingDoc 0;
  2816.         $hasExpiredDoc 0;
  2817.         $documentListByStatus = [];
  2818.         $applicantDetails $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
  2819.             array
  2820.             (
  2821.                 'applicantId' => $applicantId
  2822.             )
  2823.         );
  2824.         if ($applicantDetails) {
  2825.             $toGetDocumentIds = [];
  2826.             $stagesArray = [];
  2827.             $documentByStages = [];
  2828.             $studentDocData json_decode($applicantDetails->getDocumentList(), true);
  2829.             if ($studentDocData == null$studentDocData = [];
  2830.             foreach ($studentDocData as $did => $dt) {
  2831.                 if (!in_array($did$toGetDocumentIds))
  2832.                     $toGetDocumentIds[] = $did;
  2833.             }
  2834.             $documentDataByTopicId = [];
  2835.             $documentDataByTopicIdArray = [];
  2836.             //$topicId = $id;
  2837.             $topics = [];
  2838.             $documentListFindData = [];
  2839.             $documentListFindData = [];
  2840.             $topicDocumentList = [];
  2841.             if ($topicId != 0) {
  2842.                 $topics $em->getRepository('CompanyGroupBundle\\Entity\\EntityCreateTopic')->findBy(
  2843.                     array(
  2844.                         'id' => $topicId
  2845.                     )
  2846.                 );
  2847.                 $toGetDocumentIds = [];
  2848.                 foreach ($topics as $topic) {
  2849.                     $topicDocumentData json_decode($topic->getDocumentData(), true);
  2850.                     if ($topicDocumentData == null$topicDocumentData = [];
  2851.                     foreach ($topicDocumentData as $did => $dt) {
  2852.                         if (!in_array($dt['document'], $toGetDocumentIds))
  2853.                             $toGetDocumentIds[] = $dt['document'];
  2854.                     }
  2855.                 }
  2856.                 $documentListFindData $em->getRepository('CompanyGroupBundle\\Entity\\EntityCreateDocument')->findBy(
  2857.                     array(
  2858.                         'Id' => $toGetDocumentIds
  2859.                     )
  2860.                 );
  2861.             } else {
  2862.                 $documentListFindData $em->getRepository('CompanyGroupBundle\\Entity\\EntityCreateDocument')->findBy(
  2863.                     array()
  2864.                 );
  2865.             }
  2866.             $currDateTime = new \DateTime();
  2867.             $currDateTimeStr $currDateTime->format('Y-m-d');
  2868.             $currentNow time();
  2869.             foreach ($documentListFindData as $did => $document) {
  2870.                 $chkList json_decode($document->getCheckList(), true);
  2871.                 if ($chkList == null$chkList = [];
  2872.                 $expireDate = isset($studentDocData[$document->getId()]) ? $studentDocData[$document->getId()]['docExpiryDate'] : '';
  2873.                 $expiredFlag 2//pending
  2874.                 if ($expireDate != '') {
  2875.                     $expireDateTime = new \DateTime($expireDate);
  2876.                     if ($expireDateTime <= $currDateTime)
  2877.                         $expiredFlag 1;
  2878.                     else
  2879.                         $expiredFlag 0;
  2880.                 }
  2881.                 if ($expiredFlag == 1)
  2882.                     $hasExpiredDoc 1;
  2883.                 $evaluationStatus 0;  //pending
  2884.                 $evaluationComment = [];
  2885.                 if (isset($studentDocData[$document->getId()])) {
  2886.                     if (isset($studentDocData[$document->getId()]['evaluationStatus']))
  2887.                         $evaluationStatus $studentDocData[$document->getId()]['evaluationStatus'];
  2888.                     if (isset($studentDocData[$document->getId()]['evaluationComment']))
  2889.                         $evaluationComment $studentDocData[$document->getId()]['evaluationComment'];
  2890.                 }
  2891.                 $docImage = isset($studentDocData[$document->getId()]) ? $studentDocData[$document->getId()]['docImage'] : '';
  2892.                 $documentStatus 0;// required  or not uploaded
  2893.                 if ($docImage != '') {
  2894.                     if ($expiredFlag == 1)
  2895.                         $documentStatus 0;
  2896.                     else {
  2897.                         if ($evaluationStatus == 1)
  2898.                             $documentStatus 1;/// complete
  2899.                         else
  2900.                             $documentStatus 2;/// Pending
  2901.                     }
  2902.                 }
  2903.                 if ($documentStatus == 0)
  2904.                     $hasMissingDoc 1;
  2905.                 $docData = array(
  2906.                     'docId' => $document->getId(),
  2907.                     'docName' => $document->getDocumentName(),
  2908.                     'docExpiryDays' => $document->getExpiryDays(),
  2909.                     'docExpiryDate' => $expireDate,
  2910.                     'minEtaDate' => $currDateTimeStr,
  2911.                     'minEtaDays' => 0,
  2912.                     'docExpiredFlag' => $expiredFlag,
  2913.                     'docImage' => $docImage,
  2914.                     'documentStatus' => $documentStatus,
  2915.                     'evaluationStatus' => $evaluationStatus,
  2916.                     'evaluationComment' => $evaluationComment,
  2917.                     'processingDays' => $document->getProcessingDays(),
  2918.                     'emergencyProcessingDays' => $document->getEmergencyProcessingDays(),
  2919.                     'docChecklist' => $chkList,
  2920.                     'docAcquiredChecklist' => isset($studentDocData[$document->getId()]) ? $studentDocData[$document->getId()]['docCheckList'] : [],
  2921.                 );
  2922.                 $documentList[] = $docData;
  2923.                 $documentListObj[$document->getId()] = $docData;
  2924.             }
  2925.             if ($topicId != 0) {
  2926.                 foreach ($topics as $topic) {
  2927.                     $topicDocumentData json_decode($topic->getDocumentData(), true);
  2928.                     if ($topicDocumentData == null$topicDocumentData = [];
  2929.                     $docDataForThisTopic = [];
  2930.                     $minEtaThisTopic = clone($currDateTime);
  2931.                     $minEtaStrThisTopic $currDateTimeStr;
  2932.                     if (!empty($semesterIdsData))
  2933.                         if (isset($semesterIdsData[$topic->getId()])) {
  2934.                             $topicSemesterData json_decode($topic->getSessionData(), true);
  2935.                             if ($topicSemesterData == null$topicSemesterData = [];
  2936.                             foreach ($topicSemesterData as $topicSemester) {
  2937.                                 if (in_array($topicSemester['sessionId'], $semesterIdsData[$topic->getId()])) {
  2938.                                     $thresholdThisSemester = new \DateTime($topicSemester['threshold']);
  2939.                                     if ($thresholdThisSemester $minEtaThisTopic) {
  2940.                                         $minEtaThisTopic = clone($thresholdThisSemester);
  2941.                                         $minEtaStrThisTopic $thresholdThisSemester->format('Y-m-d');
  2942.                                     }
  2943.                                 }
  2944.                             }
  2945.                         }
  2946.                     foreach ($topicDocumentData as $did => $dt) {
  2947.                         if (isset($documentListObj[$dt['document']])) {
  2948.                             $docData $documentListObj[$dt['document']];
  2949.                             $currMinEtaDoc = new \DateTime($docData['minEtaDate']);
  2950.                             if ($docData['docExpiryDays'] == '')
  2951.                                 $docData['docExpiryDays'] = $dt['expDays'];
  2952.                             $docData['stage'] = $dt['stage'];
  2953.                             $thresholdDaysOffsetForThis = isset($dt['thresholdDaysOffset']) ? $dt['thresholdDaysOffset'] : 0;
  2954.                             $minEtaThisTopicThisDoc = clone $minEtaThisTopic;
  2955.                             if ($thresholdDaysOffsetForThis 0)
  2956.                                 $minEtaThisTopicThisDoc->modify('-' $thresholdDaysOffsetForThis ' day');
  2957.                             if ($minEtaThisTopicThisDoc $currMinEtaDoc) {
  2958.                                 $docData['minEtaDate'] = $minEtaThisTopicThisDoc->format('Y-m-d');
  2959.                                 $now time(); // or your date as well
  2960.                                 $eta_date strtotime($minEtaThisTopicThisDoc->format('Y-m-d'));
  2961.                                 $etaDays = (($eta_date $currentNow) / (60 60 24));
  2962.                                 $docData['minEtaDays'] = $etaDays;
  2963.                                 $documentListObj[$dt['document']]['minEtaDate'] = $minEtaThisTopicThisDoc->format('Y-m-d');;
  2964.                                 $documentListObj[$dt['document']]['minEtaDays'] = $etaDays;
  2965.                             }
  2966.                             $docData['emergencyProcessingDays'] = $dt['emergencyProcessingDays'];
  2967.                             $docData['generalProcessingDays'] = $dt['generalProcessingDays'];
  2968.                             $docData['docChecklist'] = $dt['checklist'];
  2969.                             $docDataForThisTopic[] = $docData;
  2970.                         }
  2971.                     }
  2972.                     $documentDataByTopicId[$topic->getId()] = $docDataForThisTopic;
  2973.                 }
  2974.             }
  2975.             if ($sort == '_BY_STATUS_') {
  2976.                 $documentListByStatus[0] = array(
  2977.                     'hashed_topic_ids' => '',
  2978.                     'docList' => []
  2979.                 );
  2980.                 foreach ($documentListObj as $doc) {
  2981.                     if ($doc['documentStatus'] == 0) {
  2982.                         $documentListByStatus[0]['docList'][] = $doc;
  2983.                     }
  2984.                 }
  2985.                 $documentListByStatus[1] = array(
  2986.                     'hashed_topic_ids' => '',
  2987.                     'docList' => []
  2988.                 );
  2989.                 foreach ($documentListObj as $doc) {
  2990.                     if ($doc['documentStatus'] == 1) {
  2991.                         $documentListByStatus[1]['docList'][] = $doc;
  2992.                     }
  2993.                 }
  2994.                 $documentListByStatus[2] = array(
  2995.                     'hashed_topic_ids' => '',
  2996.                     'docList' => []
  2997.                 );
  2998.                 foreach ($documentListObj as $doc) {
  2999.                     if ($doc['documentStatus'] == 2) {
  3000.                         $documentListByStatus[2]['docList'][] = $doc;
  3001.                     }
  3002.                 }
  3003.             }
  3004.             $data = [
  3005.                 'hasMissingDoc' => $hasMissingDoc,
  3006.                 'hasExpiredDoc' => $hasExpiredDoc,
  3007.                 'documentList' => $documentList,
  3008.                 'documentListByStatus' => $documentListByStatus,
  3009.                 'documentListObj' => $documentListObj,
  3010.                 'documentDataByTopicId' => $documentDataByTopicId,
  3011.             ];
  3012.         }
  3013.         return $data;
  3014.     }
  3015.     public static function GetDocumentDataForBuddybeeConsultantApply($em$applicantId$countryId 0$sort '_DEFAULT_'$outputAs 'object')
  3016.     {
  3017.         $data = [];
  3018.         $applicantDetails $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
  3019.             array
  3020.             (
  3021.                 'applicantId' => $applicantId
  3022.             )
  3023.         );
  3024.         $toGetDocumentIds = [];
  3025.         $studentDocData json_decode($applicantDetails->getDocumentList(), true);
  3026.         if ($studentDocData == null$studentDocData = [];
  3027.         foreach ($studentDocData as $did => $dt) {
  3028.             if (!in_array($did$toGetDocumentIds))
  3029.                 $toGetDocumentIds[] = $did;
  3030.         }
  3031.         $documentDataByTopicId = [];
  3032.         $documentDataByTopicIdArray = [];
  3033.         //$topicId = $id;
  3034.         $topics = [];
  3035.         $documentListFindData = [];
  3036.         $documentList = [];
  3037.         $documentListObj = [];
  3038.         $documentListFindData = [];
  3039.         $topicDocumentList = [];
  3040.         if ($countryId != 0) {
  3041.             $topics $em->getRepository('CompanyGroupBundle\\Entity\\EntityCountryConsultantRequirements')->findBy(
  3042.                 array(
  3043.                     'countryId' => $countryId
  3044.                 )
  3045.             );
  3046.             $toGetDocumentIds = [];
  3047.             foreach ($topics as $topic) {
  3048.                 $topicDocumentList json_decode($topic->getDocumentList(), true);
  3049.                 if ($topicDocumentList == null$topicDocumentList = [];
  3050.                 foreach ($topicDocumentList as $did => $dt) {
  3051.                     if (!in_array($dt['document'], $toGetDocumentIds))
  3052.                         $toGetDocumentIds[] = $dt['document'];
  3053.                 }
  3054.             }
  3055.             $documentListFindData $em->getRepository('CompanyGroupBundle\\Entity\\EntityCreateDocument')->findBy(
  3056.                 array(
  3057.                     'Id' => $toGetDocumentIds
  3058.                 )
  3059.             );
  3060.         } else {
  3061.             $documentListFindData $em->getRepository('CompanyGroupBundle\\Entity\\EntityCreateDocument')->findBy(
  3062.                 array()
  3063.             );
  3064.         }
  3065.         $currDateTime = new \DateTime();
  3066.         foreach ($documentListFindData as $did => $document) {
  3067.             $chkList json_decode($document->getCheckList(), true);
  3068.             if ($chkList == null$chkList = [];
  3069.             $expireDate = isset($studentDocData[$document->getId()]) ? $studentDocData[$document->getId()]['docExpiryDate'] : '';
  3070.             $expiredFlag 2//pending
  3071.             if ($expireDate != '') {
  3072.                 $expireDateTime = new \DateTime($expireDate);
  3073.                 if ($expireDateTime <= $currDateTime)
  3074.                     $expiredFlag 1;
  3075.                 else
  3076.                     $expiredFlag 0;
  3077.             }
  3078.             $evaluationStatus 0;  //pending
  3079.             $evaluationComment = [];
  3080.             if (isset($studentDocData[$document->getId()])) {
  3081.                 if (isset($studentDocData[$document->getId()]['evaluationStatus']))
  3082.                     $evaluationStatus $studentDocData[$document->getId()]['evaluationStatus'];
  3083.                 if (isset($studentDocData[$document->getId()]['evaluationComment']))
  3084.                     $evaluationComment $studentDocData[$document->getId()]['evaluationComment'];
  3085.             }
  3086.             $docImage = isset($studentDocData[$document->getId()]) ? $studentDocData[$document->getId()]['docImage'] : '';
  3087.             $documentStatus 0;// required  or not uploaded
  3088.             if ($docImage != '') {
  3089.                 if ($expiredFlag == 1)
  3090.                     $documentStatus 0;
  3091.                 else {
  3092.                     if ($evaluationStatus == 1)
  3093.                         $documentStatus 1;/// complete
  3094.                     else
  3095.                         $documentStatus 2;/// Pending
  3096.                 }
  3097.             }
  3098.             $docData = array(
  3099.                 'docId' => $document->getId(),
  3100.                 'docName' => $document->getDocumentName(),
  3101.                 'docExpiryDays' => $document->getExpiryDays(),
  3102.                 'docExpiryDate' => $expireDate,
  3103.                 'docExpiredFlag' => $expiredFlag,
  3104.                 'docImage' => $docImage,
  3105.                 'documentStatus' => $documentStatus,
  3106.                 'evaluationStatus' => $evaluationStatus,
  3107.                 'evaluationComment' => $evaluationComment,
  3108.                 'processingDays' => $document->getProcessingDays(),
  3109.                 'emergencyProcessingDays' => $document->getEmergencyProcessingDays(),
  3110.                 'docChecklist' => $chkList,
  3111.                 'docAcquiredChecklist' => isset($studentDocData[$document->getId()]) ? $studentDocData[$document->getId()]['docCheckList'] : [],
  3112.             );
  3113.             $documentList[] = $docData;
  3114.             $documentListObj[$document->getId()] = $docData;
  3115.         }
  3116.         if ($countryId != 0) {
  3117.             foreach ($topics as $topic) {
  3118.                 $topicDocumentData json_decode($topic->getDocumentList(), true);
  3119.                 if ($topicDocumentData == null$topicDocumentData = [];
  3120.                 $docDataForThisTopic = [];
  3121.                 foreach ($topicDocumentData as $did => $dt) {
  3122.                     if (isset($documentListObj[$dt['document']])) {
  3123.                         $docData $documentListObj[$dt['document']];
  3124.                         $docDataForThisTopic[] = $docData;
  3125.                     }
  3126.                 }
  3127.                 $documentDataByTopicId[$topic->getCountryId()] = $docDataForThisTopic;
  3128.             }
  3129.         }
  3130.         $data = [
  3131.             'documentList' => $documentList,
  3132.             'documentListObj' => $documentListObj,
  3133.             'documentDataByTopicId' => $documentDataByTopicId,
  3134.         ];
  3135.         return $data;
  3136.     }
  3137.     public static function ModifyDocumentStatus($em$applicantId$documentId$toSetStatus 1$topicId 0$comment '')
  3138.     {
  3139.         $user $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
  3140.             array(
  3141.                 'applicantId' => $applicantId
  3142.             ));
  3143.         $docData json_decode($user->getDocumentList(), true);
  3144.         $docDataByTopicId json_decode($user->getDocumentListByTopicId(), true);
  3145.         if ($docData == null$docData = [];
  3146.         if ($docDataByTopicId == null$docDataByTopicId = [];
  3147.         if (isset($docData[$documentId])) {
  3148.             $docData[$documentId]['evaluationStatus'] = $toSetStatus;
  3149.             if (!isset($docData[$documentId]['evaluationComment']))
  3150.                 $docData[$documentId]['evaluationComment'] = [];
  3151.             $docData[$documentId]['evaluationComment'][] = $comment;
  3152.         }
  3153.         if (isset($docDataByTopicId[$topicId])) {
  3154.             if (isset($docDataByTopicId[$topicId][$documentId])) {
  3155.                 $docDataByTopicId[$topicId][$documentId]['evaluationStatus'] = $toSetStatus;
  3156.                 if (!isset($docDataByTopicId[$topicId][$documentId]['evaluationComment']))
  3157.                     $docDataByTopicId[$topicId][$documentId]['evaluationComment'] = [];
  3158.                 $docDataByTopicId[$topicId][$documentId]['evaluationComment'][] = $comment;
  3159.             }
  3160.         }
  3161.         $user->setDocumentList(json_encode($docData));
  3162.         $user->setDocumentListByTopicId(json_encode($docDataByTopicId));
  3163.         $em->flush();
  3164.         return true;
  3165.     }
  3166.     public static function RefreshBuddybeeBalanceOnSession($em$session)
  3167.     {
  3168.         if ($session->has(UserConstants::USER_ID)) {
  3169.             if ($session->get(UserConstants::USER_ID) != 0) {
  3170.                 if ($session->get(UserConstants::USER_TYPE) == UserConstants::USER_TYPE_APPLICANT) {
  3171.                     $user $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
  3172.                         array(
  3173.                             'applicantId' => $session->get(UserConstants::USER_ID)
  3174.                         ));
  3175.                     $session->set('BUDDYBEE_BALANCE'$user->getAccountBalance());
  3176.                     $session->set('BUDDYBEE_COIN_BALANCE'$user->getSessionCountBalance());
  3177.                 }
  3178.             }
  3179.         }
  3180.         return $session;
  3181.     }
  3182.     public static function ConvertCurrentUserToAdmin($em$session$level 1)
  3183.     {
  3184.         if ($session->has(UserConstants::USER_ID)) {
  3185.             if ($session->get(UserConstants::USER_ID) != 0) {
  3186.                 if ($session->get(UserConstants::USER_TYPE) == UserConstants::USER_TYPE_APPLICANT) {
  3187.                     $user $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
  3188.                         array(
  3189.                             'applicantId' => $session->get(UserConstants::USER_ID)
  3190.                         ));
  3191.                     $user->setIsAdmin(1);
  3192.                     $user->setAdminLevel($level);
  3193.                     $em->flush();
  3194.                     $session->set('BUDDYBEE_BALANCE'$user->getAccountBalance());
  3195.                     $session->set('BUDDYBEE_COIN_BALANCE'$user->getSessionCountBalance());
  3196.                     $session->set(UserConstants::IS_BUDDYBEE_RETAILER$user->getIsRetailer() == 0);
  3197.                     $session->set(UserConstants::BUDDYBEE_RETAILER_LEVEL$user->getRetailerLevel() == 0);
  3198.                     $session->set(UserConstants::BUDDYBEE_ADMIN_LEVEL$user->getIsAdmin() == ? (($user->getAdminLevel() != null && $user->getAdminLevel() != 0) ? $user->getAdminLevel() : 1) : ($user->getIsModerator() == 0));
  3199.                     $session->set(UserConstants::IS_BUDDYBEE_MODERATOR$user->getIsModerator() == 0);
  3200.                     $session->set(UserConstants::IS_BUDDYBEE_ADMIN$user->getIsAdmin() == 0);
  3201.                 }
  3202.             }
  3203.         }
  3204.         return $session;
  3205.     }
  3206.     public static function GetDtDataAjax($em$method 'GET'$postData = [], $companyId 0$kernelRoot '')
  3207.     {
  3208.         $entityConfig = [];
  3209.         if ($postData->has('config')) {
  3210.             $entityConfig $postData->get('config');
  3211.         }
  3212. //        System::log_it($kernelRoot,json_encode( $entityConfig),'entityConfig',0);
  3213.         $Transaction = [];
  3214.         $dt_list = [];
  3215.         $response = [];
  3216.         $skipColumnNames = isset($entityConfig['skipColumnNames']) ? $entityConfig['skipColumnNames'] : [];
  3217.         $flagColNames = isset($entityConfig['flagColNames']) ? $entityConfig['flagColNames'] : [];
  3218.         $flagConversionByCols = isset($entityConfig['flagConversionByCols']) ? $entityConfig['flagConversionByCols'] : [];
  3219.         $draftFlagList = array(
  3220.             '' => '',
  3221.             '0' => 'No',
  3222.             '1' => 'Yes',
  3223.         );
  3224.         $stageFlagList = array(
  3225.             => 'Pending',
  3226.             '' => '',
  3227.             => 'Pending',
  3228.             => 'Complete',
  3229.             => 'Partial',
  3230.         );
  3231.         $approvedFlagList = array(
  3232.             => 'Declined',
  3233.             '' => '',
  3234.             => 'Approved',
  3235.             => 'Reverted',
  3236.             => 'Pending',
  3237.             => 'Forwarded',
  3238.         );
  3239.         if ($method == 'POST') {
  3240.             $getUnitListFlag 1;
  3241.             if ($postData->has('columns') || $postData->has('pageNumber')) {
  3242.                 $draw intval($postData->get('draw'));
  3243.                 $start $postData->has('start') ? $postData->get('start') : ($postData->get('pageNumber') - 1) * $postData->get('pageSize');
  3244.                 $length $postData->has('length') ? $postData->get('length') : $postData->get('pageSize');
  3245.                 $search $postData->has('search') ? $postData->get('search') : '';
  3246.                 $orders $postData->has('order') ? $postData->get('order') : (isset($entityConfig['order']) ? $entityConfig['order'] : []);
  3247.                 $joinOrders $postData->has('joinOrder') ? $postData->get('joinOrder') : (isset($entityConfig['joinOrder']) ? $entityConfig['joinOrder'] : []);
  3248.                 $columns $postData->has('columns') ? $postData->get('columns') : (isset($entityConfig['columns']) ? $entityConfig['columns'] : []);
  3249.                 $getUnitListFlag $postData->has('getUnitListFlag') ? $postData->get('getUnitListFlag') : 1;
  3250.                 // Orders
  3251.                 foreach ($orders as $key => $order) {
  3252.                     $orders[$key]['name'] = $columns[$order['column']]['name'];
  3253.                 }
  3254.                 foreach ($joinOrders as $key => $order) {
  3255.                     $orders[array_key_last($orders) + 1] = $order;
  3256.                 }
  3257.                 // Get results from the Repository
  3258.                 $results $em->getRepository(str_replace(':''\\Entity\\'$entityConfig['mainTableClass']))->getRequiredDTData($em$entityConfig$start$length$orders,
  3259.                     $search$columns$skipColumnNames$flagColNames$flagConversionByCols);
  3260.                 $objects $results["results"];
  3261. //                $total_objects_count = $em->getRepository($entityConfig['mainTableClass'])->countRel();
  3262.                 $total_objects_count $results["countResult"];
  3263.                 $selected_objects_count count($objects);
  3264.                 $filtered_objects_count $results["countResult"];
  3265. //                System::log_it($kernelRoot,json_encode( $objects),'test_dt_data',0);
  3266.                 $dateFieldsToStr = isset($entityConfig['dateFieldsToStr']) ? $entityConfig['dateFieldsToStr'] : [];
  3267.                 $otherDateFieldsToStr = isset($entityConfig['otherDateFieldsToStr']) ? $entityConfig['otherDateFieldsToStr'] : [];
  3268.                 $convertToObjectFields = isset($entityConfig['convertToObjectFields']) ? $entityConfig['convertToObjectFields'] : [];
  3269.                 $timestampFieldsToStr = isset($entityConfig['timestampFieldsToStr']) ? $entityConfig['timestampFieldsToStr'] : [];
  3270.                 $timestampFieldsToStrFormat = isset($entityConfig['timestampFieldsToStrFormat']) ? $entityConfig['timestampFieldsToStrFormat'] : [];
  3271.                 $dateFieldsToStrFormat = isset($entityConfig['dateFieldsToStrFormat']) ? $entityConfig['dateFieldsToStrFormat'] : [];
  3272.                 $otherDateFieldsToStrFormat = isset($entityConfig['otherDateFieldsToStrFormat']) ? $entityConfig['otherDateFieldsToStrFormat'] : [];
  3273.                 $joinTableList = isset($entityConfig['joinTableList']) ? $entityConfig['joinTableList'] : [];
  3274.                 $encryptedDataList = isset($entityConfig['encryptedDataList']) ? $entityConfig['encryptedDataList'] : [];
  3275.                 if (empty($joinTableList)) {
  3276.                     foreach ($objects as $pq) {
  3277.                         $p $pq;
  3278.                         $d $pq;
  3279.                         $d[$entityConfig['mainTableAlias']] = $pq;
  3280.                         foreach ($convertToObjectFields as $key_ind => $convertToObjectField//for now main table only
  3281.                         {
  3282.                             $curr_obj = [];
  3283.                             if (isset($d[$entityConfig['mainTableAlias']][$convertToObjectField]))
  3284.                                 $curr_obj json_decode($d[$entityConfig['mainTableAlias']][$convertToObjectField], true);
  3285.                             else
  3286.                                 $curr_obj = [];
  3287.                             if ($curr_obj == null)
  3288.                                 $curr_obj = [];
  3289.                             $d[$entityConfig['mainTableAlias']][$convertToObjectField] = $curr_obj;
  3290.                         }
  3291.                         foreach ($dateFieldsToStr as $key_ind => $dateField//for now main table only
  3292.                         {
  3293.                             $formatForThis = isset($dateFieldsToStrFormat[$key_ind]) ? $dateFieldsToStrFormat[$key_ind] : 'm-d-Y';
  3294. //                        System::log_it($kernelRoot,json_encode( $d[$entityConfig['mainTableAlias']][$dateField]),'date_test');
  3295. //                        System::log_it($kernelRoot,$d[$entityConfig['mainTableAlias']][$dateField]->format('m-d-Y'),'date_test_again');
  3296.                             if (isset($d[$entityConfig['mainTableAlias']][$dateField]))
  3297.                                 $this_date $d[$entityConfig['mainTableAlias']][$dateField];
  3298.                             else
  3299.                                 $this_date null;
  3300.                             $d[$entityConfig['mainTableAlias']][$dateField 'Str'] = ($this_date == null || $this_date == '') ? '' $this_date->format($formatForThis);
  3301.                         }
  3302.                         foreach ($encryptedDataList as $key_ind => $encryptedDataCon//for now main table only
  3303.                         {
  3304.                             if (isset($d[$entityConfig['mainTableAlias']][$encryptedDataCon])) {
  3305.                                 $iv '1234567812345678';
  3306.                                 $pass '_enc_';
  3307.                                 $suffix '_enpaac_';
  3308.                                 // {field:alias}
  3309.                                 $str $d[$entityConfig['mainTableAlias']][$encryptedDataCon];
  3310.                                 $data openssl_encrypt($str"AES-128-CBC"$passOPENSSL_RAW_DATA$iv);
  3311.                                 $data base64_encode($data) . '' $suffix;
  3312.                                 $d['encrypted_' $encryptedDataCon] = $data;
  3313.                             }
  3314.                         }
  3315.                         foreach ($otherDateFieldsToStr as $key_ind => $dateField) {
  3316.                             $formatForThis = isset($otherDateFieldsToStrFormat[$key_ind]) ? $otherDateFieldsToStrFormat[$key_ind] : 'm-d-Y';
  3317.                             if (isset($d[$dateField]))
  3318.                                 $this_date $d[$dateField];
  3319.                             else
  3320.                                 $this_date = new \DateTime();
  3321.                             $d[$dateField 'Str'] = ($this_date == null || $this_date == '') ? '' $this_date->format($formatForThis);
  3322.                         }
  3323. //                        System::log_it($kernelRoot, json_encode($otherDateFieldsToStr),'date_test_again');
  3324.                         foreach ($timestampFieldsToStr as $key_ind => $dateField//for now main table only
  3325.                         {
  3326.                             $formatForThis = isset($timestampFieldsToStrFormat[$key_ind]) ? $timestampFieldsToStrFormat[$key_ind] : 'm-d-Y';
  3327. //                        System::log_it($kernelRoot,json_encode( $d[$entityConfig['mainTableAlias']][$dateField]),'date_test');
  3328. //                        System::log_it($kernelRoot,$d[$entityConfig['mainTableAlias']][$dateField]->format('m-d-Y'),'date_test_again');
  3329.                             if (isset($d[$entityConfig['mainTableAlias']][$dateField]))
  3330.                                 $this_date = new \DateTime('@' $d[$entityConfig['mainTableAlias']][$dateField]);
  3331.                             else
  3332.                                 $this_date null;
  3333.                             $d[$entityConfig['mainTableAlias']][$dateField 'Str'] = ($this_date == null || $this_date == '') ? '' $this_date->format($formatForThis);
  3334.                         }
  3335. //                    $q=$pq[1];
  3336.                         $dt_list[] = $d;
  3337.                     }
  3338.                 } else {
  3339.                     foreach ($objects as $pq) {
  3340.                         $p $pq[0];
  3341.                         $d $pq;
  3342.                         $d[$entityConfig['mainTableAlias']] = $pq[0];
  3343.                         $d[0] = [];
  3344.                         foreach ($convertToObjectFields as $key_ind => $convertToObjectField//for now main table only
  3345.                         {
  3346.                             $curr_obj = [];
  3347.                             if (isset($d[$entityConfig['mainTableAlias']][$convertToObjectField]))
  3348.                                 $curr_obj json_decode($d[$entityConfig['mainTableAlias']][$convertToObjectField], true);
  3349.                             else
  3350.                                 $curr_obj = [];
  3351.                             if ($curr_obj == null)
  3352.                                 $curr_obj = [];
  3353.                             $d[$entityConfig['mainTableAlias']][$convertToObjectField] = $curr_obj;
  3354.                         }
  3355.                         foreach ($dateFieldsToStr as $key_ind => $dateField//for now main table only
  3356.                         {
  3357.                             $formatForThis = isset($dateFieldsToStrFormat[$key_ind]) ? $dateFieldsToStrFormat[$key_ind] : 'm-d-Y';
  3358. //                        System::log_it($kernelRoot,json_encode( $d[$entityConfig['mainTableAlias']][$dateField]),'date_test');
  3359. //                        System::log_it($kernelRoot,$d[$entityConfig['mainTableAlias']][$dateField]->format('m-d-Y'),'date_test_again');
  3360.                             if (isset($d[$entityConfig['mainTableAlias']][$dateField]))
  3361.                                 $this_date $d[$entityConfig['mainTableAlias']][$dateField];
  3362.                             else
  3363.                                 $this_date null;
  3364.                             $d[$entityConfig['mainTableAlias']][$dateField 'Str'] = ($this_date == null || $this_date == '') ? '' $this_date->format($formatForThis);
  3365.                         }
  3366.                         $encData = [];
  3367.                         foreach ($encryptedDataList as $key_ind => $encryptedDataCon//for now main table only
  3368.                         {
  3369.                             if (isset($d[$entityConfig['mainTableAlias']][$encryptedDataCon])) {
  3370.                                 $iv '1234567812345678';
  3371.                                 $pass '_enc_';
  3372.                                 $suffix '_enpaac_';
  3373.                                 // {field:alias}
  3374.                                 $str $d[$entityConfig['mainTableAlias']][$encryptedDataCon];
  3375.                                 $data openssl_encrypt($str"AES-128-CBC"$passOPENSSL_RAW_DATA$iv);
  3376.                                 $data base64_encode($data) . '' $suffix;
  3377.                                 $d['encrypted_' $encryptedDataCon] = $data;
  3378. //                                $d['encrypted_' . $encryptedDataCon] = $str;
  3379.                             }
  3380.                         }
  3381.                         foreach ($otherDateFieldsToStr as $key_ind => $dateField) {
  3382.                             $formatForThis = isset($otherDateFieldsToStrFormat[$key_ind]) ? $otherDateFieldsToStrFormat[$key_ind] : 'm-d-Y';
  3383.                             if (isset($d[$dateField]))
  3384.                                 $this_date $d[$dateField];
  3385.                             else
  3386.                                 $this_date = new \DateTime();
  3387.                             $d[$dateField 'Str'] = ($this_date == null || $this_date == '') ? '' $this_date->format($formatForThis);
  3388.                         }
  3389. //                        System::log_it($kernelRoot, json_encode($otherDateFieldsToStr),'date_test_again');
  3390.                         foreach ($timestampFieldsToStr as $key_ind => $dateField//for now main table only
  3391.                         {
  3392.                             $formatForThis = isset($timestampFieldsToStrFormat[$key_ind]) ? $timestampFieldsToStrFormat[$key_ind] : 'm-d-Y';
  3393. //                        System::log_it($kernelRoot,json_encode( $d[$entityConfig['mainTableAlias']][$dateField]),'date_test');
  3394. //                        System::log_it($kernelRoot,$d[$entityConfig['mainTableAlias']][$dateField]->format('m-d-Y'),'date_test_again');
  3395.                             if (isset($d[$entityConfig['mainTableAlias']][$dateField]))
  3396.                                 $this_date = new \DateTime('@' $d[$entityConfig['mainTableAlias']][$dateField]);
  3397.                             else
  3398.                                 $this_date null;
  3399.                             $d[$entityConfig['mainTableAlias']][$dateField 'Str'] = ($this_date == null || $this_date == '') ? '' $this_date->format($formatForThis);
  3400.                         }
  3401. //                    $q=$pq[1];
  3402.                         $dt_list[] = $d;
  3403.                     }
  3404.                 }
  3405.                 // Construct response
  3406.                 $response = array(
  3407.                     "draw" => $draw,
  3408.                     "objects" => $objects,
  3409.                     "unitList" => [],
  3410.                     "getUnitListFlag" => $getUnitListFlag,
  3411.                     'totalObjectsCount' => $total_objects_count,
  3412.                     "recordsTotal" => $total_objects_count,
  3413.                     "recordsFiltered" => $filtered_objects_count,
  3414.                     "data" => $dt_list,
  3415.                     "debugData" => $results['debugData']
  3416.                 );
  3417.             }
  3418.         } else {
  3419. //
  3420. //            $Transaction = $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findBy(
  3421. //                array(), array('transactionDate' => 'desc')
  3422. //            );
  3423. //            foreach ($Transaction as $p) {
  3424. //                array_push($v_list,
  3425. //                    array(
  3426. //                        'id' => $p->getTransactionId(),
  3427. //                        'id_padded' => str_pad($p->getTransactionId(), 8, '0', STR_PAD_LEFT),
  3428. //                        'doc_hash' => $p->getDocumentHash(),
  3429. //                        'desc' => $p->getDescription(),
  3430. //                        'date' => $p->getTransactionDate(),
  3431. //                        'date_str' => $p->getTransactionDate()->format('F d, Y'),
  3432. //                        'type' => $type_list[$p->getDocumentType()],
  3433. //                        'amount' => $p->getTransactionAmount(),
  3434. //                        'provisional' => $p->getProvisional(),
  3435. //                        'ledgerHit' => $p->getLedgerHit(),
  3436. //                        'approved' => $p->getApproved(),
  3437. //                        'view_button' => 'view',
  3438. //                        'print_button' => 'print',
  3439. //                        'status' => GeneralConstant::$approvalAction[$p->getApproved()],
  3440. ////                    'total_dr'=>$total_dr,
  3441. ////                    'total_cr'=>$total_cr
  3442. //                    ));
  3443. //            }
  3444.             $response = array(
  3445.                 "draw" => 1,
  3446.                 "recordsTotal" => 0,
  3447.                 "recordsFiltered" => 0,
  3448.                 "data" => $dt_list,
  3449.             );
  3450.         }
  3451.         return $response;
  3452.     }
  3453.     public static function uploadFile($fileObj$uplDir)
  3454.     {
  3455.         $path "";
  3456.         $uploadedFile $fileObj;
  3457.         {
  3458.             if ($uploadedFile != null) {
  3459.                 $fileName 'p' md5(uniqid()) . '.' $uploadedFile->guessExtension();
  3460.                 $path $fileName;
  3461. //                $upl_dir = $uplDir;
  3462.                 if (!file_exists($uplDir)) {
  3463.                     mkdir($uplDir0777true);
  3464.                 }
  3465.                 $file $uploadedFile->move($uplDir$path);
  3466.             }
  3467.             $file_list[] = $path;
  3468.             $defaultImage $path;
  3469.         }
  3470.         return $path;
  3471.     }
  3472.     public static function GetNumberHash($em$t$p$a$timestamp ''$documentId 0$companyId 0)
  3473.     {
  3474.         $result = [];
  3475.         $t strtoupper($t);
  3476.         $entityListByTypeHash GeneralConstant::$Entity_list_by_type_hash;
  3477.         if (isset($entityListByTypeHash[$t])) {
  3478.             $entityName $entityListByTypeHash[$t];
  3479.             //1st of all check if the doc exists as booked with current timestamp if yes just return the doc numberhash and change dochash if needed
  3480.             if ($documentId != 0) {
  3481.                 $qryArray = array(
  3482.                     GeneralConstant::$Entity_id_field_list[array_flip(GeneralConstant::$Entity_list)[$entityName]] => $documentId,
  3483.                 );
  3484.                 $doc $em->getRepository('ApplicationBundle\\Entity\\' $entityName)
  3485.                     ->findOneBy(
  3486.                         $qryArray,
  3487.                         array()
  3488.                     );
  3489.                 if ($doc) {
  3490.                     //doc found so refresh the doc has if neeeded other wise return the number hash
  3491.                     if ($doc->getTypeHash() == $t && $doc->getPrefixHash() == $p && $doc->getAssocHash() == $a) {
  3492.                         return $doc->getNumberHash();
  3493.                     }
  3494.                 }
  3495.             }
  3496.             if ($timestamp != '') {
  3497.                 $qryArray = array(
  3498. //                    'typeHash' => $t,
  3499. //                    'prefixHash' => $p,
  3500. //                    'assocHash' => $a,
  3501.                     'timeStampOfForm' => $timestamp,
  3502.                     'docBookedFlag' => 1,
  3503.                     'CompanyId' => $companyId,
  3504.                 );
  3505.                 $doc $em->getRepository('ApplicationBundle\\Entity\\' $entityName)
  3506.                     ->findOneBy(
  3507.                         $qryArray,
  3508.                         array(
  3509.                             'numberHash' => 'DESC'
  3510.                         )
  3511.                     );
  3512.                 if ($doc) {
  3513.                     //doc found so refresh the doc has if neeeded other wise return the number hash
  3514.                     if ($doc->getTypeHash() == $t && $doc->getPrefixHash() == $p && $doc->getAssocHash() == $a) {
  3515.                         return $doc->getNumberHash();
  3516.                     } else {
  3517.                         $result $em->getRepository('ApplicationBundle\\Entity\\' $entityName)
  3518.                             ->findOneBy(
  3519.                                 array(
  3520.                                     'typeHash' => $t,
  3521.                                     'prefixHash' => $p,
  3522.                                     'assocHash' => $a,
  3523.                                 ),
  3524.                                 array(
  3525.                                     'numberHash' => 'DESC'
  3526.                                 )
  3527.                             );
  3528.                         $numberhash 1;
  3529.                         if ($result) {
  3530.                             $numberhash + ($result->getNumberhash());
  3531.                         } else {
  3532.                         }
  3533.                         $doc->setTypeHash($t);
  3534.                         $doc->setPrefixHash($p);
  3535.                         $doc->setAssocHash($a);
  3536.                         $doc->setNumberHash($numberhash);
  3537.                         $doc->setDocumentHash($t '/' $p '/' $a '/' $numberhash);
  3538.                         $em->flush();
  3539.                         return $numberhash;
  3540.                     }
  3541.                 } else {
  3542.                     $cname "ApplicationBundle\\Entity\\" $entityName;
  3543.                     $doc = new $cname;
  3544.                     $result $em->getRepository('ApplicationBundle\\Entity\\' $entityName)
  3545.                         ->findOneBy(
  3546.                             array(
  3547.                                 'typeHash' => $t,
  3548.                                 'prefixHash' => $p,
  3549.                                 'assocHash' => $a,
  3550.                             ),
  3551.                             array(
  3552.                                 'numberHash' => 'DESC'
  3553.                             )
  3554.                         );
  3555.                     $numberhash 1;
  3556.                     if ($result) {
  3557.                         $numberhash + ($result->getNumberhash());
  3558.                     } else {
  3559.                     }
  3560.                     $doc->setTypeHash($t);
  3561.                     $doc->setPrefixHash($p);
  3562.                     $doc->setAssocHash($a);
  3563.                     $doc->setNumberHash($numberhash);
  3564.                     $doc->setTimeStampOfForm($timestamp);
  3565.                     $doc->setDocBookedFlag(1);
  3566.                     $doc->setCompanyId($companyId);
  3567.                     $doc->setDocumentHash($t '/' $p '/' $a '/' $numberhash);
  3568.                     method_exists($doc'setProjectId') ? $doc->setProjectId(0) : 0;
  3569.                     $em->persist($doc);
  3570.                     $em->flush();
  3571.                     return $numberhash;
  3572.                 }
  3573.             } else {
  3574.                 $result $em->getRepository('ApplicationBundle\\Entity\\' $entityName)
  3575.                     ->findOneBy(
  3576.                         array(
  3577.                             'typeHash' => $t,
  3578.                             'prefixHash' => $p,
  3579.                             'assocHash' => $a,
  3580.                         ),
  3581.                         array(
  3582.                             'numberHash' => 'DESC'
  3583.                         )
  3584.                     );
  3585.                 $numberhash 1;
  3586.                 if ($result) {
  3587.                     $numberhash + ($result->getNumberhash());
  3588.                 } else {
  3589.                 }
  3590.                 return $numberhash;
  3591.             }
  3592.         } else {
  3593. //            if ($t == 'DO') {
  3594. //                $result = $em
  3595. //                    ->getRepository('ApplicationBundle\\Entity\\DeliveryOrder')
  3596. //                    ->findBy(
  3597. //                        array(
  3598. //                            'typeHash' => $t,
  3599. //                            'prefixHash' => $p,
  3600. //                            'assocHash' => $a,
  3601. //                        )
  3602. //                    );
  3603. //            }
  3604.         }
  3605.         $max 0;
  3606. //        $debug_data='';
  3607. //        $debug_data=[];
  3608.         foreach ($result as $res) {
  3609. //            $debug_data.=','.$res->getNumberHash();
  3610.             if (($res->getNumberHash()) > $max)
  3611.                 $max = ($res->getNumberHash());
  3612.         }
  3613. //        $count = count($result);
  3614.         $count $max;
  3615.         $count++;
  3616.         return ($count);
  3617. //        return($entityListByTypeHash[$t]);
  3618. //        return($debug_data);
  3619. //        return(json_encode($debug_data));
  3620.     }
  3621.     //task related
  3622.     public static function AddCashFlowProjection($em$id 0$data = [])
  3623.     {
  3624.         $sampleData = [
  3625.             'planningItemId' => 0,
  3626.             'fundRequisitionId' => 0,
  3627.             'concernedPersonId' => 0,
  3628.             'type' => 1//exp
  3629.             'subType' => 1//1== khoroch hobe 2: ashbe
  3630.             'cashFlowType' => 1//2== RCV /in  1: Payment/out
  3631.             'creationType' => 1//auto 2: doc 3 :manual
  3632.             'entity' => 0,
  3633.             'entityId' => 0,
  3634.             'checkId' => 0,
  3635.             'entityDocHash' => '',
  3636.             'amountType' => 1// 1:Fund/Money 2:Material 3: Bank Guarantee 4: Credit
  3637.             'cashFlowAmount' => 0,
  3638.             'expAstAmount' => 0,
  3639.             'accumulatedCashFlowAmount' => 0,
  3640.             'accumulatedCashFlowBalance' => 0,
  3641.             'accumulatedExpAstAmount' => 0,
  3642.             'relevantExpAstHeadId' => 0,
  3643.             'balancingHeadId' => 0,
  3644.             'cashFlowHeadId' => 0,
  3645.             'cashFlowHeadType' => 1,
  3646.             'relevantProductIds' => [],
  3647.             'reminderDateTs' => 0,
  3648.             'cashFlowDateTs' => 0,
  3649.             'expireDateTs' => 0,
  3650.             'expAstRealizationDateTs' => 0,
  3651.         ];
  3652.         foreach ($sampleData as $index => $value) {
  3653.             if (!isset($data[$index]))
  3654.                 $data[$index] = $value;
  3655.         }
  3656.         if (!isset($data['planningItemId'])) $data['planningItemId'] = 0;
  3657.         if (!isset($data['fundRequisitionId'])) $data['fundRequisitionId'] = 0;
  3658.         if ($id != 0)
  3659.             $cf $em
  3660.                 ->getRepository('ApplicationBundle\\Entity\\CashFlowProjection')
  3661.                 ->findOneBy(
  3662.                     array(
  3663.                         'id' => $id,
  3664.                     )
  3665.                 );
  3666.         else if ($data['planningItemId'] != 0)
  3667.             $cf $em
  3668.                 ->getRepository('ApplicationBundle\\Entity\\CashFlowProjection')
  3669.                 ->findOneBy(
  3670.                     array(
  3671.                         'planningItemId' => $data['planningItemId'],
  3672.                     )
  3673.                 );
  3674.         else if ($data['fundRequisitionId'] != 0)
  3675.             $cf $em
  3676.                 ->getRepository('ApplicationBundle\\Entity\\CashFlowProjection')
  3677.                 ->findOneBy(
  3678.                     array(
  3679.                         'fundRequisitionId' => $data['fundRequisitionId'],
  3680.                     )
  3681.                 );
  3682.         else
  3683.             $cf = new CashFlowProjection();
  3684.         $cf->setPlanningItemId(isset($data['planningItemId']) ? $data['planningItemId'] : 0);
  3685.         $cf->setFundRequisitionId(isset($data['fundRequisitionId']) ? $data['fundRequisitionId'] : 0);
  3686.         $cf->setCheckId(isset($data['checkId']) ? $data['checkId'] : 0);
  3687.         $cf->setType(isset($data['type']) ? $data['type'] : 1);
  3688.         $cf->setSubType(isset($data['subType']) ? $data['subType'] : 1);
  3689.         $cf->setCashFlowType(isset($data['cashFlowType']) ? $data['cashFlowType'] : 1);
  3690.         $cf->setCreationType(isset($data['creationType']) ? $data['creationType'] : 1);
  3691.         $cf->setEntity($data['entity']);
  3692.         $cf->setEntityId($data['entityId']);
  3693.         $cf->setCheckId($data['checkId']);
  3694.         $cf->setEntityDocHash($data['entityDocHash']);
  3695.         $cf->setConcernedPersonId(isset($data['concernedPersonId']) ? $data['concernedPersonId'] : 0);
  3696.         $cf->setAmountType(isset($data['amountType']) ? $data['amountType'] : 1);
  3697.         $cf->setcashFlowAmount(isset($data['cashFlowAmount']) ? $data['cashFlowAmount'] : 0);
  3698.         $cf->setAccumulatedCashFlowAmount(isset($data['accumulatedCashFlowAmount']) ? $data['accumulatedCashFlowAmount'] : 0);
  3699.         $cf->setAccumulatedCashFlowBalance(isset($data['accumulatedCashFlowBalance']) ? $data['accumulatedCashFlowBalance'] : 0);
  3700.         $cf->setAccumulatedExpAstAmount(isset($data['accumulatedExpAstAmount']) ? $data['accumulatedExpAstAmount'] : 0);
  3701.         $cf->setExpAstAmount(isset($data['expAstAmount']) ? $data['expAstAmount'] : 0);
  3702.         $cf->setRelevantExpAstHeadId(isset($data['relevantExpAstHeadId']) ? $data['relevantExpAstHeadId'] : 0);
  3703.         $cf->setRelevantExpAstHeadId(isset($data['relevantExpAstHeadId']) ? $data['relevantExpAstHeadId'] : 0);
  3704.         $cf->setBalancingHeadId(isset($data['balancingHeadId']) ? $data['balancingHeadId'] : 0);
  3705.         if ($data['cashFlowHeadId'] != '_UNCHANGED_')
  3706.             $cf->setCashFlowHeadId(isset($data['cashFlowHeadId']) ? $data['cashFlowHeadId'] : 0);
  3707.         $cf->setCashFlowHeadType(isset($data['cashFlowHeadType']) ? $data['cashFlowHeadType'] : 1);
  3708.         $cf->setRelevantProductIds(isset($data['relevantProductIds']) ? json_encode($data['relevantProductIds']) : '[]');
  3709.         $cf->setCashFlowDateTs(isset($data['cashFlowDateTs']) ? $data['cashFlowDateTs'] : 0);
  3710.         $cf->setReminderDateTs(isset($data['reminderDateTs']) ? $data['reminderDateTs'] : 0);
  3711.         $cf->setExpireDateTs(isset($data['expireDateTs']) ? $data['expireDateTs'] : 0);
  3712.         $cf->setExpAstRealizationDateTs(isset($data['expAstRealizationDateTs']) ? $data['expAstRealizationDateTs'] : 0);
  3713.         $em->persist($cf);
  3714.         $em->flush();
  3715.         return $cf;
  3716.     }
  3717.     //task related end
  3718.     public static function getDocumentsByUserId($em$user_id 0)
  3719.     {
  3720.         $data = [];
  3721.         $differentDocHashGetMethodByEntityId = [
  3722.             '54' => 'getName'
  3723.         ];
  3724. //1st get login ids basedon user id
  3725.         $new_cc $em
  3726.             ->getRepository('ApplicationBundle\\Entity\\SysLoginLog')
  3727.             ->findBy(
  3728.                 array(
  3729.                     'userId' => $user_id,
  3730.                 )
  3731.             );
  3732.         $skipEntities = [5476];
  3733.         if (!empty($new_cc)) {
  3734.             $loginIdList = [];
  3735.             foreach ($new_cc as $dt) {
  3736.                 $loginIdList[] = $dt->getLoginId();
  3737.             }
  3738.             if (!empty($loginIdList)) {
  3739.                 $documents GeneralConstant::$Entity_list;
  3740.                 $documentDetails GeneralConstant::$Entity_list_details;
  3741.                 $documentIdMethodList GeneralConstant::$Entity_id_get_method_list;
  3742. //                foreach ($documents as $key => $document) {
  3743. //
  3744. //                    if (in_array($key, $skipEntities))
  3745. //                        continue;
  3746. ////                    if ($key>70)
  3747. ////                        continue;
  3748. ////                    if($em->getRepository('ApplicationBundle\\Entity\\' . $document)) {
  3749. //                    if (!$em->getMetadataFactory()->isTransient('ApplicationBundle:' . $document)) {
  3750. //                        $query = $em
  3751. //                            ->getRepository('ApplicationBundle\\Entity\\' . $document)
  3752. //                            ->findBy(
  3753. //                                array(
  3754. //                                    'createdLoginId' => $loginIdList,
  3755. //                                ),
  3756. //                                array(
  3757. //                                    'createdAt' => 'DESC'
  3758. //                                )
  3759. //                            );
  3760. //                        if ($query) {
  3761. //                            foreach ($query as $q) {
  3762. //                                $doc = array(
  3763. //                                    'documentHash' => isset($differentDocHashGetMethodByEntityId[$key]) ? $q->{$differentDocHashGetMethodByEntityId[$key]}() : $q->getDocumentHash(),
  3764. //                                    'lastModifiedDate' => $q->getlastModifiedDate(),
  3765. //                                    'createdAt' => $q->getCreatedAt(),
  3766. //                                    'approved' => method_exists($q, 'getApproved') ? $q->getApproved() : 1,
  3767. //                                    'status' => GeneralConstant::$approvalAction[method_exists($q, 'getApproved') ? $q->getApproved() : 1],
  3768. //                                    'documentType' => $documentDetails[$key]['entity_alias'],
  3769. //                                    'documentViewPathName' => isset($documentDetails[$key]['entity_view_route_path_name']) ? $documentDetails[$key]['entity_view_route_path_name']
  3770. //                                        : (isset($documentDetails[$key]['entity_view_route_path_name']) ? $documentDetails[$key]['entity_view_route_path_name'] : 'dashboard'),
  3771. //                                    'documentId' => $q->{$documentIdMethodList[$key]}(),
  3772. //                                    'documentTypeId' => $key
  3773. //                                );
  3774. //                                $data[] = $doc;
  3775. //                            }
  3776. //                        }
  3777. //                    }
  3778. //                }
  3779.                 foreach ($documents as $key => $document) {
  3780.                     if (in_array($key$skipEntities)) {
  3781.                         continue;
  3782.                     }
  3783.                     $entityClass 'ApplicationBundle\\Entity\\' $document;
  3784.                     // ðŸš¨ Skip if entity class does not exist
  3785.                     if (!class_exists($entityClass)) {
  3786.                         continue;
  3787.                     }
  3788.                     // ðŸš¨ Skip if not a Doctrine entity
  3789.                     if ($em->getMetadataFactory()->isTransient($entityClass)) {
  3790.                         continue;
  3791.                     }
  3792.                     $query $em
  3793.                         ->getRepository($entityClass)
  3794.                         ->findBy(
  3795.                             ['createdLoginId' => $loginIdList],
  3796.                             ['createdAt' => 'DESC']
  3797.                         );
  3798.                     if ($query) {
  3799.                         foreach ($query as $q) {
  3800.                             $doc = [
  3801.                                 'documentHash' => isset($differentDocHashGetMethodByEntityId[$key])
  3802.                                     ? $q->{$differentDocHashGetMethodByEntityId[$key]}()
  3803.                                     : $q->getDocumentHash(),
  3804.                                 'lastModifiedDate' => $q->getlastModifiedDate(),
  3805.                                 'createdAt' => $q->getCreatedAt(),
  3806.                                 'approved' => method_exists($q'getApproved') ? $q->getApproved() : 1,
  3807.                                 'status' => GeneralConstant::$approvalAction[method_exists($q'getApproved') ? $q->getApproved() : 1],
  3808.                                 'documentType' => $documentDetails[$key]['entity_alias'],
  3809.                                 'documentViewPathName' => $documentDetails[$key]['entity_view_route_path_name'] ?? 'dashboard',
  3810.                                 'documentId' => $q->{$documentIdMethodList[$key]}(),
  3811.                                 'documentTypeId' => $key
  3812.                             ];
  3813.                             $data[] = $doc;
  3814.                         }
  3815.                     }
  3816.                 }
  3817.             }
  3818.         }
  3819.         return $data;
  3820.     }
  3821.     public static function getDocumentsByUserIdForApp($em$user_id 0$includeAbsoluteUrl 0$absoluteUrlList = [])
  3822.     {
  3823.         $data = [];
  3824.         $grouped_approval_list = [];
  3825.         $differentDocHashGetMethodByEntityId = [
  3826.             '54' => 'getName'
  3827.         ];
  3828. //1st get login ids basedon user id
  3829.         $new_cc $em
  3830.             ->getRepository('ApplicationBundle\\Entity\\SysLoginLog')
  3831.             ->findBy(
  3832.                 array(
  3833.                     'userId' => $user_id,
  3834.                 )
  3835.             );
  3836.         $skipEntities = [5476];
  3837.         if (!empty($new_cc)) {
  3838.             $loginIdList = [];
  3839.             foreach ($new_cc as $dt) {
  3840.                 $loginIdList[] = $dt->getLoginId();
  3841.             }
  3842.             if (!empty($loginIdList)) {
  3843.                 $documents GeneralConstant::$Entity_list;
  3844.                 $documentDetails GeneralConstant::$Entity_list_details;
  3845.                 $documentIdMethodList GeneralConstant::$Entity_id_get_method_list;
  3846.                 $amount_methods ApprovalConstant::$Entity_amount_method;
  3847.                 foreach ($documents as $key => $document) {
  3848.                     if (in_array($key$skipEntities))
  3849.                         continue;
  3850. //                    if($em->getRepository('ApplicationBundle\\Entity\\' . $document)) {
  3851.                     if (!$em->getMetadataFactory()->isTransient('ApplicationBundle\\Entity\\' $document)) {
  3852.                         $query $em
  3853.                             ->getRepository('ApplicationBundle\\Entity\\' $document)
  3854.                             ->findBy(
  3855.                                 array(
  3856.                                     'createdLoginId' => $loginIdList,
  3857.                                 ),
  3858.                                 array(
  3859.                                     'createdAt' => 'DESC'
  3860.                                 )
  3861.                             );
  3862.                         if ($query) {
  3863.                             foreach ($query as $q) {
  3864.                                 $doc = array(
  3865.                                     'documentHash' => isset($differentDocHashGetMethodByEntityId[$key]) ? $q->{$differentDocHashGetMethodByEntityId[$key]}() : $q->getDocumentHash(),
  3866. //                                    'lastModifiedDate' => $q->getlastModifiedDate(),
  3867.                                     'createdAt' => $q->getCreatedAt()->format('U'),
  3868.                                     'approved' => method_exists($q'getApproved') ? $q->getApproved() : 1,
  3869.                                     'status' => GeneralConstant::$approvalAction[method_exists($q'getApproved') ? $q->getApproved() : 1],
  3870.                                     'documentType' => $documentDetails[$key]['entity_alias'],
  3871.                                     'documentPrintPathName' => '',
  3872.                                     'documentViewPathName' => isset($documentDetails[$key]['entity_view_route_path_name']) ? $documentDetails[$key]['entity_view_route_path_name']
  3873.                                         : (isset($documentDetails[$key]['entity_view_route_path_name']) ? $documentDetails[$key]['entity_view_route_path_name'] : 'dashboard'),
  3874. //                                    'documentId' => $q->{$documentIdMethodList[$key]}(),
  3875.                                     'documentTypeId' => $key,
  3876.                                     'entity' => $key,
  3877.                                     'entityId' => $q->{$documentIdMethodList[$key]}(),
  3878.                                     'summary' => GeneralConstant::$documentSummaryList,
  3879.                                     "relatedDoc" => "",
  3880.                                     "documentImage" => isset(GeneralConstant::$Entity_list_details[$key]['image_url']) ?
  3881.                                         GeneralConstant::$Entity_list_details[$key]['image_url'] : 'https://ibb.co.com/rfk8x7m4',
  3882.                                 );
  3883.                                 if ($includeAbsoluteUrl == && isset($absoluteUrlList[$key])) {
  3884.                                     $doc['documentPrintPathName'] = $absoluteUrlList[$key] . '/' $q->{$documentIdMethodList[$key]}();
  3885.                                 }
  3886.                                 if (isset($amount_methods[$key])) {
  3887.                                     $doc['amount'] = $q->{$amount_methods[$key]}();
  3888.                                 } else
  3889.                                     $doc['amount'] = '';
  3890.                                 $data[] = $doc;
  3891.                                 if (!isset($grouped_approval_list[$key])) {
  3892.                                     $applicableEntities[] = array(
  3893.                                         'id' => $key,
  3894.                                         'alias' => GeneralConstant::$Entity_list_details[$key]['entity_alias'],
  3895.                                         'imageUrl' => isset(GeneralConstant::$Entity_list_details[$key]['image_url']) ?
  3896.                                             GeneralConstant::$Entity_list_details[$key]['image_url'] : 'https://ibb.co.com/4RBXD5pt',
  3897.                                         'documentImage' => isset(GeneralConstant::$Entity_list_details[$key]['image_url']) ?
  3898.                                             GeneralConstant::$Entity_list_details[$key]['image_url'] : 'https://ibb.co.com/rfk8x7m4'
  3899.                                     );
  3900.                                     $grouped_approval_list[$key] = array();
  3901.                                 }
  3902.                             }
  3903.                         }
  3904.                     }
  3905.                 }
  3906.             }
  3907.         }
  3908.         return array(
  3909.             'documentData' => $data,
  3910.             "applicable_entities" => $applicableEntities,
  3911.         );
  3912.     }
  3913.     public static function getLoginIdsByUserId($em$user_id 0)
  3914.     {
  3915.         $data = [];
  3916. //1st get login ids based on user id
  3917.         $new_cc $em
  3918.             ->getRepository('ApplicationBundle\\Entity\\SysLoginLog')
  3919.             ->findBy(
  3920.                 array(
  3921.                     'userId' => $user_id,
  3922.                 )
  3923.             );
  3924.         $loginIdList = [];
  3925.         if (!empty($new_cc)) {
  3926.             foreach ($new_cc as $dt) {
  3927.                 $loginIdList[] = $dt->getLoginId();
  3928.             }
  3929.         }
  3930.         return $loginIdList;
  3931.     }
  3932.     public static function GetSessionDataFromToken($em$token ''$isEntityToken 1$clearExpired 1$updateValidity 1)
  3933.     {
  3934.         $isEntityToken 1;
  3935.         $sessionData = [];
  3936.         if ($token != '') {
  3937.             $new_cc $em
  3938. //                ->getRepository($isEntityToken == 1 ? 'CompanyGroupBundle\\Entity\\EntityTokenStorage' : 'ApplicationBundle:TokenStorage')
  3939.                 ->getRepository('CompanyGroupBundle\\Entity\\EntityTokenStorage')//enforced
  3940.                 ->findOneBy(
  3941.                     array(
  3942.                         'token' => $token,
  3943.                     )
  3944.                 );
  3945.             if ($new_cc) {
  3946.                 $sessionData json_decode($new_cc->getSessionData(), true);
  3947.                 if ($sessionData == null)
  3948.                     $sessionData = [];
  3949.                 if ($updateValidity == 1) {
  3950. //                    $expire_time = $new_cc->getExpiresAt();
  3951.                     $expire_time = new \DateTime();
  3952.                     $expire_time->modify('+24 hour');
  3953.                     $new_cc->setExpiresAt($expire_time);
  3954.                     $em->flush();
  3955.                 }
  3956.                 //$new_cc->setFireBaseToken($expire_time->format(DATE_RFC7231));
  3957.                 $em->flush();
  3958.             }
  3959.         }
  3960.         if ($clearExpired == 1) {
  3961.             $get_kids_sql "DELETE FROM " . ($isEntityToken == 'entity_token_storage' 'token_storage');
  3962.             $get_kids_sql .= " WHERE (  perpetual !=1  ) and expires_at < NOW(); ";
  3963.             $stmt $em->getConnection()->executeStatement($get_kids_sql);
  3964.         }
  3965.         $loginIdList = [];
  3966.         return array(
  3967.             'sessionData' => $sessionData,
  3968.         );
  3969.     }
  3970.     public static function UpdateSessionDataFromToken($em$token ''$isEntityToken 1$clearExpired 1$updateValidity 1)
  3971.     {
  3972.         $isEntityToken 1;
  3973.         $sessionData = [];
  3974.         if ($token != '') {
  3975.             $new_cc $em
  3976. //                ->getRepository($isEntityToken == 1 ? 'CompanyGroupBundle\\Entity\\EntityTokenStorage' : 'ApplicationBundle:TokenStorage')
  3977.                 ->getRepository('CompanyGroupBundle\\Entity\\EntityTokenStorage')//enforced
  3978.                 ->findOneBy(
  3979.                     array(
  3980.                         'token' => $token,
  3981.                     )
  3982.                 );
  3983.             if ($new_cc) {
  3984.                 $sessionData json_decode($new_cc->getSessionData(), true);
  3985.                 if ($sessionData == null)
  3986.                     $sessionData = [];
  3987.                 if ($updateValidity == 1) {
  3988.                     $expire_time = new \DateTime();
  3989.                     $expire_time->modify('+24 hour');
  3990.                     $new_cc->setExpiresAt($expire_time);
  3991.                     $em->flush();
  3992.                 }
  3993.                 //$new_cc->setFireBaseToken('U'.$expire_time->format(DATE_RFC7231));
  3994.                 $em->flush();
  3995.             }
  3996.         }
  3997.         if ($clearExpired == 1) {
  3998.             $get_kids_sql "DELETE FROM " . ($isEntityToken == 'entity_token_storage' 'token_storage');
  3999.             $get_kids_sql .= " WHERE (  perpetual !=1   ) and expires_at < NOW(); ";
  4000.             $stmt $em->getConnection()->executeStatement($get_kids_sql);
  4001.         }
  4002.         $loginIdList = [];
  4003.         return array(
  4004.             'sessionData' => $sessionData,
  4005.         );
  4006.     }
  4007.     public static function UpdateCompanyListInSession($em$applicantId ''$isEntityToken 1$clearExpired 1$updateValidity 1$newCompany = [])
  4008.     {
  4009.         $sessionData = [];
  4010. //        return [];
  4011.         if ($applicantId != '') {
  4012.             $new_cc $em;
  4013.             $new_ccs $em
  4014.                 ->getRepository('CompanyGroupBundle\\Entity\\EntityTokenStorage')
  4015.                 ->findBy(
  4016.                     array(
  4017.                         'userId' => $applicantId,
  4018.                     )
  4019.                 );
  4020.             foreach ($new_ccs as $new_cc) {
  4021.                 $currDt = new \DateTime();
  4022.                 if ($new_cc) {
  4023.                     $sessionData json_decode($new_cc->getSessionData(), true);
  4024.                     if ($sessionData == null$sessionData = [
  4025.                         'userAccessList' => []
  4026.                     ];
  4027.                     if ($new_cc->getExpiresAt() <= $currDt) {
  4028.                         $em->remove($new_cc);
  4029.                     } else {
  4030.                         $sessionData json_decode($new_cc->getSessionData(), true);
  4031.                         if ($sessionData == null$sessionData = [
  4032.                             'userAccessList' => []
  4033.                         ];
  4034.                         $sessionData['userAccessList'][] = $newCompany;
  4035.                         if ($updateValidity == 1) {
  4036.                             $expire_time = new \DateTime();
  4037.                             $expire_time->modify('+24 hour');
  4038.                             $new_cc->setExpiresAt($expire_time);
  4039.                             $new_cc->setSessionData(json_encode($sessionData));
  4040.                             $em->persist($new_cc);
  4041.                             //$new_cc->setFireBaseToken('C'.$expire_time->format(DATE_RFC7231));
  4042.                             $em->flush();
  4043.                         }
  4044.                     }
  4045.                 }
  4046.             }
  4047.         }
  4048.     }
  4049. //    public static function UpdateCompanyListInSession($em, $applicantId = '', $isEntityToken = 1, $clearExpired = 1, $updateValidity = 1,$newCompany)
  4050. //    {
  4051. //        $sessionData = [];
  4052. //
  4053. //        if ($applicantId != '') {
  4054. //            $new_cc = $em
  4055. //                ->getRepository('CompanyGroupBundle\\Entity\\EntityTokenStorage')
  4056. //                ->findBy(
  4057. //                    array(
  4058. //                        'userId' => $applicantId,
  4059. //                    )
  4060. //                );
  4061. //
  4062. //            if ($new_cc) {
  4063. //                $sessionData = json_decode($new_cc->getSessionData(), true);
  4064. //                if($sessionData == null)$sessionData=[
  4065. //                    'userAccessList'=>[]
  4066. //                ];
  4067. //
  4068. //
  4069. //                    $sessionData['userAccessList'][] = $newCompany;
  4070. //
  4071. //
  4072. //                if ($updateValidity == 1) {
  4073. //                    $expire_time = $new_cc->getExpiresAt();
  4074. //                    $expire_time = $expire_time->modify('+24 hour');
  4075. //                    $new_cc->setExpiresAt($expire_time);
  4076. //                    $new_cc->getSessionData($sessionData);
  4077. //                    $em->persist();
  4078. //                    $em->flush();
  4079. //                }
  4080. //            }
  4081. //        }
  4082. //        return array(
  4083. //            'sessionData' => $sessionData,
  4084. //        );
  4085. //    }
  4086.     public static function DeleteToken($em$token ''$isEntityToken 1$clearExpired 1$updateValidity 1)
  4087.     {
  4088.         $isEntityToken 1;
  4089.         $sessionData = [];
  4090.         if ($token != '') {
  4091.             $new_cc $em
  4092. //                ->getRepository($isEntityToken == 1 ? 'CompanyGroupBundle\\Entity\\EntityTokenStorage' : 'ApplicationBundle:TokenStorage')
  4093.                 ->getRepository('CompanyGroupBundle\\Entity\\EntityTokenStorage')
  4094.                 ->findOneBy(
  4095.                     array(
  4096.                         'token' => $token,
  4097.                     )
  4098.                 );
  4099.             if ($new_cc) {
  4100.                 $em->remove($new_cc);
  4101.                 $em->flush();
  4102.             }
  4103.         }
  4104.         if ($clearExpired == 1) {
  4105.             $get_kids_sql "DELETE FROM " . ($isEntityToken == 'entity_token_storage' 'token_storage');
  4106.             $get_kids_sql .= " WHERE ( perpetual !=1  ) and expires_at < NOW(); ";
  4107.             $stmt $em->getConnection()->executeStatement($get_kids_sql);
  4108.         }
  4109.         $loginIdList = [];
  4110.         return array(
  4111.             'sessionData' => $sessionData,
  4112.         );
  4113.     }
  4114.     public static function CreateTokenFromSessionData($em$sessionData = [], $isEntityToken 1$clearExpired 1$updateValidity 1$updateOnly 0)
  4115.     {
  4116. //        $sessionData=[];
  4117.         $token '';
  4118.         $isEntityToken 1;
  4119.         if ($sessionData != []) {
  4120.             if ($updateOnly == 0) {
  4121. //                if ($isEntityToken == 1)
  4122.                 $new_cc = new EntityTokenStorage();
  4123. //                else
  4124. //                    $new_cc = new TokenStorage();
  4125.                 $token Generic::simpleRandString();
  4126.                 $token $token '' time();
  4127.                 $sessionData['token'] = $token;
  4128.                 $new_cc->setSessionData(json_encode($sessionData));
  4129.                 $new_cc->setToken($token);
  4130.                 $new_cc->setFireBaseToken(isset($sessionData['firebaseToken']) ? $sessionData['firebaseToken'] : '');
  4131.                 $new_cc->setUserId(isset($sessionData['userId']) ? $sessionData['userId'] : null);
  4132.                 $new_cc->setUserType(isset($sessionData['userType']) ? $sessionData['userType'] : 0);
  4133.                 $em->persist($new_cc);
  4134.                 $em->flush();
  4135.                 if ($new_cc) {
  4136.                     $sessionData json_decode($new_cc->getSessionData(), true);
  4137.                     if ($sessionData == null)
  4138.                         $sessionData = [];
  4139.                     if ($updateValidity == 1) {
  4140.                         $expire_time = new \DateTime();
  4141.                         $expire_time $expire_time->modify('+24 hour');
  4142.                         $new_cc->setExpiresAt($expire_time);
  4143.                         $em->flush();
  4144.                     }
  4145.                 }
  4146.             } else {
  4147. //                if ($isEntityToken == 1)
  4148. //                {
  4149.                 $new_cc $em
  4150.                     ->getRepository('CompanyGroupBundle\\Entity\\EntityTokenStorage')
  4151.                     ->findOneBy(
  4152.                         array(
  4153.                             'token' => $sessionData['token'],
  4154.                         )
  4155.                     );
  4156. //
  4157. //                    if(!$new_cc)
  4158. //                        $new_cc = new EntityTokenStorage();
  4159. //                }
  4160. //
  4161. //                else
  4162. //                {
  4163. //                    $new_cc = $em
  4164. //                        ->getRepository('ApplicationBundle\\Entity\\TokenStorage')
  4165. //                        ->findOneBy(
  4166. //                            array(
  4167. //                                'token' => $sessionData['token'],
  4168. //                            )
  4169. //                        );
  4170. //
  4171. ////                    if(!$new_cc)
  4172. ////                    $new_cc = new TokenStorage();
  4173. //
  4174. //                }
  4175.                 if ($new_cc) {
  4176.                     $token $sessionData['token'];
  4177.                     $new_cc->setSessionData(json_encode($sessionData));
  4178.                     $new_cc->setFireBaseToken(isset($sessionData['firebaseToken']) ? $sessionData['firebaseToken'] : '');
  4179.                     $new_cc->setUserId(isset($sessionData['userId']) ? $sessionData['userId'] : null);
  4180.                     $new_cc->setUserType(isset($sessionData['userType']) ? $sessionData['userType'] : 0);
  4181.                     $new_cc->setToken($token);
  4182.                     if ($updateValidity == 1) {
  4183.                         $expire_time = new \DateTime();
  4184.                         $expire_time $expire_time->modify('+24 hour');
  4185.                         $new_cc->setExpiresAt($expire_time);
  4186.                         $em->flush();
  4187.                     }
  4188. //                    $em->persist($new_cc);
  4189.                     $em->flush();
  4190.                 }
  4191.             }
  4192.         }
  4193.         if ($clearExpired == 1) {
  4194.             $get_kids_sql "DELETE FROM " . ($isEntityToken == 'entity_token_storage' 'token_storage');
  4195.             $get_kids_sql .= " WHERE ( perpetual !=1 ) and expires_at < NOW(); ";
  4196.             $stmt $em->getConnection()->executeStatement($get_kids_sql);
  4197.         }
  4198.         $loginIdList = [];
  4199.         return array(
  4200.             'token' => $token,
  4201.             'sessionData' => $sessionData,
  4202.         );
  4203.     }
  4204.     public static function addEntityUserLoginLog($em$userId$applicantId$isApplicant$ip$PositionId 0$deviceId ''$oAuthToken ''$oAuthType ''$locale 'en'$firebaseToken '')
  4205.     {
  4206.         $loginLog = new EntityLoginLog();
  4207.         $loginLog->setLogStatus(true);
  4208.         $loginLog->setLoginIp($ip);
  4209.         $loginLog->setLogTime(new \DateTime('now'));
  4210.         $loginLog->setUserId($userId);
  4211.         $loginLog->setApplicantId($applicantId);
  4212.         $loginLog->setisApplicant($isApplicant);
  4213.         $loginLog->setPositionId($PositionId);
  4214.         $loginLog->setDeviceId($deviceId);
  4215.         $loginLog->setLocale($locale);
  4216.         $loginLog->setFirebaseToken($firebaseToken);
  4217.         $loginLog->setDeviceId($deviceId);
  4218.         $loginLog->setOAuthToken($oAuthToken);
  4219.         $loginLog->setOAuthType($oAuthType);
  4220.         $em->persist($loginLog);
  4221.         $em->flush();
  4222.         return $loginLog->getLoginId();
  4223.     }
  4224.     public static function refreshTransactions($em$start_id 0)
  4225.     {
  4226.         $query "UPDATE acc_accounts_head SET current_balance=opening_balance,current_balance_reconciled=opening_balance WHERE 1;
  4227. UPDATE acc_transactions SET ledger_hit=0 WHERE 1;
  4228. truncate acc_closing_balance;
  4229. truncate acc_actual_closing_balance;";
  4230.         $stmt $em->getConnection()->fetchAllAssociative($query);
  4231.         System::UpdatePostDatedTransaction($em);
  4232. //        $distinct_parent_ids=$stmt;s
  4233.     }
  4234.     public static function clearAccRelatedstuffs($em$start_id 0)
  4235.     {
  4236.         $query "UPDATE acc_accounts_head SET current_balance=opening_balance,current_balance_reconciled=opening_balance WHERE 1;
  4237.             UPDATE acc_transactions SET ledger_hit=0 WHERE 1;
  4238.             truncate acc_closing_balance;
  4239.             truncate acc_actual_closing_balance;";
  4240.         $stmt $em->getConnection()->fetchAllAssociative($query);
  4241. //        System::UpdatePostDatedTransaction($em);
  4242. //        $distinct_parent_ids=$stmt;s
  4243.     }
  4244.     public static function refreshClosing($em$start_id 0)
  4245.     {
  4246.         // step: 1 lets  set all heads' balance as their opening balance
  4247.         $query "UPDATE  acc_accounts_head set current_balance=opening_balance, current_balance_reconciled=opening_balance where 1";
  4248.         $stmt $em->getConnection()->executeStatement($query);
  4249. //        $distinct_parent_ids=$stmt;
  4250. //        $em->flush();
  4251.         // step:2  set ledger hit on all vouchers after the fiscal closing to 0
  4252.         $new_cc $em
  4253.             ->getRepository('ApplicationBundle\\Entity\\AccSettings')
  4254.             ->findOneBy(
  4255.                 array(
  4256.                     'name' => 'accounting_year_start',
  4257.                 )
  4258.             );
  4259.         $query "UPDATE  acc_transactions set ledger_hit=0  ";
  4260.         $date_start "";
  4261.         $date_start_str "";
  4262.         if ($new_cc) {
  4263.             $date_start = new \DateTime($new_cc->getData());
  4264.             $date_start_str $date_start->format('Y-m-d');
  4265.         }
  4266.         if ($new_cc)
  4267.             $query .= " where transaction_date>= '" $date_start_str " 00:00:00' ";
  4268.         $stmt $em->getConnection()->executeStatement($query);
  4269.         //now step:3 clear all closing after the fiscal year start
  4270.         $query "DELETE From  acc_closing_balance ";
  4271.         if ($new_cc)
  4272.             $query .= " where date>= '" $date_start_str " 00:00:00' ";
  4273.         $stmt $em->getConnection()->executeStatement($query);
  4274.         $query "DELETE From  acc_actual_closing_balance ";
  4275.         if ($new_cc)
  4276.             $query .= " where date>= '" $date_start_str " 00:00:00' ";
  4277.         $stmt $em->getConnection()->executeStatement($query);
  4278. //        System::UpdatePostDatedTransaction($em);
  4279. //        $distinct_parent_ids=$stmt;
  4280.     }
  4281.     public static function setOpening($em$id$amount 0$headNature ''$year_start)
  4282.     {
  4283.         $head $em->getRepository('ApplicationBundle\\Entity\\AccAccountsHead')->findOneBy(
  4284.             array(
  4285.                 'accountsHeadId' => $id
  4286.             )
  4287.         );
  4288.         if ($headNature == '' || $headNature == $head->getHeadNature()) {
  4289.             $head->setOpeningBalance($head->getOpeningBalance() * + ($amount));
  4290.         } else {
  4291.             $head->setOpeningBalance($head->getOpeningBalance() * - ($amount));
  4292. //            Accounts::SetClosingBalance($em,$id,$amount,$head->getHeadNature(),$year_start,0);
  4293. //            Accounts::SetActualClosingBalance($em,$id,$amount,$head->getHeadNature(),$year_start,0);
  4294.         }
  4295.         $em->flush();
  4296.         if ($head->getParentId() != 0) {
  4297.             self::setOpening($em$head->getParentId(), $head->getOpeningBalance(), $head->getHeadNature(), $year_start);
  4298.         }
  4299.         return 1;
  4300.     }
  4301.     public static function prepareDatabaseForCompany($em)
  4302.     {
  4303.         //1st clear the documents
  4304.         $query "  TRUNCATE acc_actual_closing_balance;
  4305.                     TRUNCATE acc_check;
  4306.                     TRUNCATE acc_closing_balance;
  4307.                     TRUNCATE acc_transactions;
  4308.                     TRUNCATE acc_transaction_details;
  4309.                     TRUNCATE approval;
  4310.                     TRUNCATE delivery_confirmation;
  4311.                     TRUNCATE delivery_order;
  4312.                     TRUNCATE delivery_order_item;
  4313.                     TRUNCATE delivery_receipt;
  4314.                     TRUNCATE delivery_receipt_item;
  4315.                     TRUNCATE expense_invoice;
  4316.                     TRUNCATE fiscal_closing;
  4317.                     TRUNCATE grn;
  4318.                     TRUNCATE grn_item;
  4319.                     TRUNCATE inventory_storage;
  4320.                     TRUNCATE inv_closing_balance;
  4321.                     TRUNCATE inv_item_transaction;
  4322.                     TRUNCATE material_inward;
  4323.                     TRUNCATE monthly_summary;
  4324.                     TRUNCATE payment_log;
  4325.                     TRUNCATE payment_schedule;
  4326.                     TRUNCATE purchase_invoice;
  4327.                     TRUNCATE purchase_invoice_item;
  4328.                     TRUNCATE purchase_order;
  4329.                     TRUNCATE purchase_order_item;
  4330.                     TRUNCATE purchase_requisition;
  4331.                     TRUNCATE purchase_requisition_item;
  4332.                     TRUNCATE quality_control;
  4333.                     TRUNCATE receipt_check;
  4334.                     TRUNCATE receipt_log;
  4335.                     TRUNCATE sales_invoice;
  4336.                     TRUNCATE sales_invoice_item;
  4337.                     TRUNCATE sales_order;
  4338.                     TRUNCATE sales_order_item;
  4339.                     TRUNCATE signature;
  4340.                     TRUNCATE stock_requisition;
  4341.                     TRUNCATE stock_requisition_item;
  4342.                     TRUNCATE store_requisition;
  4343.                     TRUNCATE store_requisition_item;";
  4344.         $stmt $em->getConnection()->fetchAllAssociative($query);
  4345.         //1st prepare the company
  4346.         //now set the company data to 0
  4347.         $query "UPDATE company SET cash=0,sales=0,expense=0,payable=0,net_worth=0,monthly_growth=0 WHERE 1";
  4348.         $stmt $em->getConnection()->executeStatement($query);
  4349.         //now add the initial Head, cost centres and settings
  4350.         //now set opening to all head to 0;
  4351.         $query "UPDATE  acc_accounts_head set opening_balance=0 where 1;
  4352.                 UPDATE acc_clients SET client_order_amount=0,client_invoice_amount=0,client_received=0,client_due=0 WHERE 1;
  4353.                 UPDATE acc_suppliers SET supplier_paid=0,supplier_due=0 WHERE 1";
  4354.         $stmt $em->getConnection()->executeStatement($query);
  4355.     }
  4356.     public static function refreshDatabase($em)
  4357.     {
  4358.         //1st clear the documents
  4359.         $query "TRUNCATE acc_actual_closing_balance;
  4360. TRUNCATE acc_check;
  4361. TRUNCATE acc_closing_balance;
  4362. TRUNCATE acc_transactions;
  4363. TRUNCATE acc_transaction_details;
  4364. TRUNCATE approval;
  4365. TRUNCATE delivery_confirmation;
  4366. TRUNCATE delivery_order;
  4367. TRUNCATE delivery_order_item;
  4368. TRUNCATE delivery_receipt;
  4369. TRUNCATE delivery_receipt_item;
  4370. TRUNCATE expense_invoice;
  4371. TRUNCATE fiscal_closing;
  4372. TRUNCATE grn;
  4373. TRUNCATE grn_item;
  4374. TRUNCATE inventory_storage;
  4375. TRUNCATE inv_closing_balance;
  4376. TRUNCATE inv_item_transaction;
  4377. TRUNCATE material_inward;
  4378. TRUNCATE monthly_summary;
  4379. TRUNCATE payment_log;
  4380. TRUNCATE payment_schedule;
  4381. TRUNCATE purchase_invoice;
  4382. TRUNCATE purchase_invoice_item;
  4383. TRUNCATE purchase_order;
  4384. TRUNCATE purchase_order_item;
  4385. TRUNCATE purchase_requisition;
  4386. TRUNCATE purchase_requisition_item;
  4387. TRUNCATE quality_control;
  4388. TRUNCATE receipt_check;
  4389. TRUNCATE receipt_log;
  4390. TRUNCATE sales_invoice;
  4391. TRUNCATE sales_invoice_item;
  4392. TRUNCATE sales_order;
  4393. TRUNCATE sales_order_item;
  4394. TRUNCATE signature;
  4395. TRUNCATE stock_requisition;
  4396. TRUNCATE stock_requisition_item;
  4397. TRUNCATE store_requisition;
  4398. TRUNCATE store_requisition_item;";
  4399.         $stmt $em->getConnection()->fetchAllAssociative($query);
  4400.         //now set the company data to 0
  4401.         $query "UPDATE company SET cash=0,sales=0,expense=0,payable=0,net_worth=0,monthly_growth=0 WHERE 1";
  4402.         $stmt $em->getConnection()->executeStatement($query);
  4403.         //now set opening to all head to 0;
  4404.         $query "UPDATE  acc_accounts_head set opening_balance=0 where 1;
  4405.                 UPDATE acc_clients SET client_order_amount=0,client_invoice_amount=0,client_received=0,client_due=0 WHERE 1;
  4406.                 UPDATE acc_suppliers SET supplier_paid=0,supplier_due=0 WHERE 1";
  4407.         $stmt $em->getConnection()->executeStatement($query);
  4408.     }
  4409.     public static function initiateAdminUser($em$freshFlag 1$userName 'admin'$name 'System'$email "admin"$encodedPassword ""$appIds = [], $companyIds = [])
  4410.     {
  4411.         //1st clear the admin
  4412.         if ($freshFlag == 1) {
  4413.             $query "DELETE FROM sys_user WHERE user_type=1";
  4414.             $stmt $em->getConnection()->executeStatement($query);
  4415.         }
  4416.         //now set admin with pass username admin;
  4417.         $query "INSERT INTO sys_user (user_id, name, email, password, salt, user_type, position_ids, supervisor_id, company_id, status, last_edit_login_id, last_mongolog_id, created_at, updated_at, image) VALUES
  4418. (1, 'System', 'admin', '6526eaf09f043a8078b70b79334b166922857b666350a2aa4946ed7e895cf941', '128541067656c1689d9db24', 1, '[]', NULL, 1, 1, '0', '', '0000-00-00 00:00:00', NULL, '');";
  4419.         $stmt $em->getConnection()->executeStatement($query);
  4420.     }
  4421.     public static function getSummaryData($em$pending_data)
  4422.     {
  4423.         $pending_approval_list $pending_data['pending_approval_list'];
  4424.         $override_approval_list $pending_data['override_approval_list'];
  4425.         $Entity_list GeneralConstant::$Entity_list;
  4426.         $Entity_id_field_list GeneralConstant::$Entity_id_field_list;
  4427.         $Entity_amount_method_list ApprovalConstant::$Entity_amount_method;
  4428.         $Entity_party_method_list ApprovalConstant::$Entity_party_method;
  4429.         $differentDocHashGetMethodByEntityId = [
  4430.             '54' => 'getName'
  4431.         ];
  4432.         //data format=
  4433.         // {
  4434.         //     'documentAmount'=>0,
  4435.         //     'documentPendingAmount'=>0,
  4436.         //     'documentQty'=>0,
  4437.         //     'documentPartyName'=>'abc'
  4438.         // }
  4439.         //'documentHash' =>isset($differentDocHashGetMethodByEntityId[$key])?$q->{$differentDocHashGetMethodByEntityId[$key]}(): $q->getDocumentHash(),
  4440.         foreach ($pending_approval_list as $key => $dt) {
  4441.             $entity $dt['entity'];
  4442.             $entityId $dt['entityId'];
  4443.             $doc $em->getRepository('ApplicationBundle\\Entity\\' $Entity_list[$entity])
  4444.                 ->findOneBy(array(
  4445.                     $Entity_id_field_list[$entity] => $entityId
  4446.                 ));
  4447.             if ($doc) {
  4448.                 $docAmount '';
  4449.                 $docPartyName '';
  4450.                 $docPartyMethod '';
  4451.                 $docPartyId 0;
  4452.                 if (isset($Entity_amount_method_list[$entity])) {
  4453.                     $docAmount method_exists($doc$Entity_amount_method_list[$entity]) ? ($doc->{$Entity_amount_method_list[$entity]}()) : 0;
  4454.                 }
  4455.                 if (isset($Entity_party_method_list[$entity])) {
  4456.                     if ($Entity_party_method_list[$entity] != '_NONE_') {//please correct these
  4457.                         $docPartyId method_exists($doc$Entity_party_method_list[$entity]) ? ($doc->{$Entity_party_method_list[$entity]}()) : 0;
  4458.                         $docPartyMethod method_exists($doc$Entity_party_method_list[$entity]) ? $Entity_party_method_list[$entity] : 0;
  4459.                     }
  4460.                 }
  4461.                 if ($docPartyMethod != '') {
  4462.                     if ($docPartyMethod == 'getSupplierId') {
  4463.                         $party $em->getRepository('ApplicationBundle\\Entity\\AccSuppliers')
  4464.                             ->findOneBy(array(
  4465.                                 'supplierId' => $docPartyId
  4466.                             ));
  4467.                         if ($party)
  4468.                             $docPartyName $party->getSupplierName();
  4469.                     } else if ($docPartyMethod == 'getExpenseTypeId') {
  4470.                         $party $em->getRepository('ApplicationBundle\\Entity\\AccAccountsHead')
  4471.                             ->findOneBy(array(
  4472.                                 'accountsHeadId' => $docPartyId
  4473.                             ));
  4474.                         if ($party)
  4475.                             $docPartyName $party->getName();
  4476.                     } else {
  4477.                         $party $em->getRepository('ApplicationBundle\\Entity\\AccClients')
  4478.                             ->findOneBy(array(
  4479.                                 'clientId' => $docPartyId
  4480.                             ));
  4481.                         if ($party)
  4482.                             $docPartyName $party->getClientName();
  4483.                     }
  4484.                 }
  4485.                 $pending_approval_list[$key]['summaryData'] = array(
  4486.                     'documentAmount' => $docAmount,
  4487.                     'documentPartyName' => $docPartyName,
  4488.                 );
  4489.             }
  4490.         }
  4491.         foreach ($override_approval_list as $key => $dt) {
  4492.             $entity $dt['entity'];
  4493.             $entityId $dt['entityId'];
  4494.             $doc $em->getRepository('ApplicationBundle\\Entity\\' $Entity_list[$entity])
  4495.                 ->findOneBy(array(
  4496.                     $Entity_id_field_list[$entity] => $entityId
  4497.                 ));
  4498.             if ($doc) {
  4499.                 $docAmount '';
  4500.                 $docPartyName '';
  4501.                 $docPartyMethod '';
  4502.                 $docPartyId 0;
  4503.                 if (isset($Entity_amount_method_list[$entity])) {
  4504.                     $docAmount method_exists($doc$Entity_amount_method_list[$entity]) ? ($doc->{$Entity_amount_method_list[$entity]}()) : 0;
  4505.                 }
  4506.                 if ($Entity_party_method_list[$entity] != '_NONE_') {
  4507.                     $docPartyId method_exists($doc$Entity_party_method_list[$entity]) ? ($doc->{$Entity_party_method_list[$entity]}()) : 0;
  4508.                     $docPartyMethod method_exists($doc$Entity_party_method_list[$entity]) ? $Entity_party_method_list[$entity] : 0;
  4509.                 }
  4510.                 if ($docPartyMethod != '') {
  4511.                     if ($docPartyMethod == 'getSupplierId') {
  4512.                         $party $em->getRepository('ApplicationBundle\\Entity\\AccSuppliers')
  4513.                             ->findOneBy(array(
  4514.                                 'supplierId' => $docPartyId
  4515.                             ));
  4516.                         if ($party)
  4517.                             $docPartyName $party->getSupplierName();
  4518.                     } else {
  4519.                         $party $em->getRepository('ApplicationBundle\\Entity\\AccClients')
  4520.                             ->findOneBy(array(
  4521.                                 'clientId' => $docPartyId
  4522.                             ));
  4523.                         if ($party)
  4524.                             $docPartyName $party->getClientName();
  4525.                     }
  4526.                 }
  4527.                 $pending_approval_list[$key]['summaryData'] = array(
  4528.                     'documentAmount' => $docAmount,
  4529.                     'documentPartyName' => $docPartyName,
  4530.                 );
  4531.             }
  4532.         }
  4533.         return array(
  4534.             "pending_approval_list" => $pending_approval_list,
  4535.             "override_approval_list" => $override_approval_list
  4536.         );
  4537.     }
  4538.     public static function selectDataSystem($em$queryStr '_EMPTY_'$data = [], $userId 0)
  4539.     {
  4540.         $companyId 0;
  4541.         $data = [];
  4542.         $data_by_id = [];
  4543.         $html '';
  4544.         $productByCodeData = [];
  4545.         $setValueArray = [];
  4546.         $setValue 0;
  4547.         $setValueType 0;// 0 for id , 1 for query
  4548.         $selectAll 0;
  4549.         if ($queryStr == '_EMPTY_')
  4550.             $queryStr '';
  4551.         if (isset($dataConfig['query']))
  4552.             $queryStr $dataConfig['query'];
  4553.         if ($queryStr == '_EMPTY_')
  4554.             $queryStr '';
  4555.         $queryStr str_replace('_FSLASH_''/'$queryStr);
  4556.         if ($queryStr === '#setValue:') {
  4557.             $queryStr '';
  4558.         }
  4559.         if (!(strpos($queryStr'#setValue:') === false)) {
  4560.             $setValueArrayBeforeFilter explode(','str_replace('#setValue:'''$queryStr));
  4561.             foreach ($setValueArrayBeforeFilter as $svf) {
  4562.                 if ($svf == '_ALL_') {
  4563.                     $selectAll 1;
  4564.                     $setValueArray = [];
  4565.                     continue;
  4566.                 }
  4567.                 if (is_numeric($svf)) {
  4568.                     $setValueArray[] = ($svf 1);
  4569.                     $setValue $svf 1;
  4570.                 }
  4571.             }
  4572.             $queryStr '';
  4573.         }
  4574.         $valueField = isset($dataConfig['valueField']) ? $dataConfig['valueField'] : 'id';
  4575.         $headMarkers = isset($dataConfig['headMarkers']) ? $dataConfig['headMarkers'] : ''//Special Field
  4576.         $headMarkersStrictMatch = isset($dataConfig['headMarkersStrictMatch']) ? $dataConfig['headMarkersStrictMatch'] : 0//Special Field
  4577.         $itemLimit = isset($dataConfig['itemLimit']) ? $dataConfig['itemLimit'] : 25;
  4578.         $selectorId = isset($dataConfig['selectorId']) ? $dataConfig['selectorId'] : '_NONE_';
  4579.         $textField = isset($dataConfig['textField']) ? $dataConfig['textField'] : 'name';
  4580.         $table = isset($dataConfig['tableName']) ? $dataConfig['tableName'] : '';
  4581.         $isMultiple = isset($dataConfig['isMultiple']) ? $dataConfig['isMultiple'] : 0;
  4582.         $orConditions = isset($dataConfig['orConditions']) ? $dataConfig['orConditions'] : [];
  4583.         $andConditions = isset($dataConfig['andConditions']) ? $dataConfig['andConditions'] : [];
  4584.         $andOrConditions = isset($dataConfig['andOrConditions']) ? $dataConfig['andOrConditions'] : [];
  4585.         $mustConditions = isset($dataConfig['mustConditions']) ? $dataConfig['mustConditions'] : [];
  4586.         $joinTableData = isset($dataConfig['joinTableData']) ? $dataConfig['joinTableData'] : [];
  4587.         $renderTextFormat = isset($dataConfig['renderTextFormat']) ? $dataConfig['renderTextFormat'] : '';
  4588.         $setDataForSingle = isset($dataConfig['setDataForSingle']) ? $dataConfig['setDataForSingle'] : 0;
  4589.         $dataId = isset($dataConfig['dataId']) ? $dataConfig['dataId'] : 0;
  4590.         $lastChildrenOnly = isset($dataConfig['lastChildrenOnly']) ? $dataConfig['lastChildrenOnly'] : 0;
  4591.         $parentOnly = isset($dataConfig['parentOnly']) ? $dataConfig['parentOnly'] : 0;
  4592.         $parentIdField = isset($dataConfig['parentIdField']) ? $dataConfig['parentIdField'] : 'parent_id';
  4593.         $skipDefaultCompanyId = isset($dataConfig['skipDefaultCompanyId']) ? $dataConfig['skipDefaultCompanyId'] : 1;
  4594.         $offset = isset($dataConfig['offset']) ? $dataConfig['offset'] : 0;
  4595.         $returnTotalMatchedEntriesFlag = isset($dataConfig['returnTotalMatched']) ? $dataConfig['returnTotalMatched'] : 0;
  4596.         $nextOffset 0;
  4597.         $totalMatchedEntries 0;
  4598.         $convertToObjectFieldList = isset($dataConfig['convertToObject']) ? $dataConfig['convertToObject'] : [];
  4599.         $convertDateToStringFieldList = isset($dataConfig['convertDateToStringFieldList']) ? $dataConfig['convertDateToStringFieldList'] : [];
  4600.         $orderByConditions = isset($dataConfig['orderByConditions']) ? $dataConfig['orderByConditions'] : [];
  4601.         $convertToUrl = isset($dataConfig['convertToUrl']) ? $dataConfig['convertToUrl'] : [];
  4602.         if (is_string($andConditions)) $andConditions json_decode($andConditionstrue);
  4603.         if (is_string($orConditions)) $orConditions json_decode($orConditionstrue);
  4604.         if (is_string($andOrConditions)) $andOrConditions json_decode($andOrConditionstrue);
  4605.         if (is_string($mustConditions)) $mustConditions json_decode($mustConditionstrue);
  4606.         if (is_string($joinTableData)) $joinTableData json_decode($joinTableDatatrue);
  4607.         if (is_string($convertToObjectFieldList)) $convertToObjectFieldList json_decode($convertToObjectFieldListtrue);
  4608.         if (is_string($orderByConditions)) $orderByConditions json_decode($orderByConditionstrue);
  4609.         if (is_string($convertToUrl)) $convertToUrl json_decode($convertToUrltrue);
  4610.         if ($table == '') {
  4611.             return new JsonResponse(
  4612.                 array(
  4613.                     'success' => false,
  4614. //                    'page_title' => 'Product Details',
  4615. //                    'company_data' => $company_data,
  4616.                     'currentTs' => (new \Datetime())->format('U'),
  4617.                     'isMultiple' => $isMultiple,
  4618.                     'setValueArray' => $setValueArray,
  4619.                     'setValue' => $setValue,
  4620.                     'data' => $data,
  4621.                     'dataId' => $dataId,
  4622.                     'selectorId' => $selectorId,
  4623.                     'dataById' => $data_by_id,
  4624.                     'selectedId' => 0,
  4625.                     'ret_data' => isset($dataConfig['ret_data']) ? $dataConfig['ret_data'] : [],
  4626.                 )
  4627.             );
  4628.         }
  4629.         $restrictionData = array(
  4630. //            'table'=>'relevantField in restriction'
  4631.             'warehouse_action' => 'warehouseActionIds',
  4632.             'branch' => 'branchIds',
  4633.             'warehouse' => 'warehouseIds',
  4634.             'production_process_settings' => 'productionProcessIds',
  4635.         );
  4636.         $restrictionIdList = [];
  4637.         $filterQryForCriteria "select ";
  4638.         $selectQry "";
  4639. //        $selectQry=" `$table`.* ";
  4640.         $selectFieldList = isset($dataConfig['selectFieldList']) ? $dataConfig['selectFieldList'] : ['*'];
  4641.         $selectPrefix = isset($dataConfig['selectPrefix']) ? $dataConfig['selectPrefix'] : '';
  4642.         if (is_string($selectFieldList)) $selectFieldList json_decode($selectFieldListtrue);
  4643.         foreach ($selectFieldList as $selField) {
  4644.             if ($selectQry != '')
  4645.                 $selectQry .= ", ";
  4646.             if ($selField == '*')
  4647.                 $selectQry .= " `$table`.$selField ";
  4648.             else if ($selField == 'count(*)' || $selField == '_RESULT_COUNT_') {
  4649.                 if ($selectPrefix == '')
  4650.                     $selectQry .= " count(*)  ";
  4651.                 else
  4652.                     $selectQry .= (" count(*  )  $selectPrefix"_RESULT_COUNT_ ");
  4653.             } else {
  4654.                 if ($selectPrefix == '')
  4655.                     $selectQry .= " `$table`.`$selField` ";
  4656.                 else
  4657.                     $selectQry .= (" `$table`.`$selField`  $selectPrefix"$selField ");
  4658.             }
  4659.         }
  4660.         $joinQry " from $table ";
  4661. //        $filterQryForCriteria = "select * from $table ";
  4662.         foreach ($joinTableData as $joinIndex => $joinTableDatum) {
  4663. //            $conditionStr.=' 1=1 ';
  4664.             $joinTableName = isset($joinTableDatum['tableName']) ? $joinTableDatum['tableName'] : '=';
  4665.             $joinTableAlias $joinTableName '_' $joinIndex;
  4666.             $joinTablePrimaryField = isset($joinTableDatum['joinFieldPrimary']) ? $joinTableDatum['joinFieldPrimary'] : ''//field of main table
  4667.             $joinTableOnField = isset($joinTableDatum['joinOn']) ? $joinTableDatum['joinOn'] : ''//field of joining table
  4668.             $fieldJoinType = isset($joinTableDatum['fieldJoinType']) ? $joinTableDatum['fieldJoinType'] : '=';
  4669.             $tableJoinType = isset($joinTableDatum['tableJoinType']) ? $joinTableDatum['tableJoinType'] : 'join';//or inner join
  4670.             $selectFieldList = isset($joinTableDatum['selectFieldList']) ? $joinTableDatum['selectFieldList'] : ['*'];
  4671.             $selectPrefix = isset($joinTableDatum['selectPrefix']) ? $joinTableDatum['selectPrefix'] : '';
  4672.             $joinAndConditions = isset($joinTableDatum['joinAndConditions']) ? $joinTableDatum['joinAndConditions'] : [];
  4673.             $joinAndOrConditions = isset($joinTableDatum['joinAndOrConditions']) ? $joinTableDatum['joinAndOrConditions'] : [];
  4674.             $joinOrConditions = isset($joinTableDatum['joinOrConditions']) ? $joinTableDatum['joinOrConditions'] : [];
  4675.             if (is_string($joinAndConditions)) $joinAndConditions json_decode($joinAndConditionstrue);
  4676.             if (is_string($joinAndOrConditions)) $joinAndOrConditions json_decode($joinAndOrConditionstrue);
  4677.             if (is_string($joinOrConditions)) $joinOrConditions json_decode($joinOrConditionstrue);
  4678.             foreach ($selectFieldList as $selField) {
  4679.                 if ($selField == '*')
  4680.                     $selectQry .= ", `$joinTableAlias`.$selField ";
  4681.                 else if ($selField == 'count(*)' || $selField == '_RESULT_COUNT_') {
  4682.                     if ($selectPrefix == '')
  4683.                         $selectQry .= ", count(`$joinTableAlias`." $joinTableOnField ")  ";
  4684.                     else
  4685.                         $selectQry .= (", count(`$joinTableAlias`." $joinTableOnField ")  $selectPrefix"_RESULT_COUNT_ ");
  4686.                 } else {
  4687.                     if ($selectPrefix == '')
  4688.                         $selectQry .= ", `$joinTableAlias`.`$selField`  ";
  4689.                     else
  4690.                         $selectQry .= (", `$joinTableAlias`.`$selField`  $selectPrefix"$selField ");
  4691.                 }
  4692.             }
  4693.             $joinQry .= $tableJoinType $joinTableName $joinTableAlias on  ";
  4694. //            if($joinTablePrimaryField!='')
  4695. //                $joinQry .= "  `$joinTableAlias`.`$joinTableOnField` $fieldJoinType `$table`.`$joinTablePrimaryField` ";
  4696. //            $joinAndString = '';
  4697.             $joinAndString '';
  4698.             if ($joinTablePrimaryField != '')
  4699.                 $joinAndString .= "  `$joinTableAlias`.`$joinTableOnField$fieldJoinType `$table`.`$joinTablePrimaryField` ";
  4700.             foreach ($joinAndConditions as $andCondition) {
  4701. //            $conditionStr.=' 1=1 ';
  4702.                 $ctype = isset($andCondition['type']) ? $andCondition['type'] : '=';
  4703.                 $cfield = isset($andCondition['field']) ? $andCondition['field'] : '';
  4704.                 $aliasInCondition $table;
  4705.                 if (!(strpos($cfield'.') === false)) {
  4706.                     $fullCfieldArray explode('.'$cfield);
  4707.                     $aliasInCondition $fullCfieldArray[0];
  4708.                     $cfield $fullCfieldArray[1];
  4709.                 }
  4710.                 $cvalue = isset($andCondition['value']) ? $andCondition['value'] : $queryStr;
  4711.                 if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  4712.                     if ($joinAndString != '')
  4713.                         $joinAndString .= " and ";
  4714.                     if ($ctype == 'like') {
  4715.                         $joinAndString .= ("`$joinTableAlias`.$cfield like '%" $cvalue "%' ");
  4716.                         $wordsBySpaces explode(' '$cvalue);
  4717.                         foreach ($wordsBySpaces as $word) {
  4718.                             if ($joinAndString != '')
  4719.                                 $joinAndString .= " and ";
  4720.                             $joinAndString .= ("`$joinTableAlias`.$cfield like '%" $word "%' ");
  4721.                         }
  4722.                     } else if ($ctype == 'not like') {
  4723.                         $joinAndString .= ("`$joinTableAlias`.$cfield not like '%" $cvalue "%' ");
  4724.                         $wordsBySpaces explode(' '$cvalue);
  4725.                         foreach ($wordsBySpaces as $word) {
  4726.                             if ($joinAndString != '')
  4727.                                 $joinAndString .= " and ";
  4728.                             $joinAndString .= ("`$joinTableAlias`.$cfield not like '%" $word "%' ");
  4729.                         }
  4730.                     } else if ($ctype == 'not_in') {
  4731.                         $joinAndString .= " ( ";
  4732.                         if (in_array('null'$cvalue)) {
  4733.                             $joinAndString .= " `$joinTableAlias`.$cfield is not null";
  4734.                             $cvalue array_diff($cvalue, ['null']);
  4735.                             if (!empty($cvalue))
  4736.                                 $joinAndString .= " and ";
  4737.                         }
  4738.                         if (in_array(''$cvalue)) {
  4739.                             $joinAndString .= "`$joinTableAlias`.$cfield = '' ";
  4740.                             $cvalue array_diff($cvalue, ['']);
  4741.                             if (!empty($cvalue))
  4742.                                 $joinAndString .= " and ";
  4743.                         }
  4744.                         $joinAndString .= "`$joinTableAlias`.$cfield not in (" implode(','$cvalue) . ") ) ";
  4745.                     } else if ($ctype == 'in') {
  4746.                         if (in_array('null'$cvalue)) {
  4747.                             $joinAndString .= "`$joinTableAlias`.$cfield is null";
  4748.                             $cvalue array_diff($cvalue, ['null']);
  4749.                             if (!empty($cvalue))
  4750.                                 $joinAndString .= " and ";
  4751.                         }
  4752.                         if (in_array(''$cvalue)) {
  4753.                             $joinAndString .= "`$joinTableAlias`.$cfield = '' ";
  4754.                             $cvalue array_diff($cvalue, ['']);
  4755.                             if (!empty($cvalue))
  4756.                                 $joinAndString .= " and ";
  4757.                         }
  4758.                         $joinAndString .= "`$joinTableAlias`.$cfield in (" implode(','$cvalue) . ") ";
  4759.                     } else if ($ctype == '=') {
  4760. //                        if (!(strpos($cvalue, '.') === false) && !(strpos($cvalue, '_PRIMARY_TABLE_') === false)) {
  4761. //                            $fullCfieldArray = explode('.', $cfield);
  4762. //                            $aliasInCondition = $fullCfieldArray[0];
  4763. //                            $cfield = $fullCfieldArray[1];
  4764. //                        }
  4765.                         if ($cvalue == 'null' || $cvalue == 'Null')
  4766.                             $joinAndString .= "`$joinTableAlias`.$cfield is null ";
  4767.                         else
  4768.                             $joinAndString .= "`$joinTableAlias`.$cfield = $cvalue ";
  4769.                     } else if ($ctype == '!=') {
  4770.                         if ($cvalue == 'null' || $cvalue == 'Null')
  4771.                             $joinAndString .= "`$joinTableAlias`.$cfield is not null ";
  4772.                         else
  4773.                             $joinAndString .= "`$joinTableAlias`.$cfield != $cvalue ";
  4774.                     } else {
  4775.                         if (is_string($cvalue))
  4776.                             $joinAndString .= "`$joinTableAlias`.$cfield $ctype '" $cvalue "' ";
  4777.                         else
  4778.                             $joinAndString .= "`$joinTableAlias`.$cfield $ctype " $cvalue " ";
  4779.                     }
  4780.                 }
  4781.             }
  4782. //            if ($joinAndString != '') {
  4783. //                if ($conditionStr != '')
  4784. //                    $conditionStr .= (" and (" . $joinAndString . ") ");
  4785. //                else
  4786. //                    $conditionStr .= ("  (" . $joinAndString . ") ");
  4787. //            }
  4788.             if ($joinAndString != '')
  4789.                 $joinQry .= $joinAndString;
  4790.             $joinAndOrString "";
  4791.             foreach ($joinAndOrConditions as $andOrCondition) {
  4792. //            $conditionStr.=' 1=1 ';
  4793.                 $ctype = isset($andOrCondition['type']) ? $andOrCondition['type'] : '=';
  4794.                 $cfield = isset($andOrCondition['field']) ? $andOrCondition['field'] : '';
  4795.                 $aliasInCondition $table;
  4796.                 if (!(strpos($cfield'.') === false)) {
  4797.                     $fullCfieldArray explode('.'$cfield);
  4798.                     $aliasInCondition $fullCfieldArray[0];
  4799.                     $cfield $fullCfieldArray[1];
  4800.                 }
  4801.                 $cvalue = isset($andOrCondition['value']) ? $andOrCondition['value'] : $queryStr;
  4802.                 if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  4803.                     if ($joinAndOrString != '')
  4804.                         $joinAndOrString .= " or ";
  4805.                     if ($ctype == 'like') {
  4806.                         $joinAndOrString .= ("`$joinTableAlias`.$cfield like '%" $cvalue "%' ");
  4807.                         $wordsBySpaces explode(' '$cvalue);
  4808.                         foreach ($wordsBySpaces as $word) {
  4809.                             if ($joinAndOrString != '')
  4810.                                 $joinAndOrString .= " or ";
  4811.                             $joinAndOrString .= ("`$joinTableAlias`.$cfield like '%" $word "%' ");
  4812.                         }
  4813.                     } else if ($ctype == 'not like') {
  4814.                         $joinAndOrString .= ("`$joinTableAlias`.$cfield not like '%" $cvalue "%' ");
  4815.                         $wordsBySpaces explode(' '$cvalue);
  4816.                         foreach ($wordsBySpaces as $word) {
  4817.                             if ($joinAndOrString != '')
  4818.                                 $joinAndOrString .= " or ";
  4819.                             $joinAndOrString .= ("`$joinTableAlias`.$cfield not like '%" $word "%' ");
  4820.                         }
  4821.                     } else if ($ctype == 'not_in') {
  4822.                         $joinAndOrString .= " ( ";
  4823.                         if (in_array('null'$cvalue)) {
  4824.                             $joinAndOrString .= " `$joinTableAlias`.$cfield is not null";
  4825.                             $cvalue array_diff($cvalue, ['null']);
  4826.                             if (!empty($cvalue))
  4827.                                 $joinAndOrString .= " or ";
  4828.                         }
  4829.                         if (in_array(''$cvalue)) {
  4830.                             $joinAndOrString .= "`$joinTableAlias`.$cfield = '' ";
  4831.                             $cvalue array_diff($cvalue, ['']);
  4832.                             if (!empty($cvalue))
  4833.                                 $joinAndOrString .= " or ";
  4834.                         }
  4835.                         $joinAndOrString .= "`$joinTableAlias`.$cfield not in (" implode(','$cvalue) . ") ) ";
  4836.                     } else if ($ctype == 'in') {
  4837.                         if (in_array('null'$cvalue)) {
  4838.                             $joinAndOrString .= "`$joinTableAlias`.$cfield is null";
  4839.                             $cvalue array_diff($cvalue, ['null']);
  4840.                             if (!empty($cvalue))
  4841.                                 $joinAndOrString .= " or ";
  4842.                         }
  4843.                         if (in_array(''$cvalue)) {
  4844.                             $joinAndOrString .= "`$joinTableAlias`.$cfield = '' ";
  4845.                             $cvalue array_diff($cvalue, ['']);
  4846.                             if (!empty($cvalue))
  4847.                                 $joinAndOrString .= " or ";
  4848.                         }
  4849.                         $joinAndOrString .= "`$joinTableAlias`.$cfield in (" implode(','$cvalue) . ") ";
  4850.                     } else if ($ctype == '=') {
  4851. //                        if (!(strpos($cvalue, '.') === false) && !(strpos($cvalue, '_PRIMARY_TABLE_') === false)) {
  4852. //                            $fullCfieldArray = explode('.', $cfield);
  4853. //                            $aliasInCondition = $fullCfieldArray[0];
  4854. //                            $cfield = $fullCfieldArray[1];
  4855. //                        }
  4856.                         if ($cvalue == 'null' || $cvalue == 'Null')
  4857.                             $joinAndOrString .= "`$joinTableAlias`.$cfield is null ";
  4858.                         else
  4859.                             $joinAndOrString .= "`$joinTableAlias`.$cfield = $cvalue ";
  4860.                     } else if ($ctype == '!=') {
  4861.                         if ($cvalue == 'null' || $cvalue == 'Null')
  4862.                             $joinAndOrString .= "`$joinTableAlias`.$cfield is not null ";
  4863.                         else
  4864.                             $joinAndOrString .= "`$joinTableAlias`.$cfield != $cvalue ";
  4865.                     } else {
  4866.                         if (is_string($cvalue))
  4867.                             $joinAndOrString .= "`$joinTableAlias`.$cfield $ctype '" $cvalue "' ";
  4868.                         else
  4869.                             $joinAndOrString .= "`$joinTableAlias`.$cfield $ctype " $cvalue " ";
  4870.                     }
  4871.                 }
  4872.             }
  4873. //            if ($joinAndOrString != '')
  4874. //                $joinQry .= $joinAndOrString;
  4875.             if ($joinAndOrString != '') {
  4876.                 if ($joinQry != '')
  4877.                     $joinQry .= (" and (" $joinAndOrString ") ");
  4878.                 else
  4879.                     $joinQry .= ("  (" $joinAndOrString ") ");
  4880.             }
  4881.             //pika
  4882.             $joinOrString "";
  4883.             foreach ($joinOrConditions as $orCondition) {
  4884. //            $conditionStr.=' 1=1 ';
  4885.                 $ctype = isset($orCondition['type']) ? $orCondition['type'] : '=';
  4886.                 $cfield = isset($orCondition['field']) ? $orCondition['field'] : '';
  4887.                 $aliasInCondition $table;
  4888.                 if (!(strpos($cfield'.') === false)) {
  4889.                     $fullCfieldArray explode('.'$cfield);
  4890.                     $aliasInCondition $fullCfieldArray[0];
  4891.                     $cfield $fullCfieldArray[1];
  4892.                 }
  4893.                 $cvalue = isset($orCondition['value']) ? $orCondition['value'] : $queryStr;
  4894.                 if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  4895.                     if ($joinOrString != '')
  4896.                         $joinOrString .= " or ";
  4897.                     if ($ctype == 'like') {
  4898.                         $joinOrString .= ("`$joinTableAlias`.$cfield like '%" $cvalue "%' ");
  4899.                         $wordsBySpaces explode(' '$cvalue);
  4900.                         foreach ($wordsBySpaces as $word) {
  4901.                             if ($joinOrString != '')
  4902.                                 $joinOrString .= " or ";
  4903.                             $joinOrString .= ("`$joinTableAlias`.$cfield like '%" $word "%' ");
  4904.                         }
  4905.                     } else if ($ctype == 'not like') {
  4906.                         $joinOrString .= ("`$joinTableAlias`.$cfield not like '%" $cvalue "%' ");
  4907.                         $wordsBySpaces explode(' '$cvalue);
  4908.                         foreach ($wordsBySpaces as $word) {
  4909.                             if ($joinOrString != '')
  4910.                                 $joinOrString .= " or ";
  4911.                             $joinOrString .= ("`$joinTableAlias`.$cfield not like '%" $word "%' ");
  4912.                         }
  4913.                     } else if ($ctype == 'not_in') {
  4914.                         $joinOrString .= " ( ";
  4915.                         if (in_array('null'$cvalue)) {
  4916.                             $joinOrString .= " `$joinTableAlias`.$cfield is not null";
  4917.                             $cvalue array_diff($cvalue, ['null']);
  4918.                             if (!empty($cvalue))
  4919.                                 $joinOrString .= " or ";
  4920.                         }
  4921.                         if (in_array(''$cvalue)) {
  4922.                             $joinOrString .= "`$joinTableAlias`.$cfield = '' ";
  4923.                             $cvalue array_diff($cvalue, ['']);
  4924.                             if (!empty($cvalue))
  4925.                                 $joinOrString .= " or ";
  4926.                         }
  4927.                         $joinOrString .= "`$joinTableAlias`.$cfield not in (" implode(','$cvalue) . ") ) ";
  4928.                     } else if ($ctype == 'in') {
  4929.                         if (in_array('null'$cvalue)) {
  4930.                             $joinOrString .= "`$joinTableAlias`.$cfield is null";
  4931.                             $cvalue array_diff($cvalue, ['null']);
  4932.                             if (!empty($cvalue))
  4933.                                 $joinOrString .= " or ";
  4934.                         }
  4935.                         if (in_array(''$cvalue)) {
  4936.                             $joinOrString .= "`$joinTableAlias`.$cfield = '' ";
  4937.                             $cvalue array_diff($cvalue, ['']);
  4938.                             if (!empty($cvalue))
  4939.                                 $joinOrString .= " or ";
  4940.                         }
  4941.                         $joinOrString .= "`$joinTableAlias`.$cfield in (" implode(','$cvalue) . ") ";
  4942.                     } else if ($ctype == '=') {
  4943. //                        if (!(strpos($cvalue, '.') === false) && !(strpos($cvalue, '_PRIMARY_TABLE_') === false)) {
  4944. //                            $fullCfieldArray = explode('.', $cfield);
  4945. //                            $aliasInCondition = $fullCfieldArray[0];
  4946. //                            $cfield = $fullCfieldArray[1];
  4947. //                        }
  4948.                         if ($cvalue == 'null' || $cvalue == 'Null')
  4949.                             $joinOrString .= "`$joinTableAlias`.$cfield is null ";
  4950.                         else
  4951.                             $joinOrString .= "`$joinTableAlias`.$cfield = $cvalue ";
  4952.                     } else if ($ctype == '!=') {
  4953.                         if ($cvalue == 'null' || $cvalue == 'Null')
  4954.                             $joinOrString .= "`$joinTableAlias`.$cfield is not null ";
  4955.                         else
  4956.                             $joinOrString .= "`$joinTableAlias`.$cfield != $cvalue ";
  4957.                     } else {
  4958.                         if (is_string($cvalue))
  4959.                             $joinOrString .= "`$joinTableAlias`.$cfield $ctype '" $cvalue "' ";
  4960.                         else
  4961.                             $joinOrString .= "`$joinTableAlias`.$cfield $ctype " $cvalue " ";
  4962.                     }
  4963.                 }
  4964.             }
  4965. //            if ($joinOrString != '')
  4966. //                $joinQry .= $joinOrString;
  4967.             if ($joinOrString != '') {
  4968.                 if ($joinQry != '')
  4969.                     $joinQry .= (" or (" $joinOrString ") ");
  4970.                 else
  4971.                     $joinQry .= ("  (" $joinOrString ") ");
  4972.             }
  4973. //
  4974. //                $joinQry .= "  `$joinTableAlias`.`$joinTableOnField` $fieldJoinType `$table`.`$joinTablePrimaryField` ";
  4975.         }
  4976.         $filterQryForCriteria .= $selectQry;
  4977.         $filterQryForCriteria .= $joinQry;
  4978.         if ($skipDefaultCompanyId == && $companyId != && !isset($dataConfig['entity_group']))
  4979.             $filterQryForCriteria .= " where `$table`.`company_id`=" $companyId " ";
  4980.         else
  4981.             $filterQryForCriteria .= " where 1=1 ";
  4982.         $conditionStr "";
  4983.         $aliasInCondition $table;
  4984.         if ($headMarkers != '' && $table == 'acc_accounts_head') {
  4985.             $markerList explode(','$headMarkers);
  4986.             $spMarkerQry "SELECT distinct accounts_head_id FROM acc_accounts_head where 1=1 ";
  4987.             $markerPassedHeads = [];
  4988.             foreach ($markerList as $mrkr) {
  4989.                 $spMarkerQry .= " and marker_hash like '%" $mrkr "%'";
  4990.             }
  4991.             $spStmt $em->getConnection()->fetchAllAssociative($spMarkerQry);
  4992.             $spStmtResults $spStmt;
  4993.             foreach ($spStmtResults as $ggres) {
  4994.                 $markerPassedHeads[] = $ggres['accounts_head_id'];
  4995.             }
  4996.             if (!empty($markerPassedHeads)) {
  4997.                 if ($conditionStr != '')
  4998.                     $conditionStr .= " and (";
  4999.                 else
  5000.                     $conditionStr .= " (";
  5001.                 if ($headMarkersStrictMatch != 1) {
  5002.                     foreach ($markerPassedHeads as $mh) {
  5003.                         $conditionStr .= " `$aliasInCondition`.`path_tree` like'%/" $mh "/%' or ";
  5004.                     }
  5005.                 }
  5006.                 $conditionStr .= "  `$aliasInCondition`.`accounts_head_id` in (" implode(','$markerPassedHeads) . ") ";
  5007.                 $conditionStr .= " )";
  5008.             }
  5009.         }
  5010.         if (isset($restrictionData[$table])) {
  5011.             $userRestrictionData Users::getUserApplicationAccessSettings($em$userId)['options'];
  5012.             if (isset($userRestrictionData[$restrictionData[$table]])) {
  5013.                 $restrictionIdList $userRestrictionData[$restrictionData[$table]];
  5014.                 if ($restrictionIdList == null)
  5015.                     $restrictionIdList = [];
  5016.             }
  5017.             if (!empty($restrictionIdList)) {
  5018.                 if ($conditionStr != '')
  5019.                     $conditionStr .= " and ";
  5020.                 $conditionStr .= " `$table`.$valueField in (" implode(','$restrictionIdList) . ") ";
  5021.             }
  5022.         }
  5023. //        $aliasInCondition = $table;
  5024.         if (!empty($setValueArray) || $selectAll == 1) {
  5025.             if (!empty($setValueArray)) {
  5026.                 if ($conditionStr != '')
  5027.                     $conditionStr .= " and ";
  5028.                 $conditionStr .= " `$aliasInCondition`.$valueField in (" implode(','$setValueArray) . ") ";
  5029.             }
  5030.         } else {
  5031.             $andString '';
  5032.             foreach ($andConditions as $andCondition) {
  5033. //            $conditionStr.=' 1=1 ';
  5034.                 $ctype = isset($andCondition['type']) ? $andCondition['type'] : '=';
  5035.                 $cfield = isset($andCondition['field']) ? $andCondition['field'] : '';
  5036.                 $aliasInCondition $table;
  5037.                 if (!(strpos($cfield'.') === false)) {
  5038.                     $fullCfieldArray explode('.'$cfield);
  5039.                     $aliasInCondition $fullCfieldArray[0];
  5040.                     $cfield $fullCfieldArray[1];
  5041.                 }
  5042.                 $cvalue = isset($andCondition['value']) ? $andCondition['value'] : $queryStr;
  5043.                 if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  5044.                     if ($andString != '')
  5045.                         $andString .= " and ";
  5046.                     if ($ctype == 'like') {
  5047.                         $andString .= ("`$aliasInCondition`.$cfield like '%" $cvalue "%' ");
  5048.                         $wordsBySpaces explode(' '$cvalue);
  5049.                         foreach ($wordsBySpaces as $word) {
  5050.                             if ($andString != '')
  5051.                                 $andString .= " and ";
  5052.                             $andString .= ("`$aliasInCondition`.$cfield like '%" $word "%' ");
  5053.                         }
  5054.                     } else if ($ctype == 'not like') {
  5055.                         $andString .= ("`$aliasInCondition`.$cfield not like '%" $cvalue "%' ");
  5056.                         $wordsBySpaces explode(' '$cvalue);
  5057.                         foreach ($wordsBySpaces as $word) {
  5058.                             if ($andString != '')
  5059.                                 $andString .= " and ";
  5060.                             $andString .= ("`$aliasInCondition`.$cfield not like '%" $word "%' ");
  5061.                         }
  5062.                     } else if ($ctype == 'not_in') {
  5063.                         $andString .= " ( ";
  5064.                         if (in_array('null'$cvalue)) {
  5065.                             $andString .= " `$aliasInCondition`.$cfield is not null";
  5066.                             $cvalue array_diff($cvalue, ['null']);
  5067.                             if (!empty($cvalue))
  5068.                                 $andString .= " and ";
  5069.                         }
  5070.                         if (in_array(''$cvalue)) {
  5071.                             $andString .= "`$aliasInCondition`.$cfield = '' ";
  5072.                             $cvalue array_diff($cvalue, ['']);
  5073.                             if (!empty($cvalue))
  5074.                                 $andString .= " and ";
  5075.                         }
  5076.                         $andString .= "`$aliasInCondition`.$cfield not in (" implode(','$cvalue) . ") ) ";
  5077.                     } else if ($ctype == 'in') {
  5078.                         if (in_array('null'$cvalue)) {
  5079.                             $andString .= "`$aliasInCondition`.$cfield is null";
  5080.                             $cvalue array_diff($cvalue, ['null']);
  5081.                             if (!empty($cvalue))
  5082.                                 $andString .= " and ";
  5083.                         }
  5084.                         if (in_array(''$cvalue)) {
  5085.                             $andString .= "`$aliasInCondition`.$cfield = '' ";
  5086.                             $cvalue array_diff($cvalue, ['']);
  5087.                             if (!empty($cvalue))
  5088.                                 $andString .= " and ";
  5089.                         }
  5090.                         $andString .= "`$aliasInCondition`.$cfield in (" implode(','$cvalue) . ") ";
  5091.                     } else if ($ctype == '=') {
  5092.                         if ($cvalue == 'null' || $cvalue == 'Null')
  5093.                             $andString .= "`$aliasInCondition`.$cfield is null ";
  5094.                         else
  5095.                             $andString .= "`$aliasInCondition`.$cfield = $cvalue ";
  5096.                     } else if ($ctype == '!=') {
  5097.                         if ($cvalue == 'null' || $cvalue == 'Null')
  5098.                             $andString .= "`$aliasInCondition`.$cfield is not null ";
  5099.                         else
  5100.                             $andString .= "`$aliasInCondition`.$cfield != $cvalue ";
  5101.                     } else {
  5102.                         if (is_string($cvalue))
  5103.                             $andString .= "`$aliasInCondition`.$cfield $ctype '" $cvalue "' ";
  5104.                         else
  5105.                             $andString .= "`$aliasInCondition`.$cfield $ctype " $cvalue " ";
  5106.                     }
  5107.                 }
  5108.             }
  5109.             if ($andString != '') {
  5110.                 if ($conditionStr != '')
  5111.                     $conditionStr .= (" and (" $andString ") ");
  5112.                 else
  5113.                     $conditionStr .= ("  (" $andString ") ");
  5114.             }
  5115.             $orString '';
  5116.             foreach ($orConditions as $orCondition) {
  5117.                 $ctype = isset($orCondition['type']) ? $orCondition['type'] : '=';
  5118.                 $cfield = isset($orCondition['field']) ? $orCondition['field'] : '';
  5119.                 $aliasInCondition $table;
  5120.                 if (!(strpos($cfield'.') === false)) {
  5121.                     $fullCfieldArray explode('.'$cfield);
  5122.                     $aliasInCondition $fullCfieldArray[0];
  5123.                     $cfield $fullCfieldArray[1];
  5124.                 }
  5125.                 $cvalue = isset($orCondition['value']) ? $orCondition['value'] : $queryStr;
  5126.                 if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  5127.                     if ($orString != '')
  5128.                         $orString .= " or ";
  5129.                     if ($ctype == 'like') {
  5130.                         $orString .= ("`$aliasInCondition`.$cfield like '%" $cvalue "%' ");
  5131.                         $wordsBySpaces explode(' '$cvalue);
  5132.                         foreach ($wordsBySpaces as $word) {
  5133.                             if ($orString != '')
  5134.                                 $orString .= " or ";
  5135.                             $orString .= ("`$aliasInCondition`.$cfield like '%" $word "%' ");
  5136.                         }
  5137.                     } else if ($ctype == 'not like') {
  5138.                         $orString .= ("`$aliasInCondition`.$cfield not like '%" $cvalue "%' ");
  5139.                         $wordsBySpaces explode(' '$cvalue);
  5140.                         foreach ($wordsBySpaces as $word) {
  5141.                             if ($orString != '')
  5142.                                 $orString .= " or ";
  5143.                             $orString .= ("`$aliasInCondition`.$cfield not like '%" $word "%' ");
  5144.                         }
  5145.                     } else if ($ctype == 'not_in') {
  5146.                         $orString .= " ( ";
  5147.                         if (in_array('null'$cvalue)) {
  5148.                             $orString .= " `$aliasInCondition`.$cfield is not null";
  5149.                             $cvalue array_diff($cvalue, ['null']);
  5150.                             if (!empty($cvalue))
  5151.                                 $orString .= " or ";
  5152.                         }
  5153.                         if (in_array(''$cvalue)) {
  5154.                             $orString .= "`$aliasInCondition`.$cfield = '' ";
  5155.                             $cvalue array_diff($cvalue, ['']);
  5156.                             if (!empty($cvalue))
  5157.                                 $orString .= " or ";
  5158.                         }
  5159.                         $orString .= "`$aliasInCondition`.$cfield not in (" implode(','$cvalue) . ") ) ";
  5160.                     } else if ($ctype == 'in') {
  5161.                         $orString .= " ( ";
  5162.                         if (in_array('null'$cvalue)) {
  5163.                             $orString .= " `$aliasInCondition`.$cfield is null";
  5164.                             $cvalue array_diff($cvalue, ['null']);
  5165.                             if (!empty($cvalue))
  5166.                                 $orString .= " or ";
  5167.                         }
  5168.                         if (in_array(''$cvalue)) {
  5169.                             $orString .= "`$aliasInCondition`.$cfield = '' ";
  5170.                             $cvalue array_diff($cvalue, ['']);
  5171.                             if (!empty($cvalue))
  5172.                                 $orString .= " or ";
  5173.                         }
  5174.                         $orString .= "`$aliasInCondition`.$cfield in (" implode(','$cvalue) . ") ) ";
  5175.                     } else if ($ctype == '=') {
  5176.                         if ($cvalue == 'null' || $cvalue == 'Null')
  5177.                             $orString .= "`$aliasInCondition`.$cfield is null ";
  5178.                         else
  5179.                             $orString .= "`$aliasInCondition`.$cfield = $cvalue ";
  5180.                     } else if ($ctype == '!=') {
  5181.                         if ($cvalue == 'null' || $cvalue == 'Null')
  5182.                             $orString .= "`$aliasInCondition`.$cfield is not null ";
  5183.                         else
  5184.                             $orString .= "`$aliasInCondition`.$cfield != $cvalue ";
  5185.                     } else {
  5186.                         if (is_string($cvalue))
  5187.                             $orString .= "`$aliasInCondition`.$cfield $ctype '" $cvalue "' ";
  5188.                         else
  5189.                             $orString .= "`$aliasInCondition`.$cfield $ctype " $cvalue " ";
  5190.                     }
  5191.                 }
  5192.             }
  5193.             if ($orString != '') {
  5194.                 if ($conditionStr != '')
  5195.                     $conditionStr .= (" or (" $orString ") ");
  5196.                 else
  5197.                     $conditionStr .= ("  (" $orString ") ");
  5198.             }
  5199.             $andOrString '';
  5200.             foreach ($andOrConditions as $andOrCondition) {
  5201.                 $ctype = isset($andOrCondition['type']) ? $andOrCondition['type'] : '=';
  5202.                 $cfield = isset($andOrCondition['field']) ? $andOrCondition['field'] : '';
  5203.                 $aliasInCondition $table;
  5204.                 if (!(strpos($cfield'.') === false)) {
  5205.                     $fullCfieldArray explode('.'$cfield);
  5206.                     $aliasInCondition $fullCfieldArray[0];
  5207.                     $cfield $fullCfieldArray[1];
  5208.                 }
  5209.                 $cvalue = isset($andOrCondition['value']) ? $andOrCondition['value'] : $queryStr;
  5210.                 if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  5211.                     if ($andOrString != '')
  5212.                         $andOrString .= " or ";
  5213.                     if ($ctype == 'like') {
  5214.                         $andOrString .= (" `$aliasInCondition`.$cfield like '%" $cvalue "%' ");
  5215.                         $wordsBySpaces explode(' '$cvalue);
  5216.                         foreach ($wordsBySpaces as $word) {
  5217.                             if ($andOrString != '')
  5218.                                 $andOrString .= " or ";
  5219.                             $andOrString .= ("`$aliasInCondition`.$cfield like '%" $word "%' ");
  5220.                         }
  5221.                     } else if ($ctype == 'not like') {
  5222.                         $andOrString .= (" `$aliasInCondition`.$cfield not like '%" $cvalue "%' ");
  5223.                         $wordsBySpaces explode(' '$cvalue);
  5224.                         foreach ($wordsBySpaces as $word) {
  5225.                             if ($andOrString != '')
  5226.                                 $andOrString .= " or ";
  5227.                             $andOrString .= ("`$aliasInCondition`.$cfield not like '%" $word "%' ");
  5228.                         }
  5229.                     } else if ($ctype == 'in') {
  5230.                         $andOrString .= " ( ";
  5231.                         if (in_array('null'$cvalue)) {
  5232.                             $andOrString .= " `$aliasInCondition`.$cfield is null";
  5233.                             $cvalue array_diff($cvalue, ['null']);
  5234.                             if (!empty($cvalue))
  5235.                                 $andOrString .= " or ";
  5236.                         }
  5237.                         if (in_array(''$cvalue)) {
  5238.                             $andOrString .= "`$aliasInCondition`.$cfield = '' ";
  5239.                             $cvalue array_diff($cvalue, ['']);
  5240.                             if (!empty($cvalue))
  5241.                                 $andOrString .= " or ";
  5242.                         }
  5243.                         if (!empty($cvalue))
  5244.                             $andOrString .= " `$aliasInCondition`.$cfield in (" implode(','$cvalue) . ") ) ";
  5245.                         else
  5246.                             $andOrString .= "  ) ";
  5247.                     } else if ($ctype == 'not_in') {
  5248.                         $andOrString .= " ( ";
  5249.                         if (in_array('null'$cvalue)) {
  5250.                             $andOrString .= " `$aliasInCondition`.$cfield is not null";
  5251.                             $cvalue array_diff($cvalue, ['null']);
  5252.                             if (!empty($cvalue))
  5253.                                 $andOrString .= " or ";
  5254.                         }
  5255.                         if (in_array(''$cvalue)) {
  5256.                             $andOrString .= "`$aliasInCondition`.$cfield = '' ";
  5257.                             $cvalue array_diff($cvalue, ['']);
  5258.                             if (!empty($cvalue))
  5259.                                 $andOrString .= " or ";
  5260.                         }
  5261.                         if (!empty($cvalue))
  5262.                             $andOrString .= "`$aliasInCondition`.$cfield not in (" implode(','$cvalue) . ") ) ";
  5263.                         else
  5264.                             $andOrString .= "  ) ";
  5265.                     } else if ($ctype == '=') {
  5266.                         if ($cvalue == 'null' || $cvalue == 'Null')
  5267.                             $andOrString .= "`$aliasInCondition`.$cfield is null ";
  5268.                         else
  5269.                             $andOrString .= "`$aliasInCondition`.$cfield = $cvalue ";
  5270.                     } else if ($ctype == '!=') {
  5271.                         if ($cvalue == 'null' || $cvalue == 'Null')
  5272.                             $andOrString .= "`$aliasInCondition`.$cfield is not null ";
  5273.                         else
  5274.                             $andOrString .= "`$aliasInCondition`.$cfield != $cvalue ";
  5275.                     } else {
  5276.                         if (is_string($cvalue))
  5277.                             $andOrString .= "`$aliasInCondition`.$cfield $ctype '" $cvalue "' ";
  5278.                         else
  5279.                             $andOrString .= "`$aliasInCondition`.$cfield $ctype " $cvalue " ";
  5280.                     }
  5281.                 }
  5282.             }
  5283.             if ($andOrString != '') {
  5284.                 if ($conditionStr != '')
  5285.                     $conditionStr .= (" and (" $andOrString ") ");
  5286.                 else
  5287.                     $conditionStr .= ("  (" $andOrString ") ");
  5288.             }
  5289.         }
  5290.         $mustStr '';
  5291. ///now must conditions
  5292.         foreach ($mustConditions as $mustCondition) {
  5293. //            $conditionStr.=' 1=1 ';
  5294.             $ctype = isset($mustCondition['type']) ? $mustCondition['type'] : '=';
  5295.             $cfield = isset($mustCondition['field']) ? $mustCondition['field'] : '';
  5296.             $aliasInCondition $table;
  5297.             if (!(strpos($cfield'.') === false)) {
  5298.                 $fullCfieldArray explode('.'$cfield);
  5299.                 $aliasInCondition $fullCfieldArray[0];
  5300.                 $cfield $fullCfieldArray[1];
  5301.             }
  5302.             $cvalue = isset($mustCondition['value']) ? $mustCondition['value'] : $queryStr;
  5303.             if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  5304.                 if ($mustStr != '')
  5305.                     $mustStr .= " and ";
  5306.                 if ($ctype == 'like') {
  5307.                     $mustStr .= ("(`$aliasInCondition`.$cfield like '%" $cvalue "%' ");
  5308.                     $wordsBySpaces explode(' '$cvalue);
  5309.                     foreach ($wordsBySpaces as $word) {
  5310.                         if ($mustStr != '')
  5311.                             $mustStr .= " or ";
  5312.                         $mustStr .= ("`$aliasInCondition`.$cfield like '%" $word "%' ");
  5313.                     }
  5314.                     $mustStr .= " )";
  5315.                 } else if ($ctype == 'not like') {
  5316.                     $mustStr .= ("`$aliasInCondition`.$cfield not like '%" $cvalue "%' ");
  5317.                     $wordsBySpaces explode(' '$cvalue);
  5318.                     foreach ($wordsBySpaces as $word) {
  5319.                         if ($mustStr != '')
  5320.                             $mustStr .= " and ";
  5321.                         $mustStr .= ("`$aliasInCondition`.$cfield not like '%" $word "%' ");
  5322.                     }
  5323.                 } else if ($ctype == 'in') {
  5324.                     $mustStr .= " ( ";
  5325.                     if (in_array('null'$cvalue)) {
  5326.                         $mustStr .= " `$aliasInCondition`.$cfield is null";
  5327.                         $cvalue array_diff($cvalue, ['null']);
  5328.                         if (!empty($cvalue))
  5329.                             $mustStr .= " or ";
  5330.                     }
  5331.                     if (in_array(''$cvalue)) {
  5332.                         $mustStr .= "`$aliasInCondition`.$cfield = '' ";
  5333.                         $cvalue array_diff($cvalue, ['']);
  5334.                         if (!empty($cvalue))
  5335.                             $mustStr .= " or ";
  5336.                     }
  5337.                     $mustStr .= "`$aliasInCondition`.$cfield in (" implode(','$cvalue) . ") ) ";
  5338.                 } else if ($ctype == 'not_in') {
  5339.                     $mustStr .= " ( ";
  5340.                     if (in_array('null'$cvalue)) {
  5341.                         $mustStr .= " `$aliasInCondition`.$cfield is not null";
  5342.                         $cvalue array_diff($cvalue, ['null']);
  5343.                         if (!empty($cvalue))
  5344.                             $mustStr .= " and ";
  5345.                     }
  5346.                     if (in_array(''$cvalue)) {
  5347.                         $mustStr .= "`$aliasInCondition`.$cfield = '' ";
  5348.                         $cvalue array_diff($cvalue, ['']);
  5349.                         if (!empty($cvalue))
  5350.                             $mustStr .= " and ";
  5351.                     }
  5352.                     $mustStr .= "`$aliasInCondition`.$cfield not in (" implode(','$cvalue) . ") ) ";
  5353.                 } else if ($ctype == '=') {
  5354.                     if ($cvalue == 'null' || $cvalue == 'Null')
  5355.                         $mustStr .= "`$aliasInCondition`.$cfield is null ";
  5356.                     else
  5357.                         $mustStr .= "`$aliasInCondition`.$cfield = $cvalue ";
  5358.                 } else if ($ctype == '!=') {
  5359.                     if ($cvalue == 'null' || $cvalue == 'Null')
  5360.                         $mustStr .= "`$aliasInCondition`.$cfield is not null ";
  5361.                     else
  5362.                         $mustStr .= "`$aliasInCondition`.$cfield != $cvalue ";
  5363.                 } else {
  5364.                     if (is_string($cvalue))
  5365.                         $mustStr .= "`$aliasInCondition`.$cfield $ctype '" $cvalue "' ";
  5366.                     else
  5367.                         $mustStr .= "`$aliasInCondition`.$cfield $ctype " $cvalue " ";
  5368.                 }
  5369.             }
  5370.         }
  5371.         if ($mustStr != '') {
  5372.             if ($conditionStr != '')
  5373.                 $conditionStr .= (" and (" $mustStr ") ");
  5374.             else
  5375.                 $conditionStr .= ("  (" $mustStr ") ");
  5376.         }
  5377.         if ($conditionStr != '')
  5378.             $filterQryForCriteria .= (" and (" $conditionStr ") ");
  5379.         if ($lastChildrenOnly == 1) {
  5380.             if ($filterQryForCriteria != '')
  5381.                 $filterQryForCriteria .= ' and';
  5382.             $filterQryForCriteria .= "`$table`.`$valueField` not in ( select distinct $parentIdField from  $table)";
  5383.         } else if ($parentOnly == 1) {
  5384.             if ($filterQryForCriteria != '')
  5385.                 $filterQryForCriteria .= ' and';
  5386.             $filterQryForCriteria .= "`$table`.`$valueField`  in ( select distinct $parentIdField from  $table)";
  5387.         }
  5388.         if (!empty($orderByConditions)) {
  5389.             $filterQryForCriteria .= "  order by ";
  5390.             $fone 1;
  5391.             foreach ($orderByConditions as $orderByCondition) {
  5392.                 if ($fone != 1) {
  5393.                     $filterQryForCriteria .= " , ";
  5394.                 }
  5395.                 if (isset($orderByCondition['valueList'])) {
  5396.                     if (is_string($orderByCondition['valueList'])) $orderByCondition['valueList'] = json_decode($orderByCondition['valueList'], true);
  5397.                     if ($orderByCondition['valueList'] == null)
  5398.                         $orderByCondition['valueList'] = [];
  5399.                     $filterQryForCriteria .= "   field(" $orderByCondition['field'] . "," implode(','$orderByCondition['valueList']) . "," $orderByCondition['field'] . ") " $orderByCondition['sortType'] . " ";
  5400.                 } else
  5401.                     $filterQryForCriteria .= " " $orderByCondition['field'] . " " $orderByCondition['sortType'] . " ";
  5402.                 $fone 0;
  5403.             }
  5404.         }
  5405.         if ($returnTotalMatchedEntriesFlag == 1) {
  5406. //            $stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
  5407. //            
  5408. //            $get_kids = $stmt;
  5409.         }
  5410.         if ($filterQryForCriteria != '')
  5411.             if (!empty($setValueArray) || $selectAll == 1) {
  5412.             } else {
  5413.                 if ($itemLimit != '_ALL_')
  5414.                     $filterQryForCriteria .= "  limit $offset$itemLimit ";
  5415.                 else
  5416.                     $filterQryForCriteria .= "  limit $offset, 18446744073709551615 ";
  5417.             }
  5418.         $get_kids_sql $filterQryForCriteria;
  5419.         $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  5420.         $get_kids $stmt;
  5421.         $selectedId 0;
  5422.         if ($table == 'warehouse_action') {
  5423.             if (empty($get_kids)) {
  5424.                 $get_kids_sql_2 "select * from warehouse_action";
  5425.                 $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql_2);
  5426.                 $get_kids2 $stmt;
  5427.                 if (empty($get_kids2))
  5428.                     $get_kids GeneralConstant::$warehouse_action_list;
  5429.             }
  5430.         }
  5431.         if (!empty($get_kids)) {
  5432.             $nextOffset $offset count($get_kids);
  5433.             $nextOffset++;
  5434.             foreach ($get_kids as $pa) {
  5435.                 if (!empty($setValueArray) && $selectAll == 0) {
  5436.                     if (!in_array($pa[$valueField], $setValueArray))
  5437.                         continue;
  5438.                 }
  5439.                 if (!empty($restrictionIdList)) {
  5440.                     if (!in_array($pa[$valueField], $restrictionIdList))
  5441.                         continue;
  5442.                 }
  5443.                 if ($selectAll == 1) {
  5444.                     $setValueArray[] = $pa[$valueField];
  5445.                     $setValue $pa[$valueField];
  5446.                 } else if (count($get_kids) == && $setDataForSingle == 1) {
  5447.                     $setValueArray[] = $pa[$valueField];
  5448.                     $setValue $pa[$valueField];
  5449.                 }
  5450.                 if ($valueField != '')
  5451.                     $pa['value'] = $pa[$valueField];
  5452.                 $renderedText $renderTextFormat;
  5453.                 $compare_array = [];
  5454.                 if ($renderTextFormat != '') {
  5455.                     $renderedText $renderTextFormat;
  5456.                     $compare_arrayFull = [];
  5457.                     $compare_array = [];
  5458.                     $toBeReplacedData = array(//                        'curr'=>'tobereplaced'
  5459.                     );
  5460.                     preg_match_all("/__\w+__/"$renderedText$compare_arrayFull);
  5461.                     if (isset($compare_arrayFull[0]))
  5462.                         $compare_array $compare_arrayFull[0];
  5463. //                   $compare_array= preg_split("/__\w+__/",$renderedText);
  5464.                     foreach ($compare_array as $cmpdt) {
  5465.                         $tbr str_replace("__"""$cmpdt);
  5466.                         if ($tbr != '') {
  5467.                             if (isset($pa[$tbr])) {
  5468.                                 if ($pa[$tbr] == null)
  5469.                                     $renderedText str_replace($cmpdt''$renderedText);
  5470.                                 else
  5471.                                     $renderedText str_replace($cmpdt$pa[$tbr], $renderedText);
  5472.                             } else {
  5473.                                 $renderedText str_replace($cmpdt''$renderedText);
  5474.                             }
  5475.                         }
  5476.                     }
  5477.                 }
  5478.                 $pa['rendered_text'] = $renderedText;
  5479.                 $pa['text'] = ($textField != '' $pa[$textField] : '');
  5480. //                $pa['compare_array'] = $compare_array;
  5481.                 foreach ($convertToObjectFieldList as $convField) {
  5482.                     if (isset($pa[$convField])) {
  5483.                         $taA json_decode($pa[$convField], true);
  5484.                         if ($taA == null$taA = [];
  5485.                         $pa[$convField] = $taA;
  5486.                     } else {
  5487.                         $pa[$convField] = [];
  5488.                     }
  5489.                 }
  5490.                 foreach ($convertDateToStringFieldList as $convField) {
  5491.                     if (is_array($convField)) {
  5492.                         $fld $convField['field'];
  5493.                         $frmt = isset($convField['format']) ? $convField['format'] : 'Y-m-d H:i:s';
  5494.                     } else {
  5495.                         $fld $convField;
  5496.                         $frmt 'Y-m-d H:i:s';
  5497.                     }
  5498.                     if (isset($pa[$fld])) {
  5499.                         $taA = new \DateTime($pa[$fld]);
  5500.                         $pa[$fld] = $taA->format($frmt);
  5501.                     }
  5502.                 }
  5503.                 foreach ($convertToUrl as $convField) {
  5504.                     $fld $convField;
  5505.                     if (isset($pa[$fld])) {
  5506. //                        $pa[$fld] =
  5507. //                            $this->generateUrl(
  5508. //                                $pa[$fld], [
  5509. ////                                'refRoute' => $refRoute
  5510. //                            ], UrlGenerator::ABSOLUTE_URL
  5511. //                            );
  5512.                     }
  5513.                 }
  5514.                 $pa['currentTs'] = (new \Datetime())->format('U');
  5515.                 $data[] = $pa;
  5516.                 if ($valueField != '') {
  5517.                     $data_by_id[$pa[$valueField]] = $pa;
  5518.                     $selectedId $pa[$valueField];
  5519.                 }
  5520.             }
  5521.         }
  5522.         $resultData = array(
  5523.             'success' => true,
  5524.             'data' => $data,
  5525.             'tableName' => $table,
  5526.             'setValue' => $setValue,
  5527.             'currentTs' => (new \Datetime())->format('U'),
  5528.             'restrictionIdList' => $restrictionIdList,
  5529.             'andConditions' => $andConditions,
  5530.             'queryStr' => $queryStr,
  5531.             'isMultiple' => $isMultiple,
  5532.             'nextOffset' => $nextOffset,
  5533.             'totalMatchedEntries' => $totalMatchedEntries,
  5534.             'selectorId' => $selectorId,
  5535.             'setValueArray' => $setValueArray,
  5536.             'conditionStr' => $conditionStr,
  5537. //                    'andStr' => $andString,
  5538. //                    'andOrStr' => $andOrString,
  5539.             'dataById' => $data_by_id,
  5540.             'selectedId' => $selectedId,
  5541.             'dataId' => $dataId,
  5542.             'ret_data' => isset($dataConfig['ret_data']) ? $dataConfig['ret_data'] : [],
  5543.         );
  5544.         return $resultData;
  5545.     }
  5546.     public static function getServerListById($default_server_user$default_server_pass$server_config_from_parameter_array)
  5547.     {
  5548.         $serverList GeneralConstant::$serverListById;
  5549.         $newServerList = [];
  5550.         $default_server_data = [
  5551.             "port" => "",
  5552.             "dbUser" => $default_server_user,
  5553.             "dbPass" => $default_server_pass,
  5554.             "dedicated" => "0",
  5555.             "ram" => "4"//GB
  5556.             "cpu" => "2"//cpu core
  5557.             "storage" => "80"//GBN
  5558.             "transfer" => "4"//TB
  5559.             "bwIn" => "40"//GBbps
  5560.             "bwOut" => "4"//GBbps
  5561.         ];
  5562.         $server_config_from_parameter = [];
  5563.         //1st get from config
  5564.         foreach ($server_config_from_parameter_array as $server) {
  5565.             $key $server['id'];
  5566.             if (isset($serverList[$key]))
  5567.                 foreach ($serverList[$key] as $index => $value) {
  5568.                     if (!isset($server[$index]))
  5569.                         $server[$index] = $value;
  5570.                 }
  5571.             else {
  5572.                 foreach ($default_server_data as $index => $value) {
  5573.                     if (!isset($server[$index]))
  5574.                         $server[$index] = $value;
  5575.                 }
  5576.             }
  5577.             $server['id'] = $key;
  5578.             $newServerList[$key] = $server;
  5579.             $server_config_from_parameter[$key] = $server;
  5580.         }
  5581.         //then get the others
  5582.         foreach ($serverList as $key => $server) {
  5583.             if (!isset($newServerList[$key])) {
  5584.                 if (isset($server_config_from_parameter[$key]))
  5585.                     foreach ($server_config_from_parameter[$key] as $index => $value) {
  5586.                         $server[$index] = $value;
  5587.                     }
  5588.                 else {
  5589.                     $server['dbUser'] = $default_server_user;
  5590.                     $server['dbPass'] = $default_server_pass;
  5591.                 }
  5592.                 $newServerList[$key] = $server;
  5593.             }
  5594.         }
  5595.         return $newServerList;
  5596.     }
  5597. }