src/ApplicationBundle/Controller/ApplicationManagementController.php line 1145

Open in your IDE?
  1. <?php
  2. namespace ApplicationBundle\Controller;
  3. use ApplicationBundle\ApplicationBundle;
  4. use ApplicationBundle\Constants\GeneralConstant;
  5. use ApplicationBundle\Constants\ModuleConstant;
  6. use ApplicationBundle\Entity\Approval;
  7. use ApplicationBundle\Entity\Company;
  8. use ApplicationBundle\Entity\DocumentData;
  9. use ApplicationBundle\Entity\SysModule;
  10. use ApplicationBundle\Entity\SysUser;
  11. use ApplicationBundle\Interfaces\LoginInterface;
  12. use ApplicationBundle\Modules\Authentication\Constants\UserConstants;
  13. use ApplicationBundle\Modules\Inventory\Inventory;
  14. use ApplicationBundle\Modules\System\MiscActions;
  15. use ApplicationBundle\Modules\System\System;
  16. use ApplicationBundle\Modules\User\Users;
  17. use CompanyGroupBundle\Entity\CompanyGroup;
  18. use CompanyGroupBundle\Entity\DeviceSensorData;
  19. use CompanyGroupBundle\Entity\DeviceSensorDataDay;
  20. use CompanyGroupBundle\Entity\DeviceSensorDataHour;
  21. use CompanyGroupBundle\Entity\DeviceSensorDataMonth;
  22. use CompanyGroupBundle\Entity\DeviceSensorDataWeek;
  23. use CompanyGroupBundle\Entity\EntityApplicantDetails;
  24. use Doctrine\ORM\Tools\SchemaTool;
  25. use Symfony\Component\HttpFoundation\JsonResponse;
  26. use Symfony\Component\HttpFoundation\Request;
  27. use Symfony\Component\HttpFoundation\Response;
  28. use Symfony\Component\Routing\Generator\UrlGenerator;
  29. class ApplicationManagementController extends GenericController implements LoginInterface
  30. {
  31.     public function DeviceDataEmsIngestAction(Request $request$id 0)
  32.     {
  33.         $em_goc $this->getDoctrine()->getManager('company_group');
  34.         $content $request->getContent(); // raw body string
  35.         $data json_decode($contenttrue); // decode JSON if needed
  36.         // Example: access fields
  37.         if ($data == null$data = [];
  38.         $emsDataSegregation GeneralConstant::$emsDataSegregation;
  39.         $segregatedData = [];
  40.         $segregatedDataByDeviceId = [];
  41.         $siteId = (isset($data['siteId'])) ? $data['siteId'] : 0;
  42.         //first create a new array or records which will then be modified and or created
  43.         $modifiedData = array();
  44.         $firstTs 0;
  45.         $lastTs 0;
  46.         $siteIds = [$siteId];
  47. //        $defaultData = [
  48. //            'marker' => '',
  49. //            'ts' => '',
  50. //            'data' => []
  51. //        ];
  52.         $defaultValues = [0000];
  53.         if (isset($data['records']))
  54.             foreach ($data['records'] as $key => $value) {
  55.                 $timeStampDt = new \DateTime($value['timestamp']);
  56.                 $timeStampDt->setTimezone(new \DateTimeZone('+0000'));
  57.                 $timeStampTs $timeStampDt->format('U');
  58.                 if ($timeStampTs $lastTs$lastTs $timeStampTs;
  59.                 if ($timeStampTs $firstTs || $firstTs 0$firstTs $timeStampTs;
  60.                 if (!in_array($data['siteId'], $siteIds)) $siteIds[] = $data['siteId'];
  61.                 foreach ($emsDataSegregation as $key2 => $dataSegregation) {
  62.                     if (!isset($segregatedDataByDeviceId[$value['device_id']]))
  63.                         $segregatedDataByDeviceId[$value['device_id']] = [];
  64.                     if (!isset($segregatedDataByDeviceId[$value['device_id']][$key2]))
  65.                         $segregatedDataByDeviceId[$value['device_id']][$key2] = [];
  66.                     $segregatedData $segregatedDataByDeviceId[$value['device_id']];
  67. //                    $segregatedData[$key2] = [
  68. ////                             '20250406':   [
  69. ////                                    'marker' => '',
  70. ////                                    'ts' => '',
  71. ////                                    'data' => ['Battery_power' => [0, 2, 1, 4]]
  72. ////                                ]
  73. //                        ];
  74. //                    [{'_identifier_':{min,max,avg,count}}]
  75.                     $markerForThis $timeStampDt->format($dataSegregation['markerStr']);
  76.                     if (isset($dataSegregation['isWeek'])) {
  77.                         $startDtForThis = new \DateTime();
  78.                         $startDtForThis->setISODate($timeStampDt->format('Y'), $timeStampDt->format('W'));
  79.                     } else {
  80.                         $startDtForThis = new \DateTime($timeStampDt->format($dataSegregation['startTsFormat']));
  81.                     }
  82.                     $startDtForThis->setTimezone(new \DateTimeZone('+0000'));
  83.                     $startTsForThis $startDtForThis->format('U');
  84.                     if (!isset($segregatedData[$key2][$markerForThis]))
  85.                         $segregatedData[$key2][$markerForThis] = [
  86.                             'marker' => $markerForThis,
  87.                             'ts' => $startTsForThis,
  88.                             'data' => []
  89.                         ];
  90.                     if (!isset($segregatedData[$key2][$markerForThis]['data'][$value['identifier']]))
  91.                         $segregatedData[$key2][$markerForThis]['data'][$value['identifier']] = $defaultValues;
  92.                     $newValues $segregatedData[$key2][$markerForThis]['data'][$value['identifier']];
  93.                     //indexes 0:min, 1:max, 2:avg, 3:count
  94.                     $min $newValues[0];
  95.                     $max $newValues[1];
  96.                     $avg $newValues[2];
  97.                     $count $newValues[3];
  98.                     //now modify
  99.                     if ($value['value'] > $max$max $value['value'];
  100.                     if ($value['value'] < $min$min $value['value'];
  101.                     $avg = ($count $avg $value['value']) / ($count 1);
  102.                     $count++;
  103.                     $newValues = [$min$max$avg$count];
  104.                     $segregatedData[$key2][$markerForThis]['data'][$value['identifier']] = $newValues;
  105.                     $segregatedDataByDeviceId[$value['device_id']] = $segregatedData;
  106.                 }
  107.             }
  108.         //nnow data are segregated now add them
  109.         foreach ($emsDataSegregation as $key2 => $dataSegregation) {
  110.             foreach ($segregatedDataByDeviceId as $deviceId => $segregatedData) {
  111.                 if (!isset($segregatedData[$key2]))
  112.                     $segregatedData[$key2] = [];
  113.                 foreach ($segregatedData[$key2] as $key3 => $dt) {
  114.                     $timeStampDt = new \DateTime('@' $dt['ts']);
  115.                     $timeStampDt->setTimezone(new \DateTimeZone('+0000'));
  116.                     $markerForThis $dt['marker'];
  117.                     $entry $this->getDoctrine()->getManager('company_group')
  118.                         ->getRepository('CompanyGroupBundle:' $dataSegregation['repository'])
  119.                         ->findOneBy(array(
  120.                             'marker' => $markerForThis,
  121.                             'siteId' => $siteId,
  122.                             'deviceId' => $deviceId
  123.                         ));
  124.                     $repoClassName "CompanyGroupBundle\\Entity\\" $dataSegregation['repository'];
  125.                     $hasEntry 1;
  126.                     if (!$entry) {
  127.                         $hasEntry 0;
  128.                         $entry = new $repoClassName();
  129.                         $entry->setTimeStamp($timeStampDt);
  130.                         $entry->setTimeStampTs($dt['ts']);
  131.                         $entry->setSiteId($siteId);
  132.                         $entry->setMarker($markerForThis);
  133.                         $entry->setDeviceId($deviceId);
  134.                     }
  135.                     $existingData json_decode($entry->getData(), true);
  136.                     if ($existingData == null$existingData = [];
  137. //                    $existingData=$segregatedDataByDeviceId; //temp
  138.                     foreach ($dt['data'] as $identifier => $newValues) {
  139.                         if (!isset($existingData[$identifier]))
  140.                             $existingData[$identifier] = $newValues;
  141.                         else {
  142.                             //indexes 0:min, 1:max, 2:avg, 3:count
  143.                             $min $existingData[$identifier][0];
  144.                             $max $existingData[$identifier][1];
  145.                             $avg $existingData[$identifier][2];
  146.                             $count $existingData[$identifier][3];
  147.                             //now modify
  148.                             if ($newValues[1] > $max$max $newValues[1];
  149.                             if ($newValues[0] < $min$min $newValues[0];
  150.                             $avg = ($count $avg $newValues[2] * $newValues[3]) / ($count $newValues[3]);
  151.                             $count $count $newValues[3];
  152.                             $existingData[$identifier] = [$min$max$avg$count];
  153.                         }
  154.                     }
  155.                     $entry->setData(json_encode($existingData));
  156.                     if ($hasEntry == 0)
  157.                         $em_goc->persist($entry);
  158.                     $em_goc->flush();
  159.                 }
  160.             }
  161.         }
  162.         return new JsonResponse(array(
  163.             'success' => true,
  164.         ));
  165.     }
  166.     public function DeviceDataEmsIngestActionLater(Request $request$id 0)
  167.     {
  168.         $em_goc $this->getDoctrine()->getManager('company_group');
  169.         $content $request->getContent(); // raw body string
  170.         $data json_decode($contenttrue); // decode JSON if needed
  171.         // Example: access fields
  172.         if ($data == null$data = [];
  173.         $siteId = (isset($data['siteId'])) ? $data['siteId'] : 0;
  174.         if (isset($data['records']))
  175.             foreach ($data['records'] as $key => $value) {
  176. //                $entry = $this->getDoctrine()->getManager('company_group')
  177. //                    ->getRepository("CompanyGroupBundle:DeviceSensorData")
  178. //                    ->findOneBy(array(
  179. //                        'recordId' => $value['record_id']
  180. //                    ));
  181.                 $entry null;
  182.                 $hasEntry 1;
  183.                 if (!$entry) {
  184.                     $hasEntry 0;
  185.                     $entry = new DeviceSensorData();
  186.                 }
  187.                 $timeStampDt = new \DateTime($value['timestamp']);
  188.                 $entry->setDeviceId($value['device_id']);
  189.                 $entry->setRecordId($value['record_id']);
  190.                 $entry->setSiteId($siteId);
  191.                 $entry->setAlias($value['alias']);
  192.                 $entry->setValue($value['value']);
  193.                 $entry->setIdentifier($value['identifier']);
  194.                 $entry->setTimeStamp($timeStampDt);
  195.                 $entry->setTimeStampTs($timeStampDt->format('U'));
  196.                 if ($hasEntry == 0)
  197.                     $em_goc->persist($entry);
  198.                 $em_goc->flush();
  199.             }
  200.         return new JsonResponse(array(
  201.             'success' => true,
  202.         ));
  203.     }
  204.     public function DeviceDataEmsGetAction(Request $request$id 0)
  205.     {
  206.         $em_goc $this->getDoctrine()->getManager('company_group');
  207.         $returnData = array(
  208.             'success' => false,
  209.             'dataList' => []
  210.         );
  211.         $getDatakeys = ['_BY_DAY_''_BY_HOUR_'];
  212.         $emsDataSegregation GeneralConstant::$emsDataSegregation;
  213.         foreach ($getDatakeys as $key2) {
  214.             $dataSegregation $emsDataSegregation[$key2];
  215.             if (!isset($returnData['dataList'][$key2]))
  216.                 $returnData['dataList'][$key2] = [];
  217.             $repoClassName $dataSegregation['repository'];
  218.             $dataQry $this->getDoctrine()->getManager('company_group')
  219.                 ->getRepository('CompanyGroupBundle:' $dataSegregation['repository'])
  220.                 ->createQueryBuilder('a')
  221.                 ->where('1=1');
  222.             if ($request->get('start_ts'0) != 0$dataQry->andWhere('a.timeStampTs >= ' $request->get('start_ts'0));
  223.             if ($request->get('end_ts'0) != 0$dataQry->andWhere('a.timeStampTs <= ' $request->get('end_ts'0));
  224.             if (!empty($request->get('device_ids', [])))
  225.                 $dataQry->andWhere('a.deviceId  in ( ' implode(','$request->get('device_ids', [])) . ' ) ');
  226.             if (!empty($request->get('identifiers', [])))
  227.                 $dataQry->andWhere('a.identifier  in ( ' implode(','$request->get('identifiers', [])) . ' ) ');
  228.             if (!empty($request->get('site_ids', [])))
  229.                 $dataQry->andWhere('a.siteId  in ( ' implode(','$request->get('site_ids', [])) . ' ) ');
  230.             $data $dataQry
  231.                 ->setMaxResults(1000)
  232.                 ->getQuery()
  233.                 ->getResult();
  234.             if (!empty($data))
  235.                 $returnData['success'] = true;
  236.             foreach ($data as $key => $entry) {
  237.                 $value = array();
  238.                 $timeStampDt $entry->getTimeStamp();
  239.                 $timeStampDt->setTimezone(new \DateTimeZone('+0000'));
  240.                 $existingData json_decode($entry->getData(), true);
  241.                 if ($existingData == null$existingData = [];
  242.                 foreach ($existingData as $identifier => $newValues) {
  243.                     $value['device_id'] = $entry->getDeviceId();
  244.                     $value['value'] = $newValues[2];
  245.                     $value['identifier'] = $identifier;
  246.                     $value['timestamp'] = $timeStampDt;
  247.                     $value['timestamp_ts'] = $entry->getTimeStampTs();;
  248.                     $returnData['dataList'][$key2][] = $value;
  249.                 }
  250.             }
  251.         }
  252.         return new JsonResponse($returnData);
  253.     }
  254.     public function UpdateCompanyGroupAction(Request $request$id 0)
  255.     {
  256.         $systemType $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
  257.         $appId $request->get('app_id'0);
  258.         $post $request;
  259.         $session $request->getSession();
  260.         $d = array();
  261.         if ($systemType == '_CENTRAL_') {
  262.             $em_goc $this->getDoctrine()->getManager('company_group');
  263.             $em_goc->getConnection()->connect();
  264.             $connected $em_goc->getConnection()->isConnected();
  265.             $gocDataList = [];
  266.             if ($connected) {
  267.                 $goc null;
  268.                 $serverList GeneralConstant::$serverListById;
  269.                 $companyGroupHash $post->get('company_short_code''');
  270.                 $defaultUsageDate = new \DateTime();
  271.                 $defaultUsageDate->modify('+1 year');
  272.                 $usageValidUpto = new \DateTime($post->get('usage_valid_upto_dt_str'$defaultUsageDate->format('Y-m-d')));
  273.                 $companyGroupServerId $post->get('server_id'1);
  274.                 $companyGroupServerAddress $serverList[$companyGroupServerId]['absoluteUrl'];
  275.                 $companyGroupServerPort $serverList[$companyGroupServerId]['port'];
  276.                 $companyGroupServerHash $serverList[$companyGroupServerId]['serverMarker'];
  277. //                $dbUser=
  278.                 if ($appId != 0)
  279.                     $goc $this->getDoctrine()->getManager('company_group')
  280.                         ->getRepository("CompanyGroupBundle:CompanyGroup")
  281.                         ->findOneBy(array(
  282.                             'appId' => $appId
  283.                         ));
  284.                 if (!$goc)
  285.                     $goc = new CompanyGroup();
  286.                 if ($appId == 0) {
  287.                     $biggestAppIdCg $this->getDoctrine()->getManager('company_group')
  288.                         ->getRepository("CompanyGroupBundle:CompanyGroup")
  289.                         ->findOneBy(array(//                            'appId' => $appId
  290.                         ), array(
  291.                             'appId' => 'desc'
  292.                         ));
  293.                     if ($biggestAppIdCg)
  294.                         $appId $biggestAppIdCg->getAppId();
  295.                 }
  296.                 if ($post->get('company_name''') != '') {
  297.                     $goc->setName($post->get('company_name'));
  298.                     $goc->setCompanyGroupHash($companyGroupHash);
  299.                     $goc->setAppId($appId);
  300.                     $goc->setActive(1);
  301.                     $goc->setAddress($post->get('address'));
  302.                     $goc->setShippingAddress($post->get('s_address'));
  303.                     $goc->setBillingAddress($post->get('b_address'));
  304.                     $goc->setMotto($post->get('motto'));
  305.                     $goc->setInitiateFlag($post->get('initiate_flag'2));
  306.                     $goc->setInvoiceFooter($post->get('i_footer'));
  307.                     $goc->setGeneralFooter($post->get('g_footer'));
  308.                     $goc->setCompanyReg($post->get('company_reg'''));
  309.                     $goc->setCompanyTin($post->get('company_tin'''));
  310.                     $goc->setCompanyBin($post->get('company_bin'''));
  311.                     $goc->setCompanyTl($post->get('company_tl'''));
  312.                     $goc->setCompanyType($post->get('company_type'''));
  313.                     $goc->setCurrentSubscriptionPackageId($post->get('package'''));
  314.                     $goc->setUsageValidUptoDate($usageValidUpto);
  315.                     $goc->setUsageValidUptoDateTs($usageValidUpto->format('U'));
  316. //                $goc->setCu($post->get('package', ''));
  317.                     $goc->setAdminUserAllowed($post->get('number_of_admin_user'''));
  318.                     $goc->setUserAllowed($post->get('number_of_user'''));
  319.                     $goc->setSubscriptionMonth($post->get('subscription_month'''));
  320.                     $goc->setCompanyDescription($post->get('company_description'''));
  321.                     $goc->setDbUser($post->get('db_user'));
  322.                     $goc->setDbPass($post->get('db_pass'));
  323.                     $goc->setDbHost($post->get('db_host'));
  324.                     $goc->setCompanyGroupServerId($companyGroupServerId);
  325.                     $goc->setCompanyGroupServerAddress($companyGroupServerAddress);
  326.                     $goc->setCompanyGroupServerPort($companyGroupServerPort);
  327.                     $goc->setCompanyGroupServerHash($companyGroupServerHash);
  328.                     foreach ($request->files as $uploadedFile) {
  329.                         if ($uploadedFile != null) {
  330.                             $fileName 'company_image' $appId '.' $uploadedFile->guessExtension();
  331.                             $path $fileName;
  332.                             $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/CompanyImage/';
  333.                             if ($goc->getImage() != null && $goc->getImage() != '' && file_exists($this->container->getParameter('kernel.root_dir') . '/../web' $goc->getImage())) {
  334.                                 unlink($this->container->getParameter('kernel.root_dir') . '/../web' $goc->getImage());
  335.                             }
  336.                             if (!file_exists($upl_dir)) {
  337.                                 mkdir($upl_dir0777true);
  338.                             }
  339.                             $file $uploadedFile->move($upl_dir$path);
  340.                             if ($path != "")
  341.                                 $goc->setImage('/uploads/CompanyImage/' $path);
  342.                         }
  343.                     }
  344.                     $em_goc->persist($goc);
  345.                     $em_goc->flush();
  346.                     $goc->setDbName('cg_' $appId '_' $companyGroupHash);
  347.                     $goc->setDbUser($serverList[$companyGroupServerId]['dbUser']);
  348.                     $goc->setDbPass($serverList[$companyGroupServerId]['dbPass']);
  349.                     $goc->setDbHost('localhost');
  350.                     $em_goc->flush();
  351.                     $centralUser $this->getDoctrine()->getManager('company_group')
  352.                         ->getRepository("CompanyGroupBundle:EntityApplicantDetails")
  353.                         ->findOneBy(array(
  354.                             'applicantId' => $session->get(UserConstants::USER_ID0)
  355.                         ));
  356.                     if ($centralUser) {
  357.                         $userAppIds json_decode($centralUser->getUserAppIds(), true);
  358.                         $userTypesByAppIds json_decode($centralUser->getUserTypesByAppIds(), true);
  359.                         if ($userAppIds == null$userAppIds = [];
  360.                         if ($userTypesByAppIds == null$userTypesByAppIds = [];
  361.                         $userAppIds array_merge($userAppIdsarray_diff([$appId], $userAppIds));
  362.                         if (!isset($userTypesByAppIds[$appId])) {
  363.                             $userTypesByAppIds[$appId] = [];
  364.                         }
  365.                         $userTypesByAppIds[$appId] = array_merge($userTypesByAppIds[$appId], array_diff([UserConstants::USER_TYPE_SYSTEM], $userTypesByAppIds[$appId]));
  366.                         $centralUser->setUserAppIds(json_encode($userAppIds));
  367.                         $centralUser->setUserTypesByAppIds(json_encode($userTypesByAppIds));
  368.                         $em_goc->flush();
  369.                     }
  370.                     $accessList $session->get('userAccessList', []);
  371.                     $d = array(
  372.                         'userType' => UserConstants::USER_TYPE_SYSTEM,
  373.                         'globalId' => $session->get(UserConstants::USER_ID0),
  374.                         'serverId' => $companyGroupServerId,
  375.                         'serverUrl' => $companyGroupServerAddress,
  376.                         'serverPort' => $companyGroupServerPort,
  377.                         'systemType' => '_ERP_',
  378.                         'companyId' => 1,
  379.                         'appId' => $appId,
  380.                         'companyLogoUrl' => $goc->getImage(),
  381.                         'companyName' => $goc->getName(),
  382.                         'authenticationStr' => $this->get('url_encryptor')->encrypt(json_encode(
  383.                                 array(
  384.                                     'globalId' => $session->get(UserConstants::USER_ID0),
  385.                                     'appId' => $appId,
  386.                                     'authenticate' => 1,
  387.                                     'userType' => UserConstants::USER_TYPE_SYSTEM
  388.                                 )
  389.                             )
  390.                         ),
  391.                         'userCompanyList' => [
  392.                         ]
  393.                     );
  394.                     $accessList[] = $d;
  395.                     $session->set('userAccessList'$accessList);
  396.                 }
  397.                 ///now update Server
  398.                 ///
  399.                 if ($goc->getInitiateFlag() == || $goc->getInitiateFlag() == 1//pending Initiation and paid
  400.                 {
  401.                     ///NOw pushing to server
  402.                     $output '';
  403.                     $file $this->container->getParameter('kernel.root_dir') . '/../web' $goc->getImage(); //<-- Path could be relative
  404.                     if (file_exists($file)) {
  405. //                        $file = new \CURLFile($this->container->getParameter('kernel.root_dir') . '/../web/uploads/CompanyImage/' . $company->getImage()); //<-- Path could be relative
  406.                         $mime mime_content_type($file);
  407.                         $info pathinfo($file);
  408.                         $name $info['basename'];
  409.                         if (strpos($mime'image') !== false) {
  410.                             $output = new \CURLFile($file$mime$name);
  411.                         }
  412.                     }
  413.                     $post_fields = array(
  414.                         'company_id' => 1,
  415.                         'goc_id' => $goc->getId(),
  416.                         'app_id' => $goc->getAppId(),
  417.                         'dark_vibrant' => '',
  418.                         'light_vibrant' => '',
  419.                         'vibrant' => '',
  420.                         'company_type' => $goc->getCompanyType(),
  421.                         'company_name' => $goc->getName(),
  422.                         'company_address' => $goc->getAddress(),
  423.                         'company_s_address' => $goc->getShippingAddress(),
  424.                         'company_b_address' => $goc->getBillingAddress(),
  425.                         'company_image' => $goc->getImage(),
  426.                         'company_motto' => $goc->getMotto(),
  427.                         'company_i_footer' => $goc->getInvoiceFooter(),
  428.                         'company_g_footer' => $goc->getGeneralFooter(),
  429.                         'company_tin' => $goc->getCompanyTin(),
  430.                         'company_bin' => $goc->getCompanyBin(),
  431.                         'company_reg' => $goc->getCompanyReg(),
  432.                         'company_tl' => $goc->getCompanyTl(),
  433.                         'usage_valid_upto_dt_str' => '@' $usageValidUpto->format('U'),
  434. //                    'sms_enabled' => $goc->getSmsNotificationEnabled(),
  435. //                    'sms_settings' => $goc->getSmsSettings(),
  436.                         'companyGroupHash' => $goc->getCompanyGroupHash(),
  437.                         'number_of_admin_user' => $goc->getAdminUserAllowed(),
  438.                         'number_of_user' => $goc->getUserAllowed(),
  439.                         'db_name' => $goc->getDbName(),
  440.                         'db_user' => $goc->getDbUser(),
  441.                         'db_pass' => $goc->getDbPass(),
  442.                         'db_host' => $goc->getDbHost(),
  443.                         'companyGroupServerId' => $goc->getCompanyGroupServerId(),
  444.                         'companyGroupServerAddress' => $goc->getCompanyGroupServerAddress(),
  445.                         'companyGroupServerHash' => $goc->getCompanyGroupServerHash(),
  446.                         'companyGroupServerPort' => $goc->getCompanyGroupServerPort(),
  447.                         'file' => $output
  448.                     );
  449.                     $urlToCall $goc->getCompanyGroupServerAddress() . '/UpdateCompanyGroupDataToRelevantServer';
  450.                     $curl curl_init();
  451.                     curl_setopt_array($curl, array(
  452.                         CURLOPT_RETURNTRANSFER => 1,
  453.                         CURLOPT_POST => 1,
  454.                         CURLOPT_URL => $urlToCall,
  455.                         CURLOPT_CONNECTTIMEOUT => 10,
  456.                         CURLOPT_SSL_VERIFYPEER => false,
  457.                         CURLOPT_SSL_VERIFYHOST => false,
  458.                         CURLOPT_HTTPHEADER => array(),
  459.                         CURLOPT_POSTFIELDS => $post_fields
  460.                     ));
  461.                     $retData curl_exec($curl);
  462.                     $errData curl_error($curl);
  463.                     curl_close($curl);
  464.                     $goc->setInitiateFlag(1);// initiated
  465.                 }
  466.             }
  467.             return new JsonResponse(array(
  468.                 'user_access_data' => $d,
  469.                 'initiated' => 1
  470.             ));
  471.         } else {
  472.             $em_goc $this->getDoctrine()->getManager('company_group');
  473.             $findByQuery = array(
  474. //                'active' => 1
  475.                 'appId' => $post->get('app_id')
  476.             );
  477.             $goc $em_goc->getRepository("CompanyGroupBundle:CompanyGroup")
  478.                 ->findOneBy($findByQuery);
  479.             if (!$goc)
  480.                 $goc = new CompanyGroup();
  481.             $goc->setName($post->get('company_name'));
  482.             $goc->setCompanyGroupHash($post->get('companyGroupHash'));
  483.             $goc->setAppId($post->get('app_id'));
  484. //            $goc->setCompanyType($post->get('company_type'));
  485.             $goc->setAddress($post->get('address'));
  486. //            $goc->setDarkVibrant($post->get('dark_vibrant'));
  487. //            $goc->setLightVibrant($post->get('light_vibrant'));
  488. //            $goc->setVibrant($post->get('vibrant'));
  489.             $goc->setDbName($post->get('db_name'));
  490.             $goc->setDbUser($post->get('db_user'));
  491.             $goc->setDbPass($post->get('db_pass'));
  492.             $goc->setDbHost($post->get('db_host'));
  493.             $goc->setActive(1);
  494.             $goc->setShippingAddress($post->get('s_address'));
  495.             $goc->setBillingAddress($post->get('b_address'));
  496.             $goc->setMotto($post->get('motto'));
  497.             $goc->setInvoiceFooter($post->get('i_footer'));
  498.             $goc->setGeneralFooter($post->get('g_footer'));
  499.             $goc->setCompanyReg($post->get('company_reg'''));
  500.             $goc->setCompanyTin($post->get('company_tin'''));
  501.             $goc->setCompanyBin($post->get('company_bin'''));
  502.             $goc->setCompanyTl($post->get('company_tl'''));
  503.             $goc->setCompanyType($post->get('company_type'''));
  504.             $goc->setCurrentSubscriptionPackageId($post->get('package'''));
  505. //                $goc->setCu($post->get('package', ''));
  506.             $goc->setAdminUserAllowed($post->get('number_of_admin_user'''));
  507.             $goc->setUserAllowed($post->get('number_of_user'''));
  508.             $goc->setSubscriptionMonth($post->get('subscription_month'''));
  509.             $goc->setCompanyDescription($post->get('company_description'''));
  510.             $goc->setCompanyGroupServerId($post->get('companyGroupServerId'''));
  511.             $goc->setCompanyGroupServerAddress($post->get('companyGroupServerAddress'''));
  512.             $goc->setCompanyGroupServerPort($post->get('companyGroupServerPort'''));
  513.             $goc->setCompanyGroupServerHash($post->get('companyGroupServerHash'''));
  514. //            $goc->setSmsNotificationEnabled($post->get('sms_enabled'));
  515. //            $goc->setSmsSettings($post->get('sms_settings'));
  516.             foreach ($request->files as $uploadedFile) {
  517. //            if($uploadedFile->getImage())
  518. //                var_dump($uploadedFile->getFile());
  519. //                var_dump($uploadedFile);
  520.                 if ($uploadedFile != null) {
  521.                     $fileName 'company_image' $post->get('app_id') . '.' $uploadedFile->guessExtension();
  522.                     $path $fileName;
  523.                     $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/CompanyImage/';
  524.                     if ($goc->getImage() != null && $goc->getImage() != '' && file_exists($this->container->getParameter('kernel.root_dir') . '/../web' $goc->getImage())) {
  525.                         unlink($this->container->getParameter('kernel.root_dir') . '/../web' $goc->getImage());
  526.                     }
  527.                     if (!file_exists($upl_dir)) {
  528.                         mkdir($upl_dir0777true);
  529.                     }
  530.                     $file $uploadedFile->move($upl_dir$path);
  531.                     if ($path != "")
  532.                         $goc->setImage('/uploads/CompanyImage/' $path);
  533.                 }
  534.             }
  535.             $em_goc->persist($goc);
  536.             $em_goc->flush();
  537.             $connector $this->container->get('application_connector');
  538.             $connector->resetConnection(
  539.                 'default',
  540.                 $goc->getDbName(),
  541.                 $goc->getDbUser(),
  542.                 $goc->getDbPass(),
  543.                 $goc->getDbHost(),
  544.                 $reset true);
  545.             $em $this->getDoctrine()->getManager();
  546.             $prePopulateFlag 0;
  547.             if ($em->getConnection()->isConnected()) {
  548.             } else {
  549.                 $servername $goc->getDbHost();
  550.                 $username $goc->getDbUser();
  551.                 $password $goc->getDbPass();
  552.                 // Create connection
  553.                 $conn = new \mysqli($servername$username$password);
  554.                 // Check connection
  555.                 if ($conn->connect_error) {
  556.                     die("Connection failed: " $conn->connect_error);
  557.                 }
  558.                 // Create database
  559.                 $sql "CREATE DATABASE " $goc->getDbName();
  560.                 if ($conn->query($sql) === TRUE) {
  561.                     $prePopulateFlag 1;
  562.                     //                                echo "Database created successfully";
  563.                 } else {
  564.                     //                                echo "Error creating database: " . $conn->error;
  565.                 }
  566.                 $conn->close();
  567.             }
  568.             $connector->resetConnection(
  569.                 'default',
  570.                 $goc->getDbName(),
  571.                 $goc->getDbUser(),
  572.                 $goc->getDbPass(),
  573.                 $goc->getDbHost(),
  574.                 $reset true);
  575.             $em $this->getDoctrine()->getManager();
  576.             $tool = new SchemaTool($em);
  577.             $classes $em->getMetadataFactory()->getAllMetadata();
  578. //                    $tool->createSchema($classes);
  579.             $tool->updateSchema($classes);
  580.             if ($prePopulateFlag == 1) {
  581.                 System::prePopulateDatabase($em);
  582.             }
  583.             //now modify the company
  584.             $company $em
  585.                 ->getRepository('ApplicationBundle:Company')
  586.                 ->findOneBy(
  587.                     array()
  588.                 );
  589.             if (!$company)
  590.                 $company = new Company();
  591.             $company->setImage($goc->getImage());
  592.             $company->setName($post->get('company_name'));
  593.             $company->setCompanyHash($post->get('company_short_code'));
  594.             $company->setAppId($post->get('app_id'));
  595.             $company->setActive(1);
  596.             $company->setAddress($post->get('address'));
  597.             $company->setShippingAddress($post->get('s_address'));
  598.             $company->setBillingAddress($post->get('b_address'));
  599.             $company->setMotto($post->get('motto'));
  600.             $company->setInvoiceFooter($post->get('i_footer'));
  601.             $company->setGeneralFooter($post->get('g_footer'));
  602.             $company->setCompanyReg($post->get('company_reg'''));
  603.             $company->setCompanyTin($post->get('company_tin'''));
  604.             $company->setCompanyBin($post->get('company_bin'''));
  605.             $company->setCompanyTl($post->get('company_tl'''));
  606.             $company->setCompanyType($post->get('company_type'''));
  607.             $company->setAdminUserAllowed($post->get('number_of_admin_user'''));
  608.             $company->setUserAllowed($post->get('number_of_user'''));
  609. //            $company->setCompanyGroupServerId($post->get('companyGroupServerId', ''));
  610. //            $company->setCompanyGroupServerAddress($post->get('companyGroupServerAddress', ''));
  611. //            $company->setCompanyGroupServerPort($post->get('companyGroupServerPort', ''));
  612.             $company->setCompanyHash($post->get('companyGroupHash'''));
  613. //            $company->setCompanyGroupServerHash($post->get('companyGroupServerHash', ''));
  614.             //new fields
  615.             if ($post->get('usage_valid_upto_dt_str'null) != null) {
  616.                 $usageValidUpto = new \DateTime($post->get('usage_valid_upto_dt_str'null));
  617.                 $company->setUsageValidUptoDate($usageValidUpto);
  618.                 $company->setUsageValidUptoDateTs($usageValidUpto->format('U'));
  619.             } else {
  620.                 $company->setUsageValidUptoDate(null);
  621.                 $company->setUsageValidUptoDateTs(0);
  622.             }
  623.             $em->persist($company);
  624.             $em->flush();
  625.             //initiate Admin
  626.             $userName $request->request->get('username'$request->query->get('username''admin'));
  627.             $name $request->request->get('name'$request->query->get('name''System Admin'));
  628.             $password $request->request->get('password'$request->query->get('password''admin'));
  629.             $email $request->request->get('email'$request->query->get('email''admin'));
  630.             $encodedPassword $this->container->get('sha256salted_encoder')->encodePassword($password$userName);
  631.             $companyIds $request->request->get('companyIds'$request->query->get('companyIds', [1]));
  632.             $branchIds $request->request->get('branchIds'$request->query->get('branchIds', []));
  633.             $appIds $request->request->get('appIds'$request->query->get('appIds', [$post->get('app_id'0)]));
  634.             $freshFlag $request->request->get('fresh'$request->query->get('fresh'0));
  635.             $message $this->get('user_module')->addNewUser(
  636.                 $name,
  637.                 $email,
  638.                 $userName,
  639.                 $password,
  640.                 '',
  641.                 0,
  642.                 1,
  643.                 UserConstants::USER_TYPE_SYSTEM,
  644.                 $companyIds,
  645.                 $branchIds,
  646.                 '',
  647.                 "",
  648.                 1
  649.             );
  650.             $post_fields = array(
  651.                 'app_id' => $company->getAppId(),
  652.             );
  653.             return new JsonResponse($post_fields);
  654.         }
  655.     }
  656.     //update database schema
  657.     public function RunScheduledNotificationAction(Request $request)
  658.     {
  659.         $message "";
  660.         $gocList = [];
  661.         $outputList = [];
  662.         $scheduler $this->get('scheduler_service');
  663.         $connector $this->get('application_connector');
  664.         $mail_module $this->get('mail_module');
  665.         $gocEnabled 1;
  666. //        if($this->getContainer()->hasParameter('entity_group_enabled'))
  667. //            $gocEnabled= $this->getContainer()->getParameter('entity_group_enabled');
  668. //        $to_print=$app_data->UpdatePostDatedTransaction();
  669. //        $output->writeln($to_print);
  670.         $to_print $scheduler->checkAndSendScheduledNotification($connector$gocEnabled0$mail_module);
  671.         return new JsonResponse(array(
  672.             'to_print' => $to_print
  673.         ));
  674.     }
  675.     public function UpdateDatabaseSchemaAction(Request $request)
  676.     {
  677.         $dtHere = array(
  678.             'autoStartUpdateHit' => $request->query->get('autoStartUpdateHit'0),
  679.             'page_title' => 'Server Actions',
  680.         );
  681.         if ($request->query->get('returnJson'0) == 1) {
  682.             $message "";
  683.             $gocList = [];
  684.             $outputList = [];
  685.             $configJson = array();
  686.             $configJson['appVersion'] = GeneralConstant::ENTITY_APP_VERSION;
  687.             $configJson['success'] = false;
  688.             $configJson['debugData'] = [];
  689.             $configJson['pending_doc_count'] = 0;
  690.             $configJson['initiateDataBaseFlagByGoc'] = array();
  691.             $configJson['motherLode'] = "http://erp.ourhoneybee.eu";
  692.             $systemType $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
  693.             $thisMomentNow = new \DateTime();
  694.             $currTimeTs $thisMomentNow->format('U');
  695.             $em $this->getDoctrine()->getManager('company_group');
  696.             $em_goc $this->getDoctrine()->getManager('company_group');
  697.             $em->getConnection()->connect();
  698.             $connected $em->getConnection()->isConnected();
  699.             $serverId $this->container->hasParameter('server_id') ? $this->container->getParameter('server_id') : '_ALL_';
  700.             if ($connected) {
  701.                 if ($request->query->get('prepareEntityGroup'0) == 1) {
  702.                     $tool = new SchemaTool($em);
  703.                     $classes $em->getMetadataFactory()->getAllMetadata();
  704. //                    $tool->createSchema($classes);
  705.                     $tool->updateSchema($classes);
  706.                     if ($request->query->get('fixEmptyPassword'0) == 1) {
  707.                         $query "SELECT * from  entity_applicant_details   where password not like '##UNLOCKED##'";
  708.                         $stmt $em_goc->getConnection()->prepare($query);
  709.                         $stmt->execute();
  710.                         $results $stmt->fetchAll();
  711.                         foreach ($results as $qpo) {
  712.                             if ($this->container->get('sha256salted_encoder')->isPasswordValid($qpo['password'], ''$qpo['salt'])
  713.                                 || $this->container->get('sha256salted_encoder')->isPasswordValid($qpo['password'], null$qpo['salt'])
  714.                             ) {
  715.                                 $queryGG "update entity_applicant_details set password ='##UNLOCKED##' and trigger_reset_password=1 where applicant_id=" $qpo['applicant_id'];
  716.                                 $stmt $em_goc->getConnection()->prepare($queryGG);
  717.                                 $stmt->execute();
  718.                                 $stmt->closeCursor();
  719.                             }
  720.                         }
  721.                     }
  722.                     if ($request->query->get('triggerReferScore'0) == 1) {
  723.                         $query "SELECT * from  entity_meeting_session   where booked_by_id !=0 and booked_by_id is not NULL and booked_by_id !=student_id";
  724.                         $stmt $em_goc->getConnection()->prepare($query);
  725.                         $stmt->execute();
  726.                         $results $stmt->fetchAll();
  727.                         foreach ($results as $qpo) {
  728.                             MiscActions::updateEntityPerformanceIndex($em_goc, [
  729.                                 'targetId' => $qpo['booked_by_id'],
  730.                                 'conversionData' => [
  731.                                     'count' => 1,
  732.                                     'score' => 10,
  733.                                 ]
  734.                             ],
  735.                                 new \DateTime($qpo['created_at']));
  736.                         }
  737.                         $query "SELECT * from  entity_meeting_session   where booking_referer_id !=0 and booking_referer_id is not NULL and booking_referer_id !=student_id";
  738.                         $stmt $em_goc->getConnection()->prepare($query);
  739.                         $stmt->execute();
  740.                         $results $stmt->fetchAll();
  741.                         foreach ($results as $qpo) {
  742.                             MiscActions::updateEntityPerformanceIndex($em_goc, [
  743.                                 'targetId' => $qpo['booking_referer_id'],
  744.                                 'referData' => [
  745.                                     'count' => 1,
  746.                                     'score' => 10,
  747.                                 ]
  748.                             ],
  749.                                 new \DateTime($qpo['created_at'])
  750.                             );
  751.                         }
  752.                     }
  753.                     if ($request->query->get('refreshBuddyBeeSalt'0) == 1) {
  754.                         $query "
  755.                         UPDATE entity_applicant_details set temp_password=''  where 1;
  756.                         UPDATE entity_applicant_details set salt=username  where username != '' and username is not NULL and (salt ='' or salt is  NULL);
  757.                         UPDATE entity_applicant_details set salt='beesalt'  where (salt ='' or salt is  NULL) and (username ='' or username is  NULL);
  758.                       ";
  759.                         $stmt $em_goc->getConnection()->prepare($query);
  760.                         $stmt->execute();
  761.                         $stmt->closeCursor();
  762.                     }
  763.                     if ($request->query->get('refreshLastSettingsUpdatedTs'0) == 1) {
  764.                         $query "
  765.               
  766.                         UPDATE entity_user set last_settings_updated_ts=$currTimeTs  where 1;
  767.                         UPDATE entity_applicant_details set last_settings_updated_ts=$currTimeTs  where 1;
  768.                      
  769.                       ";
  770.                         $stmt $em_goc->getConnection()->prepare($query);
  771.                         $stmt->execute();
  772.                         $stmt->closeCursor();
  773.                     }
  774.                     $get_kids_sql "update `company_group` set `schema_update_pending_flag` =1 where 1;";
  775.                     $stmt $em_goc->getConnection()->prepare($get_kids_sql);
  776.                     $stmt->execute();
  777.                     $stmt->closeCursor();
  778.                     $stmt $em_goc->getConnection()->prepare("select count(id) id_count from company_group where active=1 and schema_update_pending_flag=1;");
  779.                     $stmt->execute();
  780.                     $check_here $stmt->fetchAll();
  781.                     $pending_id_count 0;
  782.                     if (isset($check_here[0]))
  783.                         $pending_id_count $check_here[0]['id_count'];
  784.                     return new JsonResponse(array(
  785.                         'pending_doc_count' => $pending_id_count,
  786.                         'success' => true
  787.                     ));
  788.                 } else
  789.                     if ($systemType != '_CENTRAL_') {
  790.                         $stmt $em_goc->getConnection()->prepare("select count(id) id_count from company_group where active=1 and schema_update_pending_flag=1;");
  791.                         $stmt->execute();
  792.                         $check_here $stmt->fetchAll();
  793.                         if (isset($check_here[0]))
  794.                             $configJson['pending_doc_count'] = $check_here[0]['id_count'];
  795. //                        if($serverId!='_ALL_')
  796.                         $gocList $this->getDoctrine()->getManager('company_group')
  797.                             ->getRepository("CompanyGroupBundle:CompanyGroup")
  798.                             ->findBy(
  799.                                 array(
  800.                                     'active' => 1,
  801. //                                    'serverId' => 1,
  802.                                     'schemaUpdatePendingFlag' => 1
  803.                                 ), array(), 1
  804.                             );
  805.                     }
  806.             }
  807.             $gocDataList = [];
  808.             $gocEntryObjectList = [];
  809.             foreach ($gocList as $entry) {
  810.                 $d = array(
  811.                     'name' => $entry->getName(),
  812.                     'image' => $entry->getImage(),
  813.                     'shippingAddress' => $entry->getShippingAddress(),
  814.                     'billingAddress' => $entry->getBillingAddress(),
  815.                     'id' => $entry->getId(),
  816.                     'dbName' => $entry->getDbName(),
  817.                     'dbUser' => $entry->getDbUser(),
  818.                     'dbPass' => $entry->getDbPass(),
  819.                     'dbHost' => $entry->getDbHost(),
  820.                     'appId' => $entry->getAppId(),
  821.                     'companyRemaining' => $entry->getCompanyRemaining(),
  822.                     'companyAllowed' => $entry->getCompanyAllowed(),
  823.                 );
  824.                 $gocDataList[$entry->getId()] = $d;
  825.                 $gocEntryObjectList[$entry->getId()] = $entry;
  826.             }
  827.             $gocDbName '';
  828.             $gocDbUser '';
  829.             $gocDbPass '';
  830.             $gocDbHost '';
  831.             $gocId 0;
  832.             foreach ($gocDataList as $gocId => $entry) {
  833.                 if (1) {
  834.                     $connector $this->container->get('application_connector');
  835.                     $connector->resetConnection(
  836.                         'default',
  837.                         $gocDataList[$gocId]['dbName'],
  838.                         $gocDataList[$gocId]['dbUser'],
  839.                         $gocDataList[$gocId]['dbPass'],
  840.                         $gocDataList[$gocId]['dbHost'],
  841.                         $reset true);
  842.                     $em $this->getDoctrine()->getManager();
  843.                     $configJson['name'] = $entry['name'];
  844.                     $configJson['image'] = $entry['image'];
  845.                     $configJson['appId'] = $entry['appId'];
  846.                     if ($request->query->get('delTable''') != '') {
  847.                         $get_kids_sql "DROP TABLE " $request->query->get('delTable') . "  ;";
  848.                         $stmt $em->getConnection()->prepare($get_kids_sql);
  849.                         $stmt->execute();
  850.                         $stmt->closeCursor();
  851.                     }
  852.                     $tool = new SchemaTool($em);
  853.                     $classes $em->getMetadataFactory()->getAllMetadata();
  854. //                    $tool->createSchema($classes);
  855.                     $tool->updateSchema($classes);
  856.                     //temp
  857.                     //temp end
  858.                     if ($request->query->get('refreshLastSettingsUpdatedTs'0) == 1) {
  859.                         $query "
  860.                                     UPDATE sys_user set last_settings_updated_ts=$currTimeTs  where 1;
  861.                                     UPDATE acc_clients set last_settings_updated_ts=$currTimeTs  where 1;
  862.                                     UPDATE acc_suppliers set last_settings_updated_ts=$currTimeTs  where 1;
  863.                      
  864.                       ";
  865.                         $stmt $em->getConnection()->prepare($query);
  866.                         $stmt->execute();
  867.                         $stmt->closeCursor();
  868.                     }
  869.                     if ($request->query->get('encryptTrans'0) == 1) {
  870.                         MiscActions::encryptTrans($em'_ALL_'0);
  871.                     }
  872.                     if ($request->query->get('decryptTrans'0) == 1) {
  873.                         MiscActions::decryptTrans($em'_ALL_'0);
  874.                     }
  875.                     if ($request->query->get('createdByRefresh'0) == 1) {
  876.                         foreach (GeneralConstant::$Entity_list as $entity => $entityName) {
  877.                             if (in_array($entity, [54]))
  878.                                 continue;
  879.                             if (!$em->getMetadataFactory()->isTransient('ApplicationBundle:' $entityName)) {
  880. //                                $className = ('\\ApplicationBundle\\Entity\\') . $entityName;
  881. //                                $theEntity = new $className();
  882. //                                $test_now=$theEntity->getCreatedUserId();
  883.                                 //if its approval decode signature and add it to dbase and pass the id
  884.                                 $sigId null;
  885.                                 $doc null;
  886.                                 $docList $em->getRepository('ApplicationBundle:' $entityName)
  887.                                     ->findBy(
  888.                                         array(//                                        GeneralConstant::$Entity_id_field_list[$entity] => $entity_id,
  889.                                         )
  890.                                     );
  891.                                 foreach ($docList as $doc) {
  892.                                     $notYetAdded 1;
  893.                                     foreach ([12] as $approveRole) {
  894.                                         $getIdfunc GeneralConstant::$Entity_id_get_method_list[$entity];
  895.                                         $entity_id $doc->$getIdfunc();
  896.                                         $loginId null;
  897.                                         $sigId null;
  898.                                         $user_data = [];
  899.                                         if ($approveRole == 1//created
  900.                                         {
  901.                                             $loginId $doc->getCreatedLoginId();
  902.                                             $notYetAdded $doc->getCreatedUserId() == null 0;
  903.                                             $sigId $doc->getCreatedSigId();
  904.                                             $user_data Users::getUserInfoByLoginId($em$loginId);
  905.                                             if (isset($user_data['id'])) {
  906.                                                 $doc->setCreatedUserId($user_data['id']);
  907.                                                 $doc->setCreatedSigId(null);
  908.                                             }
  909.                                             $em->flush();
  910.                                         }
  911.                                         if ($approveRole == 2//edited
  912.                                         {
  913.                                             $loginId $doc->getEditedLoginId();
  914.                                             $sigId $doc->getEditedSigId();
  915.                                             $notYetAdded $doc->getEditedUserId() == null 0;
  916.                                             $user_data Users::getUserInfoByLoginId($em$loginId);
  917.                                             $doc->setEditedSigId($sigId);
  918.                                             if (isset($user_data['id'])) {
  919.                                                 $doc->setEditedUserId($user_data['id']);
  920.                                                 $doc->setEditedSigId(null);
  921.                                                 $doc->setLastModifiedDate(new \DateTime());
  922.                                             }
  923.                                             $em->flush();
  924.                                         }
  925.                                         if (isset($user_data['id']) && $notYetAdded == 1) {
  926.                                             $new = new Approval();
  927.                                             $new->setEntity($entity);
  928.                                             $new->setEntityId($entity_id);
  929.                                             $new->setPositionId(null);
  930.                                             $new->setSequence(0);
  931.                                             $new->setSkipPrintFlag(0);
  932.                                             $new->setUserAssignType(1);
  933.                                             $new->setDocumentHash($doc->getDocumentHash());
  934.                                             //            $new->setUserIds($value->getUserId()); //<-----
  935.                                             $new->setRoleType($approveRole);
  936.                                             $new->setRequired(0);
  937.                                             $new->setSuccession(0);
  938.                                             $new->setAction(1); //pending status
  939.                                             $new->setLoginId($loginId); //pending status
  940.                                             $new->setCurrent(GeneralConstant::CURRENTLY_NON_PENDING_APPROVAL);
  941.                                             $new->setSuccessionTimeout(0);
  942.                                             $new->setSigId($sigId);
  943.                                             $new->setNote('');
  944.                                             $new->setUserIds(json_encode([$user_data['id']])); //<-----
  945.                                             $em->persist($new);
  946.                                             $em->flush();
  947.                                         }
  948.                                     }
  949.                                 }
  950.                             }
  951.                         }
  952.                     }
  953.                     if ($request->query->get('rectifyOldBoq'0) == 1) {
  954.                         $boqs $em
  955.                             ->getRepository('ApplicationBundle:ProjectBoq')
  956.                             ->findby(array(//                                    'projectId'=>$projectId
  957.                             ));
  958.                         foreach ($boqs as $boq) {
  959. //
  960. //                            //now the data
  961. //                            $data = [];
  962. //                            $newData = [];
  963. //                            if ($boq)
  964. //                                $data = json_decode($boq->getData(), true);
  965. //                            if ($data == null)
  966. //                                $data = [];
  967. //                            $defValuesProduct = array(
  968. //                                'product_note' => '',
  969. //                                'product_alias' => '',
  970. //                                'is_foreign_item' => 0,
  971. //                                'product_segmentIndex' => 0,
  972. //                                'product_currency_id' => 0,
  973. //                                'product_currency_text' => '',
  974. //                                'product_currency_multiply_rate' => 1,
  975. //                                'product_scope' => 1,
  976. //                                'product_scopeHolderId' => 0,
  977. //                                'product_scopeHolderName' => '',
  978. //                                'product_scopeDescription' => '',
  979. //                            );
  980. //                            $defValuesService = array(
  981. //                                'service_note' => '',
  982. //                                'service_alias' => '',
  983. //                                'is_foreign_service' => 0,
  984. //                                'service_segmentIndex' => 0,
  985. //                                'service_currency_id' => 0,
  986. //                                'service_currency_text' => '',
  987. //                                'service_currency_multiply_rate' => 1,
  988. //                                'service_scope' => 1,
  989. //                                'service_scopeHolderId' => 0,
  990. //                                'service_scopeHolderName' => '',
  991. //                                'service_scopeDescription' => '',
  992. //                            );
  993. //
  994. //
  995. //                            if (!empty($data)) {
  996. //                                $last_key = array_key_last($data);
  997. ////                                if (isset($data[$last_key]['Products']['product_scope']))
  998. ////                                    continue;
  999. ////                                    if (count($data[$last_key]['Products']['products'])==count($data[$last_key]['Products']['is_foreign_item']) )
  1000. //
  1001. //
  1002. //                                $kho = 0;
  1003. //                                $dt_poka = $data[0];
  1004. //                                foreach ($data as $kho => $dt_poka) {
  1005. //
  1006. //
  1007. //                                    if (isset($dt_poka['Products']['products']))
  1008. //                                        foreach ($defValuesProduct as $gopaa => $boka) {
  1009. //                                            if (!isset($dt_poka['Products'][$gopaa]))
  1010. //                                                $dt_poka['Products'][$gopaa] = array_fill(0, count($dt_poka['Products']['products']), $boka);
  1011. //                                            else if ($dt_poka['Products'][$gopaa] == null)
  1012. //                                                $dt_poka['Products'][$gopaa] = array_fill(0, count($dt_poka['Products']['products']), $boka);
  1013. //
  1014. //
  1015. //                                        }
  1016. //                                    if (isset($dt_poka['Services']['services']))
  1017. //                                        foreach ($defValuesService as $gopaa => $boka) {
  1018. //                                            if (!isset($dt_poka['Services'][$gopaa]))
  1019. //                                                $dt_poka['Services'][$gopaa] = array_fill(0, count($dt_poka['Services']['services']), $boka);
  1020. //                                            else if ($dt_poka['Services'][$gopaa] == null)
  1021. //                                                $dt_poka['Services'][$gopaa] = array_fill(0, count($dt_poka['Services']['services']), $boka);
  1022. //
  1023. //                                        }
  1024. //
  1025. //                                    if (!isset($dt_poka['serviceSegmentData']))
  1026. //                                        $dt_poka['serviceSegmentData'] = [
  1027. //                                            array(
  1028. //                                                "title" => "General Services",
  1029. //                                                "index" => 0,
  1030. //                                            )
  1031. //                                        ];
  1032. //                                    else if ($dt_poka['serviceSegmentData'] == null || empty($dt_poka['serviceSegmentData']))
  1033. //                                        $dt_poka['serviceSegmentData'] = [
  1034. //                                            array(
  1035. //                                                "title" => "General Services",
  1036. //                                                "index" => 0,
  1037. //                                            )
  1038. //                                        ];
  1039. //
  1040. //                                    if (!isset($dt_poka['productSegmentData']))
  1041. //                                        $dt_poka['productSegmentData'] = [
  1042. //                                            array(
  1043. //                                                "title" => "General Items",
  1044. //                                                "index" => 0,
  1045. //                                            )
  1046. //                                        ];
  1047. //                                    else if ($dt_poka['productSegmentData'] == null || empty($dt_poka['productSegmentData']))
  1048. //                                        $dt_poka['productSegmentData'] = [
  1049. //                                            array(
  1050. //                                                "title" => "General Items",
  1051. //                                                "index" => 0,
  1052. //                                            )
  1053. //                                        ];
  1054. //
  1055. //
  1056. //                                    $newData[$kho] = $dt_poka;
  1057. //                                }
  1058. //
  1059. //
  1060. //                                $boq->setData(json_encode($newData));
  1061. //                                $em->flush();
  1062. //
  1063. //
  1064. //                            }
  1065.                             $theProj $em->getRepository('ApplicationBundle:Project')
  1066.                                 ->findOneBy(
  1067.                                     array(
  1068.                                         'projectId' => $boq->getProjectId()
  1069.                                     )
  1070.                                 );
  1071.                             if ($theProj)
  1072.                                 $theProj->setDocumentDataId($boq->getDocumentDataId());
  1073.                             $em->flush();
  1074.                         }
  1075.                     }
  1076.                     if ($request->query->get('oldBoqToNewSystem'0) == 1) {
  1077.                         $entitiesGG = [
  1078.                             array_flip(GeneralConstant::$Entity_list)['ProjectBoq'],
  1079.                             array_flip(GeneralConstant::$Entity_list)['ProjectMaterial'],
  1080.                             array_flip(GeneralConstant::$Entity_list)['SalesProposal'],
  1081.                             array_flip(GeneralConstant::$Entity_list)['SalesLead'],
  1082.                             array_flip(GeneralConstant::$Entity_list)['ProjectOffer'],
  1083.                             array_flip(GeneralConstant::$Entity_list)['ProjectProposal'],
  1084.                         ];
  1085.                         foreach ($entitiesGG as $ent) {
  1086.                             $entityNameHere GeneralConstant::$Entity_list[$ent];
  1087.                             $the_actual_docs $em->getRepository('ApplicationBundle:' GeneralConstant::$Entity_list[$ent])
  1088.                                 ->findBy(
  1089.                                     array(//                                        GeneralConstant::$Entity_id_field_list[$ent] => $entity_id,
  1090.                                     )
  1091.                                 );
  1092.                             foreach ($the_actual_docs as $the_actual_doc) {
  1093.                                 //now the data
  1094.                                 //first find the docData if available
  1095.                                 $theDocData null;
  1096.                                 if ($entityNameHere == 'SalesProposal' || $entityNameHere == 'SalesLead') {
  1097.                                     $theDocData $em->getRepository('ApplicationBundle:DocumentData')
  1098.                                         ->findOneBy(
  1099.                                             array(
  1100.                                                 'id' => $the_actual_doc->getDocumentDataId()
  1101.                                             )
  1102.                                         );
  1103.                                     if (!$theDocData)
  1104.                                         if ($the_actual_doc->getSalesProposalId() != null && $the_actual_doc->getSalesProposalId() != 0)
  1105.                                             $theDocData $em->getRepository('ApplicationBundle:DocumentData')
  1106.                                                 ->findOneBy(
  1107.                                                     array(
  1108.                                                         'proposalId' => $the_actual_doc->getSalesProposalId()
  1109.                                                     )
  1110.                                                 );
  1111.                                     if (!$theDocData)
  1112.                                         if ($the_actual_doc->getLeadId() != null && $the_actual_doc->getLeadId() != 0)
  1113.                                             $theDocData $em->getRepository('ApplicationBundle:DocumentData')
  1114.                                                 ->findOneBy(
  1115.                                                     array(
  1116.                                                         'leadId' => $the_actual_doc->getLeadId()
  1117.                                                     )
  1118.                                                 );
  1119.                                     if (!$theDocData)
  1120.                                         if ($the_actual_doc->getProjectId() != null && $the_actual_doc->getProjectId() != 0)
  1121.                                             $theDocData $em->getRepository('ApplicationBundle:DocumentData')
  1122.                                                 ->findOneBy(
  1123.                                                     array(
  1124.                                                         'projectId' => $the_actual_doc->getProjectId()
  1125.                                                     )
  1126.                                                 );
  1127.                                     if (!$theDocData) {
  1128.                                         $theDocData = new DocumentData();
  1129.                                         if ($entityNameHere == 'SalesProposal')
  1130.                                             $theDocData->setProposalId($the_actual_doc->getSalesProposalId());
  1131.                                         if ($entityNameHere == 'SalesLead')
  1132.                                             $theDocData->setLeadId($the_actual_doc->getLeadId());
  1133.                                     }
  1134.                                 } else {
  1135.                                     $theDocData $em->getRepository('ApplicationBundle:DocumentData')
  1136.                                         ->findOneBy(
  1137.                                             array(
  1138.                                                 'id' => $the_actual_doc->getDocumentDataId()
  1139.                                             )
  1140.                                         );
  1141.                                     if (!$theDocData)
  1142.                                         $theDocData $em->getRepository('ApplicationBundle:DocumentData')
  1143.                                             ->findOneBy(
  1144.                                                 array(
  1145.                                                     'projectId' => $the_actual_doc->getProjectId()
  1146.                                                 )
  1147.                                             );
  1148.                                     if (!$theDocData) {
  1149.                                         $theDocData = new DocumentData();
  1150.                                         $theDocData->setProjectId($the_actual_doc->getProjectId());
  1151.                                     }
  1152.                                 }
  1153.                                 if ($entityNameHere == 'ProjectBoq' || $entityNameHere == 'SalesLead' || $entityNameHere == 'SalesProposal') {
  1154.                                     $data = [];
  1155.                                     $newData = [];
  1156.                                     $data json_decode($the_actual_doc->getData(), true);
  1157.                                     if ($data == null)
  1158.                                         $data = [];
  1159.                                     if (!empty($data)) {
  1160.                                         $last_key array_key_last($data);
  1161.                                         $lastIndex 0;
  1162.                                         foreach ($data as $kho => $dt_poka) {
  1163.                                             $cur_date = new \DateTime();
  1164.                                             $lead_date = new \DateTime(isset($dt_poka['lead_date']) ? $dt_poka['lead_date'] : '');
  1165.                                             $newSingleSet = array(
  1166.                                                 'refPoNumber' => isset($dt_poka['refPoNumber']) ? $dt_poka['refPoNumber'] : '',
  1167.                                                 'segmentData' => isset($dt_poka['segmentData']) ? $dt_poka['segmentData'] : [],
  1168.                                                 'proposal_title' => isset($dt_poka['proposal_title']) ? $dt_poka['proposal_title'] : '',
  1169.                                                 'to_position' => isset($dt_poka['to_position']) ? $dt_poka['to_position'] : '',
  1170.                                                 'system_subCategory' => isset($dt_poka['system_subCategory']) ? $dt_poka['system_subCategory'] : '',
  1171.                                                 'system_size' => isset($dt_poka['system_size']) ? $dt_poka['system_size'] : '',
  1172.                                                 'system_unit' => isset($dt_poka['system_unit']) ? $dt_poka['system_unit'] : '',
  1173.                                                 'system_price' => isset($dt_poka['system_price']) ? $dt_poka['system_price'] : '',
  1174.                                                 'msaTotal' => isset($dt_poka['msaTotal']) ? $dt_poka['msaTotal'] : 0,
  1175.                                                 'totalProjectValue' => isset($dt_poka['totalProjectValue']) ? $dt_poka['totalProjectValue'] : 0,
  1176.                                                 'cl_subject' => isset($dt_poka['cl_subject']) ? $dt_poka['cl_subject'] : '',
  1177.                                                 'cl_body' => isset($dt_poka['cl_body']) ? $dt_poka['cl_body'] : '',
  1178.                                                 'vatPercentage' => isset($dt_poka['vatPercentage']) ? $dt_poka['vatPercentage'] : '',
  1179.                                                 'aitPercentage' => isset($dt_poka['aitPercentage']) ? $dt_poka['aitPercentage'] : '',
  1180.                                                 'proposalSalesValue' => isset($dt_poka['proposalSalesValue']) ? $dt_poka['proposalSalesValue'] : '',
  1181.                                                 'combined_proposal_item_name' => isset($dt_poka['combined_proposal_item_name']) ? $dt_poka['combined_proposal_item_name'] : '',
  1182.                                                 'combined_proposal_details_price' => isset($dt_poka['combined_proposal_details_price']) ? $dt_poka['combined_proposal_details_price'] : '',
  1183.                                                 'check_boq' => isset($dt_poka['check_boq']) ? $dt_poka['check_boq'] : 0,
  1184.                                                 'check_boq_individual_price' => isset($dt_poka['check_boq_individual_price']) ? $dt_poka['check_boq_individual_price'] : 0,
  1185.                                                 'check_show_combined_only' => isset($dt_poka['check_show_combined_only']) ? $dt_poka['check_show_combined_only'] : 0,
  1186.                                                 'check_override_markup' => isset($dt_poka['check_show_combined_only']) ? $dt_poka['check_show_combined_only'] : 0,
  1187.                                                 'clientId' => isset($dt_poka['client_id']) ? $dt_poka['client_id'] : 0,
  1188.                                                 'salesPersonId' => isset($dt_poka['salesPersonID']) ? $dt_poka['salesPersonID'] : 0,
  1189.                                                 'clientName' => isset($dt_poka['clientName']) ? $dt_poka['clientName'] : '',
  1190.                                                 'ClientContactPerson' => isset($dt_poka['ClientContactPerson']) ? $dt_poka['ClientContactPerson'] : '',
  1191.                                                 'ClientContactNumber' => isset($dt_poka['ClientContactNumber']) ? $dt_poka['ClientContactNumber'] : '',
  1192.                                                 'ClientDeliveryAddress' => isset($dt_poka['ClientDeliveryAddress']) ? $dt_poka['ClientDeliveryAddress'] : '',
  1193.                                                 'ClientBillingAddress' => isset($dt_poka['ClientBillingAddress']) ? $dt_poka['ClientBillingAddress'] : '',
  1194.                                                 'leadDate' => $lead_date->format('Y-m-d'),
  1195.                                                 'date' => $cur_date->format('Y-m-d'),
  1196.                                             );
  1197.                                             $newSegmentData = array();
  1198.                                             $oldSegmentSystem 0;
  1199.                                             if (isset($dt_poka['productSegmentData']) || isset($dt_poka['serviceSegmentData']))
  1200.                                                 $oldSegmentSystem 1;
  1201.                                             if ($oldSegmentSystem == 1) {
  1202.                                                 //unify the ids of segmnent. services will start from 1000+service segmentId for unification
  1203.                                                 if (isset($dt_poka['productSegmentData']))
  1204.                                                     foreach ($dt_poka['productSegmentData'] as $supu => $gupu) {
  1205.                                                         $newModSeg $gupu;
  1206.                                                         $newModSeg['index'] = $gupu['index'];
  1207.                                                         $newModSeg['title'] = isset($gupu['title']) ? $gupu['title'] : 'Items';
  1208.                                                         $newModSeg['scfc'] = isset($gupu['scfc']) ? $gupu['scfc'] : 0;
  1209.                                                         $newModSeg['uomCust'] = isset($gupu['uomCust']) ? $gupu['uomCust'] : '';
  1210.                                                         $newModSeg['unitCust'] = isset($gupu['unitCust']) ? $gupu['unitCust'] : '';
  1211.                                                         $newModSeg['priceCust'] = isset($gupu['priceCust']) ? $gupu['priceCust'] : '';
  1212.                                                         $newModSeg['currCust'] = isset($gupu['currCust']) ? $gupu['currCust'] : '';
  1213.                                                         $newModSeg['descCust'] = isset($gupu['descCust']) ? $gupu['descCust'] : '';
  1214.                                                         $newModSeg['scope'] = isset($gupu['scope']) ? $gupu['scope'] : 0;
  1215.                                                         $newModSeg['scopeId'] = isset($gupu['scopeId']) ? $gupu['scopeId'] : 0;
  1216.                                                         $newModSeg['scopeName'] = isset($gupu['scopeName']) ? $gupu['scopeName'] : '';
  1217.                                                         $newModSeg['scopeDescription'] = isset($gupu['scopeDescription']) ? $gupu['scopeDescription'] : '';
  1218.                                                         $newSegmentData[] = $newModSeg;
  1219.                                                     }
  1220.                                                 if (isset($dt_poka['serviceSegmentData']))
  1221.                                                     if ($dt_poka['serviceSegmentData'] == null || empty($dt_poka['serviceSegmentData']))
  1222.                                                         foreach ($dt_poka['serviceSegmentData'] as $supu => $gupu) {
  1223.                                                             if ($gupu['index'] == 'undefined'$gupu['index'] = 0;
  1224.                                                             if (!is_numeric($gupu['index'])) $gupu['index'] = 0;
  1225.                                                             $newModSeg $gupu;
  1226.                                                             $newModSeg['index'] = 1000 $gupu['index'];
  1227.                                                             $newModSeg['title'] = isset($gupu['title']) ? $gupu['title'] : 'Services';
  1228.                                                             $newModSeg['scfc'] = isset($gupu['scfc']) ? $gupu['scfc'] : 0;
  1229.                                                             $newModSeg['uomCust'] = isset($gupu['uomCust']) ? $gupu['uomCust'] : '';
  1230.                                                             $newModSeg['unitCust'] = isset($gupu['unitCust']) ? $gupu['unitCust'] : '';
  1231.                                                             $newModSeg['priceCust'] = isset($gupu['priceCust']) ? $gupu['priceCust'] : '';
  1232.                                                             $newModSeg['currCust'] = isset($gupu['currCust']) ? $gupu['currCust'] : '';
  1233.                                                             $newModSeg['descCust'] = isset($gupu['descCust']) ? $gupu['descCust'] : '';
  1234.                                                             $newModSeg['scope'] = isset($gupu['scope']) ? $gupu['scope'] : 0;
  1235.                                                             $newModSeg['scopeId'] = isset($gupu['scopeId']) ? $gupu['scopeId'] : 0;
  1236.                                                             $newModSeg['scopeName'] = isset($gupu['scopeName']) ? $gupu['scopeName'] : '';
  1237.                                                             $newModSeg['scopeDescription'] = isset($gupu['scopeDescription']) ? $gupu['scopeDescription'] : '';
  1238.                                                             $newSegmentData[] = $newModSeg;
  1239.                                                         }
  1240.                                                 $newSingleSet['itemSegmentData'] = $newSegmentData;
  1241.                                             }
  1242.                                             $lastSequenceBySegment = array();
  1243.                                             //now modify Services or products
  1244.                                             $oldProductSystem 0;
  1245.                                             if (!isset($dt_poka['rowData']))
  1246.                                                 $dt_poka['rowData'] = array();
  1247.                                             if (isset($dt_poka['Products']) || isset($dt_poka['Services']) || isset($dt_poka['ArCosts'])) {
  1248.                                                 $oldProductSystem 1;
  1249.                                             }
  1250.                                             if ($oldProductSystem == 1) {
  1251.                                                 $theDt = array(
  1252.                                                     'products' => [],
  1253.                                                     'services' => [],
  1254.                                                     'ar_heads' => [],
  1255.                                                 );
  1256.                                                 if (isset($dt_poka['Products']))
  1257.                                                     $theDt $dt_poka['Products'];
  1258.                                                 if (isset($theDt['products']))
  1259.                                                     foreach ($theDt['products'] as $f => $pid) {
  1260.                                                         $unit = isset($theDt['product_units'][$f]) ? $theDt['product_units'][$f] : 0;
  1261.                                                         $indexForThis = isset($theDt['index'][$f]) ? $theDt['index'][$f] : -1;
  1262.                                                         if ($indexForThis == -1) {
  1263.                                                             $indexForThis $lastIndex;
  1264.                                                             $lastIndex++;
  1265.                                                         }
  1266.                                                         $unitPrice = isset($theDt['product_unit_price'][$f]) ? $theDt['product_unit_price'][$f] : 0;
  1267.                                                         if ($unit == ''$unit 0;
  1268.                                                         if ($unitPrice == ''$unitPrice 0;
  1269.                                                         $totalPrice $unit $unitPrice;
  1270.                                                         $segmentIndex = isset($theDt['product_segmentIndex'][$f]) ? $theDt['product_segmentIndex'][$f] : 0;
  1271.                                                         $sequence = isset($theDt['product_segmentIndex'][$f]) ? $theDt['product_segmentIndex'][$f] : '_UNSET_';
  1272.                                                         if (!isset($lastSequenceBySegment[$segmentIndex]))
  1273.                                                             $lastSequenceBySegment[$segmentIndex] = -1;
  1274.                                                         if ($sequence == '_UNSET_')
  1275.                                                             $sequence $lastSequenceBySegment[$segmentIndex] + 1;
  1276.                                                         else if ($sequence == $lastSequenceBySegment[$segmentIndex])
  1277.                                                             $sequence $lastSequenceBySegment[$segmentIndex] + 1;
  1278.                                                         $lastSequenceBySegment[$segmentIndex] = $sequence;
  1279.                                                         $unitSalesPrice = isset($theDt['product_unit_sales_price'][$f]) ? $theDt['product_unit_sales_price'][$f] : $unitPrice;
  1280.                                                         if ($unitSalesPrice == ''$unitSalesPrice 0;
  1281.                                                         $totalSalesPrice $unit $unitSalesPrice;
  1282.                                                         $marginAmount = isset($theDt['product_ma'][$f]) ? $theDt['product_ma'][$f] : ($unitSalesPrice $unitPrice);
  1283.                                                         $marginRate = isset($theDt['product_ma'][$f]) ? $theDt['product_ma'][$f] : ($unitPrice == : (100 $marginAmount $unitPrice));
  1284.                                                         $discountAmount = isset($theDt['product_dr'][$f]) ? $theDt['product_dr'][$f] : 0;
  1285.                                                         $discountRate = isset($theDt['product_da'][$f]) ? $theDt['product_da'][$f] : ($totalSalesPrice == : (100 $discountAmount $totalSalesPrice));
  1286.                                                         $discountedAmount $totalSalesPrice $discountAmount;
  1287.                                                         $taxRate = isset($theDt['product_tax_percentage'][$f]) ? $theDt['product_tax_percentage'][$f] : ($unitPrice == : (100 $discountAmount $unitPrice));
  1288.                                                         $taxAmount = isset($theDt['product_tax_amount'][$f]) ? $theDt['product_tax_amount'][$f] : 0;
  1289.                                                         $finalAmount $discountedAmount $taxAmount;
  1290.                                                         $row = array(
  1291.                                                             'type' => 1,//1:product 2=service 4=tools 5:text 6: expense against head
  1292.                                                             'id' => $pid,
  1293.                                                             'index' => $indexForThis,
  1294.                                                             'isForeign' => isset($theDt['is_foreign_item'][$f]) ? $theDt['is_foreign_item'][$f] : 0,
  1295.                                                             'sequence' => $sequence,
  1296.                                                             'segmentIndex' => $segmentIndex,
  1297.                                                             'soItemId' => isset($theDt['product_soItemId'][$f]) ? $theDt['product_soItemId'][$f] : 0,
  1298.                                                             'soItemDelivered' => isset($theDt['product_soItemDelivered'][$f]) ? $theDt['product_soItemDelivered'][$f] : 0,
  1299.                                                             'soItemFound' => isset($theDt['product_soItemFound'][$f]) ? $theDt['product_soItemFound'][$f] : 0,
  1300.                                                             'alias' => isset($theDt['product_alias'][$f]) ? $theDt['product_alias'][$f] : '',
  1301.                                                             'name' => isset($theDt['product_name'][$f]) ? $theDt['product_name'][$f] : '',
  1302.                                                             'note' => isset($theDt['product_note'][$f]) ? $theDt['product_note'][$f] : '',
  1303.                                                             'fdm' => isset($theDt['product_fdm'][$f]) ? $theDt['product_fdm'][$f] : null,
  1304.                                                             'unit' => isset($theDt['product_units'][$f]) ? $theDt['product_units'][$f] : 0,
  1305.                                                             'unitTypeId' => isset($theDt['product_unit_type'][$f]) ? $theDt['product_unit_type'][$f] : 0,
  1306.                                                             'unitPrice' => $unitPrice,
  1307.                                                             'totalPrice' => $totalPrice,
  1308.                                                             'unitSalesPrice' => $unitSalesPrice,
  1309.                                                             'totalSalesPrice' => $totalSalesPrice,
  1310.                                                             'marginRate' => $marginRate,
  1311.                                                             'marginAmount' => $marginAmount,
  1312.                                                             'discountRate' => $discountRate,
  1313.                                                             'discountAmount' => $discountAmount,
  1314.                                                             'discountedAmount' => $discountedAmount,
  1315.                                                             'taxRate' => $taxRate,
  1316.                                                             'taxAmount' => $taxAmount,
  1317.                                                             'finalAmount' => $finalAmount,
  1318.                                                             'recurring' => isset($theDt['product_recurring'][$f]) ? $theDt['product_recurring'][$f] : 0,
  1319.                                                             'currency' => isset($theDt['product_currency_id'][$f]) ? $theDt['product_currency_id'][$f] : 0,
  1320.                                                             'currencyText' => isset($theDt['product_currency_text'][$f]) ? $theDt['product_currency_text'][$f] : '',
  1321.                                                             'currencyMultiplyRate' => isset($theDt['product_currency_multiply_rate'][$f]) ? $theDt['product_currency_multiply_rate'][$f] : 1,
  1322.                                                             'incoterm' => isset($theDt['incoterm'][$f]) ? $theDt['incoterm'][$f] : '',
  1323.                                                             'taxId' => isset($theDt['product_tax_config_id'][$f]) ? $theDt['product_tax_config_id'][$f] : 0,
  1324.                                                             'taxName' => isset($theDt['product_tax_config_text'][$f]) ? $theDt['product_tax_config_text'][$f] : '',
  1325.                                                             'dependencyOnIndex' => isset($theDt['product_dependency_of_index'][$f]) ? $theDt['product_dependency_of_index'][$f] : 0,
  1326.                                                             'dependencyOnPid' => isset($theDt['product_dependency_of_product_id'][$f]) ? $theDt['product_dependency_of_product_id'][$f] : 0,
  1327.                                                             'dependencyOnSid' => isset($theDt['product_dependency_of_service_id'][$f]) ? $theDt['product_dependency_of_service_id'][$f] : 0,
  1328.                                                             'dependencyOnSegment' => isset($theDt['product_dependency_of_product_index'][$f]) ? $theDt['product_dependency_of_product_index'][$f] : 0,
  1329.                                                             'warranty' => isset($theDt['product_delivery_schedule'][$f]) ? $theDt['product_delivery_schedule'][$f] : 0,
  1330.                                                             'origin' => isset($theDt['product_origin'][$f]) ? $theDt['product_origin'][$f] : 0,
  1331.                                                             'origins' => isset($theDt['product_origin'][$f]) ? [$theDt['product_origin'][$f]] : [],
  1332.                                                             'scope' => isset($theDt['product_scope'][$f]) ? $theDt['product_scope'][$f] : 0,
  1333.                                                             'scopeId' => isset($theDt['product_scopeHolderId'][$f]) ? [$theDt['product_scopeHolderId'][$f]] : 0,
  1334.                                                             'scopeName' => isset($theDt['product_scopeHolderName'][$f]) ? [$theDt['product_scopeHolderName'][$f]] : '',
  1335.                                                             'scopeDescription' => isset($theDt['product_scopeDescription'][$f]) ? [$theDt['product_scopeDescription'][$f]] : '',
  1336.                                                             'deliverySchedule' => isset($theDt['product_delivery_schedule'][$f]) ? $theDt['product_delivery_schedule'][$f] : [],
  1337.                                                             'deliveryPorts' => isset($theDt['product_delivery_ports'][$f]) ? $theDt['product_delivery_ports'][$f] : [],
  1338.                                                             'billingSchedule' => isset($theDt['product_billing_schedule'][$f]) ? $theDt['product_billing_schedule'][$f] : [],
  1339.                                                             'referenceNo' => isset($theDt['product_reference_price'][$f]) ? $theDt['product_reference_price'][$f] : '',
  1340.                                                             'referenceFiles' => isset($theDt['product_reference_price_file'][$f]) ? $theDt['product_reference_price_file'][$f] : '',
  1341.                                                         );
  1342.                                                         $dt_poka['rowData'][] = $row;
  1343.                                                     }
  1344.                                                 //now the services
  1345.                                                 $theDt = array(
  1346.                                                     'products' => [],
  1347.                                                     'services' => [],
  1348.                                                     'ar_heads' => [],
  1349.                                                 );
  1350.                                                 if (isset($dt_poka['Services']))
  1351.                                                     $theDt $dt_poka['Services'];
  1352.                                                 if (isset($theDt['services']))
  1353.                                                     foreach ($theDt['services'] as $f => $pid) {
  1354.                                                         $unit = isset($theDt['service_units'][$f]) ? $theDt['service_units'][$f] : 0;
  1355.                                                         $indexForThis = isset($theDt['index'][$f]) ? $theDt['index'][$f] : -1;
  1356.                                                         if ($indexForThis == -1) {
  1357.                                                             $indexForThis $lastIndex;
  1358.                                                             $lastIndex++;
  1359.                                                         }
  1360.                                                         $unitPrice = isset($theDt['service_unit_price'][$f]) ? $theDt['service_unit_price'][$f] : 0;
  1361.                                                         $totalPrice $unit $unitPrice;
  1362.                                                         $segmentIndex = isset($theDt['service_segmentIndex'][$f]) ? $theDt['service_segmentIndex'][$f] : 0;
  1363.                                                         if ($segmentIndex == 'undefined'$segmentIndex 0;
  1364.                                                         if (!is_numeric($segmentIndex)) $segmentIndex 0;
  1365.                                                         if ($oldSegmentSystem == 1)
  1366.                                                             $segmentIndex 1000 $segmentIndex;
  1367.                                                         $sequence = isset($theDt['service_segmentIndex'][$f]) ? $theDt['service_segmentIndex'][$f] : '_UNSET_';
  1368.                                                         if (!isset($lastSequenceBySegment[$segmentIndex]))
  1369.                                                             $lastSequenceBySegment[$segmentIndex] = -1;
  1370.                                                         if ($sequence == '_UNSET_')
  1371.                                                             $sequence $lastSequenceBySegment[$segmentIndex] + 1;
  1372.                                                         else if ($sequence == $lastSequenceBySegment[$segmentIndex])
  1373.                                                             $sequence $lastSequenceBySegment[$segmentIndex] + 1;
  1374.                                                         $lastSequenceBySegment[$segmentIndex] = $sequence;
  1375.                                                         $unitSalesPrice = isset($theDt['service_unit_sales_price'][$f]) ? $theDt['service_unit_sales_price'][$f] : $unitPrice;
  1376.                                                         $totalSalesPrice $unit $unitSalesPrice;
  1377.                                                         $marginAmount = isset($theDt['service_ma'][$f]) ? $theDt['service_ma'][$f] : ($unitSalesPrice $unitPrice);
  1378.                                                         $marginRate = isset($theDt['service_ma'][$f]) ? $theDt['service_ma'][$f] : ($unitPrice == : (100 $marginAmount $unitPrice));
  1379.                                                         $discountAmount = isset($theDt['service_dr'][$f]) ? $theDt['service_dr'][$f] : 0;
  1380.                                                         $discountRate = isset($theDt['service_da'][$f]) ? $theDt['service_da'][$f] : ($totalSalesPrice == : (100 $discountAmount $totalSalesPrice));
  1381.                                                         $discountedAmount $totalSalesPrice $discountAmount;
  1382.                                                         $taxRate = isset($theDt['service_tax_percentage'][$f]) ? $theDt['service_tax_percentage'][$f] : ($unitPrice == : (100 $discountAmount $unitPrice));
  1383.                                                         $taxAmount = isset($theDt['service_tax_amount'][$f]) ? $theDt['service_tax_amount'][$f] : 0;
  1384.                                                         $finalAmount $discountedAmount $taxAmount;
  1385.                                                         $row = array(
  1386.                                                             'type' => 2,//1:product 2=service 4=tools 5:text 6: expense against head
  1387.                                                             'id' => $pid,
  1388.                                                             'index' => $indexForThis,
  1389.                                                             'isForeign' => isset($theDt['is_foreign_service'][$f]) ? $theDt['is_foreign_service'][$f] : 0,
  1390.                                                             'sequence' => $sequence,
  1391.                                                             'segmentIndex' => $segmentIndex,
  1392.                                                             'soItemId' => isset($theDt['service_soItemId'][$f]) ? $theDt['service_soItemId'][$f] : 0,
  1393.                                                             'soItemDelivered' => isset($theDt['service_soItemDelivered'][$f]) ? $theDt['service_soItemDelivered'][$f] : 0,
  1394.                                                             'soItemFound' => isset($theDt['service_soItemFound'][$f]) ? $theDt['service_soItemFound'][$f] : 0,
  1395.                                                             'alias' => isset($theDt['service_alias'][$f]) ? $theDt['service_alias'][$f] : '',
  1396.                                                             'name' => isset($theDt['service_name'][$f]) ? $theDt['service_name'][$f] : '',
  1397.                                                             'note' => isset($theDt['service_note'][$f]) ? $theDt['service_note'][$f] : '',
  1398.                                                             'fdm' => isset($theDt['service_fdm'][$f]) ? $theDt['service_fdm'][$f] : null,
  1399.                                                             'unit' => isset($theDt['service_units'][$f]) ? $theDt['service_units'][$f] : 0,
  1400.                                                             'unitTypeId' => isset($theDt['service_unit_type'][$f]) ? $theDt['service_unit_type'][$f] : 0,
  1401.                                                             'unitPrice' => $unitPrice,
  1402.                                                             'totalPrice' => $totalPrice,
  1403.                                                             'unitSalesPrice' => $unitSalesPrice,
  1404.                                                             'totalSalesPrice' => $totalSalesPrice,
  1405.                                                             'marginRate' => $marginRate,
  1406.                                                             'marginAmount' => $marginAmount,
  1407.                                                             'discountRate' => $discountRate,
  1408.                                                             'discountAmount' => $discountAmount,
  1409.                                                             'discountedAmount' => $discountedAmount,
  1410.                                                             'taxRate' => $taxRate,
  1411.                                                             'taxAmount' => $taxAmount,
  1412.                                                             'finalAmount' => $finalAmount,
  1413.                                                             'recurring' => isset($theDt['service_recurring'][$f]) ? $theDt['service_recurring'][$f] : 0,
  1414.                                                             'currency' => isset($theDt['service_currency_id'][$f]) ? $theDt['service_currency_id'][$f] : 0,
  1415.                                                             'currencyText' => isset($theDt['service_currency_text'][$f]) ? $theDt['service_currency_text'][$f] : '',
  1416.                                                             'currencyMultiplyRate' => isset($theDt['service_currency_multiply_rate'][$f]) ? $theDt['service_currency_multiply_rate'][$f] : 1,
  1417.                                                             'incoterm' => isset($theDt['incoterm'][$f]) ? $theDt['incoterm'][$f] : '',
  1418.                                                             'taxId' => isset($theDt['service_tax_config_id'][$f]) ? $theDt['service_tax_config_id'][$f] : 0,
  1419.                                                             'taxName' => isset($theDt['service_tax_config_text'][$f]) ? $theDt['service_tax_config_text'][$f] : '',
  1420.                                                             'dependencyOnIndex' => isset($theDt['service_dependency_of_index'][$f]) ? $theDt['service_dependency_of_index'][$f] : 0,
  1421.                                                             'dependencyOnPid' => isset($theDt['service_dependency_of_service_id'][$f]) ? $theDt['service_dependency_of_service_id'][$f] : 0,
  1422.                                                             'dependencyOnSid' => isset($theDt['service_dependency_of_service_id'][$f]) ? $theDt['service_dependency_of_service_id'][$f] : 0,
  1423.                                                             'dependencyOnSegment' => isset($theDt['service_dependency_of_service_index'][$f]) ? $theDt['service_dependency_of_service_index'][$f] : 0,
  1424.                                                             'warranty' => isset($theDt['service_delivery_schedule'][$f]) ? $theDt['service_delivery_schedule'][$f] : 0,
  1425.                                                             'origin' => isset($theDt['service_origin'][$f]) ? $theDt['service_origin'][$f] : 0,
  1426.                                                             'origins' => isset($theDt['service_origin'][$f]) ? [$theDt['service_origin'][$f]] : [],
  1427.                                                             'scope' => isset($theDt['service_scope'][$f]) ? $theDt['service_scope'][$f] : 0,
  1428.                                                             'scopeId' => isset($theDt['service_scopeHolderId'][$f]) ? [$theDt['service_scopeHolderId'][$f]] : 0,
  1429.                                                             'scopeName' => isset($theDt['service_scopeHolderName'][$f]) ? [$theDt['service_scopeHolderName'][$f]] : '',
  1430.                                                             'scopeDescription' => isset($theDt['service_scopeDescription'][$f]) ? [$theDt['service_scopeDescription'][$f]] : '',
  1431.                                                             'deliverySchedule' => isset($theDt['service_delivery_schedule'][$f]) ? $theDt['service_delivery_schedule'][$f] : [],
  1432.                                                             'deliveryPorts' => isset($theDt['service_delivery_ports'][$f]) ? $theDt['service_delivery_ports'][$f] : [],
  1433.                                                             'billingSchedule' => isset($theDt['service_billing_schedule'][$f]) ? $theDt['service_billing_schedule'][$f] : [],
  1434.                                                             'referenceNo' => isset($theDt['service_reference_price'][$f]) ? $theDt['service_reference_price'][$f] : '',
  1435.                                                             'referenceFiles' => isset($theDt['service_reference_price_file'][$f]) ? $theDt['service_reference_price_file'][$f] : '',
  1436.                                                         );
  1437.                                                         $dt_poka['rowData'][] = $row;
  1438.                                                     }
  1439.                                                 //now accounts /Cost
  1440.                                                 $theDt = array(
  1441.                                                     'products' => [],
  1442.                                                     'services' => [],
  1443.                                                     'ar_heads' => [],
  1444.                                                 );
  1445.                                                 if (isset($dt_poka['ArCosts']))
  1446.                                                     $theDt $dt_poka['ArCosts'];
  1447.                                                 if (isset($theDt['ar_heads']))
  1448.                                                     foreach ($theDt['ar_heads'] as $f => $pid) {
  1449.                                                         $unit = isset($theDt['ar_units'][$f]) ? $theDt['ar_units'][$f] : 0;
  1450.                                                         if (!is_numeric($unit)) $unit 0;
  1451.                                                         $indexForThis = isset($theDt['index'][$f]) ? $theDt['index'][$f] : -1;
  1452.                                                         if ($indexForThis == -1) {
  1453.                                                             $indexForThis $lastIndex;
  1454.                                                             $lastIndex++;
  1455.                                                         }
  1456.                                                         $unitPrice = isset($theDt['ar_unit_price'][$f]) ? $theDt['ar_unit_price'][$f] : 0;
  1457.                                                         if (!is_numeric($unitPrice)) $unitPrice 0;
  1458.                                                         $totalPrice $unit $unitPrice;
  1459.                                                         $segmentIndex = isset($theDt['ar_segmentIndex'][$f]) ? $theDt['ar_segmentIndex'][$f] : 0;
  1460.                                                         if ($oldSegmentSystem == 1)
  1461.                                                             $segmentIndex 1000 $segmentIndex;
  1462.                                                         $sequence = isset($theDt['ar_segmentIndex'][$f]) ? $theDt['ar_segmentIndex'][$f] : '_UNSET_';
  1463.                                                         if (!isset($lastSequenceBySegment[$segmentIndex]))
  1464.                                                             $lastSequenceBySegment[$segmentIndex] = -1;
  1465.                                                         if ($sequence == '_UNSET_')
  1466.                                                             $sequence $lastSequenceBySegment[$segmentIndex] + 1;
  1467.                                                         else if ($sequence == $lastSequenceBySegment[$segmentIndex])
  1468.                                                             $sequence $lastSequenceBySegment[$segmentIndex] + 1;
  1469.                                                         $lastSequenceBySegment[$segmentIndex] = $sequence;
  1470.                                                         $unitSalesPrice = isset($theDt['ar_unit_sales_price'][$f]) ? $theDt['ar_unit_sales_price'][$f] : $unitPrice;
  1471.                                                         $totalSalesPrice $unit $unitSalesPrice;
  1472.                                                         $marginAmount = isset($theDt['ar_ma'][$f]) ? $theDt['ar_ma'][$f] : ($unitSalesPrice $unitPrice);
  1473.                                                         $marginRate = isset($theDt['ar_ma'][$f]) ? $theDt['ar_ma'][$f] : ($unitPrice == : (100 $marginAmount $unitPrice));
  1474.                                                         $discountAmount = isset($theDt['ar_dr'][$f]) ? $theDt['ar_dr'][$f] : 0;
  1475.                                                         $discountRate = isset($theDt['ar_da'][$f]) ? $theDt['ar_da'][$f] : ($totalSalesPrice == : (100 $discountAmount $totalSalesPrice));
  1476.                                                         $discountedAmount $totalSalesPrice $discountAmount;
  1477.                                                         $taxRate = isset($theDt['ar_tax_percentage'][$f]) ? $theDt['ar_tax_percentage'][$f] : ($unitPrice == : (100 $discountAmount $unitPrice));
  1478.                                                         $taxAmount = isset($theDt['ar_tax_amount'][$f]) ? $theDt['ar_tax_amount'][$f] : 0;
  1479.                                                         $finalAmount $discountedAmount $taxAmount;
  1480.                                                         $row = array(
  1481.                                                             'type' => 6,//1:product 2=service 4=tools 5:text 6: expense against head
  1482.                                                             'id' => $pid,
  1483.                                                             'index' => $indexForThis,
  1484.                                                             'isForeign' => isset($theDt['is_foreign_cost'][$f]) ? $theDt['is_foreign_cost'][$f] : 0,
  1485.                                                             'sequence' => $sequence,
  1486.                                                             'segmentIndex' => $segmentIndex,
  1487.                                                             'soItemId' => isset($theDt['ar_soItemId'][$f]) ? $theDt['ar_soItemId'][$f] : 0,
  1488.                                                             'soItemDelivered' => isset($theDt['ar_soItemDelivered'][$f]) ? $theDt['ar_soItemDelivered'][$f] : 0,
  1489.                                                             'soItemFound' => isset($theDt['ar_soItemFound'][$f]) ? $theDt['ar_soItemFound'][$f] : 0,
  1490.                                                             'alias' => isset($theDt['ar_alias'][$f]) ? $theDt['ar_alias'][$f] : '',
  1491.                                                             'name' => isset($theDt['ar_name'][$f]) ? $theDt['ar_name'][$f] : '',
  1492.                                                             'note' => isset($theDt['ar_note'][$f]) ? $theDt['ar_note'][$f] : '',
  1493.                                                             'fdm' => isset($theDt['ar_fdm'][$f]) ? $theDt['ar_fdm'][$f] : null,
  1494.                                                             'unit' => isset($theDt['ar_units'][$f]) ? $theDt['ar_units'][$f] : 0,
  1495.                                                             'unitTypeId' => isset($theDt['ar_unit_type'][$f]) ? $theDt['ar_unit_type'][$f] : 0,
  1496.                                                             'unitPrice' => $unitPrice,
  1497.                                                             'totalPrice' => $totalPrice,
  1498.                                                             'unitSalesPrice' => $unitSalesPrice,
  1499.                                                             'totalSalesPrice' => $totalSalesPrice,
  1500.                                                             'marginRate' => $marginRate,
  1501.                                                             'marginAmount' => $marginAmount,
  1502.                                                             'discountRate' => $discountRate,
  1503.                                                             'discountAmount' => $discountAmount,
  1504.                                                             'discountedAmount' => $discountedAmount,
  1505.                                                             'taxRate' => $taxRate,
  1506.                                                             'taxAmount' => $taxAmount,
  1507.                                                             'finalAmount' => $finalAmount,
  1508.                                                             'recurring' => isset($theDt['ar_recurring'][$f]) ? $theDt['ar_recurring'][$f] : 0,
  1509.                                                             'currency' => isset($theDt['ar_currency_id'][$f]) ? $theDt['ar_currency_id'][$f] : 0,
  1510.                                                             'currencyText' => isset($theDt['ar_currency_text'][$f]) ? $theDt['ar_currency_text'][$f] : '',
  1511.                                                             'currencyMultiplyRate' => isset($theDt['ar_currency_multiply_rate'][$f]) ? $theDt['ar_currency_multiply_rate'][$f] : 1,
  1512.                                                             'incoterm' => isset($theDt['incoterm'][$f]) ? $theDt['incoterm'][$f] : '',
  1513.                                                             'taxId' => isset($theDt['ar_tax_config_id'][$f]) ? $theDt['ar_tax_config_id'][$f] : 0,
  1514.                                                             'taxName' => isset($theDt['ar_tax_config_text'][$f]) ? $theDt['ar_tax_config_text'][$f] : '',
  1515.                                                             'dependencyOnIndex' => isset($theDt['ar_dependency_of_index'][$f]) ? $theDt['ar_dependency_of_index'][$f] : 0,
  1516.                                                             'dependencyOnPid' => isset($theDt['ar_dependency_of_ar_id'][$f]) ? $theDt['ar_dependency_of_ar_id'][$f] : 0,
  1517.                                                             'dependencyOnSid' => isset($theDt['ar_dependency_of_ar_id'][$f]) ? $theDt['ar_dependency_of_ar_id'][$f] : 0,
  1518.                                                             'dependencyOnSegment' => isset($theDt['ar_dependency_of_ar_index'][$f]) ? $theDt['ar_dependency_of_ar_index'][$f] : 0,
  1519.                                                             'warranty' => isset($theDt['ar_delivery_schedule'][$f]) ? $theDt['ar_delivery_schedule'][$f] : 0,
  1520.                                                             'origin' => isset($theDt['ar_origin'][$f]) ? $theDt['ar_origin'][$f] : 0,
  1521.                                                             'origins' => isset($theDt['ar_origin'][$f]) ? [$theDt['ar_origin'][$f]] : [],
  1522.                                                             'scope' => isset($theDt['ar_scope'][$f]) ? $theDt['ar_scope'][$f] : 0,
  1523.                                                             'scopeId' => isset($theDt['ar_scopeHolderId'][$f]) ? [$theDt['ar_scopeHolderId'][$f]] : 0,
  1524.                                                             'scopeName' => isset($theDt['ar_scopeHolderName'][$f]) ? [$theDt['ar_scopeHolderName'][$f]] : '',
  1525.                                                             'scopeDescription' => isset($theDt['ar_scopeDescription'][$f]) ? [$theDt['ar_scopeDescription'][$f]] : '',
  1526.                                                             'deliverySchedule' => isset($theDt['ar_delivery_schedule'][$f]) ? $theDt['ar_delivery_schedule'][$f] : [],
  1527.                                                             'deliveryPorts' => isset($theDt['ar_delivery_ports'][$f]) ? $theDt['ar_delivery_ports'][$f] : [],
  1528.                                                             'billingSchedule' => isset($theDt['ar_billing_schedule'][$f]) ? $theDt['ar_billing_schedule'][$f] : [],
  1529.                                                             'referenceNo' => isset($theDt['ar_reference_price'][$f]) ? $theDt['ar_reference_price'][$f] : '',
  1530.                                                             'referenceFiles' => isset($theDt['ar_reference_price_file'][$f]) ? $theDt['ar_reference_price_file'][$f] : '',
  1531.                                                         );
  1532.                                                         $dt_poka['rowData'][] = $row;
  1533.                                                     }
  1534. //                                                $configJson['debugData'][]=$dt_poka;
  1535.                                             }
  1536.                                             $newSingleSet['rowData'] = $dt_poka['rowData'];
  1537.                                             unset($dt_poka['productSegmentData']);
  1538.                                             unset($dt_poka['serviceSegmentData']);
  1539.                                             unset($dt_poka['Products']);
  1540.                                             unset($dt_poka['Services']);
  1541.                                             $newData[$kho] = $newSingleSet;
  1542.                                         }
  1543.                                         $theDocData->setData(json_encode($newData));
  1544.                                         $em->persist($theDocData);
  1545.                                         $em->flush();
  1546.                                     }
  1547.                                     $tempId 0;
  1548.                                     if ($entityNameHere == 'SalesProposal'$tempId $the_actual_doc->getSalesProposalId();
  1549.                                     if ($entityNameHere == 'ProjectBoq'$tempId $the_actual_doc->getProjectId();
  1550.                                     if ($entityNameHere == 'SalesLead'$tempId $the_actual_doc->getLeadId();
  1551.                                     $configJson['debugData'][] = array(
  1552.                                         'entityNameHere' => $entityNameHere,
  1553.                                         'entityId' => $tempId,
  1554.                                         'dt' => $newData,
  1555.                                     );
  1556.                                 }
  1557.                                 $the_actual_doc->setData(null);
  1558.                                 $the_actual_doc->setDocumentDataId($theDocData->getId());
  1559.                                 $em->flush();
  1560.                                 if ($entityNameHere == 'ProjectBoq') {
  1561.                                     $theProj $em->getRepository('ApplicationBundle:Project')
  1562.                                         ->findOneBy(
  1563.                                             array(
  1564.                                                 'projectId' => $the_actual_doc->getProjectId()
  1565.                                             )
  1566.                                         );
  1567.                                     if ($theProj)
  1568.                                         $theProj->setDocumentDataId($the_actual_doc->getDocumentDataId());
  1569.                                     $em->flush();
  1570.                                 }
  1571.                             }
  1572.                         }
  1573.                     }
  1574.                     if ($request->query->get('convertMarginToMarkupOldDocumentData'0) == 1) {
  1575.                         $the_actual_docs $em->getRepository('ApplicationBundle:DocumentData')
  1576.                             ->findBy(
  1577.                                 array(//                                        GeneralConstant::$Entity_id_field_list[$ent] => $entity_id,
  1578.                                 )
  1579.                             );
  1580.                         foreach ($the_actual_docs as $the_actual_doc) {
  1581.                             //now the data
  1582.                             //first find the docData if available
  1583.                             $theDocData = [];
  1584.                             $theDocData json_decode($the_actual_doc->getData(), true);
  1585.                             if ($theDocData == null)
  1586.                                 $theDocData = [];
  1587.                             $entries $theDocData;
  1588.                             foreach ($entries as $jojo => $mod) {
  1589.                                 if (isset($mod['rowData'])) {
  1590.                                     $rows $mod['rowData'];
  1591.                                     if (is_string($rows))
  1592.                                         $rows json_decode($rowstrue);
  1593.                                     if ($rows == null)
  1594.                                         $rows = [];
  1595.                                     foreach ($rows as $indu => $row) {
  1596.                                         if (!is_numeric($row['unitSalesPrice'])) $row['unitSalesPrice'] = 0;
  1597.                                         if (!is_numeric($row['unitPrice'])) $row['unitPrice'] = 0;
  1598.                                         if (!is_numeric($row['marginAmount'])) $row['marginAmount'] = 0;
  1599.                                         if (!isset($row['markupRate'])) {
  1600.                                             $rows[$indu]['markupRate'] = $row['marginRate'];
  1601.                                         }
  1602.                                         $rows[$indu]['marginRate'] = $row['unitSalesPrice'] != 100 $row['marginAmount'] / $row['unitSalesPrice'] : 0;
  1603.                                     }
  1604.                                     $entries[$jojo]['rowData'] = $rows;
  1605.                                 }
  1606.                             }
  1607.                             $the_actual_doc->setData(json_encode($entries));
  1608. //                                $the_actual_doc->setDocumentDataId($theDocData->getId());
  1609.                             $em->flush();
  1610.                         }
  1611.                     }
  1612.                     if ($request->query->get('rectifyTransCurr'0) == 1) {
  1613.                         $query "
  1614.                                     UPDATE `acc_transaction_details` SET currency_multiply_rate=1 WHERE currency_multiply_rate is NULL or currency_multiply_rate=0 ;
  1615.                                     UPDATE `acc_transaction_details` SET currency_multiply=1 WHERE currency_multiply is NULL or currency_multiply=0 ;
  1616.                                     UPDATE `acc_transactions` SET currency_multiply_rate=1 WHERE currency_multiply_rate is NULL or currency_multiply_rate=0 ;
  1617.                                     UPDATE `acc_transactions` SET currency_multiply=1 WHERE currency_multiply is NULL or currency_multiply=0 ;
  1618.                                     UPDATE `expense_invoice` SET currency_multiply_rate=1 WHERE currency_multiply_rate is NULL or currency_multiply_rate=0 ;
  1619.                                     UPDATE `expense_invoice` SET currency_multiply=1 WHERE currency_multiply is NULL or currency_multiply=0 ;
  1620.   
  1621.                      
  1622.                       ";
  1623.                         $stmt $em->getConnection()->prepare($query);
  1624.                         $stmt->execute();
  1625.                         $stmt->closeCursor();
  1626.                     }
  1627.                     if ($request->query->get('deepRefresh'0) == 1) {
  1628.                         //new for updating app id
  1629.                         $get_kids_sql "UPDATE `company` set app_id=" $entry['appId'] . " ;
  1630.                         UPDATE `sys_user` set app_id=" $entry['appId'] . " ;";
  1631.                         $get_kids_sql .= "
  1632.                                       UPDATE `inv_products` set default_color_id=0  where default_color_id ='' or default_color_id is null ;
  1633.                                       UPDATE `inv_products` set default_size=0  where default_size ='' or default_size is null ;
  1634.                                         UPDATE `inventory_storage` set color= (select default_color_id from inv_products where inv_products.id=inventory_storage.product_id)
  1635.                                          where inventory_storage.color =0 or inventory_storage.color is null or inventory_storage.color ='' ;
  1636.                                          UPDATE `inventory_storage` set owner_type= 0 where inventory_storage.owner_type is null or inventory_storage.owner_type ='' ;
  1637.                                          UPDATE `inventory_storage` set owner_id= 0 where inventory_storage.owner_id is null or inventory_storage.owner_id ='' ;
  1638.                                          UPDATE `acc_clients` set client_level= 1 where client_level is null or client_level ='' or client_level=0 ;
  1639.                                          UPDATE `acc_clients` set parent_id= 0 where parent_id is null or parent_id ='' ;
  1640.                                          UPDATE `sales_order` set sales_level= 0 where sales_level is null or sales_level ='' ;
  1641.                                          ";
  1642.                         $get_kids_sql .= "                UPDATE `inventory_storage` set color=0 where color='' or color is null;
  1643.                                         UPDATE `inventory_storage` set `size`=0 where `size`='' or size is null;
  1644.                                         UPDATE `inv_item_transaction` set color=0 where color='' or color is null;
  1645.                                         UPDATE `inv_item_transaction` set `size`=0 where `size`='' or size is null;
  1646.                                         UPDATE `inv_closing_balance` set color=0 where color='' or color is null;
  1647.                                         UPDATE `inv_closing_balance` set `size`=0 where `size`='' or size is null;
  1648.                                         UPDATE `sales_order_item` set `size_id`=(select default_size from inv_products where inv_products.id=sales_order_item.product_id ) where sales_order_item.product_id!=0 and (`size_id`='' or size_id is null);
  1649.                                         UPDATE `sales_order_item` set `color_id`=(select default_color_id from inv_products where inv_products.id=sales_order_item.product_id ) where sales_order_item.product_id!=0 and (`color_id`='' or color_id is null);
  1650.                                         UPDATE `delivery_receipt_item` set `size_id`=(select default_size from inv_products where inv_products.id=delivery_receipt_item.product_id ) where delivery_receipt_item.product_id!=0 and (`size_id`='' or size_id is null);
  1651.                                         UPDATE `delivery_receipt_item` set `color_id`=(select default_color_id from inv_products where inv_products.id=delivery_receipt_item.product_id ) where delivery_receipt_item.product_id!=0 and (`color_id`='' or color_id is null);
  1652.                                         UPDATE `delivery_order_item` set `size_id`=(select default_size from inv_products where inv_products.id=delivery_order_item.product_id ) where delivery_order_item.product_id!=0 and (`size_id`='' or size_id is null);
  1653.                                         UPDATE `delivery_order_item` set `color_id`=(select default_color_id from inv_products where inv_products.id=delivery_order_item.product_id ) where delivery_order_item.product_id!=0 and (`color_id`='' or color_id is null);
  1654.                                         UPDATE `sales_invoice_item` set `size_id`=(select default_size from inv_products where inv_products.id=sales_invoice_item.product_id ) where sales_invoice_item.product_id!=0 and (`size_id`='' or size_id is null);
  1655.                                         UPDATE `sales_invoice_item` set `color_id`=(select default_color_id from inv_products where inv_products.id=sales_invoice_item.product_id ) where sales_invoice_item.product_id!=0 and (`color_id`='' or color_id is null);
  1656.                                         UPDATE `inventory_storage` set curr_purchase_price= (select curr_purchase_price from inv_products where inv_products.id=inventory_storage.product_id)
  1657.                                          where inventory_storage.curr_purchase_price=0 or inventory_storage.curr_purchase_price is null;
  1658.                                        delete TABLE service_opearation;
  1659.                                        delete TABLE assesment_and_confirmation;
  1660.                                        ";
  1661.                         $stmt $em->getConnection()->prepare($get_kids_sql);
  1662.                         $stmt->execute();
  1663.                         $stmt->closeCursor();
  1664.                         $query "SELECT * from  company   where 1";
  1665.                         $stmt $em->getConnection()->prepare($query);
  1666.                         $stmt->execute();
  1667.                         $results $stmt->fetchAll();
  1668.                         if (empty($results)) {
  1669.                             //insert client level query here
  1670.                             $createdDate = new \DateTime();
  1671.                             $cgEntry $gocEntryObjectList[$gocId];
  1672.                             $get_kids_sql "INSERT INTO `company` (`id`, `name`, `image`, `app_id`,  `created_at`,   `company_hash`, `company_unique_code`, `enabled_module_id_list`, `usage_valid_upto_date`,`active`) VALUES
  1673. (1, '" $cgEntry->getName() . "', '" $cgEntry->getImage() . "'," $cgEntry->getAppId() . ",'" $createdDate->format('Y-m-d H:i:s') . "', '" $cgEntry->getCompanyGroupHash() . "','" $cgEntry->getCompanyGroupUniqueCode() . "',NULL, NULL,1);";
  1674.                             $stmt $em->getConnection()->prepare($get_kids_sql);
  1675.                             $stmt->execute();
  1676.                             $stmt->closeCursor();
  1677.                         }
  1678.                         $query "SELECT * from  client_level   where 1";
  1679.                         $stmt $em->getConnection()->prepare($query);
  1680.                         $stmt->execute();
  1681.                         $results $stmt->fetchAll();
  1682.                         if (empty($results)) {
  1683.                             //insert client level query here
  1684.                             $get_kids_sql "INSERT INTO `client_level` (`id`, `name`, `level_value`,`company_id`, `parent_level_id`, `status`, `created_at`, `updated_at`, `doc_booked_flag`, `time_stamp_of_form`) VALUES
  1685. (1, 'Primary',1, 1, 0, 1, '2022-02-22 20:58:51', NULL, NULL, NULL),
  1686. (2, 'Secondary',2, 1, 1, 1, '2022-02-22 20:58:51', NULL, NULL, NULL),
  1687. (3, 'Tertiary',3, 1, 2, 1, '2022-02-22 20:58:51', NULL, NULL, NULL)
  1688. ;";
  1689.                             $stmt $em->getConnection()->prepare($get_kids_sql);
  1690.                             $stmt->execute();
  1691.                             $stmt->closeCursor();
  1692.                         }
  1693.                         $query "SELECT * from  sales_level   where 1";
  1694.                         $stmt $em->getConnection()->prepare($query);
  1695.                         $stmt->execute();
  1696.                         $results $stmt->fetchAll();
  1697.                         if (empty($results)) {
  1698.                             //insert client level query here
  1699.                             $get_kids_sql "INSERT INTO `sales_level` (`id`, `name`, `level_value`,`company_id`, `parent_level_id`, `status`, `created_at`, `updated_at`, `doc_booked_flag`, `time_stamp_of_form`) VALUES
  1700. (1, 'Primary',0, 1, 0, 1, '2022-02-22 20:58:51', NULL, NULL, NULL),
  1701. (2, 'Secondary',1, 1, 1, 1, '2022-02-22 20:58:51', NULL, NULL, NULL),
  1702. (3, 'Tertiary',2, 1, 2, 1, '2022-02-22 20:58:51', NULL, NULL, NULL);";
  1703.                             $stmt $em->getConnection()->prepare($get_kids_sql);
  1704.                             $stmt->execute();
  1705.                             $stmt->closeCursor();
  1706.                         }
  1707.                         $services $em->getRepository('ApplicationBundle:AccService')->findBy(array(
  1708. //                            'serviceId' => $ex_id//for now for stock of goods
  1709. //                    'opening_locked'=>0
  1710.                         ));
  1711.                         foreach ($services as $service) {
  1712.                             $productFdm $service->getProductFdm();
  1713.                             if (strpos($productFdm'P_') !== false)
  1714.                                 $productFdm str_replace('P_''P' $service->getServiceId() . '_'$productFdm);
  1715.                             $service->setProductFdm($productFdm);
  1716.                             $em->flush();
  1717.                         }
  1718.                         $query "SELECT * from  warehouse_action   where 1";
  1719.                         $stmt $em->getConnection()->prepare($query);
  1720.                         $stmt->execute();
  1721.                         $results $stmt->fetchAll();
  1722.                         if (!empty($results)) {
  1723.                             //insert client level query here
  1724.                             foreach ($results as $qryResult) {
  1725.                                 $get_kids_sql "update `warehouse_action` set `accounts_head_id` =(select `data` from acc_setting where acc_setting.`name` like 'warehouse_action_" $qryResult['id'] . "') where id=" $qryResult['id'];
  1726.                                 $stmt $em->getConnection()->prepare($get_kids_sql);
  1727.                                 $stmt->execute();
  1728.                                 $stmt->closeCursor();
  1729.                             }
  1730.                         } else {
  1731.                             foreach (GeneralConstant::$warehouse_action_list as $dt_pika) {
  1732.                                 $get_kids_sql "INSERT INTO `warehouse_action` (`id`, `name`,`company_id`,  `status`, `created_at`, `updated_at`, `doc_booked_flag`, `time_stamp_of_form`)
  1733. VALUES(" $dt_pika['id'] . ", '" $dt_pika['name'] . "', 1, 1, '2022-02-22 20:58:51', NULL, NULL, NULL)";
  1734.                                 $stmt $em->getConnection()->prepare($get_kids_sql);
  1735.                                 $stmt->execute();
  1736.                                 $stmt->closeCursor();
  1737.                             }
  1738. //
  1739.                             $query "SELECT * from  warehouse_action   where 1";
  1740.                             $stmt $em->getConnection()->prepare($query);
  1741.                             $stmt->execute();
  1742.                             $newresults $stmt->fetchAll();
  1743.                             foreach ($newresults as $qryResult) {
  1744.                                 $get_kids_sql "update `warehouse_action` set `accounts_head_id` =(select `data` from acc_setting where acc_setting.`name` like 'warehouse_action_" $qryResult['id'] . "') where id=" $qryResult['id'];
  1745.                                 $stmt $em->getConnection()->prepare($get_kids_sql);
  1746.                                 $stmt->execute();
  1747.                                 $stmt->closeCursor();
  1748.                             }
  1749.                         }
  1750.                         $modify_product_by_code_ids_table_list = [
  1751.                             'stock_transfer_item',
  1752.                         ];
  1753.                         $modify_product_by_code_ids_field_list = [
  1754.                             'product_by_code_ids'
  1755.                         ];
  1756.                         $modify_product_by_code_sales_code_field_list = [
  1757.                             'sales_code_range'
  1758.                         ];
  1759.                         $modify_product_by_code_item_id_field_list = [
  1760.                             'id'
  1761.                         ];
  1762.                         foreach ($modify_product_by_code_ids_table_list as $mindex => $dt_table_name) {
  1763.                             $get_kids_sql "select * from " $dt_table_name " where " .
  1764.                                 $modify_product_by_code_ids_field_list[$mindex] . " is null  or " .
  1765.                                 $modify_product_by_code_ids_field_list[$mindex] . " =''  or " .
  1766.                                 $modify_product_by_code_ids_field_list[$mindex] . " ='[]' ;";
  1767.                             $stmt $em->getConnection()->prepare($get_kids_sql);
  1768.                             $stmt->execute();
  1769.                             $dataList $stmt->fetchAll();
  1770.                             foreach ($dataList as $mdt) {
  1771.                                 $sales_code_range_str $mdt[$modify_product_by_code_sales_code_field_list[$mindex]];
  1772.                                 $sales_code_range = [];
  1773.                                 if (version_compare(PHP_VERSION'5.4.0''>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE 4)) {
  1774.                                     $sales_code_range json_decode($sales_code_range_strtrue512JSON_BIGINT_AS_STRING);
  1775.                                 } else {
  1776.                                     $max_int_length strlen((string)PHP_INT_MAX) - 1;
  1777.                                     $json_without_bigints preg_replace('/:\s*(-?\d{' $max_int_length ',})/'': "$1"'$sales_code_range_str);
  1778.                                     $sales_code_range json_decode($json_without_bigintstrue);
  1779.                                 }
  1780. //                    $sales_code_range= json_decode($entry->getSalesCodeRange(),true,512,JSON_BIGINT_AS_STRING);
  1781.                                 $pbcIds = [];
  1782.                                 if ($sales_code_range == null)
  1783.                                     $sales_code_range = [];
  1784.                                 if (empty($sales_code_range)) {
  1785.                                 } else {
  1786.                                     $get_kids_sql_2 "select * from  product_by_code  where sales_code in ('" implode("','"$sales_code_range) . "');";
  1787.                                     $stmt $em->getConnection()->prepare($get_kids_sql_2);
  1788.                                     $stmt->execute();
  1789.                                     $dataList $stmt->fetchAll();
  1790.                                     foreach ($dataList as $pbc) {
  1791.                                         $pbcIds[] = $pbc['product_by_code_id'];
  1792.                                     }
  1793.                                 }
  1794.                                 $get_kids_sql_3 "update " $dt_table_name .
  1795.                                     " set  " $modify_product_by_code_ids_field_list[$mindex] . "='" json_encode($pbcIds) . "'" .
  1796.                                     " where " $modify_product_by_code_item_id_field_list[$mindex] . "=" $mdt[$modify_product_by_code_item_id_field_list[$mindex]] . ";";
  1797.                                 $stmt $em->getConnection()->prepare($get_kids_sql_3);
  1798.                                 $stmt->execute();
  1799.                                 $stmt->closeCursor();
  1800.                             }
  1801.                         }
  1802.                         $modify_voucher_date_table_list = [
  1803. //                            'stock_received_note',
  1804. //                            'stock_transfer',
  1805. //                            'stock_consumption_note',
  1806. //                            'fixed_asset_conversion_note',
  1807. //                            'fixed_asset_product'
  1808.                         ];
  1809.                         $modify_date_field_list = [
  1810. //                            'stock_received_note_date',
  1811. //                            'stock_transfer_date',
  1812. //                            'stock_consumption_note_date',
  1813. //                            'fixed_asset_conversion_note_date',
  1814. //                            'fixed_asset_product'
  1815.                         ];
  1816.                         foreach ($modify_voucher_date_table_list as $mindex => $dt_table_name) {
  1817.                             $get_kids_sql "select * from " $dt_table_name " where 1;";
  1818.                             $stmt $em->getConnection()->prepare($get_kids_sql);
  1819.                             $stmt->execute();
  1820.                             $dataList $stmt->fetchAll();
  1821.                             foreach ($dataList as $mdt) {
  1822.                                 $curr_v_ids json_decode($mdt['voucher_ids'], true);
  1823.                                 if ($curr_v_ids == null)
  1824.                                     $curr_v_ids = [];
  1825.                                 $date_for_this $mdt[$modify_date_field_list[$mindex]];
  1826.                                 foreach ($curr_v_ids as $vid) {
  1827.                                     //new for updating app id
  1828.                                     $get_kids_sql "UPDATE `acc_transactions`
  1829.                                                           set transaction_date='" $date_for_this "',
  1830.                                                               ledger_hit_date='" $date_for_this "'
  1831.                                                           where transaction_id=" $vid ";
  1832.                                         UPDATE `acc_transactions_details`
  1833.                                                           set transaction_date='" $date_for_this "',
  1834.                                                               ledger_hit_date='" $date_for_this "'
  1835.                                                           where transaction_id=" $vid ";";
  1836.                                     $stmt $em->getConnection()->prepare($get_kids_sql);
  1837.                                     $stmt->execute();
  1838.                                     $stmt->closeCursor();
  1839.                                 }
  1840.                             }
  1841.                         }
  1842.                         $modify_voucher_narration_table_list = [
  1843. //                            'expense_invoice',
  1844. //                            'stock_transfer',
  1845. //                            'stock_consumption_note',
  1846. //                            'fixed_asset_conversion_note',
  1847. //                            'fixed_asset_product'
  1848.                         ];
  1849.                         $modify_narr_field_list = [
  1850. //                            'description',
  1851. //                            'stock_transfer_date',
  1852. //                            'stock_consumption_note_date',
  1853. //                            'fixed_asset_conversion_note_date',
  1854. //                            'fixed_asset_product'
  1855.                         ];
  1856.                         foreach ($modify_voucher_narration_table_list as $mindex => $dt_table_name) {
  1857.                             $get_kids_sql "select * from " $dt_table_name " where 1;";
  1858.                             $stmt $em->getConnection()->prepare($get_kids_sql);
  1859.                             $stmt->execute();
  1860.                             $dataList $stmt->fetchAll();
  1861.                             foreach ($dataList as $mdt) {
  1862.                                 $curr_v_ids json_decode($mdt['voucher_ids'], true);
  1863.                                 if ($curr_v_ids == null)
  1864.                                     $curr_v_ids = [];
  1865.                                 $narr_for_this $mdt[$modify_narr_field_list[$mindex]];
  1866.                                 foreach ($curr_v_ids as $vid) {
  1867.                                     //new for updating app id
  1868.                                     $get_kids_sql "UPDATE `acc_transactions`
  1869.                                                           set description='" $narr_for_this "'
  1870.                                                           where transaction_id=" $vid "; ";
  1871.                                     $stmt $em->getConnection()->prepare($get_kids_sql);
  1872.                                     $stmt->execute();
  1873.                                     $stmt->closeCursor();
  1874.                                 }
  1875.                             }
  1876.                         }
  1877.                     }
  1878.                     $get_kids_sql "update `company_group` set `schema_update_pending_flag` =0 where `id`=$gocId;";
  1879.                     $stmt $em_goc->getConnection()->prepare($get_kids_sql);
  1880.                     $stmt->execute();
  1881.                     $stmt->closeCursor();
  1882.                     $configJson['success'] = true;
  1883.                     //this is for large amount of goc we will see  later
  1884. //                        file_put_contents($path, json_encode($configJson));//overwrite
  1885. //                        return $this->redirectToRoute('update_database_schema');
  1886.                 }
  1887.             }
  1888.             return new JsonResponse($configJson);
  1889.         } else {
  1890.             return $this->render(
  1891.                 '@System/pages/server_actions.html.twig',
  1892.                 $dtHere
  1893.             );
  1894.         }
  1895.     }
  1896.     public function UpdateRoutesAction(Request $request)
  1897.     {
  1898.         $message "";
  1899.         $gocList = [];
  1900.         $outputList = [];
  1901.         $systemType $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
  1902.         $em $this->getDoctrine()->getManager('company_group');
  1903.         $em->getConnection()->connect();
  1904.         $connected $em->getConnection()->isConnected();
  1905.         if ($connected)
  1906.             if ($systemType != '_CENTRAL_') {
  1907.                 $gocList $this->getDoctrine()->getManager('company_group')
  1908.                     ->getRepository("CompanyGroupBundle:CompanyGroup")
  1909.                     ->findBy(
  1910.                         array(
  1911.                             'active' => 1
  1912.                         )
  1913.                     );
  1914.             }
  1915.         $gocDataList = [];
  1916.         foreach ($gocList as $entry) {
  1917.             $d = array(
  1918.                 'name' => $entry->getName(),
  1919.                 'id' => $entry->getId(),
  1920.                 'dbName' => $entry->getDbName(),
  1921.                 'dbUser' => $entry->getDbUser(),
  1922.                 'dbPass' => $entry->getDbPass(),
  1923.                 'dbHost' => $entry->getDbHost(),
  1924.                 'appId' => $entry->getAppId(),
  1925.                 'companyRemaining' => $entry->getCompanyRemaining(),
  1926.                 'companyAllowed' => $entry->getCompanyAllowed(),
  1927.             );
  1928.             $gocDataList[$entry->getId()] = $d;
  1929.         }
  1930.         $gocDbName '';
  1931.         $gocDbUser '';
  1932.         $gocDbPass '';
  1933.         $gocDbHost '';
  1934.         $gocId 0;
  1935. //        $path = $this->container->get('templating.helper.assets')->getUrl('bundles/tlfront/js/channels.json');
  1936.         $config_dir $this->container->getParameter('kernel.root_dir') . '/gifnoc/';
  1937.         if (!file_exists($config_dir)) {
  1938.             mkdir($config_dir0777true);
  1939.         }
  1940. //        $path = $this->container->getParameter('kernel.root_dir') . '/gifnoc/givnocppa.json';
  1941. //        $content = file_exists($path) ? file_get_contents($path) : null;
  1942.         $content = [];
  1943.         $configJson = array();
  1944.         if ($content)
  1945.             $configJson json_decode($contenttrue);
  1946.         $configJsonOld $configJson;
  1947. //        if($configJson)
  1948. //        {
  1949. //
  1950. //        }
  1951. //        else
  1952.         {
  1953.             $configJson['appVersion'] = GeneralConstant::ENTITY_APP_VERSION;
  1954.             $configJson['dataBaseSchemaUpdateFlag'] = GeneralConstant::ENTITY_APP_FLAG_TRUE;
  1955.             $configJson['initiateDataBaseFlag'] = GeneralConstant::ENTITY_APP_FLAG_FALSE;
  1956.             $configJson['initiateDataBaseFlagByGoc'] = array();
  1957.             $configJson['motherLode'] = "http://innobd.com";
  1958.             foreach ($gocDataList as $gocId => $entry) {
  1959.                 $configJson['initiateDataBaseFlagByGoc'][$gocId "_" $entry['appId']] = GeneralConstant::ENTITY_APP_FLAG_TRUE;
  1960.             }
  1961.         }
  1962.         //now check if database shcema update is true
  1963. //        if($configJson['dataBaseSchemaUpdateFlag']==GeneralConstant::ENTITY_APP_FLAG_TRUE)
  1964.         if (1//temporary overwrite all
  1965.         {
  1966.             //if goclist is not empty switch to each company dbase and schema update
  1967. //            if(!empty($gocDataList))
  1968.             if (1) {
  1969.                 foreach ($gocDataList as $gocId => $entry) {
  1970.                     if ($configJson['initiateDataBaseFlagByGoc'][$gocId "_" $entry['appId']] == GeneralConstant::ENTITY_APP_FLAG_TRUE) {
  1971.                         $connector $this->container->get('application_connector');
  1972.                         $connector->resetConnection(
  1973.                             'default',
  1974.                             $gocDataList[$gocId]['dbName'],
  1975.                             $gocDataList[$gocId]['dbUser'],
  1976.                             $gocDataList[$gocId]['dbPass'],
  1977.                             $gocDataList[$gocId]['dbHost'],
  1978.                             $reset true);
  1979.                         $em $this->getDoctrine()->getManager();
  1980. //                        $iv = '1234567812345678';
  1981. //                        $pass = $hash;
  1982. //
  1983. //                        $str = $str . 'YmLRocksLikeABoss';
  1984. //                        $data = openssl_encrypt($str, "AES-128-CBC", $pass, OPENSSL_RAW_DATA, $iv);
  1985. //
  1986. //                        $decrypted = openssl_decrypt(base64_decode(base64_encode($data)), "AES-128-CBC", $hash, OPENSSL_RAW_DATA, $iv);
  1987. //
  1988.                         //now 1st of all lets get the Existing routes
  1989.                         $extRoutesById = [];
  1990.                         $extRoutesByRoute = [];
  1991.                         $modules $em->getRepository("ApplicationBundle:SysModule")
  1992.                             ->findBy(
  1993.                                 array()
  1994.                             );
  1995.                         $module_data = [];
  1996.                         foreach ($modules as $mod) {
  1997.                             $dt = array(
  1998.                                 'id' => $mod->getModuleId(),
  1999.                                 'route' => $mod->getModuleRoute(),
  2000.                                 'name' => $mod->getModuleName(),
  2001.                                 'parentId' => $mod->getParentId(),
  2002.                                 'level' => $mod->getLevel(),
  2003.                                 'eFA' => $mod->getEnabledForAll(),
  2004.                             );
  2005.                             $extRoutesById[$mod->getModuleId()] = $dt;
  2006.                             $extRoutesByRoute[$mod->getModuleRoute()] = $dt;
  2007.                         }
  2008.                         //now clear the module table
  2009.                         $get_kids_sql "truncate `sys_module` ; ";
  2010.                         $stmt $em->getConnection()->prepare($get_kids_sql);
  2011.                         $stmt->execute();
  2012.                         $stmt->closeCursor();
  2013.                         $newRoutes ModuleConstant::$moduleList;
  2014.                         $newRoutesByRoute = [];
  2015.                         foreach ($newRoutes as $mod) {
  2016.                             $new = new SysModule();
  2017.                             $new->setModuleId($mod['id']);
  2018.                             $new->setModuleRoute($mod['route']);
  2019.                             $new->setModuleName($mod['name']);
  2020.                             $new->setParentId($mod['parentId']);
  2021.                             $new->setlevel($mod['level']);
  2022.                             $new->setEnabledForAll($mod['eFA']);
  2023.                             $new->setStatus(isset($mod['status']) ? $mod['status'] : GeneralConstant::ACTIVE);
  2024. //                $new->set(GeneralConstant::ACTIVE);
  2025.                             $em->persist($new);
  2026.                             $newRoutesByRoute[$mod['route']] = $mod;
  2027.                         }
  2028.                         $em->flush();
  2029.                         //now lets get the ext modules for positions
  2030.                         $depPosDefModules $em->getRepository("ApplicationBundle:SysDeptPositionDefaultModule")
  2031.                             ->findBy(
  2032.                                 array()
  2033.                             );
  2034.                         foreach ($depPosDefModules as $defmod) {
  2035.                             $moduleList json_decode($defmod->getModuleIds());
  2036.                             $newModuleList = [];
  2037.                             foreach ($moduleList as $oldId) {
  2038.                                 $newId 0;
  2039.                                 if (isset($extRoutesById[$oldId])) {
  2040.                                     if (isset($newRoutesByRoute[$extRoutesById[$oldId]['route']])) {
  2041.                                         $newModuleList[] = $newRoutesByRoute[$extRoutesById[$oldId]['route']]['id'];
  2042.                                     }
  2043.                                 }
  2044.                             }
  2045.                             $defmod->setModuleIds(json_encode($newModuleList));
  2046.                             $em->flush();
  2047.                         }
  2048.                         //now users
  2049.                         $users $em->getRepository("ApplicationBundle:SysUser")
  2050.                             ->findBy(
  2051.                                 array()
  2052.                             );
  2053.                         foreach ($users as $defmod) {
  2054.                             $moduleList json_decode($defmod->getModuleIds());
  2055.                             if ($moduleList == null)
  2056.                                 continue;
  2057.                             $newModuleList = [];
  2058.                             foreach ($moduleList as $oldId) {
  2059.                                 $newId 0;
  2060.                                 if (isset($extRoutesById[$oldId])) {
  2061.                                     if (isset($newRoutesByRoute[$extRoutesById[$oldId]['route']])) {
  2062.                                         $newModuleList[] = $newRoutesByRoute[$extRoutesById[$oldId]['route']]['id'];
  2063.                                     }
  2064.                                 }
  2065.                             }
  2066.                             $defmod->setModuleIds(json_encode($newModuleList));
  2067.                             $em->flush();
  2068.                         }
  2069.                         $module_data = [];
  2070. //                        $tool = new SchemaTool($em);
  2071. //
  2072. //                        $classes = $em->getMetadataFactory()->getAllMetadata();
  2073. ////                    $tool->createSchema($classes);
  2074. //                        $tool->updateSchema($classes);
  2075. //
  2076. //                        //new for updating app id
  2077. //                        $get_kids_sql = "UPDATE `company` set app_id=".$entry['appId']." ;
  2078. //                                        UPDATE `sys_user` set app_id=".$entry['appId']." ;";
  2079. //                        $stmt = $em->getConnection()->prepare($get_kids_sql);
  2080. //                        $stmt->execute();
  2081. //                        $stmt->closeCursor();
  2082. //
  2083. //                        $configJson['initiateDataBaseFlagByGoc'][$gocId."_".$entry['appId']]=GeneralConstant::ENTITY_APP_FLAG_FALSE;
  2084.                         //this is for large amount of goc we will see  later
  2085. //                        file_put_contents($path, json_encode($configJson));//overwrite
  2086. //                        return $this->redirectToRoute('update_database_schema');
  2087.                     }
  2088.                 }
  2089.             } else {
  2090.                 $em $this->getDoctrine()->getManager();
  2091.                 $tool = new SchemaTool($em);
  2092. //                    $classes = array(
  2093. //                        $em->getClassMetadata('Entities\User'),
  2094. //                        $em->getClassMetadata('Entities\Profile')
  2095. //                    );
  2096.                 $classes $em->getMetadataFactory()->getAllMetadata();
  2097. //                    $tool->createSchema($classes);
  2098.                 $tool->updateSchema($classes);
  2099.             }
  2100.         }
  2101.         $allSchemaUpdateDone 1;
  2102.         foreach ($configJson['initiateDataBaseFlagByGoc'] as $flag) {
  2103.             if ($flag == GeneralConstant::ENTITY_APP_FLAG_TRUE)
  2104.                 $allSchemaUpdateDone 0;
  2105.         }
  2106.         if ($allSchemaUpdateDone == 1)
  2107.             $configJson['dataBaseSchemaUpdateFlag'] = GeneralConstant::ENTITY_APP_FLAG_FALSE;
  2108.         ///last
  2109. //        file_put_contents($path, json_encode($configJson));//overwrite
  2110.         return new Response(json_encode($configJsonOld));
  2111.     }
  2112.     public function CheckTimeStampAction(Request $request)
  2113.     {
  2114.         $message "";
  2115.         $gocList = [];
  2116.         $outputList = [];
  2117.         $toConvertDateStrFromQry $request->query->get('convDate''');
  2118.         $currentRegionalDateStrFromQry $request->query->get('currDate''');
  2119.         $convertedTime MiscActions::ConvertRegionalTimeToServerTime($currentRegionalDateStrFromQry$toConvertDateStrFromQry);
  2120.         $currentServerTime = new \DateTime();
  2121.         $em $this->getDoctrine()->getManager('company_group');
  2122.         $em->getConnection()->connect();
  2123.         ///last
  2124. //        file_put_contents($path, json_encode($configJson));//overwrite
  2125.         return new Response(json_encode(array(
  2126.             'convertedTime' => $convertedTime->format('Y-m-d h:i:s'),
  2127.             'convertedTimeUnix' => $convertedTime->format('U'),
  2128.             'convertedTimeRFC' => $convertedTime->format(DATE_RFC822),
  2129.             'currentServerTime' => $currentServerTime->format('Y-m-d h:i:s'),
  2130.             'currentServerTimeRFC' => $currentServerTime->format(DATE_RFC822),
  2131.             'currentServerTimeUnix' => $currentServerTime->format('U'),
  2132.         )));
  2133.     }
  2134.     public function GetUsersFromCentralServerAction(Request $request$id 0)
  2135.     {
  2136.     }
  2137.     public function UpdateCompanyDataToCentralServerAction(Request $request$id 0)
  2138.     {
  2139.         $systemType $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
  2140.         $post $request;
  2141.         $serverList GeneralConstant::$serverListById;
  2142.         if ($systemType == '_CENTRAL_') {
  2143.             $em_goc $this->getDoctrine()->getManager('company_group');
  2144.             //            'company_id' => $company->getId(),
  2145.             //                            'app_id' => $entry['appId'],
  2146.             //                            'dark_vibrant' => $company->getDarkVibrant(),
  2147.             //                            'light_vibrant' => $company->getLightVibrant(),
  2148.             //                            'vibrant' => $company->getVibrant(),
  2149.             //                            'company_type' => $company->getCompanyType(),
  2150.             //                            'company_name' => $company->getName(),
  2151.             //                            'company_address' => $company->getAddress(),
  2152.             //                            'company_s_address' => $company->getShippingAddress(),
  2153.             //                            'company_b_address' => $company->getBillingAddress(),
  2154.             //                            'company_image' => $company->getImage(),
  2155.             //                            'company_motto' => $company->getMotto(),
  2156.             //                            'company_i_footer' => $company->getInvoiceFooter(),
  2157.             //                            'company_g_footer' => $company->getGeneralFooter(),
  2158.             //                            'company_tin' => $company->getCompanyTin(),
  2159.             //                            'company_bin' => $company->getCompanyBin(),
  2160.             //                            'company_reg' => $company->getCompanyReg(),
  2161.             //                            'company_tl' => $company->getCompanyTl(),
  2162.             //                            'sms_enabled' => $company->getSmsNotificationEnabled(),
  2163.             //                            'sms_settings' => $company->getSmsSettings(),
  2164.             //                            'file'=>$output
  2165.             $findByQuery = array(
  2166. //                'active' => 1
  2167.                 'appId' => $post->get('app_id')
  2168.             );
  2169.             $goc $em_goc->getRepository("CompanyGroupBundle:CompanyGroup")
  2170.                 ->findOneBy($findByQuery);
  2171.             if (!$goc)
  2172.                 $goc = new CompanyGroup();
  2173.             $goc->setName($post->get('company_name'));
  2174.             $goc->setAppId($post->get('app_id'));
  2175. //            $goc->setCompanyType($post->get('company_type'));
  2176.             $goc->setAddress($post->get('address'));
  2177. //            $goc->setDarkVibrant($post->get('dark_vibrant'));
  2178. //            $goc->setLightVibrant($post->get('light_vibrant'));
  2179. //            $goc->setVibrant($post->get('vibrant'));
  2180.             $goc->setShippingAddress($post->get('s_address'));
  2181.             $goc->setBillingAddress($post->get('b_address'));
  2182.             $goc->setMotto($post->get('motto'));
  2183.             $goc->setInvoiceFooter($post->get('i_footer'));
  2184.             $goc->setGeneralFooter($post->get('g_footer'));
  2185.             $goc->setCompanyReg($post->get('company_reg'''));
  2186.             $goc->setCompanyTin($post->get('company_tin'''));
  2187.             $goc->setCompanyBin($post->get('company_bin'''));
  2188.             $goc->setCompanyTl($post->get('company_tl'''));
  2189.             $goc->setCompanyGroupServerId($post->get('companyGroupServerId'''));
  2190.             $goc->setCompanyGroupServerAddress($post->get('companyGroupServerAddress'''));
  2191.             $goc->setCompanyGroupServerPort($post->get('companyGroupServerPort'''));
  2192.             $goc->setCompanyGroupServerHash($post->get('companyGroupServerHash'''));
  2193. //            $goc->setSmsNotificationEnabled($post->get('sms_enabled'));
  2194. //            $goc->setSmsSettings($post->get('sms_settings'));
  2195.             foreach ($request->files as $uploadedFile) {
  2196. //            if($uploadedFile->getImage())
  2197. //                var_dump($uploadedFile->getFile());
  2198. //                var_dump($uploadedFile);
  2199.                 if ($uploadedFile != null) {
  2200.                     $fileName 'company_image' $post->get('app_id') . '.' $uploadedFile->guessExtension();
  2201.                     $path $fileName;
  2202.                     $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/CompanyImage/';
  2203.                     if ($goc->getImage() != null && $goc->getImage() != '' && file_exists($this->container->getParameter('kernel.root_dir') . '/../web' $goc->getImage())) {
  2204.                         unlink($this->container->getParameter('kernel.root_dir') . '/../web' $goc->getImage());
  2205.                     }
  2206.                     if (!file_exists($upl_dir)) {
  2207.                         mkdir($upl_dir0777true);
  2208.                     }
  2209.                     $file $uploadedFile->move($upl_dir$path);
  2210.                     if ($path != "")
  2211.                         $goc->setImage('/uploads/CompanyImage/' $path);
  2212.                 }
  2213.             }
  2214.             $em_goc->persist($goc);
  2215.             $em_goc->flush();
  2216.             return new JsonResponse([]);
  2217.         } else {
  2218.             $em $this->getDoctrine()->getManager('company_group');
  2219.             $em->getConnection()->connect();
  2220.             $connected $em->getConnection()->isConnected();
  2221.             $gocDataList = [];
  2222.             if ($connected) {
  2223.                 $findByQuery = array(
  2224.                     'active' => 1
  2225.                 );
  2226.                 $gocList $this->getDoctrine()->getManager('company_group')
  2227.                     ->getRepository("CompanyGroupBundle:CompanyGroup")
  2228.                     ->findBy($findByQuery);
  2229.                 foreach ($gocList as $entry) {
  2230.                     $d = array(
  2231.                         'name' => $entry->getName(),
  2232.                         'id' => $entry->getId(),
  2233.                         'image' => $entry->getImage(),
  2234.                         'companyGroupHash' => $entry->getCompanyGroupHash(),
  2235.                         'companyGroupServerId' => $entry->getCompanyGroupServerId(),
  2236.                         'dbName' => $entry->getDbName(),
  2237.                         'dbUser' => $entry->getDbUser(),
  2238.                         'dbPass' => $entry->getDbPass(),
  2239.                         'dbHost' => $entry->getDbHost(),
  2240.                         'appId' => $entry->getAppId(),
  2241.                         'companyRemaining' => $entry->getCompanyRemaining(),
  2242.                         'companyAllowed' => $entry->getCompanyAllowed(),
  2243.                     );
  2244.                     $gocDataList[$entry->getId()] = $d;
  2245.                 }
  2246.                 foreach ($gocDataList as $gocId => $entry) {
  2247.                     $connector $this->container->get('application_connector');
  2248.                     $connector->resetConnection(
  2249.                         'default',
  2250.                         $gocDataList[$gocId]['dbName'],
  2251.                         $gocDataList[$gocId]['dbUser'],
  2252.                         $gocDataList[$gocId]['dbPass'],
  2253.                         $gocDataList[$gocId]['dbHost'],
  2254.                         $reset true);
  2255.                     $em $this->getDoctrine()->getManager();
  2256.                     $company $this->getDoctrine()
  2257.                         ->getRepository('ApplicationBundle:Company')
  2258.                         ->findOneBy(
  2259.                             array()
  2260.                         );
  2261.                     $output '';
  2262.                     $file $this->container->getParameter('kernel.root_dir') . '/../web' $company->getImage(); //<-- Path could be relative
  2263.                     if (file_exists($file)) {
  2264. //                        $file = new \CURLFile($this->container->getParameter('kernel.root_dir') . '/../web/uploads/CompanyImage/' . $company->getImage()); //<-- Path could be relative
  2265.                         $mime mime_content_type($file);
  2266.                         $info pathinfo($file);
  2267.                         $name $info['basename'];
  2268.                         if (strpos($mime'image') !== false) {
  2269.                             $output = new \CURLFile($file$mime$name);
  2270.                         }
  2271.                     }
  2272.                     $post_fields = array(
  2273.                         'company_id' => $company->getId(),
  2274.                         'app_id' => $entry['appId'],
  2275.                         'dark_vibrant' => $company->getDarkVibrant(),
  2276.                         'light_vibrant' => $company->getLightVibrant(),
  2277.                         'vibrant' => $company->getVibrant(),
  2278.                         'company_type' => $company->getCompanyType(),
  2279.                         'company_name' => $company->getName(),
  2280.                         'company_address' => $company->getAddress(),
  2281.                         'company_s_address' => $company->getShippingAddress(),
  2282.                         'company_b_address' => $company->getBillingAddress(),
  2283.                         'company_image' => $company->getImage(),
  2284.                         'company_motto' => $company->getMotto(),
  2285.                         'company_i_footer' => $company->getInvoiceFooter(),
  2286.                         'company_g_footer' => $company->getGeneralFooter(),
  2287.                         'company_tin' => $company->getCompanyTin(),
  2288.                         'company_bin' => $company->getCompanyBin(),
  2289.                         'company_reg' => $company->getCompanyReg(),
  2290.                         'company_tl' => $company->getCompanyTl(),
  2291.                         'sms_enabled' => $company->getSmsNotificationEnabled(),
  2292.                         'sms_settings' => $company->getSmsSettings(),
  2293.                         'companyGroupHash' => $company->getCompanyHash(),
  2294.                         'companyGroupServerId' => $entry['companyGroupServerId'],
  2295.                         'companyGroupServerAddress' => $serverList[$entry['companyGroupServerId']]['absoluteUrl'],
  2296.                         'companyGroupServerHash' => $serverList[$entry['companyGroupServerId']]['serverMarker'],
  2297.                         'companyGroupServerPort' => $request->server->get("SERVER_PORT"),
  2298.                         'file' => $output
  2299.                     );
  2300.                     $urlToCall GeneralConstant::HONEYBEE_CENTRAL_SERVER '/UpdateCompanyDataToCentralServer';
  2301.                     $curl curl_init();
  2302.                     curl_setopt_array($curl, array(
  2303.                         CURLOPT_RETURNTRANSFER => 1,
  2304.                         CURLOPT_POST => 1,
  2305.                         CURLOPT_URL => $urlToCall,
  2306.                         CURLOPT_CONNECTTIMEOUT => 10,
  2307.                         CURLOPT_SSL_VERIFYPEER => false,
  2308.                         CURLOPT_SSL_VERIFYHOST => false,
  2309.                         CURLOPT_HTTPHEADER => array(),
  2310.                         CURLOPT_POSTFIELDS => $post_fields
  2311.                     ));
  2312.                     $retData curl_exec($curl);
  2313.                     $errData curl_error($curl);
  2314.                     curl_close($curl);
  2315.                 }
  2316.             }
  2317.             return new JsonResponse([]);
  2318.         }
  2319.     }
  2320.     public function GetAppListFromCentralServerAction(Request $request$id 0)
  2321.     {
  2322.         $systemType $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
  2323.         $appIds $request->get('appIds', []);
  2324.         $appId $request->get('appId'0);
  2325.         if (is_string($appIds)) $appIds json_decode($appIdstrue);
  2326.         if ($appIds == null$appIds = [];
  2327.         if ($appId != 0)
  2328.             $appIds[] = $appId;
  2329.         if ($systemType == '_CENTRAL_') {
  2330.             $em $this->getDoctrine()->getManager('company_group');
  2331.             $em->getConnection()->connect();
  2332.             $connected $em->getConnection()->isConnected();
  2333.             $gocDataList = [];
  2334.             if ($connected) {
  2335.                 $findByQuery = array(
  2336.                     'active' => 1
  2337.                 );
  2338.                 if ($appIds != '_ALL_' && $appIds != [])
  2339.                     $findByQuery['appId'] = $appIds;
  2340.                 $gocList $this->getDoctrine()->getManager('company_group')
  2341.                     ->getRepository("CompanyGroupBundle:CompanyGroup")
  2342.                     ->findBy($findByQuery);
  2343.                 foreach ($gocList as $entry) {
  2344.                     $d = array(
  2345.                         'name' => $entry->getName(),
  2346.                         'id' => $entry->getId(),
  2347.                         'image' => $entry->getImage(),
  2348.                         'companyGroupHash' => $entry->getCompanyGroupHash(),
  2349.                         'dbName' => $entry->getDbName(),
  2350.                         'dbUser' => $entry->getDbUser(),
  2351.                         'dbPass' => $entry->getDbPass(),
  2352.                         'dbHost' => $entry->getDbHost(),
  2353.                         'appId' => $entry->getAppId(),
  2354.                         'companyRemaining' => $entry->getCompanyRemaining(),
  2355.                         'companyAllowed' => $entry->getCompanyAllowed(),
  2356.                     );
  2357.                     $gocDataList[$entry->getId()] = $d;
  2358.                 }
  2359.             }
  2360.             return new JsonResponse($gocDataList);
  2361.         } else {
  2362.             $urlToCall GeneralConstant::HONEYBEE_CENTRAL_SERVER '/GetAppListFromCentralServer';
  2363.             $curl curl_init();
  2364.             curl_setopt_array($curl, array(
  2365.                 CURLOPT_RETURNTRANSFER => 1,
  2366.                 CURLOPT_URL => $urlToCall,
  2367.                 CURLOPT_CONNECTTIMEOUT => 10,
  2368.                 CURLOPT_SSL_VERIFYPEER => false,
  2369.                 CURLOPT_SSL_VERIFYHOST => false,
  2370.                 CURLOPT_HTTPHEADER => array(
  2371.                     "Accept: application/json",
  2372.                 ),
  2373.                 //                        CURLOPT_USERAGENT => 'InnoPM',
  2374.                 CURLOPT_POSTFIELDS => http_build_query([
  2375.                     'appIds' => $appIds
  2376.                 ])
  2377.             ));
  2378. //        $headers = array(
  2379. //            "Accept: application/json",
  2380. //        );
  2381. //        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
  2382. ////for debug only!
  2383. //        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
  2384. //        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
  2385.             $retData curl_exec($curl);
  2386.             $errData curl_error($curl);
  2387.             curl_close($curl);
  2388.             return new JsonResponse(json_decode($retDatatrue));
  2389.         }
  2390.     }
  2391.     public function GetTaskListForMenuAction(Request $request$id 0)
  2392.     {
  2393.         $systemType $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
  2394.         $session $request->getSession();
  2395.         $appIds $request->get('appIds', []);
  2396.         $appId $request->get('appId'0);
  2397.         if (is_string($appIds)) $appIds json_decode($appIdstrue);
  2398.         if ($appIds == null$appIds = [];
  2399.         if ($appId != 0)
  2400.             $appIds[] = $appId;
  2401.         if ($systemType == '_CENTRAL_') {
  2402.             $em $this->getDoctrine()->getManager('company_group');
  2403.             $em->getConnection()->connect();
  2404.             $connected $em->getConnection()->isConnected();
  2405.             $gocDataList = [];
  2406.             if ($connected) {
  2407.                 $findByQuery = array(
  2408.                     'active' => 1
  2409.                 );
  2410.                 if ($appIds != '_ALL_' && $appIds != [])
  2411.                     $findByQuery['appId'] = $appIds;
  2412.                 $gocList $this->getDoctrine()->getManager('company_group')
  2413.                     ->getRepository("CompanyGroupBundle:CompanyGroup")
  2414.                     ->findBy($findByQuery);
  2415.                 foreach ($gocList as $entry) {
  2416.                     $d = array(
  2417.                         'name' => $entry->getName(),
  2418.                         'id' => $entry->getId(),
  2419.                         'image' => $entry->getImage(),
  2420.                         'companyGroupHash' => $entry->getCompanyGroupHash(),
  2421.                         'dbName' => $entry->getDbName(),
  2422.                         'dbUser' => $entry->getDbUser(),
  2423.                         'dbPass' => $entry->getDbPass(),
  2424.                         'dbHost' => $entry->getDbHost(),
  2425.                         'appId' => $entry->getAppId(),
  2426.                         'companyRemaining' => $entry->getCompanyRemaining(),
  2427.                         'companyAllowed' => $entry->getCompanyAllowed(),
  2428.                     );
  2429.                     $gocDataList[$entry->getId()] = $d;
  2430.                 }
  2431.             }
  2432.             return new JsonResponse($gocDataList);
  2433.         } else {
  2434.             $findByQuery = array(
  2435.                 'userId' => $session->get(UserConstants::USER_ID0)
  2436.             );
  2437.             $employee $this->getDoctrine()->getManager()
  2438.                 ->getRepository("ApplicationBundle:Employee")
  2439.                 ->findOneBy($findByQuery);
  2440.             $assignedTaskList = array();
  2441.             $currentlyWorkingTaskList = array();
  2442.             if ($employee) {
  2443.                 $findByQuery = array(
  2444.                     'assignedTo' => $employee->getEmployeeId(),
  2445.                     'hasChild' => [0null]
  2446.                 );
  2447.                 $assignedTaskListData $this->getDoctrine()->getManager()
  2448.                     ->getRepository("ApplicationBundle:PlanningItem")
  2449.                     ->findBy($findByQuery);
  2450.                 $findByQuery = array(
  2451.                     'employeeId' => $employee->getEmployeeId(),
  2452.                 );
  2453.                 $currentlyWorkingTaskListData $this->getDoctrine()->getManager()
  2454.                     ->getRepository("ApplicationBundle:TaskLog")
  2455.                     ->findBy($findByQuery);
  2456.                 foreach ($assignedTaskListData as $entry) {
  2457.                     $dt = array(
  2458.                         'description' => $entry->getDescription(),
  2459.                         'urgency' => $entry->getUrgency()
  2460.                     );
  2461.                     $assignedTaskList[] = $dt;
  2462.                 }
  2463.                 foreach ($currentlyWorkingTaskListData as $entry) {
  2464.                     $dt = array();
  2465.                     $currentlyWorkingTaskList[] = $dt;
  2466.                 }
  2467.             }
  2468.             return new JsonResponse(array(
  2469.                 'assignedTaskList' => $assignedTaskList,
  2470.                 'currentlyWorkingTaskList' => $currentlyWorkingTaskList,
  2471.             ));
  2472.         }
  2473.     }
  2474.     public function SyncUserToCentralUserAction(Request $request)
  2475.     {
  2476.         $systemType $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
  2477.         $post $request;
  2478.         $globalIdsByAppIdAndUser = [];
  2479.         if ($systemType == '_CENTRAL_') {
  2480.             $userDataList $request->get('userData', []);
  2481.             if (is_string($userDataList)) $userDataList json_decode($userDataListtrue);
  2482.             if ($userDataList == null$userDataList = [];
  2483.             $em_goc $this->getDoctrine()->getManager('company_group');
  2484.             //1st step get all company item ids and then check for global id null if its null then the
  2485. //            return new JsonResponse(
  2486. //                array(
  2487. //                    'userDataList' => $userDataList
  2488. //                )
  2489. //            );
  2490.             ////ITEMGROUPS
  2491.             foreach ($userDataList as $k => $cwa) {
  2492.                 $centralUser $em_goc
  2493.                     ->getRepository("CompanyGroupBundle:EntityApplicantDetails")
  2494.                     ->findOneBy(
  2495.                         array(
  2496.                             'applicantId' => $cwa['getGlobalId']
  2497.                         )
  2498.                     );
  2499.                 if ($centralUser) {
  2500.                     $centralUser->setFirstname($cwa['getFirstname'] ?? null);
  2501.                     $centralUser->setLastname($cwa['getLastname'] ?? null);
  2502.                     $centralUser->setEmail($cwa['getEmail'] ?? null);
  2503.                     $centralUser->setOAuthEmail($cwa['getOAuthEmail'] ?? null);
  2504.                     $centralUser->setPhone($cwa['getPhone'] ?? null);
  2505.                     $centralUser->setNid($cwa['getNid'] ?? null);
  2506.                     $centralUser->setSex($cwa['getSex'] ?? null);
  2507.                     $centralUser->setBlood($cwa['getBlood'] ?? null);
  2508.                     $centralUser->setFather($cwa['getFather'] ?? null);
  2509.                     $centralUser->setMother($cwa['getMother'] ?? null);
  2510.                     $centralUser->setSpouse($cwa['getSpouse'] ?? null);
  2511.                     $centralUser->setCurrAddr($cwa['getCurrAddr'] ?? null);
  2512.                     $centralUser->setPermAddr($cwa['getPermAddr'] ?? null);
  2513.                     $centralUser->setPhoneCountryCode($cwa['getPhoneCountryCode'] ?? null);
  2514.                     $centralUser->setEmpType($cwa['getEmpType'] ?? null);
  2515.                     $centralUser->setTin($cwa['getTin'] ?? null);
  2516.                     $centralUser->setDept($cwa['getDept'] ?? null);
  2517.                     $centralUser->setDesg($cwa['getDesg'] ?? null);
  2518.                     $centralUser->setBranch($cwa['getBranch'] ?? null);
  2519.                     $centralUser->setWeeklyHoliday($cwa['getWeeklyHoliday'] ?? null);
  2520.                     $centralUser->setSupervisor($cwa['getSupervisor'] ?? null);
  2521.                     $centralUser->setDob(!empty($cwa['getDob']) ? new \DateTime($cwa['getDob']) : null);
  2522.                     $centralUser->setJoiningDate(!empty($cwa['getJoiningDate']) ? new \DateTime($cwa['getJoiningDate']) : null);
  2523.                     $centralUser->setEmpValidTill(!empty($cwa['getEmpValidTill']) ? new \DateTime($cwa['getEmpValidTill']) : null);
  2524.                     $centralUser->setTinValidTill(!empty($cwa['getTinValidTill']) ? new \DateTime($cwa['getTinValidTill']) : null);
  2525.                     $centralUser->setMedInsValidTill(!empty($cwa['getMedInsValidTill']) ? new \DateTime($cwa['getMedInsValidTill']) : null);
  2526.                 } else {
  2527.                     $qry $em_goc->getRepository('CompanyGroupBundle:EntityApplicantDetails')
  2528.                         ->createQueryBuilder('m')
  2529.                         ->where("m.email like '" $cwa['getEmail'] . "'");
  2530.                     if ($cwa['getOAuthEmail'] != '' && $cwa['getOAuthEmail'] != null)
  2531.                         $qry->orWhere("m.oAuthEmail like '" $cwa['getOAuthEmail'] . "'");
  2532.                     if ($cwa['getPhoneNumber'] != '' && $cwa['getPhoneNumber'] != null)
  2533.                         $qry->orWhere("m.phone like '" $cwa['getPhoneNumber'] . "'");
  2534.                     $targets $qry->getQuery()
  2535.                         ->setMaxResults(1)
  2536.                         ->getResult();
  2537.                     if (!empty($targets))
  2538.                         $centralUser $targets[0];
  2539.                 }
  2540.                 if ($centralUser) {
  2541.                     $centralUser->setFirstname($cwa['getFirstname'] ?? null);
  2542.                     $centralUser->setLastname($cwa['getLastname'] ?? null);
  2543.                     $centralUser->setEmail($cwa['getEmail'] ?? null);
  2544.                     $centralUser->setOAuthEmail($cwa['getOAuthEmail'] ?? null);
  2545.                     $centralUser->setPhone($cwa['getPhone'] ?? null);
  2546.                     $centralUser->setNid($cwa['getNid'] ?? null);
  2547.                     $centralUser->setSex($cwa['getSex'] ?? null);
  2548.                     $centralUser->setBlood($cwa['getBlood'] ?? null);
  2549.                     $centralUser->setFather($cwa['getFather'] ?? null);
  2550.                     $centralUser->setMother($cwa['getMother'] ?? null);
  2551.                     $centralUser->setSpouse($cwa['getSpouse'] ?? null);
  2552.                     $centralUser->setCurrAddr($cwa['getCurrAddr'] ?? null);
  2553.                     $centralUser->setPermAddr($cwa['getPermAddr'] ?? null);
  2554.                     $centralUser->setPhoneCountryCode($cwa['getPhoneCountryCode'] ?? null);
  2555.                     $centralUser->setEmpType($cwa['getEmpType'] ?? null);
  2556.                     $centralUser->setTin($cwa['getTin'] ?? null);
  2557.                     $centralUser->setDept($cwa['getDept'] ?? null);
  2558.                     $centralUser->setDesg($cwa['getDesg'] ?? null);
  2559.                     $centralUser->setBranch($cwa['getBranch'] ?? null);
  2560.                     $centralUser->setWeeklyHoliday($cwa['getWeeklyHoliday'] ?? null);
  2561.                     $centralUser->setSupervisor($cwa['getSupervisor'] ?? null);
  2562.                     $centralUser->setDob(!empty($cwa['getDob']) ? new \DateTime($cwa['getDob']) : null);
  2563.                     $centralUser->setJoiningDate(!empty($cwa['getJoiningDate']) ? new \DateTime($cwa['getJoiningDate']) : null);
  2564.                     $centralUser->setEmpValidTill(!empty($cwa['getEmpValidTill']) ? new \DateTime($cwa['getEmpValidTill']) : null);
  2565.                     $centralUser->setTinValidTill(!empty($cwa['getTinValidTill']) ? new \DateTime($cwa['getTinValidTill']) : null);
  2566.                     $centralUser->setMedInsValidTill(!empty($cwa['getMedInsValidTill']) ? new \DateTime($cwa['getMedInsValidTill']) : null);
  2567.                 } else
  2568.                     $centralUser = new EntityApplicantDetails();
  2569. //
  2570. //                $getters = array_filter(get_class_methods($data), function ($method) {
  2571. //                    return 'get' === substr($method, 0, 3);
  2572. //                });
  2573.                 // Manual mapping starts here
  2574.                 $centralUser->setFirstname($cwa['getFirstname'] ?? null);
  2575.                 $centralUser->setLastname($cwa['getLastname'] ?? null);
  2576.                 $centralUser->setEmail($cwa['getEmail'] ?? null);
  2577.                 $centralUser->setOAuthEmail($cwa['getOAuthEmail'] ?? null);
  2578.                 $centralUser->setPhone($cwa['getPhone'] ?? null);
  2579.                 $centralUser->setNid($cwa['getNid'] ?? null);
  2580.                 $centralUser->setSex($cwa['getSex'] ?? null);
  2581.                 $centralUser->setBlood($cwa['getBlood'] ?? null);
  2582.                 $centralUser->setFather($cwa['getFather'] ?? null);
  2583.                 $centralUser->setMother($cwa['getMother'] ?? null);
  2584.                 $centralUser->setSpouse($cwa['getSpouse'] ?? null);
  2585.                 $centralUser->setCurrAddr($cwa['getCurrAddr'] ?? null);
  2586.                 $centralUser->setPermAddr($cwa['getPermAddr'] ?? null);
  2587.                 $centralUser->setPhoneCountryCode($cwa['getPhoneCountryCode'] ?? null);
  2588.                 $centralUser->setEmpType($cwa['getEmpType'] ?? null);
  2589.                 $centralUser->setTin($cwa['getTin'] ?? null);
  2590.                 $centralUser->setDept($cwa['getDept'] ?? null);
  2591.                 $centralUser->setDesg($cwa['getDesg'] ?? null);
  2592.                 $centralUser->setBranch($cwa['getBranch'] ?? null);
  2593.                 $centralUser->setWeeklyHoliday($cwa['getWeeklyHoliday'] ?? null);
  2594.                 $centralUser->setSupervisor($cwa['getSupervisor'] ?? null);
  2595. // Date fields
  2596.                 $centralUser->setDob(!empty($cwa['getDob']) ? new \DateTime($cwa['getDob']) : null);
  2597.                 $centralUser->setJoiningDate(!empty($cwa['getJoiningDate']) ? new \DateTime($cwa['getJoiningDate']) : null);
  2598.                 $centralUser->setEmpValidTill(!empty($cwa['getEmpValidTill']) ? new \DateTime($cwa['getEmpValidTill']) : null);
  2599.                 $centralUser->setTinValidTill(!empty($cwa['getTinValidTill']) ? new \DateTime($cwa['getTinValidTill']) : null);
  2600.                 $centralUser->setMedInsValidTill(!empty($cwa['getMedInsValidTill']) ? new \DateTime($cwa['getMedInsValidTill']) : null);
  2601. // Continue mapping more fields as needed...
  2602.                 $userAppIds json_decode($centralUser->getUserAppIds(), true);
  2603.                 $userTypesByAppIds json_decode($centralUser->getUserTypesByAppIds(), true);
  2604.                 if ($userAppIds == null$userAppIds = [];
  2605.                 if ($userTypesByAppIds == null$userTypesByAppIds = [];
  2606.                 $userAppIds array_merge($userAppIdsarray_diff([$cwa['getUserAppId']], $userAppIds));
  2607.                 if (!isset($userTypesByAppIds[$cwa['getUserAppId']])) {
  2608.                     $userTypesByAppIds[$cwa['getUserAppId']] = [];
  2609.                 }
  2610.                 $userTypesByAppIds[$cwa['getUserAppId']] = array_merge($userTypesByAppIds[$cwa['getUserAppId']], array_diff([$cwa['getUserType']], $userTypesByAppIds[$cwa['getUserAppId']]));
  2611.                 $userFullName $cwa['getName'];
  2612.                 $userFullNameArr explode(' '$cwa['getName']);
  2613.                 $userFirstName = isset($userFullNameArr[0]) ? $userFullNameArr[0] : '';
  2614.                 $userLastName '';
  2615.                 if (isset($userFullNameArr[1])) {
  2616.                     foreach ($userFullNameArr as $kunky => $chunky) {
  2617.                         if ($kunky != 0) {
  2618.                             $userLastName .= $chunky;
  2619.                         }
  2620.                         if ($kunky count($userFullNameArr) - 1) {
  2621.                             $userLastName .= ' ';
  2622.                         }
  2623.                     }
  2624.                 }
  2625.                 $centralUser->setUserAppIds(json_encode($userAppIds));
  2626.                 $centralUser->setFirstname($userFirstName);
  2627.                 $centralUser->setLastname($userLastName);
  2628.                 $centralUser->setUserTypesByAppIds(json_encode($userTypesByAppIds));
  2629.                 $em_goc->persist($centralUser);
  2630.                 $em_goc->flush();
  2631.                 $uploadedFile $request->files->get('file_' $cwa['getUserAppId'] . '_' $cwa['getUserId'], null);
  2632.                 {
  2633.                     //            if($uploadedFile->getImage())
  2634.                     //                var_dump($uploadedFile->getFile());
  2635.                     //                var_dump($uploadedFile);
  2636.                     if ($uploadedFile != null) {
  2637.                         $fileName 'user_image' $centralUser->getApplicantId() . '.' $uploadedFile->guessExtension();
  2638.                         $path $fileName;
  2639.                         $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/UserImage/';
  2640.                         if ($centralUser->getImage() != '' && $centralUser->getImage() != null && file_exists($this->container->getParameter('kernel.root_dir') . '/../web/' $centralUser->getImage())) {
  2641.                             unlink($this->container->getParameter('kernel.root_dir') . '/../web/' $centralUser->getImage());
  2642.                         }
  2643.                         if (!file_exists($upl_dir)) {
  2644.                             mkdir($upl_dir0777true);
  2645.                         }
  2646.                         $file $uploadedFile->move($upl_dir$path);
  2647.                         if ($path != "")
  2648.                             $centralUser->setImage('uploads/UserImage/' $path);
  2649.                     }
  2650.                 }
  2651.                 $em_goc->flush();
  2652.                 if (!isset($globalIdsByAppIdAndUser[$cwa['getUserAppId']]))
  2653.                     $globalIdsByAppIdAndUser[$cwa['getUserAppId']] = array();
  2654.                 $globalIdsByAppIdAndUser[$cwa['getUserAppId']][$cwa['getUserId']] =
  2655.                     array(
  2656.                         'gid' => $centralUser->getApplicantId()
  2657.                     );
  2658.                 $companies $em_goc->getRepository('CompanyGroupBundle:CompanyGroup')->findBy([
  2659.                     'appId' => $userAppIds
  2660.                 ]);
  2661.                 $globalId $cwa['getGlobalId'];
  2662.                 $userData $userDataList;
  2663.                 $dataByServerId = [];
  2664.                 $gocDataListByAppId = [];
  2665.                 foreach ($companies as $entry) {
  2666.                     $gocDataListByAppId[$entry->getAppId()] = [
  2667.                         'dbName' => $entry->getDbName(),
  2668.                         'dbUser' => $entry->getDbUser(),
  2669.                         'dbPass' => $entry->getDbPass(),
  2670.                         'dbHost' => $entry->getDbHost(),
  2671.                         'serverAddress' => $entry->getCompanyGroupServerAddress(),
  2672.                         'port' => $entry->getCompanyGroupServerPort() ?: 80,
  2673.                         'appId' => $entry->getAppId(),
  2674.                         'serverId' => $entry->getCompanyGroupServerId(),
  2675.                     ];
  2676.                     if (!isset($dataByServerId[$entry->getCompanyGroupServerId()]))
  2677.                         $dataByServerId[$entry->getCompanyGroupServerId()] = array(
  2678.                             'serverId' => $entry->getCompanyGroupServerId(),
  2679.                             'serverAddress' => $entry->getCompanyGroupServerAddress(),
  2680.                             'port' => $entry->getCompanyGroupServerPort() ?: 80,
  2681.                             'appId' => $userAppIds,
  2682.                             'payload' => array(
  2683.                                 'globalId' => $globalId,
  2684.                                 'appId' => $userAppIds,
  2685.                                 'userData' => $userData,
  2686. //                                      'approvalHash' => $approvalHash
  2687.                             )
  2688.                         );
  2689.                 }
  2690.                 $urls = [];
  2691.                 foreach ($dataByServerId as $entry) {
  2692.                     $serverAddress $entry['serverAddress'];
  2693.                     if (!$serverAddress) continue;
  2694.                     $syncUrl $serverAddress '/ReceiveUserFromCentral';
  2695.                     $payload $entry['payload'];
  2696.                     $curl curl_init();
  2697.                     curl_setopt_array($curl, [
  2698.                         CURLOPT_RETURNTRANSFER => true,
  2699.                         CURLOPT_POST => true,
  2700.                         CURLOPT_URL => $syncUrl,
  2701.                         CURLOPT_CONNECTTIMEOUT => 10,
  2702.                         CURLOPT_SSL_VERIFYPEER => false,
  2703.                         CURLOPT_SSL_VERIFYHOST => false,
  2704.                         CURLOPT_HTTPHEADER => [
  2705.                             'Accept: application/json',
  2706.                             'Content-Type: application/json'
  2707.                         ],
  2708.                         CURLOPT_POSTFIELDS => json_encode($payload)
  2709.                     ]);
  2710.                     $response curl_exec($curl);
  2711.                     $err curl_error($curl);
  2712.                     $httpCode curl_getinfo($curlCURLINFO_HTTP_CODE);
  2713.                     curl_close($curl);
  2714.                     if ($err) {
  2715.                         error_log("ERP Sync Error [Server: {$entry['serverAddress']}]: $err");
  2716.                     } else {
  2717.                         error_log("ERP Sync Success [HTTP $httpCode]: $response");
  2718.                     }
  2719.                 }
  2720.             }
  2721.             return new JsonResponse(
  2722.                 array(
  2723.                     'globalIdsData' => $globalIdsByAppIdAndUser
  2724.                 )
  2725.             );
  2726.         } else {
  2727.             $em $this->getDoctrine()->getManager('company_group');
  2728.             $em->getConnection()->connect();
  2729.             $connected $em->getConnection()->isConnected();
  2730.             $gocDataList = [];
  2731.             $gocDataListByAppId = [];
  2732.             $retDataDebug = array();
  2733.             $appIds $request->get('appIds''_UNSET_');
  2734.             $userIds $request->get('userIds''_UNSET_');
  2735.             if ($connected) {
  2736.                 $findByQuery = array(
  2737.                     'active' => 1
  2738.                 );
  2739.                 if ($appIds !== '_UNSET_')
  2740.                     $findByQuery['appId'] = $appIds;
  2741.                 $gocList $this->getDoctrine()->getManager('company_group')
  2742.                     ->getRepository("CompanyGroupBundle:CompanyGroup")
  2743.                     ->findBy($findByQuery);
  2744.                 foreach ($gocList as $entry) {
  2745.                     $d = array(
  2746.                         'name' => $entry->getName(),
  2747.                         'id' => $entry->getId(),
  2748.                         'image' => $entry->getImage(),
  2749.                         'companyGroupHash' => $entry->getCompanyGroupHash(),
  2750.                         'dbName' => $entry->getDbName(),
  2751.                         'dbUser' => $entry->getDbUser(),
  2752.                         'dbPass' => $entry->getDbPass(),
  2753.                         'dbHost' => $entry->getDbHost(),
  2754.                         'appId' => $entry->getAppId(),
  2755.                         'companyRemaining' => $entry->getCompanyRemaining(),
  2756.                         'companyAllowed' => $entry->getCompanyAllowed(),
  2757.                     );
  2758.                     $gocDataList[$entry->getId()] = $d;
  2759.                     $gocDataListByAppId[$entry->getAppId()] = $d;
  2760.                 }
  2761.                 $debugCount 0;
  2762.                 foreach ($gocDataList as $gocId => $entry) {
  2763. //                    if($debugCount>0)
  2764. //                        continue;
  2765.                     $skipSend 1;
  2766.                     $connector $this->container->get('application_connector');
  2767.                     $connector->resetConnection(
  2768.                         'default',
  2769.                         $gocDataList[$gocId]['dbName'],
  2770.                         $gocDataList[$gocId]['dbUser'],
  2771.                         $gocDataList[$gocId]['dbPass'],
  2772.                         $gocDataList[$gocId]['dbHost'],
  2773.                         $reset true);
  2774.                     $em $this->getDoctrine()->getManager();
  2775.                     if ($userIds !== '_UNSET_')
  2776.                         $users $this->getDoctrine()
  2777.                             ->getRepository('ApplicationBundle:SysUser')
  2778.                             ->findBy(
  2779.                                 array(
  2780.                                     'userId' => $userIds
  2781.                                 )
  2782.                             );
  2783.                     else
  2784.                         $users $this->getDoctrine()
  2785.                             ->getRepository('ApplicationBundle:SysUser')
  2786.                             ->findBy(
  2787.                                 array()
  2788.                             );
  2789.                     $output '';
  2790.                     $userData = array();
  2791.                     $userFiles = array();
  2792.                     foreach ($users as $user) {
  2793.                         $file $this->container->getParameter('kernel.root_dir') . '/../web/' $user->getImage(); //<-- Path could be relative
  2794. //                            $output=$file;
  2795.                         if ($user->getImage() != '' && $user->getImage() != null && file_exists($file)) {
  2796. //                        $file = new \CURLFile($this->container->getParameter('kernel.root_dir') . '/../web/uploads/CompanyImage/' . $company->getImage()); //<-- Path could be relative
  2797.                             $mime mime_content_type($file);
  2798.                             $info pathinfo($file);
  2799.                             $name $info['basename'];
  2800.                             if (strpos($mime'image') !== false) {
  2801.                                 $output = new \CURLFile($file$mime$name);
  2802.                             }
  2803.                             $skipSend 0;
  2804.                             $userFiles['file_' $user->getUserAppId() . '_' $user->getUserId()] = $output;
  2805.                         } else {
  2806. //                                    unlink($this->container->getParameter('kernel.root_dir') . '/../web'. $centralUser->getImage());
  2807.                             $user->setImage(null);
  2808.                             $userFiles['file_' $user->getUserAppId() . '_' $user->getUserId()] = 'pika';
  2809.                             $em->flush();
  2810.                         }
  2811.                         $getters array_filter(get_class_methods($user), function ($method) {
  2812.                             return 'get' === substr($method03);
  2813.                         });
  2814.                         $userDataSingle = array(//                                'file'=>$output
  2815.                         );
  2816.                         foreach ($getters as $getter) {
  2817.                             if ($getter == 'getCreatedAt' || $getter == 'getUpdatedAt' || $getter == 'getImage')
  2818.                                 continue;
  2819. //                                if(is_string($user->{$getter}())|| is_numeric($user->{$getter}()))
  2820. //                                {
  2821. //                                    $userDataSingle[$getter]= $user->{$getter}();
  2822. //                                }
  2823.                             if ($user->{$getter}() instanceof \DateTime) {
  2824.                                 $ggtd $user->{$getter}();
  2825.                                 $userDataSingle[$getter] = $ggtd->format('Y-m-d');
  2826.                             } else
  2827.                                 $userDataSingle[$getter] = $user->{$getter}();
  2828.                         }
  2829.                         $userData[] = $userDataSingle;
  2830.                     }
  2831.                     $retDataDebug[$debugCount] = array(
  2832.                         'skipSend' => $skipSend
  2833.                     );
  2834.                     //now customers
  2835.                     $emailFieldName 'email';
  2836.                     $phoneFieldName 'contact_number';
  2837.                     $query "SELECT * from  acc_clients   where 1=1 ";
  2838.                     $stmt $em->getConnection()->prepare($query);
  2839.                     $stmt->execute();
  2840.                     $results $stmt->fetchAll();
  2841.                     if (!empty($results)) {
  2842.                         foreach ($results as $dt) {
  2843.                             $dt['company_id'] = "1";
  2844.                             $companyData = isset($companyList[$dt['company_id']]) ? $companyList[$dt['company_id']] : [];
  2845.                             $userDataSingle = array(
  2846.                                 'getUserAppId' => strval(UserConstants::USER_TYPE_CLIENT),
  2847.                                 'getUserName' => 'CID-' str_pad($dt['client_id'], 8'0'STR_PAD_LEFT),
  2848.                                 'getUserId' => $dt['client_id']
  2849.                             );
  2850. //                            $userData[] = $userDataSingle;
  2851.                         }
  2852.                     }
  2853.                     //now suppliers
  2854.                     $emailFieldName 'email';
  2855.                     $phoneFieldName 'contact_number';
  2856.                     $query "SELECT * from  acc_suppliers   where 1=1 ";
  2857.                     $stmt $em->getConnection()->prepare($query);
  2858.                     $stmt->execute();
  2859.                     $results $stmt->fetchAll();
  2860.                     if (!empty($results)) {
  2861.                         foreach ($results as $dt) {
  2862.                             $dt['company_id'] = "1";
  2863.                             $companyData = isset($companyList[$dt['company_id']]) ? $companyList[$dt['company_id']] : [];
  2864.                             $userDataSingle = array(
  2865.                                 'userType' => strval(UserConstants::USER_TYPE_SUPPLIER),
  2866.                                 'userName' => 'SID-' str_pad($dt['supplier_id'], 8'0'STR_PAD_LEFT),
  2867.                                 'userId' => $dt['supplier_id'],
  2868.                             );
  2869. //                            $userData[] = $userDataSingle;
  2870.                         }
  2871.                     }
  2872. //                    if ($skipSend == 0)
  2873.                     {
  2874.                         $urlToCall GeneralConstant::HONEYBEE_CENTRAL_SERVER '/SyncUserToCentralUser';
  2875.                         $userFiles['userData'] = json_encode($userData);
  2876.                         $curl curl_init();
  2877.                         curl_setopt_array($curl, array(
  2878.                             CURLOPT_RETURNTRANSFER => 1,
  2879.                             CURLOPT_POST => 1,
  2880.                             CURLOPT_URL => $urlToCall,
  2881.                             CURLOPT_CONNECTTIMEOUT => 10,
  2882.                             CURLOPT_SSL_VERIFYPEER => false,
  2883.                             CURLOPT_SSL_VERIFYHOST => false,
  2884. //                            CURLOPT_SAFE_UPLOAD => false,
  2885.                             CURLOPT_HTTPHEADER => array(//                                "Accept: multipart/form-data",
  2886.                             ),
  2887.                             //                        CURLOPT_USERAGENT => 'InnoPM',
  2888. //                            CURLOPT_POSTFIELDS => array(
  2889. //                                'userData'=>json_encode($userData),
  2890. //                                'userFiles'=>$userFiles
  2891. //                            ),
  2892.                             CURLOPT_POSTFIELDS => $userFiles
  2893.                         ));
  2894.                         $retData curl_exec($curl);
  2895.                         $errData curl_error($curl);
  2896.                         curl_close($curl);
  2897.                         $retDataObj json_decode($retDatatrue);
  2898.                         $retDataDebug[$debugCount] = $retDataObj;
  2899.                         if (isset($retDataObj['globalIdsData']))
  2900.                             foreach ($retDataObj['globalIdsData'] as $app_id => $usrList) {
  2901.                                 $connector $this->container->get('application_connector');
  2902.                                 $connector->resetConnection(
  2903.                                     'default',
  2904.                                     $gocDataListByAppId[$app_id]['dbName'],
  2905.                                     $gocDataListByAppId[$app_id]['dbUser'],
  2906.                                     $gocDataListByAppId[$app_id]['dbPass'],
  2907.                                     $gocDataListByAppId[$app_id]['dbHost'],
  2908.                                     $reset true);
  2909.                                 $em $this->getDoctrine()->getManager();
  2910.                                 foreach ($usrList as $sys_id => $globaldata) {
  2911.                                     $user $this->getDoctrine()
  2912.                                         ->getRepository('ApplicationBundle:SysUser')
  2913.                                         ->findOneBy(
  2914.                                             array(
  2915.                                                 'userId' => $sys_id
  2916.                                             )
  2917.                                         );
  2918.                                     if ($user) {
  2919.                                         $user->setGlobalId($globaldata['gid']);
  2920.                                         $em->flush();
  2921.                                     }
  2922.                                 }
  2923.                             }
  2924.                     }
  2925.                     $debugCount++;
  2926.                 }
  2927.             }
  2928.             return new JsonResponse($retDataDebug);
  2929.         }
  2930.     }
  2931.     public function ReceiveUserFromCentralAction(Request $request)
  2932.     {
  2933.         $data json_decode($request->getContent(), true);
  2934.         if (
  2935.             !$data ||
  2936.             !isset($data['globalId']) ||
  2937.             !isset($data['appId']) ||
  2938.             !isset($data['userData'])
  2939.         ) {
  2940.             return new JsonResponse(['success' => false'message' => 'Missing required fields'], 400);
  2941.         }
  2942.         $globalId $data['globalId'];
  2943.         $userDataRaw $data['userData'];
  2944.         if (is_string($userDataRaw)) {
  2945.             $userDataRaw json_decode($userDataRawtrue);
  2946.         }
  2947.         if (!is_array($userDataRaw)) {
  2948.             return new JsonResponse(['success' => false'message' => 'Invalid userData format'], 400);
  2949.         }
  2950.         $userData is_array($userDataRaw[0] ?? null) ? $userDataRaw[0] : $userDataRaw;
  2951.         if (is_string($userData)) {
  2952.             $userData json_decode($userDatatrue);
  2953.         }
  2954.         if (!is_array($userData)) {
  2955.             return new JsonResponse(['success' => false'message' => 'Invalid userData format'], 400);
  2956.         }
  2957.         $companyIds is_array($data['appId']) ? $data['appId'] : [$data['appId']];
  2958.         $em_goc $this->getDoctrine()->getManager('company_group');
  2959.         $companies $em_goc->getRepository('CompanyGroupBundle:CompanyGroup')->findBy([
  2960.             'appId' => $companyIds
  2961.         ]);
  2962.         foreach ($companies as $entry) {
  2963.             $goc = [
  2964.                 'dbName' => $entry->getDbName(),
  2965.                 'dbUser' => $entry->getDbUser(),
  2966.                 'dbPass' => $entry->getDbPass(),
  2967.                 'dbHost' => $entry->getDbHost(),
  2968.                 'serverAddress' => $entry->getCompanyGroupServerAddress(),
  2969.                 'port' => $entry->getCompanyGroupServerPort() ?: 80,
  2970.                 'appId' => $entry->getAppId(),
  2971. //                                 'serverId' => $entry->getServerId(),
  2972.             ];
  2973.             $connector $this->container->get('application_connector');
  2974.             $connector->resetConnection(
  2975.                 'default',
  2976.                 $goc['dbName'],
  2977.                 $goc['dbUser'],
  2978.                 $goc['dbPass'],
  2979.                 $goc['dbHost'],
  2980.                 $reset true
  2981.             );
  2982.             $em $this->getDoctrine()->getManager();
  2983.             $user $em->getRepository('ApplicationBundle:SysUser')->findOneBy(['globalId' => $globalId]);
  2984.             if (!$user) {
  2985.                 return new JsonResponse(['success' => false'message' => 'User not found'], 404);
  2986.             }
  2987. //            $user = $em->getRepository('ApplicationBundle:SysUser')->findOneBy(['userId' => $user->getUserId()]);
  2988. //            if (!$user) {
  2989. //                $user = new \ApplicationBundle\Entity\EncryptedSignature();
  2990. //                $user->setUserId($user->getUserId());
  2991. //                $user->setCreatedAt(new \DateTime());
  2992. //            }
  2993.             $user->setUserName($userData['getFirstname'] . ' ' $userData['getLastname']);
  2994.             $user->setUserCompanyId(1);
  2995.             $user->setGlobalId($globalId);
  2996.             $user->setUserName($userData['getName'] ?? null);
  2997.             $user->setUpdatedAt(new \DateTime());
  2998.             $em->persist($user);
  2999.             $em->flush();
  3000.             $employee $em->getRepository('ApplicationBundle:Employee')->findOneBy(['userId' => $user->getUserId()]);
  3001.             if ($employee) {
  3002.                 $employee->setFirstName($userData['getFirstname']);
  3003.                 $employee->setLastName($userData['getLastname']);
  3004.                 $em->persist($employee);
  3005.             }
  3006.             if ($employee)
  3007.                 $employeeDetails $em->getRepository('ApplicationBundle:EmployeeDetails')
  3008.                     ->findOneBy(['id' => $employee->getEmployeeId()]);
  3009.             else
  3010.                 $employeeDetails $em->getRepository('ApplicationBundle:EmployeeDetails')
  3011.                     ->findOneBy(['userId' => $user->getUserId()]);
  3012.             if ($employeeDetails) {
  3013.                 $employeeDetails->setFirstname($userData['getFirstname']);
  3014.                 $employeeDetails->setLastname($userData['getLastname']);
  3015.                 $employeeDetails->setEmail($userData['getEmail']);
  3016.                 $employeeDetails->setPhone($userData['getPhone'] ?? null);
  3017.                 $employeeDetails->setNid($userData['getNid'] ?? null);
  3018.                 $employeeDetails->setSex($userData['getSex'] ?? null);
  3019.                 $employeeDetails->setBlood($userData['getBlood'] ?? null);
  3020.                 $employeeDetails->setFather($userData['getFather'] ?? null);
  3021.                 $employeeDetails->setMother($userData['getMother'] ?? null);
  3022.                 $employeeDetails->setSpouse($userData['getSpouse'] ?? null);
  3023.                 $employeeDetails->setCurrAddr($userData['getCurrAddr'] ?? null);
  3024.                 $employeeDetails->setPermAddr($userData['getPermAddr'] ?? null);
  3025.                 $em->persist($employeeDetails);
  3026.             }
  3027.             $em->flush();
  3028.         }
  3029.         return new JsonResponse(['success' => true'message' => 'User, Employee, and EmployeeDetails updated in all ERP servers']);
  3030.     }
  3031.     public function SyncCentralUserToServerAction(Request $request)
  3032.     {
  3033.         $systemType $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
  3034.         $post $request;
  3035.         $serverList GeneralConstant::$serverListById;
  3036.         $globalIdsByAppIdAndUser = [];
  3037.         if ($systemType == '_CENTRAL_') {
  3038.             $userDataList = [];
  3039.             $retAppIds = [];
  3040.             $appIdList = [];
  3041.             $userIdList = [];
  3042.             $retDataDebug = [];
  3043.             $appIds $request->get('appIds''_UNSET_');
  3044.             if ($appIds != '_UNSET_') {
  3045.                 $appIdList $userIdList explode(','$appIds);;
  3046.                 if ($appIdList == null$appIdList = [];
  3047.             }
  3048.             $userIds $request->get('userIds''_UNSET_');
  3049.             if ($userIds != '_UNSET_') {
  3050.                 $userIdList explode(','$userIds);
  3051.                 if ($userIdList == null$userIdList = [];
  3052.             }
  3053.             if (is_string($userDataList)) $userDataList json_decode($userDataListtrue);
  3054.             if ($userDataList == null$userDataList = [];
  3055.             $em_goc $this->getDoctrine()->getManager('company_group');
  3056.             $centralUserQry $em_goc->getRepository('CompanyGroupBundle:EntityApplicantDetails')
  3057.                 ->createQueryBuilder('m')
  3058.                 ->where("1=1");
  3059.             if (!empty($userIdList))
  3060.                 $centralUserQry->andWhere("m.applicantId in (" implode(','$userIdList) . " )");
  3061.             $centralUsers $centralUserQry->getQuery()
  3062.                 ->setMaxResults(1)
  3063.                 ->getResult();
  3064.             ////ITEMGROUPS
  3065.             foreach ($centralUsers as $centralUser) {
  3066.                 if ($centralUser) {
  3067.                 } else {
  3068.                 }
  3069.                 $toSetUserData = [];
  3070.                 $userData = array();
  3071.                 $userFiles = array();
  3072.                 $file $this->container->getParameter('kernel.root_dir') . '/../web/' $centralUser->getImage(); //<-- Path could be relative
  3073. //                            $output=$file;
  3074.                 if ($centralUser->getImage() != '' && $centralUser->getImage() != null && file_exists($file)) {
  3075. //                        $file = new \CURLFile($this->container->getParameter('kernel.root_dir') . '/../web/uploads/CompanyImage/' . $company->getImage()); //<-- Path could be relative
  3076.                     $mime mime_content_type($file);
  3077.                     $info pathinfo($file);
  3078.                     $name $info['basename'];
  3079.                     if (strpos($mime'image') !== false) {
  3080.                         $output = new \CURLFile($file$mime$name);
  3081.                     }
  3082.                     $skipSend 0;
  3083.                     $userFiles['file_' $centralUser->getApplicantId()] = $output;
  3084.                 } else {
  3085.                     $centralUser->setImage(null);
  3086.                     $userFiles['file_' $centralUser->getApplicantId()] = 'pika';
  3087.                     $em_goc->flush();
  3088.                 }
  3089. //
  3090.                 $getters array_filter(get_class_methods($centralUser), function ($method) {
  3091.                     return 'get' === substr($method03);
  3092.                 });
  3093.                 $userDataSingle = array();
  3094.                 foreach ($getters as $getter) {
  3095.                     if ($getter == 'getCreatedAt' || $getter == 'getUpdatedAt' || $getter == 'getImage')
  3096.                         continue;
  3097. //                                if(is_string($user->{$getter}())|| is_numeric($user->{$getter}()))
  3098. //                                {
  3099. //                                    $userDataSingle[$getter]= $user->{$getter}();
  3100. //                                }
  3101.                     if ($centralUser->{$getter}() instanceof \DateTime) {
  3102.                         $ggtd $centralUser->{$getter}();
  3103.                         $userDataSingle[$getter] = $ggtd->format('Y-m-d');
  3104.                     } else
  3105.                         $userDataSingle[$getter] = $centralUser->{$getter}();
  3106.                 }
  3107.                 $userAppIds json_decode($centralUser->getUserAppIds(), true);
  3108.                 if ($userAppIds == null$userAppIds = [];
  3109.                 $appIdList array_merge($appIdListarray_diff($userAppIds$appIdList));
  3110.                 $userTypesByAppIds json_decode($centralUser->getUserTypesByAppIds(), true);
  3111.                 if ($userTypesByAppIds == null$userTypesByAppIds = [];
  3112.                 $userDataSingle['userTypesByAppIds'] = $userTypesByAppIds;
  3113.                 $userDataList[] = $userDataSingle;
  3114.                 $em_goc->persist($centralUser);
  3115.                 $em_goc->flush();
  3116.             }
  3117.             $em_goc->flush();
  3118.             $serverIdsCalledAlready = [];
  3119.             $appList $this->getDoctrine()->getManager('company_group')
  3120.                 ->getRepository("CompanyGroupBundle:CompanyGroup")
  3121.                 ->findBy(array(
  3122.                         'appId' => $appIdList
  3123.                     )
  3124.                 );
  3125.             $userFiles['userData'] = json_encode($userDataList);
  3126.             foreach ($appList as $app) {
  3127.                 if (!in_array($app->getCompanyGroupServerId(), $serverIdsCalledAlready)) {
  3128.                     if (isset($serverList[$app->getCompanyGroupServerId()])) {
  3129.                         //                    if ($skipSend == 0)
  3130.                         {
  3131.                             $urlToCall $serverList[$app->getCompanyGroupServerId()]['absoluteUrl'] . '/SyncCentralUserToServer';
  3132.                             $curl curl_init();
  3133.                             curl_setopt_array($curl, array(
  3134.                                 CURLOPT_RETURNTRANSFER => 1,
  3135.                                 CURLOPT_POST => 1,
  3136.                                 CURLOPT_URL => $urlToCall,
  3137.                                 CURLOPT_CONNECTTIMEOUT => 10,
  3138.                                 CURLOPT_SSL_VERIFYPEER => false,
  3139.                                 CURLOPT_SSL_VERIFYHOST => false,
  3140.                                 CURLOPT_HTTPHEADER => array(),
  3141.                                 CURLOPT_POSTFIELDS => $userFiles
  3142.                             ));
  3143.                             $retData curl_exec($curl);
  3144.                             $errData curl_error($curl);
  3145.                             curl_close($curl);
  3146.                             $retDataObj json_decode($retDatatrue);
  3147.                             $retDataDebug[] = $retDataObj;
  3148.                         }
  3149.                     }
  3150.                     $serverIdsCalledAlready[] = $app->getCompanyGroupServerId();
  3151.                 }
  3152.             }
  3153. //                if (!isset($globalIdsByAppIdAndUser[$cwa['getUserAppId']]))
  3154. //                    $globalIdsByAppIdAndUser[$cwa['getUserAppId']] = array();
  3155. //
  3156. //                $globalIdsByAppIdAndUser[$cwa['getUserAppId']][$cwa['getUserId']] =
  3157. //                    array(
  3158. //                        'gid' => $centralUser->getApplicantId()
  3159. //                    );
  3160.             return new JsonResponse(
  3161.                 array(
  3162.                     "success" => true,
  3163.                     "retDataDebug" => $retDataDebug,
  3164.                     "serverIdsCalledAlready" => $serverIdsCalledAlready,
  3165.                     "appIdList" => $appIdList,
  3166.                     "userFiles" => $userFiles,
  3167.                     "retAppIds" => $retAppIds,
  3168.                 )
  3169.             );
  3170.         } else {
  3171.             $userDataList $request->get('userData', []);
  3172.             if (is_string($userDataList)) $userDataList json_decode($userDataListtrue);
  3173.             if ($userDataList == null$userDataList = [];
  3174.             foreach ($userDataList as $userData) {
  3175.                 $em_goc $this->getDoctrine()->getManager('company_group');
  3176.                 $em $this->getDoctrine()->getManager('company_group');
  3177.                 $em->getConnection()->connect();
  3178.                 $connected $em->getConnection()->isConnected();
  3179.                 $gocDataList = [];
  3180.                 $gocDataListByAppId = [];
  3181.                 $retDataDebug = array();
  3182.                 $appIds json_decode($userData['getUserAppIds'], true);
  3183.                 if ($appIds == null$appIds = [];
  3184.                 $userTypesByAppIds json_decode($userData['getUserTypesByAppIds'], true);
  3185.                 if ($userTypesByAppIds == null$userTypesByAppIds = [];
  3186.                 $userIds $request->get('userIds''_UNSET_');
  3187.                 if ($connected && !empty($appIds)) {
  3188.                     $findByQuery = array(
  3189.                         'active' => 1
  3190.                     );
  3191.                     $findByQuery['appId'] = $appIds;
  3192.                     $gocList $this->getDoctrine()->getManager('company_group')
  3193.                         ->getRepository("CompanyGroupBundle:CompanyGroup")
  3194.                         ->findBy($findByQuery);
  3195.                     $imagePathToSet '';
  3196.                     $uploadedFile $request->files->get('file_' $userData['getApplicantId'], null);
  3197.                     {
  3198.                         if ($uploadedFile != null) {
  3199.                             $fileName 'user_image' $userData['getApplicantId'] . '.' $uploadedFile->guessExtension();
  3200.                             $path $fileName;
  3201.                             $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/UserImage/';
  3202.                             if (!file_exists($upl_dir)) {
  3203.                                 mkdir($upl_dir0777true);
  3204.                             }
  3205.                             $file $uploadedFile->move($upl_dir$path);
  3206.                             $imagePathToSet 'uploads/UserImage/' $path;
  3207.                         }
  3208.                     }
  3209.                     foreach ($gocList as $entry) {
  3210.                         $d = array(
  3211.                             'name' => $entry->getName(),
  3212.                             'id' => $entry->getId(),
  3213.                             'image' => $entry->getImage(),
  3214.                             'companyGroupHash' => $entry->getCompanyGroupHash(),
  3215.                             'dbName' => $entry->getDbName(),
  3216.                             'dbUser' => $entry->getDbUser(),
  3217.                             'dbPass' => $entry->getDbPass(),
  3218.                             'dbHost' => $entry->getDbHost(),
  3219.                             'appId' => $entry->getAppId(),
  3220.                             'companyRemaining' => $entry->getCompanyRemaining(),
  3221.                             'companyAllowed' => $entry->getCompanyAllowed(),
  3222.                         );
  3223.                         $gocDataList[$entry->getId()] = $d;
  3224.                         $gocDataListByAppId[$entry->getAppId()] = $d;
  3225.                     }
  3226.                     $debugCount 0;
  3227.                     foreach ($gocDataList as $gocId => $entry) {
  3228. //                    if($debugCount>0)
  3229. //                        continue;
  3230.                         $skipSend 1;
  3231.                         $connector $this->container->get('application_connector');
  3232.                         $connector->resetConnection(
  3233.                             'default',
  3234.                             $gocDataList[$gocId]['dbName'],
  3235.                             $gocDataList[$gocId]['dbUser'],
  3236.                             $gocDataList[$gocId]['dbPass'],
  3237.                             $gocDataList[$gocId]['dbHost'],
  3238.                             $reset true);
  3239.                         $em $this->getDoctrine()->getManager();
  3240.                         $user $this->getDoctrine()
  3241.                             ->getRepository('ApplicationBundle:SysUser')
  3242.                             ->findOneBy(
  3243.                                 array(
  3244.                                     'globalId' => $userData['getApplicantId']
  3245.                                 )
  3246.                             );
  3247.                         $output '';
  3248.                         if (!$user)
  3249.                             $user = new SysUser();
  3250.                         $user->setGlobalId($userData['getApplicantId']);
  3251.                         $user->setUserAppId($entry['appId']);
  3252.                         $user_type 1;
  3253.                         if (isset($userData['userTypesByAppIds'][$entry['appId']])) {
  3254.                             $user_type $userData['userTypesByAppIds'][$entry['appId']];
  3255.                         }
  3256.                         $user->setUserType($user_type);
  3257.                         $user->setUserAppIdList(json_encode($appIds));
  3258.                         $user->setName($userData['getFirstname'] . ' ' $userData['getLastname']);
  3259.                         $user->setStatus(UserConstants::ACTIVE_USER);
  3260.                         foreach ($userData as $getter => $value) {
  3261.                             if ($getter == 'getApplicantId')
  3262.                                 continue;
  3263.                             $setMethod str_replace('get''set'$getter);
  3264.                             if (method_exists($user$setMethod)) {
  3265.                                 if ($user->{$getter}() instanceof \DateTime)
  3266.                                     $user->{$setMethod}(new \DateTime($value)); // `foo!`
  3267.                                 else if ($setMethod == 'setUserAppIds') {
  3268.                                 } else
  3269.                                     $user->{$setMethod}($value); // `foo!`
  3270.                             }
  3271.                         }
  3272.                         if ($imagePathToSet != "") {
  3273.                             if ($user->getImage() != $imagePathToSet && $user->getImage() != '' && $user->getImage() != null && file_exists($this->container->getParameter('kernel.root_dir') . '/../web/' $user->getImage())) {
  3274.                                 unlink($this->container->getParameter('kernel.root_dir') . '/../web/' $user->getImage());
  3275.                             }
  3276.                             $user->setImage($imagePathToSet);
  3277.                         }
  3278.                         $em->persist($user);
  3279.                         $em->flush();
  3280.                         $debugCount++;
  3281.                         $retDataDebug[$debugCount] = array(
  3282.                             'skipSend' => $skipSend,
  3283.                             'userId' => $user->getUserId(),
  3284.                             'appId' => $user->getUserAppId(),
  3285.                         );
  3286.                     }
  3287.                 }
  3288.             }
  3289.             return new JsonResponse($retDataDebug);
  3290.         }
  3291.     }
  3292.     public function GetUsersByQueryAction(Request $request$id 0)
  3293.     {
  3294.         $message "";
  3295.         $gocList = [];
  3296.         $outputList = [];
  3297.         $queryType '_ANY_';
  3298. //        if ($request->has('queryType'))
  3299.         $queryType $request->get('queryType''_ANY_');
  3300.         $returnData = [];
  3301.         $debugData = [];
  3302.         $returnDataArray = [];
  3303.         $returnDataByServerId = [];
  3304.         $serverId $request->get('serverId'4);
  3305.         $serverUrl $request->get('serverUrl''http://194.195.244.141');
  3306.         $serverPort $request->get('serverPort''');
  3307.         $queryStr $request->get('queryStr''');
  3308.         $queryStrEmail $request->get('quryStrEmail''');
  3309.         $queryStrPhone $request->get('quryStrPhone''');
  3310.         if ($queryStrEmail == '' && $queryStrPhone == '') {
  3311.             $queryStrEmail $queryStr;
  3312.         }
  3313. //        sample
  3314. //        data will be by company id
  3315.         $d = array(
  3316.             'userType' => 2,
  3317.             'userId' => 4,
  3318.             'userName' => 'abc',
  3319.             'loginUserName' => 'CID-abc',
  3320.             'serverId' => $serverId,
  3321.             'serverUrl' => $serverUrl,
  3322.             'systemType' => $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_',
  3323.             'gocId' => 2,
  3324.             'companyId' => 1,
  3325.             'appId' => 45,
  3326.             'companyLogoUrl' => '/uploads/CompanyImage/4c48d9d0f26918c8bd866a197e50e15e.png',
  3327.             'companyName' => 'HoneyBee Iot Ltd.',
  3328.             'userCompanyIds' => [14],
  3329.             'userAppIds' => [140],
  3330.             'userCompanyList' => [
  3331.                 => [
  3332.                     'companyLogoUrl' => '/uploads/CompanyImage/4c48d9d0f26918c8bd866a197e50e15e.png',
  3333.                     'companyName' => 'HoneyBee IoT Ltd.',
  3334.                 ],
  3335.                 => [
  3336.                     'companyLogoUrl' => '/uploads/CompanyImage/4c48d9d0f26918c8bd866a197e50e15e.png',
  3337.                     'companyName' => 'Nastec Srl',
  3338.                 ]
  3339.             ]
  3340.         );
  3341. //        return new JsonResponse(array(
  3342. //            $d, $d
  3343. //        ));
  3344.         $em $this->getDoctrine()->getManager('company_group');
  3345.         $em->getConnection()->connect();
  3346.         $connected $em->getConnection()->isConnected();
  3347.         if ($connected)
  3348.             $gocList $this->getDoctrine()->getManager('company_group')
  3349.                 ->getRepository("CompanyGroupBundle:CompanyGroup")
  3350.                 ->findBy(
  3351.                     array(
  3352.                         'active' => 1
  3353.                     )
  3354.                 );
  3355.         $gocDataList = [];
  3356.         foreach ($gocList as $entry) {
  3357.             $d = array(
  3358.                 'name' => $entry->getName(),
  3359.                 'id' => $entry->getId(),
  3360.                 'dbName' => $entry->getDbName(),
  3361.                 'dbUser' => $entry->getDbUser(),
  3362.                 'dbPass' => $entry->getDbPass(),
  3363.                 'dbHost' => $entry->getDbHost(),
  3364.                 'appId' => $entry->getAppId(),
  3365.                 'companyRemaining' => $entry->getCompanyRemaining(),
  3366.                 'companyAllowed' => $entry->getCompanyAllowed(),
  3367.             );
  3368.             $gocDataList[$entry->getId()] = $d;
  3369.         }
  3370.         $gocDbName '';
  3371.         $gocDbUser '';
  3372.         $gocDbPass '';
  3373.         $gocDbHost '';
  3374.         $gocId 0;
  3375. //        $web_root_dir = $this->container->getParameter('kernel.root_dir'). '/../web' ;
  3376.         $web_root_dir $url $this->generateUrl('dashboard', [], UrlGenerator::ABSOLUTE_URL);
  3377. //        $root_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/temp/' . 'ledger' . '.pdf';
  3378.         foreach ($gocDataList as $gocId => $entry) {
  3379.             $connector $this->container->get('application_connector');
  3380.             $connector->resetConnection(
  3381.                 'default',
  3382.                 $gocDataList[$gocId]['dbName'],
  3383.                 $gocDataList[$gocId]['dbUser'],
  3384.                 $gocDataList[$gocId]['dbPass'],
  3385.                 $gocDataList[$gocId]['dbHost'],
  3386.                 $reset true);
  3387.             $em $this->getDoctrine()->getManager();
  3388.             $companyList = [];
  3389.             $query "SELECT * from  company   where 1";
  3390.             $stmt $em->getConnection()->prepare($query);
  3391.             $stmt->execute();
  3392.             $results $stmt->fetchAll();
  3393.             if (!empty($results))
  3394.                 foreach ($results as $dt) {
  3395.                     $companyList[$dt['id']] = $dt;
  3396.                 }
  3397.             else
  3398.                 $companyList = array(
  3399.                     => [
  3400.                         'image' => '',
  3401.                         'name' => 'Company',
  3402.                     ]
  3403.                 );
  3404.             ///SysUSER
  3405.             $fieldName = ($queryType == '_EMAIL_' || $queryType == '_ANY_') ? 'email' 'phone_number';
  3406.             if ($queryStrEmail == '' && $queryStrPhone == '') {
  3407.             } else {
  3408.                 $emailFieldName 'email';
  3409.                 $phoneFieldName 'phone_number';
  3410.                 $userNameFieldName 'user_name';
  3411.                 $query "SELECT * from  sys_user   where 1=1 ";
  3412.                 $query .= ($queryStrEmail != '') ? "and $emailFieldName like '$queryStrEmail' " '';
  3413.                 $query .= ($queryStrPhone != '') ? "and $phoneFieldName like '%$queryStrPhone%' " '';
  3414.                 $query .= ($queryStr != '') ? " or $userNameFieldName like '$queryStr' " '';
  3415.                 $stmt $em->getConnection()->prepare($query);
  3416.                 $stmt->execute();
  3417.                 $results $stmt->fetchAll();
  3418.                 if (!empty($results)) {
  3419.                     foreach ($results as $dt) {
  3420. //                        if($dt['company_id']==0 || $dt['company_id'] ==null)
  3421.                         $dt['company_id'] = "1";
  3422.                         $user_app_ids json_decode($dt['user_app_id_list'], true);
  3423.                         if ($user_app_ids == null$user_app_ids = [$dt['app_id']];
  3424.                         $user_company_ids json_decode($dt['user_company_id_list'], true);
  3425.                         if ($user_company_ids == null$user_company_ids = [$dt['company_id']];
  3426.                         $companyData = isset($companyList[$dt['company_id']]) ? $companyList[$dt['company_id']] : [];
  3427.                         $d = array(
  3428.                             'userType' => $dt['user_type'],
  3429.                             'userName' => $dt['user_name'],
  3430.                             'userId' => $dt['user_id'],
  3431.                             'loginUserName' => $dt['user_name'],
  3432.                             'email' => $dt['email'],
  3433.                             'phone' => $dt['phone_number'],
  3434.                             'serverId' => $serverId,
  3435.                             'serverUrl' => $serverUrl,
  3436.                             'systemType' => $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_',
  3437.                             'gocId' => $gocId,
  3438.                             'companyId' => $dt['company_id'],
  3439.                             'appId' => $dt['app_id'],
  3440.                             'companyLogoUrl' => $web_root_dir $companyData['image'],
  3441.                             'companyName' => $companyData['name'],
  3442.                             'userCompanyIds' => $user_company_ids,
  3443.                             'userAppIds' => $user_app_ids,
  3444.                             'userCompanyList' => [
  3445.                             ]
  3446.                         );
  3447.                         foreach ($user_company_ids as $cid) {
  3448.                             $d['userCompanyList'][$cid] = [
  3449.                                 'companyLogoUrl' => $web_root_dir $companyList[$cid]['image'],
  3450.                                 'companyName' => $companyList[$cid]['name'],
  3451.                             ];
  3452.                         }
  3453.                         $returnData[] = $d;
  3454.                         $returnDataByServerId[$serverId][] = $d;
  3455.                     }
  3456.                 }
  3457.                 //now customers
  3458.                 $emailFieldName 'email';
  3459.                 $phoneFieldName 'contact_number';
  3460.                 $query "SELECT * from  acc_clients   where 1=1 ";
  3461.                 $query .= ($queryStrEmail != '') ? "and $emailFieldName like '$queryStrEmail'" '';
  3462.                 $query .= ($queryStrPhone != '') ? "and $phoneFieldName like '%$queryStrPhone%'" '';
  3463.                 $stmt $em->getConnection()->prepare($query);
  3464.                 $stmt->execute();
  3465.                 $results $stmt->fetchAll();
  3466.                 if (!empty($results)) {
  3467.                     foreach ($results as $dt) {
  3468.                         $dt['company_id'] = "1";
  3469.                         $companyData = isset($companyList[$dt['company_id']]) ? $companyList[$dt['company_id']] : [];
  3470.                         $d = array(
  3471.                             'userType' => strval(UserConstants::USER_TYPE_CLIENT),
  3472.                             'userName' => 'CID-' str_pad($dt['client_id'], 8'0'STR_PAD_LEFT),
  3473.                             'userId' => $dt['client_id'],
  3474.                             'loginUserName' => $dt['username'],
  3475.                             'email' => $dt['email'],
  3476.                             'phone' => $dt['contact_number'],
  3477.                             'serverId' => $serverId,
  3478.                             'serverUrl' => $serverUrl,
  3479.                             'systemType' => $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_',
  3480.                             'gocId' => $gocId,
  3481.                             'companyId' => $dt['company_id'],
  3482.                             'appId' => $dt['app_id'],
  3483.                             'companyLogoUrl' => $web_root_dir $companyData['image'],
  3484.                             'companyName' => $companyData['name'],
  3485.                             'userCompanyIds' => [],
  3486.                             'userAppIds' => [],
  3487.                             'userCompanyList' => [
  3488.                             ]
  3489.                         );
  3490.                         $returnData[] = $d;
  3491.                         $returnDataByServerId[$serverId][] = $d;
  3492.                     }
  3493.                 }
  3494.                 //now suppliers
  3495.                 $emailFieldName 'email';
  3496.                 $phoneFieldName 'contact_number';
  3497.                 $query "SELECT * from  acc_suppliers   where 1=1 ";
  3498.                 $query .= ($queryStrEmail != '') ? "and $emailFieldName like '$queryStrEmail'" '';
  3499.                 $query .= ($queryStrPhone != '') ? "and $phoneFieldName like '%$queryStrPhone%'" '';
  3500.                 $stmt $em->getConnection()->prepare($query);
  3501.                 $stmt->execute();
  3502.                 $results $stmt->fetchAll();
  3503.                 if (!empty($results)) {
  3504.                     foreach ($results as $dt) {
  3505.                         $dt['company_id'] = "1";
  3506.                         $companyData = isset($companyList[$dt['company_id']]) ? $companyList[$dt['company_id']] : [];
  3507.                         $d = array(
  3508.                             'userType' => strval(UserConstants::USER_TYPE_SUPPLIER),
  3509.                             'userName' => 'SID-' str_pad($dt['supplier_id'], 8'0'STR_PAD_LEFT),
  3510.                             'userId' => $dt['supplier_id'],
  3511.                             'loginUserName' => $dt['username'],
  3512.                             'email' => $dt['email'],
  3513.                             'phone' => $dt['contact_number'],
  3514.                             'serverId' => $serverId,
  3515.                             'serverUrl' => $serverUrl,
  3516.                             'systemType' => $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_',
  3517.                             'gocId' => $gocId,
  3518.                             'companyId' => $dt['company_id'],
  3519.                             'appId' => $dt['app_id'],
  3520.                             'companyLogoUrl' => $web_root_dir $companyData['image'],
  3521.                             'companyName' => $companyData['name'],
  3522.                             'userCompanyIds' => [],
  3523.                             'userAppIds' => [],
  3524.                             'userCompanyList' => [
  3525.                             ]
  3526.                         );
  3527.                         $returnData[] = $d;
  3528.                         $returnDataByServerId[$serverId][] = $d;
  3529.                     }
  3530.                 }
  3531.             }
  3532.         }
  3533.         return new JsonResponse(array(
  3534.             'success' => true,
  3535.             'data' => $returnData,
  3536.             'debugData' => $debugData,
  3537.             'dataByServerId' => $returnDataByServerId,
  3538.             'queryType' => $queryType
  3539.         ));
  3540.     }
  3541.     public function GetHoneybeeServerListAction(Request $request$id 0)
  3542.     {
  3543.         $serverList GeneralConstant::$serverList;
  3544.         return new JsonResponse(array(
  3545.             'success' => true,
  3546.             'data' => $serverList,
  3547.         ));
  3548.     }
  3549.     public function ServerListAction()
  3550.     {
  3551.         $serverList GeneralConstant::$serverList;
  3552.         return new JsonResponse(
  3553.             $serverList
  3554.         );
  3555.     }
  3556.     public function widgetModuleListAction()
  3557.     {
  3558.         $widgetsModuleList = [
  3559.             [
  3560.                 'name' => 'Accounts',
  3561.                 'id' => 1,
  3562.                 'hash' => '_ACC_',
  3563.                 'enabled' => true,
  3564.                 'hidden' => true,
  3565.             ],
  3566.             [
  3567.                 'name' => 'Sales',
  3568.                 'id' => 2,
  3569.                 'hash' => '_SL_',
  3570.                 'enabled' => true,
  3571.                 'hidden' => true,
  3572.             ],
  3573.             [
  3574.                 'name' => 'Human Resource',
  3575.                 'id' => 3,
  3576.                 'hash' => '_HRM_',
  3577.                 'enabled' => true,
  3578.                 'hidden' => true,
  3579.             ],
  3580.             [
  3581.                 'name' => 'Admin',
  3582.                 'id' => 4,
  3583.                 'hash' => '_ADM_',
  3584.                 'enabled' => true,
  3585.                 'hidden' => true,
  3586.             ],
  3587.         ];
  3588.         return new JsonResponse(
  3589.             array(
  3590.                 'success' => true,
  3591.                 'widgetModuleList' => $widgetsModuleList
  3592.             )
  3593.         );
  3594.     }
  3595.     public function widgetListAction()
  3596.     {
  3597.         $widgetsList = [
  3598.             [
  3599.                 'id' => 1,
  3600.                 'name' => 'Expense',
  3601.                 'hash' => '_EXP_',
  3602.                 'widgetModuleId' => 1,
  3603.                 'widgetName' => 'Accounts',
  3604.                 'screenName' => '',
  3605.                 'hidden' => true,
  3606.                 'enabled' => true,
  3607.                 'image' => 'https://e7.pngegg.com/pngimages/640/646/png-clipart-expense-management-computer-icons-finance-others-miscellaneous-text.png',
  3608.                 'showOnHome' => true,
  3609.                 'routeList' => [
  3610.                 ]
  3611.             ],
  3612.             [
  3613.                 'id' => 2,
  3614.                 'name' => 'Attendance',
  3615.                 'hash' => '_ATD_',
  3616.                 'widgetModuleId' => 3,
  3617.                 'widgetName' => 'Human Resource',
  3618.                 'screenName' => '',
  3619.                 'hidden' => true,
  3620.                 'enabled' => true,
  3621.                 'image' => 'https://cdn.iconscout.com/icon/premium/png-256-thumb/biometric-attendance-1-1106795.png',
  3622.                 'showOnHome' => true,
  3623.                 'routeList' => [
  3624.                 ]
  3625.             ],
  3626.             [
  3627.                 'id' => 3,
  3628.                 'name' => 'Payment',
  3629.                 'hash' => '_PMT_',
  3630.                 'widgetModuleId' => 1,
  3631.                 'widgetName' => 'Accounts',
  3632.                 'screenName' => '',
  3633.                 'hidden' => true,
  3634.                 'enabled' => true,
  3635.                 'image' => 'https://banner2.cleanpng.com/20180628/gbi/kisspng-management-accounting-accountant-gestin-kontabil-contador-5b356a344f40d2.2788485015302272523246.jpg',
  3636.                 'showOnHome' => true,
  3637.                 'routeList' => [
  3638.                     ["id" => 3"route" => "create_payment_voucher""name" => "Make Payment""parentId" => 3,],
  3639.                     ["id" => 4"route" => "create_receipt_voucher""name" => "Make Receipt""parentId" => 3,],
  3640.                 ]
  3641.             ],
  3642.             [
  3643.                 'id' => 4,
  3644.                 'name' => 'Report',
  3645.                 'hash' => '_RPRT_',
  3646.                 'widgetModuleId' => 1,
  3647.                 'widgetName' => 'Accounts',
  3648.                 'screenName' => '',
  3649.                 'hidden' => true,
  3650.                 'enabled' => true,
  3651.                 'image' => 'https://cdn-icons-png.flaticon.com/512/3093/3093748.png',
  3652.                 'showOnHome' => true,
  3653.                 'routeList' => [
  3654.                 ]
  3655.             ],
  3656.             [
  3657.                 'id' => 5,
  3658.                 'name' => 'Leave Application',
  3659.                 'hash' => '_LEVAPP_',
  3660.                 'widgetModuleId' => 3,
  3661.                 'widgetName' => 'Human Resource',
  3662.                 'screenName' => '',
  3663.                 'hidden' => true,
  3664.                 'enabled' => true,
  3665.                 'image' => 'https://icons.veryicon.com/png/o/transport/easy-office-system-icon-library/leave-request.png',
  3666.                 'showOnHome' => true,
  3667.                 'routeList' => [
  3668.                 ]
  3669.             ],
  3670.             [
  3671.                 'id' => 6,
  3672.                 'name' => 'Fund Requisition',
  3673.                 'hash' => '_FR_',
  3674.                 'widgetModuleId' => 1,
  3675.                 'widgetName' => 'Accounts',
  3676.                 'screenName' => '',
  3677.                 'hidden' => true,
  3678.                 'enabled' => true,
  3679.                 'image' => 'https://www.pngall.com/wp-content/uploads/13/Fund-PNG-Image.png',
  3680.                 'showOnHome' => true,
  3681.                 'routeList' => [
  3682.                 ]
  3683.             ],
  3684.             [
  3685.                 'id' => 7,
  3686.                 'name' => 'My Task',
  3687.                 'hash' => '_MT_',
  3688.                 'widgetModuleId' => 3,
  3689.                 'widgetName' => 'Human Resource',
  3690.                 'screenName' => '',
  3691.                 'hidden' => true,
  3692.                 'enabled' => true,
  3693.                 'image' => 'https://st.depositphotos.com/44273736/54272/v/450/depositphotos_542726218-stock-illustration-premium-download-icon-task-management.jpg',
  3694.                 'showOnHome' => true,
  3695.                 'routeList' => [
  3696.                 ]
  3697.             ],
  3698.             [
  3699.                 'id' => 8,
  3700.                 'name' => 'Fund Transfer',
  3701.                 'hash' => '_FT_',
  3702.                 'widgetModuleId' => 3,
  3703.                 'widgetName' => 'Accounts',
  3704.                 'screenName' => '',
  3705.                 'hidden' => true,
  3706.                 'enabled' => true,
  3707.                 'image' => 'https://l450v.alamy.com/450v/r1r4rx/money-transfer-vector-icon-isolated-on-transparent-background-money-transfer-transparency-logo-concept-r1r4rx.jpg',
  3708.                 'showOnHome' => true,
  3709.                 'routeList' => [
  3710.                 ]
  3711.             ],
  3712.             [
  3713.                 'id' => 9,
  3714.                 'name' => 'Stock Management',
  3715.                 'hash' => '_SM_',
  3716.                 'widgetModuleId' => 3,
  3717.                 'widgetName' => 'Inventory',
  3718.                 'screenName' => '',
  3719.                 'hidden' => true,
  3720.                 'enabled' => true,
  3721.                 'image' => 'https://l450v.alamy.com/450v/r1r4rx/money-transfer-vector-icon-isolated-on-transparent-background-money-transfer-transparency-logo-concept-r1r4rx.jpg',
  3722.                 'showOnHome' => true,
  3723.                 'routeList' => [
  3724.                 ]
  3725.             ],
  3726.             [
  3727.                 'id' => 10,
  3728.                 'name' => 'Approval',
  3729.                 'hash' => '_ADM_',
  3730.                 'widgetModuleId' => 4,
  3731.                 'widgetName' => 'Inventory',
  3732.                 'screenName' => '',
  3733.                 'hidden' => true,
  3734.                 'enabled' => true,
  3735.                 'image' => 'https://cdn.icon-icons.com/icons2/907/PNG/512/approve-sign-in-a-black-rounded-square-shape_icon-icons.com_70558.png',
  3736.                 'showOnHome' => true,
  3737.                 'routeList' => [
  3738.                 ]
  3739.             ],
  3740.         ];
  3741.         return new JsonResponse(
  3742.             array(
  3743.                 'success' => true,
  3744.                 'widgetList' => $widgetsList
  3745.             )
  3746.         );
  3747.     }
  3748.     public function addRemoveWidgetAction(Request $request$id 0)
  3749.     {
  3750.         $em $this->getDoctrine()->getManager();
  3751. //        $user = $em->getRepository("ApplicationBundle:SysUser")
  3752. //            ->findBy();
  3753.         return new  JsonResponse(
  3754. //            $user
  3755.         );
  3756.     }
  3757.     public function EncryptParentModulesAction(Request $request$appId 0$companyId 0)
  3758.     {
  3759.         $message "";
  3760.         $gocList = [];
  3761.         $outputList = [];
  3762.         $pmodules = [];
  3763.         if ($request->query->has('modulesByComma'))
  3764.             $pmodules explode(','$request->query->get('modulesByComma'));
  3765.         $iv '1234567812345678';
  3766.         $pass $appId '_' $companyId;
  3767.         //        $method = 'aes-256-cbc';
  3768.         $str json_encode($pmodules);
  3769. //                        $str=$request->query->get('modulesByComma');
  3770.         $str $str 'YmLRocksLikeABoss';
  3771.         $data $str;
  3772.         $data openssl_encrypt($str"AES-128-CBC"$pass0$iv);
  3773.         //        $data=$str;
  3774. //                        $data = openssl_decrypt($data, "AES-128-CBC", $pass, 0, $iv);
  3775. //                        $data = openssl_decrypt(base64_decode(base64_encode($data)), "AES-128-CBC", $pass, 0, $iv);
  3776.         return new Response($data);
  3777. //        return new JsonResponse(array(
  3778. //            'encData'=>$data
  3779. //        ));
  3780.     }
  3781.     public function PrepareDatabaseAction(Request $request)
  3782.     {
  3783.         $message "";
  3784.         $gocList = [];
  3785.         $outputList = [];
  3786.         $em $this->getDoctrine()->getManager('company_group');
  3787.         $em->getConnection()->connect();
  3788.         $connected $em->getConnection()->isConnected();
  3789.         if ($connected)
  3790.             $gocList $this->getDoctrine()->getManager('company_group')
  3791.                 ->getRepository("CompanyGroupBundle:CompanyGroup")
  3792.                 ->findBy(
  3793.                     array(
  3794.                         'active' => 1
  3795.                     )
  3796.                 );
  3797.         $gocDataList = [];
  3798.         foreach ($gocList as $entry) {
  3799.             $d = array(
  3800.                 'name' => $entry->getName(),
  3801.                 'id' => $entry->getId(),
  3802.                 'dbName' => $entry->getDbName(),
  3803.                 'dbUser' => $entry->getDbUser(),
  3804.                 'dbPass' => $entry->getDbPass(),
  3805.                 'dbHost' => $entry->getDbHost(),
  3806.                 'appId' => $entry->getAppId(),
  3807.                 'companyRemaining' => $entry->getCompanyRemaining(),
  3808.                 'companyAllowed' => $entry->getCompanyAllowed(),
  3809.             );
  3810.             $gocDataList[$entry->getId()] = $d;
  3811.         }
  3812.         $gocDbName '';
  3813.         $gocDbUser '';
  3814.         $gocDbPass '';
  3815.         $gocDbHost '';
  3816.         $gocId 0;
  3817. //        $path = $this->container->get('templating.helper.assets')->getUrl('bundles/tlfront/js/channels.json');
  3818.         $config_dir $this->container->getParameter('kernel.root_dir') . '/gifnoc/';
  3819.         if (!file_exists($config_dir)) {
  3820.             mkdir($config_dir0777true);
  3821.         }
  3822. //        $path = $this->container->getParameter('kernel.root_dir') . '/gifnoc/givnocppa.json';
  3823. //        $content = file_exists($path) ? file_get_contents($path) : null;
  3824.         $content = [];
  3825.         $configJson = array();
  3826.         if ($content)
  3827.             $configJson json_decode($contenttrue);
  3828.         $configJsonOld $configJson;
  3829. //        if($configJson)
  3830. //        {
  3831. //
  3832. //        }
  3833. //        else
  3834.         {
  3835.             $configJson['appVersion'] = GeneralConstant::ENTITY_APP_VERSION;
  3836.             $configJson['dataBaseSchemaUpdateFlag'] = GeneralConstant::ENTITY_APP_FLAG_TRUE;
  3837.             $configJson['initiateDataBaseFlag'] = GeneralConstant::ENTITY_APP_FLAG_FALSE;
  3838.             $configJson['initiateDataBaseFlagByGoc'] = array();
  3839.             $configJson['motherLode'] = "http://innobd.com";
  3840.             foreach ($gocDataList as $gocId => $entry) {
  3841.                 $configJson['initiateDataBaseFlagByGoc'][$gocId "_" $entry['appId']] = GeneralConstant::ENTITY_APP_FLAG_TRUE;
  3842.             }
  3843.         }
  3844.         //now check if database shcema update is true
  3845. //        if($configJson['dataBaseSchemaUpdateFlag']==GeneralConstant::ENTITY_APP_FLAG_TRUE)
  3846.         if (1//temporary overwrite all
  3847.         {
  3848.             //if goclist is not empty switch to each company dbase and schema update
  3849. //            if(!empty($gocDataList))
  3850.             if (1) {
  3851.                 foreach ($gocDataList as $gocId => $entry) {
  3852.                     if ($configJson['initiateDataBaseFlagByGoc'][$gocId "_" $entry['appId']] == GeneralConstant::ENTITY_APP_FLAG_TRUE) {
  3853.                         $connector $this->container->get('application_connector');
  3854.                         $connector->resetConnection(
  3855.                             'default',
  3856.                             $gocDataList[$gocId]['dbName'],
  3857.                             $gocDataList[$gocId]['dbUser'],
  3858.                             $gocDataList[$gocId]['dbPass'],
  3859.                             $gocDataList[$gocId]['dbHost'],
  3860.                             true);
  3861.                         $em $this->getDoctrine()->getManager();
  3862.                         if ($em->getConnection()->isConnected()) {
  3863.                         } else {
  3864.                             $servername $gocDataList[$gocId]['dbHost'];
  3865.                             $username $gocDataList[$gocId]['dbUser'];
  3866.                             $password $gocDataList[$gocId]['dbPass'];
  3867. // Create connection
  3868.                             $conn = new \mysqli($servername$username$password);
  3869. // Check connection
  3870.                             if ($conn->connect_error) {
  3871.                                 die("Connection failed: " $conn->connect_error);
  3872.                             }
  3873. // Create database
  3874.                             $sql "CREATE DATABASE " $gocDataList[$gocId]['dbName'];
  3875.                             if ($conn->query($sql) === TRUE) {
  3876. //                                echo "Database created successfully";
  3877.                             } else {
  3878. //                                echo "Error creating database: " . $conn->error;
  3879.                             }
  3880.                             $conn->close();
  3881.                         }
  3882.                         $connector->resetConnection(
  3883.                             'default',
  3884.                             $gocDataList[$gocId]['dbName'],
  3885.                             $gocDataList[$gocId]['dbUser'],
  3886.                             $gocDataList[$gocId]['dbPass'],
  3887.                             $gocDataList[$gocId]['dbHost'],
  3888.                             true);
  3889.                         $em $this->getDoctrine()->getManager();
  3890.                         $tool = new SchemaTool($em);
  3891.                         $classes $em->getMetadataFactory()->getAllMetadata();
  3892. //                    $tool->createSchema($classes);
  3893.                         $tool->updateSchema($classes);
  3894.                         //new for updating app id
  3895.                         $get_kids_sql "UPDATE `company` set app_id=" $entry['appId'] . " ;
  3896.                                         UPDATE `sys_user` set app_id=" $entry['appId'] . " ;";
  3897.                         $stmt $em->getConnection()->prepare($get_kids_sql);
  3898.                         $stmt->execute();
  3899.                         $stmt->closeCursor();
  3900.                         $configJson['initiateDataBaseFlagByGoc'][$gocId "_" $entry['appId']] = GeneralConstant::ENTITY_APP_FLAG_FALSE;
  3901.                         //this is for large amount of goc we will see  later
  3902. //                        file_put_contents($path, json_encode($configJson));//overwrite
  3903. //                        return $this->redirectToRoute('update_database_schema');
  3904.                     }
  3905.                 }
  3906.             } else {
  3907.                 $em $this->getDoctrine()->getManager();
  3908.                 $tool = new SchemaTool($em);
  3909. //                    $classes = array(
  3910. //                        $em->getClassMetadata('Entities\User'),
  3911. //                        $em->getClassMetadata('Entities\Profile')
  3912. //                    );
  3913.                 $classes $em->getMetadataFactory()->getAllMetadata();
  3914. //                    $tool->createSchema($classes);
  3915.                 $tool->updateSchema($classes);
  3916.             }
  3917.         }
  3918.         $allSchemaUpdateDone 1;
  3919.         foreach ($configJson['initiateDataBaseFlagByGoc'] as $flag) {
  3920.             if ($flag == GeneralConstant::ENTITY_APP_FLAG_TRUE)
  3921.                 $allSchemaUpdateDone 0;
  3922.         }
  3923.         if ($allSchemaUpdateDone == 1)
  3924.             $configJson['dataBaseSchemaUpdateFlag'] = GeneralConstant::ENTITY_APP_FLAG_FALSE;
  3925.         ///last
  3926. //        file_put_contents($path, json_encode($configJson));//overwrite
  3927.         return new Response(json_encode($configJsonOld));
  3928.     }
  3929.     public function ConvertSpecificationToSubCategoryAction(Request $request)
  3930.     {
  3931.         $message "";
  3932.         $gocList = [];
  3933.         $outputList = [];
  3934.         $em $this->getDoctrine()->getManager('company_group');
  3935.         $em->getConnection()->connect();
  3936.         $connected $em->getConnection()->isConnected();
  3937.         if ($connected)
  3938.             $gocList $this->getDoctrine()->getManager('company_group')
  3939.                 ->getRepository("CompanyGroupBundle:CompanyGroup")
  3940.                 ->findBy(
  3941.                     array(
  3942.                         'active' => 1
  3943.                     )
  3944.                 );
  3945.         $gocDataList = [];
  3946.         foreach ($gocList as $entry) {
  3947.             $d = array(
  3948.                 'name' => $entry->getName(),
  3949.                 'id' => $entry->getId(),
  3950.                 'dbName' => $entry->getDbName(),
  3951.                 'dbUser' => $entry->getDbUser(),
  3952.                 'dbPass' => $entry->getDbPass(),
  3953.                 'dbHost' => $entry->getDbHost(),
  3954.                 'appId' => $entry->getAppId(),
  3955.                 'companyRemaining' => $entry->getCompanyRemaining(),
  3956.                 'companyAllowed' => $entry->getCompanyAllowed(),
  3957.             );
  3958.             $gocDataList[$entry->getId()] = $d;
  3959.         }
  3960.         $gocDbName '';
  3961.         $gocDbUser '';
  3962.         $gocDbPass '';
  3963.         $gocDbHost '';
  3964.         $gocId 0;
  3965. //        $path = $this->container->get('templating.helper.assets')->getUrl('bundles/tlfront/js/channels.json');
  3966.         $config_dir $this->container->getParameter('kernel.root_dir') . '/gifnoc/';
  3967.         if (!file_exists($config_dir)) {
  3968.             mkdir($config_dir0777true);
  3969.         }
  3970. //        $path = $this->container->getParameter('kernel.root_dir') . '/gifnoc/givnocppa.json';
  3971. //        $content = file_exists($path) ? file_get_contents($path) : null;
  3972.         $content = [];
  3973.         $configJson = array();
  3974.         if ($content)
  3975.             $configJson json_decode($contenttrue);
  3976.         $configJsonOld $configJson;
  3977. //        if($configJson)
  3978. //        {
  3979. //
  3980. //        }
  3981. //        else
  3982.         {
  3983.             $configJson['appVersion'] = GeneralConstant::ENTITY_APP_VERSION;
  3984.             $configJson['dataBaseSchemaUpdateFlag'] = GeneralConstant::ENTITY_APP_FLAG_TRUE;
  3985.             $configJson['initiateDataBaseFlag'] = GeneralConstant::ENTITY_APP_FLAG_FALSE;
  3986.             $configJson['initiateDataBaseFlagByGoc'] = array();
  3987.             $configJson['motherLode'] = "http://innobd.com";
  3988.             foreach ($gocDataList as $gocId => $entry) {
  3989.                 $configJson['initiateDataBaseFlagByGoc'][$gocId "_" $entry['appId']] = GeneralConstant::ENTITY_APP_FLAG_TRUE;
  3990.             }
  3991.         }
  3992.         $foundClasses = [];
  3993.         if (1) {
  3994.             foreach ($gocDataList as $gocId => $entry) {
  3995.                 $connector $this->container->get('application_connector');
  3996.                 $connector->resetConnection(
  3997.                     'default',
  3998.                     $gocDataList[$gocId]['dbName'],
  3999.                     $gocDataList[$gocId]['dbUser'],
  4000.                     $gocDataList[$gocId]['dbPass'],
  4001.                     $gocDataList[$gocId]['dbHost'],
  4002.                     $reset true);
  4003.                 $em $this->getDoctrine()->getManager();
  4004. /////////////////////////////Now get all entity and if entity has specificationId (and subcatid) the asssign
  4005.                 $query "show tables;";
  4006.                 $query "SELECT DISTINCT TABLE_NAME
  4007.     FROM INFORMATION_SCHEMA.COLUMNS
  4008.     WHERE COLUMN_NAME IN ('specification_id','sub_category_id')
  4009.         AND TABLE_SCHEMA='" $gocDataList[$gocId]['dbName'] . "' ;";
  4010.                 $stmt $em->getConnection()->prepare($query);
  4011.                 $stmt->execute();
  4012.                 $tables $stmt->fetchAll();
  4013.                 foreach ($tables as $tablename) {
  4014. //                        $theClass=new $entity;
  4015.                     $foundClasses[] = $tablename['TABLE_NAME'];
  4016.                     $query "UPDATE " $tablename['TABLE_NAME'] . " set sub_category_id=specification_id where 1;";
  4017.                     $stmt $em->getConnection()->prepare($query);
  4018.                     $stmt->execute();
  4019.                     $query "UPDATE " $tablename['TABLE_NAME'] . " set specification_id=null;";
  4020.                     $stmt $em->getConnection()->prepare($query);
  4021.                     $stmt->execute();
  4022.                 }
  4023.                 //now add all spec to cat table
  4024.                 $query "TRUNCATE  inv_product_sub_categories";
  4025.                 $stmt $em->getConnection()->prepare($query);
  4026.                 $stmt->execute();
  4027.                 $query "SELECT * FROM inv_product_specifications WHERE 1;";
  4028.                 $stmt $em->getConnection()->prepare($query);
  4029.                 $stmt->execute();
  4030.                 $results $stmt->fetchAll();
  4031.                 foreach ($results as $result) {
  4032.                     foreach ($result as $k => $res) {
  4033.                         if ($res == '')
  4034.                             $result[$k] = 'NULL';
  4035.                     }
  4036.                     $query "INSERT INTO `inv_product_sub_categories`(`id`,  `name`, `status`, `ig_id`, `category_id`, `company_id`,  `created_login_id`, `edited_login_id`, `created_at`, `updated_at`)
  4037. VALUES (" $result['id'] . ",'" str_replace("'""''"$result['name']) . "'," $result['status'] . "," $result['ig_id'] . "," $result['category_id'] . "," $result['company_id'] . "," $result['created_login_id'] . "," $result['edited_login_id'] . ",'" $result['created_at'] . "','" $result['updated_at'] . "')";
  4038.                     $stmt $em->getConnection()->prepare($query);
  4039.                     $stmt->execute();
  4040.                 }
  4041.                 $query "TRUNCATE  inv_product_specifications";
  4042.                 $stmt $em->getConnection()->prepare($query);
  4043.                 $stmt->execute();
  4044.             }
  4045.         }
  4046.         return new Response(json_encode($foundClasses));
  4047.     }
  4048.     public function initiateAdminAction(Request $request)
  4049.     {
  4050.         $em $this->getDoctrine()->getManager();
  4051.         $em_goc $this->getDoctrine()->getManager('company_group');
  4052.         $em_goc->getConnection()->connect();
  4053.         $gocId 0;
  4054.         $appId 0;
  4055.         $gocEnabled 0;
  4056.         if ($this->container->hasParameter('entity_group_enabled'))
  4057.             $gocEnabled $this->container->getParameter('entity_group_enabled');
  4058.         if ($gocEnabled == 1)
  4059.             $connected $em_goc->getConnection()->isConnected();
  4060.         else
  4061.             $connected false;
  4062.         if ($connected)
  4063.             $gocList $em_goc
  4064.                 ->getRepository("CompanyGroupBundle:CompanyGroup")
  4065.                 ->findBy(
  4066.                     array(
  4067.                         'active' => 1
  4068.                     )
  4069.                 );
  4070.         $gocDataList = [];
  4071.         $gocDataListForLoginWeb = [];
  4072.         $gocDataListByAppId = [];
  4073.         foreach ($gocList as $entry) {
  4074.             $d = array(
  4075.                 'name' => $entry->getName(),
  4076.                 'id' => $entry->getId(),
  4077.                 'appId' => $entry->getAppId(),
  4078.                 'skipInWebFlag' => $entry->getSkipInWebFlag(),
  4079.                 'skipInAppFlag' => $entry->getSkipInAppFlag(),
  4080.                 'dbName' => $entry->getDbName(),
  4081.                 'dbUser' => $entry->getDbUser(),
  4082.                 'dbPass' => $entry->getDbPass(),
  4083.                 'dbHost' => $entry->getDbHost(),
  4084.                 'companyRemaining' => $entry->getCompanyRemaining(),
  4085.                 'companyAllowed' => $entry->getCompanyAllowed(),
  4086.             );
  4087.             $gocDataList[$entry->getId()] = $d;
  4088.             if (in_array($entry->getSkipInWebFlag(), [0null]))
  4089.                 $gocDataListForLoginWeb[$entry->getId()] = $d;
  4090.             $gocDataListByAppId[$entry->getAppId()] = $d;
  4091.         }
  4092.         if ($request->request->has('gocId') || $request->query->has('gocId')) {
  4093.             $hasGoc 1;
  4094.             $gocId $request->request->get('gocId');
  4095.         }
  4096.         if ($request->request->has('appId') || $request->query->has('appId')) {
  4097.             $hasGoc 1;
  4098.             $appId $request->request->get('appId');
  4099.         }
  4100.         $refRoute $request->request->get('refRoute'$request->query->get('refRoute'''));
  4101.         if ($hasGoc == 1) {
  4102.             if ($gocId != && $gocId != "") {
  4103.                 $appId $gocDataList[$gocId]['appId'];
  4104.                 $connector $this->container->get('application_connector');
  4105.                 $connector->resetConnection(
  4106.                     'default',
  4107.                     $gocDataList[$gocId]['dbName'],
  4108.                     $gocDataList[$gocId]['dbUser'],
  4109.                     $gocDataList[$gocId]['dbPass'],
  4110.                     $gocDataList[$gocId]['dbHost'],
  4111.                     $reset true
  4112.                 );
  4113.             } else if ($appId != && $appId != "") {
  4114.                 $gocDbName $gocDataListByAppId[$appId]['dbName'];
  4115.                 $gocDbUser $gocDataListByAppId[$appId]['dbUser'];
  4116.                 $gocDbPass $gocDataListByAppId[$appId]['dbPass'];
  4117.                 $gocDbHost $gocDataListByAppId[$appId]['dbHost'];
  4118.                 $gocId $gocDataListByAppId[$appId]['id'];
  4119.                 $connector $this->container->get('application_connector');
  4120.                 $connector->resetConnection(
  4121.                     'default',
  4122.                     $gocDbName,
  4123.                     $gocDbUser,
  4124.                     $gocDbPass,
  4125.                     $gocDbHost,
  4126.                     $reset true
  4127.                 );
  4128.             }
  4129.         }
  4130.         $userName $request->request->get('username'$request->query->get('username''admin'));
  4131.         $name $request->request->get('name'$request->query->get('name''System Admin'));
  4132.         $password $request->request->get('password'$request->query->get('password''admin'));
  4133.         $email $request->request->get('email'$request->query->get('email''admin'));
  4134.         $encodedPassword $this->container->get('sha256salted_encoder')->encodePassword($password$userName);
  4135.         $companyIds $request->request->get('companyIds'$request->query->get('companyIds', [1]));
  4136.         $branchIds $request->request->get('branchIds'$request->query->get('branchIds', [1]));
  4137.         $appIds $request->request->get('appIds'$request->query->get('appIds', [$appId]));
  4138.         $freshFlag $request->request->get('fresh'$request->query->get('fresh'1));
  4139.         if ($freshFlag == 1) {
  4140.             $query "DELETE FROM sys_user WHERE user_type=1";
  4141.             $stmt $em->getConnection()->prepare($query);
  4142.             $stmt->execute();
  4143.         }
  4144.         $message $this->get('user_module')->addNewUser(
  4145.             $name,
  4146.             $email,
  4147.             $userName,
  4148.             $password,
  4149.             '',
  4150.             0,
  4151.             1,
  4152.             UserConstants::USER_TYPE_SYSTEM,
  4153.             $companyIds,
  4154.             $branchIds,
  4155.             '',
  4156.             "",
  4157.             1
  4158.         );
  4159.         $companyData $message[2];
  4160.         if ($message[0] == 'success') {
  4161.             $oAuthData = [
  4162.                 'email' => $email,
  4163.                 'uniqueId' => '',
  4164.                 'image' => '',
  4165.                 'emailVerified' => '',
  4166.                 'name' => $name,
  4167.                 'type' => '0',
  4168.                 'token' => '',
  4169.             ];
  4170.             if (GeneralConstant::EMAIL_ENABLED == 1) {
  4171.                 $bodyHtml '';
  4172.                 $bodyTemplate 'ApplicationBundle:email/templates:userRegistrationCompleteHoneybee.html.twig';
  4173.                 $bodyData = array(
  4174.                     'name' => $name,
  4175.                     'email' => $email,
  4176.                     'password' => $password,
  4177.                 );
  4178.                 $attachments = [];
  4179.                 $forwardToMailAddress $email;
  4180.                 if (filter_var($forwardToMailAddressFILTER_VALIDATE_EMAIL)) {
  4181. //                    $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/temp/' . 'ledger' . '.pdf'
  4182.                     $new_mail $this->get('mail_module');
  4183.                     $new_mail->sendMyMail(array(
  4184.                         'senderHash' => '_CUSTOM_',
  4185.                         //                        'senderHash'=>'_CUSTOM_',
  4186.                         'forwardToMailAddress' => $forwardToMailAddress,
  4187.                         'subject' => 'Welcome to Honeybee Ecosystem ',
  4188. //                        'fileName' => 'Order#' . str_pad($id, 8, '0', STR_PAD_LEFT) . '.pdf',
  4189.                         'attachments' => $attachments,
  4190.                         'toAddress' => $forwardToMailAddress,
  4191.                         'fromAddress' => 'no-reply@ourhoneybee.eu',
  4192.                         'userName' => 'no-reply@ourhoneybee.eu',
  4193.                         'password' => 'Honeybee@0112',
  4194.                         'smtpServer' => 'smtp.hostinger.com',
  4195.                         'smtpPort' => 465,
  4196. //                            'emailBody' => $bodyHtml,
  4197.                         'mailTemplate' => $bodyTemplate,
  4198.                         'templateData' => $bodyData,
  4199. //                        'embedCompanyImage' => 1,
  4200. //                        'companyId' => $companyId,
  4201. //                        'companyImagePath' => $company_data->getImage()
  4202.                     ));
  4203.                 }
  4204.             }
  4205. //            if ($request->request->get('remoteVerify', 0) == 1)
  4206. ////                if(1)
  4207. //                return new JsonResponse(array(
  4208. //                    'success' => true,
  4209. //                    'successStr' => 'Account Created Successfully',
  4210. //                    'id' => $newApplicant->getApplicantId(),
  4211. //                    'oAuthData' => $oAuthData,
  4212. //                    'refRoute' => $refRoute,
  4213. //                    'remoteVerify' => 1,
  4214. //                ));
  4215. //            else
  4216. //                return $this->redirectToRoute("user_login", [
  4217. //                    'id' => $newApplicant->getApplicantId(),
  4218. //                    'oAuthData' => $oAuthData,
  4219. //                    'refRoute' => $refRoute,
  4220. //
  4221. //                ]);
  4222.             $bodyHtml '';
  4223.             $bodyTemplate 'ApplicationBundle:email/user:registration.html.twig';
  4224.             $bodyData = array(
  4225.                 'name' => $request->request->get('name'),
  4226.                 'companyData' => $companyData,
  4227.                 'userName' => $request->request->get('username'),
  4228.                 'password' => $request->request->get('password'),
  4229.             );
  4230.             $attachments = [];
  4231. //                    $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/temp/' . 'ledger' . '.pdf'
  4232.             $new_mail $this->get('mail_module');
  4233.             $new_mail->sendMyMail(array(
  4234.                 'senderHash' => '_USER_MANAGEMENT_',
  4235.                 //                        'senderHash'=>'_CUSTOM_',
  4236.                 'forwardToMailAddress' => $request->request->get('email'),
  4237.                 'subject' => 'User Registration on HoneyBee Ecosystem under Company ' $companyData->getName(),
  4238.                 'fileName' => '',
  4239.                 'attachments' => $attachments,
  4240.                 'toAddress' => $request->request->get('email'),
  4241. //                        'fromAddress'=>'sales@entity.innobd.com',
  4242. //                        'userName'=>'sales@entity.innobd.com',
  4243. //                        'password'=>'Y41dh8g0112',
  4244. //                        'smtpServer'=>'smtp.hostinger.com',
  4245. //                        'smtpPort'=>587,
  4246. //                        'emailBody'=>$bodyHtml,
  4247.                 'mailTemplate' => $bodyTemplate,
  4248.                 'templateData' => $bodyData,
  4249.                 'embedCompanyImage' => 1,
  4250.                 'companyId' => $request->request->get('company'),
  4251.                 'companyImagePath' => $companyData->getImage()
  4252.             ));
  4253. //                $emailmessage = (new \Swift_Message('Registration to Entity'))
  4254. //                    ->setFrom('registration@entity.innobd.com')
  4255. //                    ->setTo($request->request->get('email'))
  4256. //                    ->setBody(
  4257. //                        $this->renderView(
  4258. //                            'ApplicationBundle:email/user:registration.html.twig',
  4259. //                            array('name' => $request->request->get('name'),
  4260. //                                'companyData' => $companyData,
  4261. //                                'userName' => $request->request->get('email'),
  4262. //                                'password' => $request->request->get('password'),
  4263. //                            )
  4264. //                        ),
  4265. //                        'text/html'
  4266. //                    );
  4267. //                /*
  4268. //                 * If you also want to include a plaintext version of the message
  4269. //                ->addPart(
  4270. //                    $this->renderView(
  4271. //                        'Emails/registration.txt.twig',
  4272. //                        array('name' => $name)
  4273. //                    ),
  4274. //                    'text/plain'
  4275. //                )
  4276. //                */
  4277. ////            ;
  4278. //                $this->get('mailer')->send($emailmessage);
  4279.         }
  4280.         $this->addFlash(
  4281.             $message[0],
  4282.             $message[1]
  4283.         );
  4284. //        MiscActions::initiateAdminUser($em,$freshFlag,$userName,$name,$email,$encodedPassword,$appIds,$companyIds);
  4285.         $this->addFlash(
  4286.             'success',
  4287.             'The Action was Successful.'
  4288.         );
  4289.         return $this->redirectToRoute('user_login');
  4290.     }
  4291.     public function DumpCurrModulesAction(Request $request)
  4292.     {
  4293.         $em $this->getDoctrine()->getManager();
  4294.         $modules $em->getRepository("ApplicationBundle:SysModule")
  4295.             ->findBy(
  4296.                 array(//                    'active'=>1
  4297.                 )
  4298.             );
  4299.         $module_data = [];
  4300.         foreach ($modules as $entry) {
  4301.             $dt = array(
  4302.                 'id' => $entry->getModuleId(),
  4303.                 'route' => $entry->getModuleRoute(),
  4304.                 'name' => $entry->getModuleName(),
  4305.                 'parentId' => $entry->getParentId(),
  4306.                 'level' => $entry->getLevel(),
  4307.                 'eFA' => $entry->getEnabledForAll(),
  4308.             );
  4309.             $module_data[$entry->getModuleId()] = $dt;
  4310.         }
  4311.         return new JsonResponse(
  4312.             $module_data
  4313.         );
  4314.     }
  4315. }