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

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