src/ApplicationBundle/Controller/DashboardController.php line 2048

Open in your IDE?
  1. <?php
  2. namespace ApplicationBundle\Controller;
  3. use ApplicationBundle\Constants\GeneralConstant;
  4. use ApplicationBundle\Entity\DashboardWidget;
  5. use ApplicationBundle\Entity\Employee;
  6. use ApplicationBundle\Entity\EmployeeDetails;
  7. use ApplicationBundle\Entity\SysUser;
  8. use ApplicationBundle\Interfaces\SessionCheckInterface;
  9. use ApplicationBundle\Modules\Accounts\Accounts;
  10. use ApplicationBundle\Modules\Authentication\Constants\UserConstants;
  11. use ApplicationBundle\Modules\HumanResource\HumanResource;
  12. use ApplicationBundle\Modules\Inventory\Inventory;
  13. use ApplicationBundle\Modules\Purchase\Supplier;
  14. use ApplicationBundle\Modules\Sales\Client;
  15. use ApplicationBundle\Modules\System\MiscActions;
  16. use ApplicationBundle\Modules\System\System;
  17. use ApplicationBundle\Modules\User\Company;
  18. use ApplicationBundle\Modules\User\Position;
  19. use ApplicationBundle\Modules\User\Users;
  20. use CompanyGroupBundle\Entity\CompanyGroup;
  21. use CompanyGroupBundle\Entity\EntityApplicantDetails;
  22. use Symfony\Component\BrowserKit\Client as BrowserClientKit;
  23. use Symfony\Component\Debug\Exception\FlattenException;
  24. use Symfony\Component\HttpFoundation\JsonResponse;
  25. use Symfony\Component\HttpFoundation\Request;
  26. use Symfony\Component\HttpFoundation\Response;
  27. use Symfony\Component\HttpKernel\Log\DebugLoggerInterface;
  28. use Symfony\Component\Routing\Generator\UrlGenerator;
  29. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  30. class DashboardController extends GenericController implements SessionCheckInterface
  31. {
  32.     public function doLoginAsAction(Request $request)
  33.     {
  34.         $session $request->getSession();
  35.         if ($request->isMethod('POST')) {
  36.             $session->set(UserConstants::USER_CURRENT_POSITION$request->request->get('position'));
  37.             $curr_position_id $request->request->get('position');
  38.             if ($session->get(UserConstants::USER_LOGIN_ID) != 0) {
  39.                 $loginID $this->get('user_module')->addUserLoginLog(
  40.                     $session->get(UserConstants::USER_ID),
  41.                     $request->server->get("REMOTE_ADDR"),
  42.                     $request->request->get('position'),
  43.                     '',
  44.                     '',
  45.                     '',
  46.                     $session->get(UserConstants::USER_LOGIN_ID)
  47.                 );
  48.             } else $loginID $this->get('user_module')->addUserLoginLog(
  49.                 $session->get(UserConstants::USER_ID),
  50.                 $request->server->get("REMOTE_ADDR"),
  51.                 $request->request->get('position'),
  52.                 '',
  53.                 '',
  54.                 '',
  55.                 0
  56.             );
  57.             if ($session->get(UserConstants::ALL_MODULE_ACCESS_FLAG) == 1)
  58.                 $prohibit_list_array = [];
  59.             else if ($curr_position_id != 0)
  60.                 $prohibit_list_array Position::getUserProhibitRouteArray($this->getDoctrine()->getManager(), $curr_position_id$session->get(UserConstants::USER_ID));
  61.             $session->set(UserConstants::USER_LOGIN_ID$loginID);
  62.             $session->set(UserConstants::USER_PROHIBIT_LISTjson_encode($prohibit_list_array));
  63.             $session->set(UserConstants::USER_ROUTE_LISTjson_encode(Position::getUserRouteArray($this->getDoctrine()->getManager(), $request->request->get('position'), $session->get(UserConstants::USER_ID))));
  64.             return $this->redirectToRoute("dashboard");
  65.         }
  66.         $message "";
  67.         $PositionList = array();
  68.         $PL json_decode($session->get(UserConstants::USER_POSITION_LIST), true);
  69.         foreach ($PL as &$positionID) {
  70.             $PositionList[$positionID] = Position::getPositionName($this->getDoctrine()->getManager(), $positionID);
  71.         }
  72.         return $this->render(
  73.             '@Authentication/pages/views/login_position.html.twig',
  74.             array(
  75.                 "message" => $message,
  76.                 'page_title' => 'Users',
  77.                 'position_list' => $PositionList
  78.             )
  79.         );
  80.     }
  81.     //    protected $twig;
  82.     //    protected $debug;
  83.     //
  84.     //    /**
  85.     //     * @param bool $debug Show error (false) or exception (true) pages by default
  86.     //     */
  87.     //    public function __construct(Environment $twig, $debug)
  88.     //    {
  89.     //        $this->twig = $twig;
  90.     //        $this->debug = $debug;
  91.     //    }
  92.     public function TestSmsAction(Request $request)
  93.     {
  94.         $em $this->getDoctrine()->getManager();
  95.         $session $request->getSession();
  96.         $em $this->getDoctrine()->getManager();
  97.         $userAppId $session->get('userAppId');
  98.         $companyId $session->get('userCompanyId');
  99.         if (GeneralConstant::SMS_ENABLED == 1) {
  100.             $company $em->getRepository('ApplicationBundle:Company')->findOneBy(
  101.                 array(
  102.                     'id' => $companyId///material
  103.                 )
  104.             );
  105.             if ($company->getSmsNotificationEnabled() == 1) {
  106.                 $smsData = [];
  107.                 $smsSettings json_decode($company->getSmsSettings(), true);
  108.                 if ($smsSettings != null && !empty($smsSettings)) {
  109.                     $method = isset($smsSettings['method']) ? $smsSettings['method'] : 'GET';
  110.                     $destination_url = isset($smsSettings['destination_url']) ? $smsSettings['destination_url'] : 'http://172.105.70.96:1234';
  111.                     $user_name = isset($smsSettings['user_name']) ? $smsSettings['user_name'] : 'test';
  112.                     $user_name_var = isset($smsSettings['user_name_var']) ? $smsSettings['user_name_var'] : 'Username';
  113.                     $password_var = isset($smsSettings['password_var']) ? $smsSettings['password_var'] : 'Password';
  114.                     $password = isset($smsSettings['password']) ? $smsSettings['password'] : '';
  115.                     $from_number_var = isset($smsSettings['from_number_var']) ? $smsSettings['from_number_var'] : 'From';
  116.                     $from_number = isset($smsSettings['from_number']) ? $smsSettings['from_number'] : '';
  117.                     $to_number_var = isset($smsSettings['to_number_var']) ? $smsSettings['to_number_var'] : 'To';
  118.                     $to_number $request->query->has('To') ? $request->query->get('To') : '01911706483';
  119.                     $text_var = isset($smsSettings['text_var']) ? $smsSettings['text_var'] : 'Message';
  120.                     $text $request->query->has('Message') ? $request->query->get('Message') : 'Test message';
  121.                     return new JsonResponse(System::sendSms(
  122.                         1,
  123.                         $method,
  124.                         $destination_url,
  125.                         $user_name_var,
  126.                         $user_name,
  127.                         $password_var,
  128.                         $password,
  129.                         $from_number_var,
  130.                         $from_number,
  131.                         $to_number_var,
  132.                         $to_number,
  133.                         $text_var,
  134.                         $text,
  135.                         $viewlink ""
  136.                     ));
  137.                 }
  138.             }
  139.             return new JsonResponse(
  140.                 [
  141.                     'companyId' => $companyId,
  142.                     'companyName' => $company->getName(),
  143.                     'enabled' => $company->getSmsNotificationEnabled(),
  144.                     //                    'smsSettings'=>$smsSettings
  145.                 ]
  146.             );
  147.         }
  148.         return new JsonResponse(
  149.             [
  150.                 'success' => false
  151.             ]
  152.         );
  153.     }
  154.     public function SyncCompanyProductToEntityProductAction(Request $request)
  155.     {
  156.         $gocId $request->query->has('gocId') ? $request->query->get('gocId') : 0;
  157.         $companyId $request->query->has('companyId') ? $request->query->get('companyId') : 1;
  158.         $genQueryArray = [];
  159.         $em_goc $this->getDoctrine()->getManager('company_group');
  160.         $em_goc->getConnection()->connect();
  161.         $em $this->getDoctrine()->getManager();
  162.         if ($request->query->has('forceRefresh')) {
  163.             $genQueryArray = [];
  164.             $query "
  165.             TRUNCATE `entity_brand_company`;
  166.             TRUNCATE `entity_item_group`;
  167.             TRUNCATE `entity_products`;
  168.             TRUNCATE `entity_product_categories`;
  169.             TRUNCATE `entity_product_specifications`;
  170.             TRUNCATE `entity_product_sub_categories`;
  171.             TRUNCATE `entity_specification_types`;
  172.             TRUNCATE `entity_unit_type`;
  173.             SELECT * from `entity_unit_type`;";
  174.             $stmt $em_goc->getConnection()->prepare($query);
  175.             $stmt->execute();
  176.             //            $Transactions = $stmt->fetchAll();
  177.             $get_kids_sql 'select * from acc_accounts_head where accounts_head_id not in (select distinct parent_id from acc_accounts_head) ;';
  178.             //UPDATE company SET sales=0, expense=0, payable=0 ,net_worth=0, monthly_growth=0 WHERE 1;';
  179.             $stmt $em->getConnection()->prepare($get_kids_sql);
  180.             $stmt->execute();
  181.             $query $stmt->fetchAll();
  182.         } else
  183.             $genQueryArray = ['globalId' => [0null]];
  184.         //1st step get all company item ids and then check for global id null if its null then the
  185.         // item group is not present in entity so add it
  186.         $company_wise_entities = [
  187.             'Currencies',
  188.             'UnitType',
  189.             'SpecType',
  190.             'BrandCompany',
  191.             'InvItemGroup',
  192.             'InvProductCategories',
  193.             'InvProductSubCategories',
  194.             'InvProductSpecifications',
  195.             'InvSpecificationTypes',
  196.             'InvProducts'
  197.         ];
  198.         $entity_wise_entities = [
  199.             'EntityCurrencies',
  200.             'EntityUnitType',
  201.             'EntitySpecType',
  202.             'EntityBrandCompany',
  203.             'EntityItemGroup',
  204.             'EntityProductCategories',
  205.             'EntityProductSubCategories',
  206.             'EntityProductSpecifications',
  207.             'EntitySpecificationTypes',
  208.             'EntityProducts'
  209.         ];
  210.         ////ITEMGROUPS
  211.         foreach ($company_wise_entities as $k => $cwa) {
  212.             $dataOnCompany $em
  213.                 ->getRepository("ApplicationBundle:" $cwa)
  214.                 ->findBy(
  215.                     $genQueryArray
  216.                 );
  217.             $match_cid_gid_itemgroup = [];  //[cid=>gid]
  218.             $match_cid_gid_itemgroup = [];  //[cid=>gid]
  219.             foreach ($dataOnCompany as $data) {
  220.                 $newClass "\\CompanyGroupBundle\\Entity\\" $entity_wise_entities[$k];
  221.                 $new = new $newClass();
  222.                 //                $new = new \CompanyGroupBundle\Entity\EntityItemGroup();
  223.                 $getters array_filter(get_class_methods($data), function ($method) {
  224.                     return 'get' === substr($method03);
  225.                 });
  226.                 foreach ($getters as $getter) {
  227.                     if ($getter == 'getGlobalId')
  228.                         continue;
  229.                     //                    if ($getter == 'getId')
  230.                     //                        continue;
  231.                     $setMethod str_replace('get''set'$getter);
  232.                     if (method_exists($new$setMethod))
  233.                         $new->{$setMethod}($data->{$getter}()); // `foo!`
  234.                 }
  235.                 $em_goc->persist($new);
  236.                 $em_goc->flush();
  237.                 if ($cwa == 'Currencies') {
  238.                     $data->setGlobalId($new->getCurrencyId());
  239.                     $new->setGlobalId($new->getCurrencyId());
  240.                 } else {
  241.                     $data->setGlobalId($new->getId());
  242.                     $new->setGlobalId($new->getId());
  243.                 }
  244.                 $em->flush();
  245.                 $em_goc->flush();
  246.                 //                $match_cid_gid_itemgroup[$data->getId()] = $new->getId();
  247.             }
  248.         }
  249.         return new JsonResponse(
  250.             array(
  251.                 'data' => $entity_wise_entities
  252.             )
  253.         );
  254.     }
  255.     public function SyncEntityProductToCompanyProductAction(Request $request)
  256.     {
  257.         $gocId $request->query->has('gocId') ? $request->query->get('gocId') : 0;
  258.         $companyId $request->query->has('companyId') ? $request->query->get('companyId') : 1;
  259.         $genQueryArray = [];
  260.         $em_goc $this->getDoctrine()->getManager('company_group');
  261.         $em_goc->getConnection()->connect();
  262.         $em $this->getDoctrine()->getManager();
  263.         if ($request->query->has('forceRefresh')) {
  264.             $genQueryArray = [];
  265.             $query "
  266.             TRUNCATE `brand_company`;
  267.             TRUNCATE `inv_item_group`;
  268.             TRUNCATE `inv_products`;
  269.             TRUNCATE `inv_product_categories`;
  270.             TRUNCATE `inv_product_specifications`;
  271.             TRUNCATE `inv_product_sub_categories`;
  272.             TRUNCATE `inv_specification_types`;
  273.             TRUNCATE `unit_type`;
  274.             SELECT * from `unit_type`;";
  275.             $stmt $em->getConnection()->prepare($query);
  276.             $stmt->execute();
  277.             //            $Transactions = $stmt->fetchAll();
  278.             $get_kids_sql 'select * from acc_accounts_head where accounts_head_id not in (select distinct parent_id from acc_accounts_head) ;';
  279.             //UPDATE company SET sales=0, expense=0, payable=0 ,net_worth=0, monthly_growth=0 WHERE 1;';
  280.             $stmt $em->getConnection()->prepare($get_kids_sql);
  281.             $stmt->execute();
  282.             $query $stmt->fetchAll();
  283.         } else {
  284.             //            $genQueryArray = ['globalId' => [0, null]];
  285.         }
  286.         //1st step get all company item ids and then check for global id null if its null then the
  287.         // item group is not present in entity so add it
  288.         $company_wise_entities = [
  289.             'Currencies',
  290.             'UnitType',
  291.             'SpecType',
  292.             'BrandCompany',
  293.             'InvItemGroup',
  294.             'InvProductCategories',
  295.             'InvProductSubCategories',
  296.             'InvProductSpecifications',
  297.             'InvSpecificationTypes',
  298.             'InvProducts'
  299.         ];
  300.         $entity_wise_entities = [
  301.             'EntityCurrencies',
  302.             'EntityUnitType',
  303.             'EntitySpecType',
  304.             'EntityBrandCompany',
  305.             'EntityItemGroup',
  306.             'EntityProductCategories',
  307.             'EntityProductSubCategories',
  308.             'EntityProductSpecifications',
  309.             'EntitySpecificationTypes',
  310.             'EntityProducts'
  311.         ];
  312.         foreach ($entity_wise_entities as $k => $ewa) {
  313.             $dataOnEntity $em_goc
  314.                 ->getRepository("CompanyGroupBundle:" $ewa)
  315.                 ->findBy(
  316.                     $genQueryArray
  317.                 );
  318.             $match_cid_gid_itemgroup = [];  //[cid=>gid]
  319.             $match_cid_gid_itemgroup = [];  //[cid=>gid]
  320.             foreach ($dataOnEntity as $data) {
  321.                 $newClass "\\ApplicationBundle\\Entity\\" $company_wise_entities[$k];
  322.                 $rec_exists 0;
  323.                 $new $em
  324.                     ->getRepository("ApplicationBundle:" $company_wise_entities[$k])
  325.                     ->findOneBy(
  326.                         array(
  327.                             'globalId' => $data->getGlobalId()
  328.                         )
  329.                     );
  330.                 if ($new) {
  331.                     $rec_exists 1;
  332.                 } else
  333.                     $new = new $newClass();
  334.                 //                $new = new \CompanyGroupBundle\Entity\EntityItemGroup();
  335.                 $getters array_filter(get_class_methods($data), function ($method) {
  336.                     return 'get' === substr($method03);
  337.                 });
  338.                 foreach ($getters as $getter) {
  339.                     if ($getter == 'getId')
  340.                         continue;
  341.                     $setMethod str_replace('get''set'$getter);
  342.                     if (method_exists($new$setMethod)) {
  343.                         if ($ewa == 'EntityProducts') {
  344.                             if ($rec_exists == 1) {
  345.                                 if (in_array($setMethod, [
  346.                                     'setPurchasePrice',
  347.                                     'setPurchasePriceWoExpense',
  348.                                     'setQty',
  349.                                     'setReorderLevel',
  350.                                     'setBookingQty',
  351.                                     'setNonSalesInvoicedQty',
  352.                                     'setNonSalesReturnReceivedQty',
  353.                                     'setBookingQty',
  354.                                     'setPhysicalQty',
  355.                                 ])) {
  356.                                     continue;
  357.                                 }
  358.                             }
  359.                         }
  360.                         $new->{$setMethod}($data->{$getter}()); // `foo!`
  361.                     }
  362.                 }
  363.                 if ($rec_exists == 0)
  364.                     $em->persist($new);
  365.                 $em->flush();
  366.                 if ($ewa == 'EntityCurrencies') {
  367.                     $new->setGlobalId($data->getCurrencyId());
  368.                 } else {
  369.                     $new->setGlobalId($data->getId());
  370.                 }
  371.                 $em->flush();
  372.                 //                $match_cid_gid_itemgroup[$data->getId()] = $new->getId();
  373.             }
  374.         }
  375.         return new JsonResponse(
  376.             array(
  377.                 'data' => $company_wise_entities
  378.             )
  379.         );
  380.     }
  381.     public function getAppGeneralDashboardDataAction(Request $request)
  382.     {
  383.         $dataFor 'client';
  384.         $personId 0;
  385.         if ($request->query->has('dataFor'))
  386.             $dataFor $request->query->get('dataFor');
  387.         if ($request->request->has('dataFor'))
  388.             $dataFor $request->request->get('dataFor');
  389.         if ($request->query->has('personId'))
  390.             $personId $request->query->get('personId');
  391.         if ($request->request->has('personId'))
  392.             $personId $request->request->get('personId');
  393.         if ($personId == 0)
  394.             return new JsonResponse(
  395.                 array(
  396.                     'success' => false,
  397.                     'data' => [],
  398.                 )
  399.             );
  400.         $session $request->getSession();
  401.         $em $this->getDoctrine()->getManager();
  402.         $userAppId $session->get('userAppId');
  403.         $companyId $session->get('userCompanyId');
  404.         $dataToConnectList = [];
  405.         $appIdList $session->get('appIdList');
  406.         $companyIdListByAppId $session->get('companyIdListByAppId');
  407.         $companyNameListByAppId $session->get('companyNameListByAppId');
  408.         $companyImageListByAppId $session->get('companyImageListByAppId');
  409.         $gocEnabled 0;
  410.         if ($this->container->hasParameter('entity_group_enabled'))
  411.             $gocEnabled $this->container->getParameter('entity_group_enabled');
  412.         $connector $this->container->get('application_connector');
  413.         $connector->resetConnection(
  414.             'default',
  415.             $session->get('gocDbName'),
  416.             $session->get('gocDbUser'),
  417.             $session->get('gocDbPass'),
  418.             $session->get('gocDbHost'),
  419.             $reset true
  420.         );
  421.         $em $this->getDoctrine()->getManager();
  422.         $data = [];
  423.         if ($dataFor == 'client') {
  424.             //get order_count, order_amount,bill_count, bill_amount, collection_amount, due_amount
  425.             $data = [
  426.                 'order_count' => 0,
  427.                 'order_amount' => 0,
  428.                 'invoice_count' => 0,
  429.                 'invoice_amount' => 0,
  430.                 'collection_amount' => 0,
  431.                 'due_amount' => 0,
  432.                 'client_count' => 1,
  433.             ];
  434.             $clientIds = [$personId];
  435.             //order count and amount
  436.             $get_sql "SELECT count(sales_order_id) order_count, sum(so_amount) order_amount
  437. FROM sales_order WHERE approved=1 and sales_order.company_id=" $companyId "  and sales_order.client_id in (" implode(','$clientIds) . ");";
  438.             $stmt $em->getConnection()->prepare($get_sql);
  439.             $stmt->execute();
  440.             $entries $stmt->fetchAll();
  441.             if (!empty($entries)) {
  442.                 $data['order_count'] = $entries[0]['order_count'];
  443.                 $data['order_amount'] = $entries[0]['order_amount'];
  444.             }
  445.             //invoice
  446.             $get_sql "SELECT count(sales_invoice_id) invoice_count, sum(invoice_amount) invoice_amount
  447. FROM sales_invoice WHERE approved=1 and sales_invoice.company_id=" $companyId "  and sales_invoice.client_id in (" implode(','$clientIds) . ");";
  448.             $stmt $em->getConnection()->prepare($get_sql);
  449.             $stmt->execute();
  450.             $entries $stmt->fetchAll();
  451.             if (!empty($entries)) {
  452.                 $data['invoice_count'] = $entries[0]['invoice_count'];
  453.                 $data['invoice_amount'] = $entries[0]['invoice_amount'];
  454.             }
  455.             //now collection
  456.             $get_sql "SELECT SUM(CASE WHEN position = 'cr' THEN amount ELSE 0 END) positive_amount,
  457. SUM(CASE WHEN position = 'dr' THEN amount ELSE 0 END) negative_amount,client_type.client_type_id, client_type.name, acc_clients.client_id, acc_clients.type, acc_clients.client_due, acc_clients.client_id
  458.  FROM acc_transaction_details
  459.    join acc_clients on acc_clients.accounts_head_id=acc_transaction_details.accounts_head_id or acc_clients.advance_head_id=acc_transaction_details.accounts_head_id
  460.   join client_type on acc_clients.type=client_type.client_type_id
  461.   WHERE acc_transaction_details.ledger_hit=1 AND acc_transaction_details.transaction_id in (select distinct transaction_id from acc_transactions where acc_transactions.document_type=6) and acc_clients.client_id in (" implode(','$clientIds) . ") ";
  462.             $stmt $em->getConnection()->prepare($get_sql);
  463.             $stmt->execute();
  464.             $entries $stmt->fetchAll();
  465.             $clientTypes = [];
  466.             $clientTypeNames = [];
  467.             $alreadyCids = [];
  468.             foreach ($entries as $entry) {
  469.                 $data['collection_amount'] += (* ($entry['positive_amount'] - $entry['negative_amount']));
  470.                 if (!in_array($entry['client_id'], $alreadyCids)) {
  471.                     $data['due_amount'] += ($entry['client_due']);
  472.                     $alreadyCids[] = $entry['client_id'];
  473.                 }
  474.             }
  475.         }
  476.         if ($dataFor == 'sales_user') {
  477.             //get order_count, order_amount,bill_count, bill_amount, collection_amount, due_amount
  478.             $data = [
  479.                 'order_count' => 0,
  480.                 'order_amount' => 0,
  481.                 'invoice_count' => 0,
  482.                 'invoice_amount' => 0,
  483.                 'collection_amount' => 0,
  484.                 'due_amount' => 0,
  485.                 'client_count' => 0,
  486.             ];
  487.             $clientIds = [];
  488.             $salesPersonIds = [];
  489.             $allSalespersonFlag 1//temp
  490.             if ($allSalespersonFlag != 1) {
  491.                 $query $em->getRepository('ApplicationBundle:Employee')->findOneBy(
  492.                     array(
  493.                         'userId' => $personId
  494.                     )
  495.                 );
  496.                 if ($query)
  497.                     $salesPersonIds[] = $query->getEmployeeId();
  498.             }
  499.             //Client count
  500.             $get_sql "SELECT  client_id
  501. FROM acc_clients WHERE  acc_clients.company_id=" $companyId " ";
  502.             if ($allSalespersonFlag != 1)
  503.                 $get_sql .= " and acc_clients.sales_person_id in (" implode(','$salesPersonIds) . ");";
  504.             else
  505.                 $get_sql .= " ;";
  506.             $stmt $em->getConnection()->prepare($get_sql);
  507.             $stmt->execute();
  508.             $entries $stmt->fetchAll();
  509.             if (!empty($entries)) {
  510.                 foreach ($entries as $entry) {
  511.                     $data['client_count'] += 1;
  512.                     $clientIds[] = $entry['client_id'];
  513.                 }
  514.             }
  515.             //order count and amount
  516.             if (!empty($clientIds)) {
  517.                 $get_sql "SELECT count(sales_order_id) order_count, sum(so_amount) order_amount
  518. FROM sales_order WHERE approved=1 and sales_order.company_id=" $companyId "  and sales_order.client_id in (" implode(','$clientIds) . ");";
  519.                 $stmt $em->getConnection()->prepare($get_sql);
  520.                 $stmt->execute();
  521.                 $entries $stmt->fetchAll();
  522.                 if (!empty($entries)) {
  523.                     $data['order_count'] = $entries[0]['order_count'];
  524.                     $data['order_amount'] = $entries[0]['order_amount'];
  525.                 }
  526.                 //invoice
  527.                 $get_sql "SELECT count(sales_invoice_id) invoice_count, sum(invoice_amount) invoice_amount
  528. FROM sales_invoice WHERE approved=1 and sales_invoice.company_id=" $companyId "  and sales_invoice.client_id in (" implode(','$clientIds) . ");";
  529.                 $stmt $em->getConnection()->prepare($get_sql);
  530.                 $stmt->execute();
  531.                 $entries $stmt->fetchAll();
  532.                 if (!empty($entries)) {
  533.                     $data['invoice_count'] = $entries[0]['invoice_count'];
  534.                     $data['invoice_amount'] = $entries[0]['invoice_amount'];
  535.                 }
  536.                 //now collection
  537.                 $get_sql "SELECT SUM(CASE WHEN position = 'cr' THEN amount ELSE 0 END) positive_amount,
  538. SUM(CASE WHEN position = 'dr' THEN amount ELSE 0 END) negative_amount,client_type.client_type_id, client_type.name, acc_clients.client_id, acc_clients.type, acc_clients.client_due, acc_clients.client_id
  539.  FROM acc_transaction_details
  540.    join acc_clients on acc_clients.accounts_head_id=acc_transaction_details.accounts_head_id or acc_clients.advance_head_id=acc_transaction_details.accounts_head_id
  541.   join client_type on acc_clients.type=client_type.client_type_id
  542.   WHERE acc_transaction_details.ledger_hit=1 AND acc_transaction_details.transaction_id in (select distinct transaction_id from acc_transactions where acc_transactions.document_type=6) and acc_clients.client_id in (" implode(','$clientIds) . ") ";
  543.                 $stmt $em->getConnection()->prepare($get_sql);
  544.                 $stmt->execute();
  545.                 $entries $stmt->fetchAll();
  546.                 $clientTypes = [];
  547.                 $clientTypeNames = [];
  548.                 $alreadyCids = [];
  549.                 foreach ($entries as $entry) {
  550.                     $data['collection_amount'] += (* ($entry['positive_amount'] - $entry['negative_amount']));
  551.                     if (!in_array($entry['client_id'], $alreadyCids)) {
  552.                         $data['due_amount'] += ($entry['client_due']);
  553.                         $alreadyCids[] = $entry['client_id'];
  554.                     }
  555.                 }
  556.             }
  557.         }
  558.         if ($dataFor == 'user') {
  559.             //get order_count, payment_amount,
  560.         }
  561.         return new JsonResponse(
  562.             array(
  563.                 'success' => true,
  564.                 'data' => $data,
  565.                 'dataFor' => $dataFor,
  566.                 'personId' => $personId,
  567.             )
  568.         );
  569.     }
  570.     public function getManagementDashboardDataAction(Request $request)
  571.     {
  572.         $session $request->getSession();
  573.         $data = array(
  574.             'cash_and_bank_position' => [],
  575.             'order_and_client_count' => [],
  576.             'expense_vs_revenue' => [],
  577.             'receivable_position' => [],
  578.             'payable_position' => [],
  579.             'expense_position' => [],
  580.             'inventory_position' => [],
  581.             'production_position' => [],
  582.             'sales_position' => [],
  583.             'collection_position' => [],
  584.             'market_return_position' => [],
  585.             'top_selling_item_position' => [],
  586.             'top_selling_client_position' => [],
  587.         );
  588.         $em $this->getDoctrine()->getManager();
  589.         $reportsToGet = [
  590.             'cash_and_bank_position',
  591.             'order_and_client_count',
  592.             'expense_vs_revenue',
  593.             'receivable_position',
  594.             'payable_position',
  595.             'expense_position',
  596.             'inventory_position',
  597.             'production_position',
  598.             'sales_position',
  599.             'collection_position',
  600.             'market_return_position',
  601.             'top_selling_item_position',
  602.             'top_selling_client_position',
  603.         ];
  604.         //        $periodType='day'; //day,month,week,year,quarter etc
  605.         $periodType 'month'//day,month,week,year,quarter etc
  606.         if ($request->request->has('reportsToGet')) {
  607.             if ($request->request->get('reportsToGet') != 'all' && !in_array('all'$request->request->get('reportsToGet'))) {
  608.                 $reportsToGet $request->request->get('reportsToGet');
  609.             }
  610.         }
  611.         if ($request->request->has('periodType')) {
  612.             $periodType $request->request->get('periodType');
  613.         }
  614.         $userAppId $session->get('userAppId');
  615.         $dataToConnectList = [];
  616.         $appIdList $session->get('appIdList');
  617.         $companyIdListByAppId $session->get('companyIdListByAppId');
  618.         $companyNameListByAppId $session->get('companyNameListByAppId');
  619.         $companyImageListByAppId $session->get('companyImageListByAppId');
  620.         $gocEnabled 0;
  621.         if ($this->container->hasParameter('entity_group_enabled'))
  622.             $gocEnabled $this->container->getParameter('entity_group_enabled');
  623.         $thisPeriodStartDate '';
  624.         $lastPeriodStartDate '';
  625.         $thisPeriodEndDate '';
  626.         $lastPeriodEndDate '';
  627.         $today = new \DateTime();
  628.         if ($periodType == 'month') {
  629.             $thisPeriodEndDate $today->format('Y-m-d');
  630.             $thisPeriodStartDate $today->format('Y-m-') . '01';
  631.             $currDate = new \DateTime($thisPeriodStartDate);
  632.             $currDate->modify('-1 day');
  633.             $lastPeriodEndDate $currDate->format('Y-m-d');
  634.             $lastPeriodStartDate $currDate->format('Y-m-') . '01';
  635.         } else if ($periodType == 'week') {
  636.             $thisPeriodEndDate $today->format('Y-m-d');
  637.             $thisWeekStartDate date("Y-m-d"strtotime("previous saturday"));
  638.             $thisPeriodStartDate date("Y-m-d"strtotime("previous saturday"));
  639.             $currDate = new \DateTime($thisPeriodStartDate);
  640.             $currDate->modify('-1 day');
  641.             $lastPeriodEndDate $currDate->format('Y-m-d');
  642.             $currDate->modify('-6 day');
  643.             $lastPeriodStartDate $currDate->format('Y-m-d');
  644.         } else if ($periodType == 'quarter') {
  645.             $thisPeriodEndDate $today->format('Y-m-d');
  646.             $thisWeekStartDate date("Y-m-d"strtotime("previous saturday"));
  647.             $thisPeriodStartDate date("Y-m-d"strtotime("previous saturday"));
  648.             $currDate = new \DateTime($thisPeriodStartDate);
  649.             $currDate->modify('-1 day');
  650.             $lastPeriodEndDate $currDate->format('Y-m-d');
  651.             $currDate->modify('-6 day');
  652.             $lastPeriodStartDate $currDate->format('Y-m-d');
  653.         } else if ($periodType == 'year') {
  654.             $thisPeriodEndDate $today->format('Y-m-d');
  655.             //            $thisWeekStartDate = date("Y-m-d", strtotime("previous saturday"));
  656.             $thisPeriodStartDate = ($today->format('Y')) . '-01-01';
  657.             $currDate = new \DateTime($thisPeriodStartDate);
  658.             $currDate->modify('-1 day');
  659.             $lastPeriodEndDate $currDate->format('Y-m-d');
  660.             $lastPeriodStartDate = ($currDate->format('Y')) . '-01-01';;
  661.         }
  662.         $companyListData = [];
  663.         foreach ($appIdList as $appId) {
  664.             //queryonly if mor ethan one app id
  665.             $skip 0;
  666.             if ($appId == $userAppId) {
  667.                 $connector $this->container->get('application_connector');
  668.                 $connector->resetConnection(
  669.                     'default',
  670.                     $session->get('gocDbName'),
  671.                     $session->get('gocDbUser'),
  672.                     $session->get('gocDbPass'),
  673.                     $session->get('gocDbHost'),
  674.                     $reset true
  675.                 );
  676.                 $em $this->getDoctrine()->getManager();
  677.             } else {
  678.                 $dataToConnect System::changeDoctrineManagerByAppId($this->getDoctrine()->getManager('company_group'), $gocEnabled$appId);
  679.                 $dataToConnectList[] = $dataToConnect;
  680.                 if (!empty($dataToConnect)) {
  681.                     $connector $this->container->get('application_connector');
  682.                     $connector->resetConnection(
  683.                         'default',
  684.                         $dataToConnect['dbName'],
  685.                         $dataToConnect['dbUser'],
  686.                         $dataToConnect['dbPass'],
  687.                         $dataToConnect['dbHost'],
  688.                         $reset true
  689.                     );
  690.                     $em $this->getDoctrine()->getManager();
  691.                 } else {
  692.                     $skip 1;
  693.                 }
  694.             }
  695.             if ($skip == 1)
  696.                 continue;
  697.             //                $companyListData[] = Company::getCompanyListWithImage($em);
  698.             //                $get_sql = "SELECT * FROM company ";
  699.             //                $stmt = $em->getConnection()->prepare($get_sql);
  700.             //                $stmt->execute();
  701.             //                $entries = $stmt->fetchAll();
  702.             //                $companyListData[] = $entries;
  703.             //                foreach ($companyIdListByAppId as $app_company_index)
  704.             if (isset($companyIdListByAppId[$appId])) {
  705.                 foreach ($companyIdListByAppId[$appId] as $app_company_index) {
  706.                     //exp vs rev
  707.                     if (in_array('expense_vs_revenue'$reportsToGet)) {
  708.                         $acHeadList = [];
  709.                         $companyId explode('_'$app_company_index)[1];
  710.                         $acHeadDataById = [];
  711.                         $thisBalanceDataByAcHead = [];
  712.                         $lastBalanceDataByAcHead = [];
  713.                         $mon_names = ["""January""February""March""April""May""June""July""August""September""October""November""December"];
  714.                         $limit 12;
  715.                         $get_kids_sql "SELECT expense, revenue, `date` summ_date
  716.                           FROM monthly_summary
  717.                             where monthly_summary.company_id=$companyId
  718.                             AND ( monthly_summary.branch_id=0 or monthly_summary.branch_id is null) ";
  719.                         //                               GROUP BY monthly_summary.`date`
  720.                         $get_kids_sql .= " ORDER BY monthly_summary.`date` DESC  limit " $limit;
  721.                         $stmt $em->getConnection()->prepare($get_kids_sql);
  722.                         $stmt->execute();
  723.                         $pl $stmt->fetchAll();
  724.                         $curr_date = new \DateTime();
  725.                         $curr_mon = ($curr_date->format('m'));
  726.                         $curr_year = ($curr_date->format('Y'));
  727.                         $object_list = [];
  728.                         $debug_list = [];
  729.                         $list = [];
  730.                         $timeStampList = [];
  731.                         //        $first
  732.                         foreach ($pl as $key => $entry) {
  733.                             $qryDate = new \DateTime($entry['summ_date']);
  734.                             $qrMon $qryDate->format('m');;
  735.                             $qrYr $qryDate->format('Y');;
  736.                             $object_list[$qrYr '_' $qrMon] = $entry;
  737.                         }
  738.                         for ($k 0$k 11$k++) {
  739.                             $debug_list[$k] = $curr_year '_' $curr_mon;
  740.                             $currTimeStamp strtotime($curr_year "-" $curr_mon '-1');
  741.                             $currTimeStampMili $currTimeStamp 1000;
  742.                             $cashAddition 0;
  743.                             $bankAddition 0;
  744.                             if (isset($object_list[$curr_year '_' $curr_mon])) {
  745.                                 $entry $object_list[$curr_year '_' $curr_mon];
  746.                                 $list['monthList'][] = $mon_names[$curr_mon];
  747.                                 $list['revenue'][] = round($entry['revenue']);
  748.                                 $list['tsCommaRevenue'][] = [$currTimeStampMiliround($entry['revenue'])];
  749.                                 $list['expense'][] = round($entry['expense']);
  750.                                 $list['tsCommaExpense'][] = [$currTimeStampMiliround($entry['expense'])];
  751.                             } else {
  752.                                 $list['monthList'][] = $mon_names[($curr_mon)];
  753.                                 $list['revenue'][] = 0;
  754.                                 $list['expense'][] = 0;
  755.                                 $list['tsCommaRevenue'][] = [$currTimeStampMili0];
  756.                                 $list['tsCommaExpense'][] = [$currTimeStampMili0];
  757.                             }
  758.                             $curr_mon--;
  759.                             if ($curr_mon <= 0) {
  760.                                 $curr_mon 12;
  761.                                 $curr_year--;
  762.                             }
  763.                             //new end
  764.                         }
  765.                         $data['expense_vs_revenue'][$app_company_index] = $list;
  766.                     }
  767.                     //cash and bank position
  768.                     if (in_array('cash_and_bank_position'$reportsToGet)) {
  769.                         $acHeadList = [];
  770.                         $companyId explode('_'$app_company_index)[1];
  771.                         $acHeadDataById = [];
  772.                         $thisBalanceDataByAcHead = [];
  773.                         $lastBalanceDataByAcHead = [];
  774.                         $bank_settings $em->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
  775.                             'name' => 'bank_parents',
  776.                             //                        'CompanyId'=>$companyId
  777.                         ));
  778.                         $bank_id_list = [];
  779.                         if ($bank_settings)
  780.                             $bank_id_list json_decode($bank_settings->getData());
  781.                         $bank_child_id_list = [];
  782.                         $likeQuery '';
  783.                         foreach ($bank_id_list as $p) {
  784.                             $likeQuery .= "OR path_tree like '%/" $p "%/' ";
  785.                         }
  786.                         $get_sql "SELECT * FROM acc_accounts_head WHERE acc_accounts_head.company_id=" $companyId " AND  accounts_head_id not in (select distinct parent_id from acc_accounts_head)and (1=0 " $likeQuery ") ";
  787.                         $stmt $em->getConnection()->prepare($get_sql);
  788.                         $stmt->execute();
  789.                         $entries $stmt->fetchAll();
  790.                         foreach ($entries as $entry) {
  791.                             $has_payments 1;
  792.                             $bank_child_id_list[] = $entry['accounts_head_id'];
  793.                             $acHeadList[] = $entry['accounts_head_id'];
  794.                             $acHeadDataById[$entry['accounts_head_id']]['name'] = $entry['name'];
  795.                         }
  796.                         $cash_settings $em->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
  797.                             'name' => 'cash_parents'
  798.                             //                        'CompanyId'=>$companyId
  799.                         ));
  800.                         $cash_id_list = [];
  801.                         if ($cash_settings)
  802.                             $cash_id_list json_decode($cash_settings->getData());
  803.                         $cash_child_id_list = [];
  804.                         $likeQuery '';
  805.                         foreach ($cash_id_list as $p) {
  806.                             $likeQuery .= "OR path_tree like '%/" $p "%/' ";
  807.                         }
  808.                         $get_sql "SELECT * FROM acc_accounts_head WHERE acc_accounts_head.company_id=" $companyId " AND accounts_head_id not in (select distinct parent_id from acc_accounts_head)and (1=0 " $likeQuery ") ";
  809.                         $stmt $em->getConnection()->prepare($get_sql);
  810.                         $stmt->execute();
  811.                         $entries $stmt->fetchAll();
  812.                         foreach ($entries as $entry) {
  813.                             $has_payments 1;
  814.                             $cash_child_id_list[] = $entry['accounts_head_id'];
  815.                             $acHeadList[] = $entry['accounts_head_id'];
  816.                             $acHeadDataById[$entry['accounts_head_id']]['name'] = $entry['name'];
  817.                         }
  818.                         $thisBalance_data Accounts::GetBalanceOnDate($em$thisPeriodEndDate, []);
  819.                         $lastBalance_data Accounts::GetBalanceOnDate($em$lastPeriodEndDate, []);
  820.                         foreach ($acHeadList as $acHead) {
  821.                             $thisBalanceDataByAcHead[$acHead]['balance'] = $thisBalance_data[$acHead]['end_balance']['balance'];
  822.                             $lastBalanceDataByAcHead[$acHead]['balance'] = $lastBalance_data[$acHead]['end_balance']['balance'];
  823.                         }
  824.                         $thisReportData = array(
  825.                             'accountsHeadList' => $acHeadList,
  826.                             'acHeadDataById' => $acHeadDataById,
  827.                             'cash_child_id_list' => $cash_child_id_list,
  828.                             'bank_child_id_list' => $bank_child_id_list,
  829.                             'thisBalanceDataByAcHead' => $thisBalanceDataByAcHead,
  830.                             'lastBalanceDataByAcHead' => $lastBalanceDataByAcHead,
  831.                         );
  832.                         $data['cash_and_bank_position'][$app_company_index] = $thisReportData;
  833.                         //                    $companyListData[] = Company::getCompanyListWithImage($em);
  834.                     }
  835.                     //Expense Position
  836.                     if (in_array('expense_position'$reportsToGet)) {
  837.                         $acHeadList = [];
  838.                         $companyId explode('_'$app_company_index)[1];
  839.                         $acHeadDataById = [];
  840.                         $thisBalanceDataByAcHead = [];
  841.                         $lastBalanceDataByAcHead = [];
  842.                         $get_sql "SELECT * FROM acc_accounts_head WHERE acc_accounts_head.company_id=" $companyId "
  843.                         AND acc_accounts_head.head_level= 2 ";
  844.                         $stmt $em->getConnection()->prepare($get_sql);
  845.                         $stmt->execute();
  846.                         $entries $stmt->fetchAll();
  847.                         foreach ($entries as $entry) {
  848.                             $has_payments 1;
  849.                             $cash_child_id_list[] = $entry['accounts_head_id'];
  850.                             $acHeadList[] = $entry['accounts_head_id'];
  851.                             $acHeadDataById[$entry['accounts_head_id']]['name'] = $entry['name'];
  852.                         }
  853.                         $thisBalance_data Accounts::GetPeriodicDataByType($em$type 'exp'$level_to_group_by 1$parent_id_list = [], $expand_level 1$thisPeriodStartDate$thisPeriodEndDate'_during_', [], [], [], false);
  854.                         $lastBalance_data Accounts::GetPeriodicDataByType($em$type 'exp'$level_to_group_by 1$parent_id_list = [], $expand_level 1$lastPeriodStartDate$lastPeriodEndDate'_during_', [], [], [], false);
  855.                         $skipHeadIds = [];
  856.                         foreach ($thisBalance_data as $parentHead => $balanceData) {
  857.                             foreach ($balanceData['data'] as $acHead => $headData) {
  858.                                 if (!in_array($acHead$acHeadList))
  859.                                     continue;
  860.                                 $thisBalanceDataByAcHead[$acHead]['balance'] = $headData['head_balance'];
  861.                                 if (isset($lastBalance_data[$parentHead])) {
  862.                                     if (isset($lastBalance_data[$parentHead]['data'][$acHead]))
  863.                                         $lastBalanceDataByAcHead[$acHead]['balance'] = $lastBalance_data[$parentHead]['data'][$acHead]['head_balance'];
  864.                                     else
  865.                                         $lastBalanceDataByAcHead[$acHead]['balance'] = 0;
  866.                                 } else
  867.                                     $lastBalanceDataByAcHead[$acHead]['balance'] = 0;
  868.                                 $skipHeadIds[] = $acHead;
  869.                             }
  870.                         }
  871.                         foreach ($lastBalance_data as $parentHead => $balanceData) {
  872.                             foreach ($balanceData['data'] as $acHead => $headData) {
  873.                                 if (in_array($acHead$skipHeadIds))
  874.                                     continue;
  875.                                 if (!in_array($acHead$acHeadList))
  876.                                     continue;
  877.                                 $lastBalanceDataByAcHead[$acHead]['balance'] = $headData['head_balance'];
  878.                                 if (isset($thisBalance_data[$parentHead])) {
  879.                                     if (isset($thisBalance_data[$parentHead]['data'][$acHead]))
  880.                                         $thisBalanceDataByAcHead[$acHead]['balance'] = $thisBalance_data[$parentHead]['data'][$acHead]['head_balance'];
  881.                                     else
  882.                                         $thisBalanceDataByAcHead[$acHead]['balance'] = 0;
  883.                                 } else
  884.                                     $thisBalanceDataByAcHead[$acHead]['balance'] = 0;
  885.                                 $skipHeadIds[] = $acHead;
  886.                             }
  887.                         }
  888.                         $thisReportData = array(
  889.                             'accountsHeadList' => $acHeadList,
  890.                             //                            'thisBalance_data' => $thisBalance_data,
  891.                             'confirmedHeadList' => $skipHeadIds,
  892.                             'acHeadDataById' => $acHeadDataById,
  893.                             'thisBalanceDataByAcHead' => $thisBalanceDataByAcHead,
  894.                             'lastBalanceDataByAcHead' => $lastBalanceDataByAcHead,
  895.                         );
  896.                         $data['expense_position'][$app_company_index] = $thisReportData;
  897.                         //                    $companyListData[] = Company::getCompanyListWithImage($em);
  898.                     }
  899.                     //Payable Position
  900.                     if (in_array('payable_position'$reportsToGet)) {
  901.                         $acHeadList = [];
  902.                         $companyId explode('_'$app_company_index)[1];
  903.                         $acHeadDataById = [];
  904.                         $thisBalanceDataByAcHead = [];
  905.                         $lastBalanceDataByAcHead = [];
  906.                         $filter_settings $em->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
  907.                             'name' => 'payable_parents',
  908.                             //                        'CompanyId'=>$companyId
  909.                         ));
  910.                         $filter_head_parents_id_list = [];
  911.                         if ($filter_settings)
  912.                             $filter_head_parents_id_list json_decode($filter_settings->getData());
  913.                         $likeQuery '';
  914.                         foreach ($filter_head_parents_id_list as $p) {
  915.                             $likeQuery .= "OR path_tree like '%/" $p "%/' ";
  916.                         }
  917.                         $get_sql "SELECT * FROM acc_accounts_head WHERE acc_accounts_head.company_id=" $companyId "
  918.                          and (1=0 " $likeQuery ") ";
  919.                         $stmt $em->getConnection()->prepare($get_sql);
  920.                         $stmt->execute();
  921.                         $entries $stmt->fetchAll();
  922.                         foreach ($entries as $entry) {
  923.                             $has_payments 1;
  924.                             $acHeadList[] = $entry['accounts_head_id'];
  925.                             $acHeadDataById[$entry['accounts_head_id']]['name'] = $entry['name'];
  926.                         }
  927.                         //                        $get_sql = "SELECT * FROM acc_accounts_head WHERE acc_accounts_head.company_id=" . $companyId . "
  928.                         //                        AND acc_accounts_head.head_level= 2 and acc_accounts_head.type='lib'";
  929.                         //
  930.                         //                        $stmt = $em->getConnection()->prepare($get_sql);
  931.                         //                        $stmt->execute();
  932.                         //                        $entries = $stmt->fetchAll();
  933.                         //
  934.                         //                        foreach ($entries as $entry) {
  935.                         //                            $has_payments = 1;
  936.                         //                            $cash_child_id_list[] = $entry['accounts_head_id'];
  937.                         //                            $acHeadList[] = $entry['accounts_head_id'];
  938.                         //                            $acHeadDataById[$entry['accounts_head_id']]['name'] = $entry['name'];
  939.                         //                        }
  940.                         $thisBalance_data Accounts::GetPeriodicDataByType($em$type 'lib'$level_to_group_by 2$parent_id_list = [], $expand_level 1$thisPeriodStartDate$thisPeriodEndDate'_during_', [], [], [], false);
  941.                         $lastBalance_data Accounts::GetPeriodicDataByType($em$type 'lib'$level_to_group_by 2$parent_id_list = [], $expand_level 1$lastPeriodStartDate$lastPeriodEndDate'_during_', [], [], [], false);
  942.                         $skipHeadIds = [];
  943.                         foreach ($thisBalance_data as $parentHead => $balanceData) {
  944.                             foreach ($balanceData['data'] as $acHead => $headData) {
  945.                                 if (!(in_array($acHead$acHeadList)))
  946.                                     continue;
  947.                                 if ($headData['head_level'] > 4)
  948.                                     continue;
  949.                                 //                                $thisBalanceDataByAcHead[$acHead]['balance'] = $headData['head_balance'];
  950.                                 $thisBalanceDataByAcHead[$acHead]['balance'] = $headData['end_balance']['balance'];
  951.                                 if (isset($lastBalance_data[$parentHead])) {
  952.                                     if (isset($lastBalance_data[$parentHead]['data'][$acHead]))
  953.                                         //                                        $lastBalanceDataByAcHead[$acHead]['balance'] = $lastBalance_data[$parentHead]['data'][$acHead]['head_balance'];
  954.                                         $lastBalanceDataByAcHead[$acHead]['balance'] = $lastBalance_data[$parentHead]['data'][$acHead]['end_balance']['balance'];
  955.                                     else
  956.                                         $lastBalanceDataByAcHead[$acHead]['balance'] = 0;
  957.                                 } else
  958.                                     $lastBalanceDataByAcHead[$acHead]['balance'] = 0;
  959.                                 $skipHeadIds[] = $acHead;
  960.                             }
  961.                         }
  962.                         foreach ($lastBalance_data as $parentHead => $balanceData) {
  963.                             foreach ($balanceData['data'] as $acHead => $headData) {
  964.                                 if (in_array($acHead$skipHeadIds))
  965.                                     continue;
  966.                                 if (!in_array($acHead$acHeadList))
  967.                                     continue;
  968.                                 if ($headData['head_level'] > 4)
  969.                                     continue;
  970.                                 $lastBalanceDataByAcHead[$acHead]['balance'] = $headData['end_balance']['balance'];
  971.                                 if (isset($thisBalance_data[$parentHead])) {
  972.                                     if (isset($thisBalance_data[$parentHead]['data'][$acHead]))
  973.                                         $thisBalanceDataByAcHead[$acHead]['balance'] = $thisBalance_data[$parentHead]['data'][$acHead]['end_balance']['balance'];
  974.                                     else
  975.                                         $thisBalanceDataByAcHead[$acHead]['balance'] = 0;
  976.                                 } else
  977.                                     $thisBalanceDataByAcHead[$acHead]['balance'] = 0;
  978.                                 $skipHeadIds[] = $acHead;
  979.                             }
  980.                         }
  981.                         $thisReportData = array(
  982.                             'accountsHeadList' => $acHeadList,
  983.                             //                            'thisBalance_data' => $thisBalance_data,
  984.                             'confirmedHeadList' => $skipHeadIds,
  985.                             'acHeadDataById' => $acHeadDataById,
  986.                             'thisBalanceDataByAcHead' => $thisBalanceDataByAcHead,
  987.                             'lastBalanceDataByAcHead' => $lastBalanceDataByAcHead,
  988.                         );
  989.                         $data['payable_position'][$app_company_index] = $thisReportData;
  990.                         //                    $companyListData[] = Company::getCompanyListWithImage($em);
  991.                     }
  992.                     //Receivable Position
  993.                     if (in_array('receivable_position'$reportsToGet)) {
  994.                         $acHeadList = [];
  995.                         $companyId explode('_'$app_company_index)[1];
  996.                         $acHeadDataById = [];
  997.                         $thisBalanceDataByAcHead = [];
  998.                         $lastBalanceDataByAcHead = [];
  999.                         //                        $filter_settings = $em->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
  1000.                         //                            'name' => 'receivable_parents',
  1001.                         ////                        'CompanyId'=>$companyId
  1002.                         //                        ));
  1003.                         //                        $filter_head_parents_id_list = [];
  1004.                         //                        if ($filter_settings)
  1005.                         //                            $filter_head_parents_id_list = json_decode($filter_settings->getData());
  1006.                         //                        $likeQuery = '';
  1007.                         //                        foreach ($filter_head_parents_id_list as $p) {
  1008.                         //                            $likeQuery .= "OR path_tree like '%/" . $p . "%/' ";
  1009.                         //                        }
  1010.                         //                        $get_sql = "SELECT * FROM acc_accounts_head WHERE acc_accounts_head.company_id=" . $companyId . "
  1011.                         //                         and (1=0 " . $likeQuery . ") ";
  1012.                         $get_sql "SELECT acc_accounts_head.*  FROM acc_accounts_head
  1013.  WHERE acc_accounts_head.company_id=" $companyId "
  1014.                          and  ( acc_accounts_head.accounts_head_id in (select distinct accounts_head_id from acc_clients)
  1015.                           OR acc_accounts_head.accounts_head_id in (select distinct advance_head_id from acc_clients)
  1016.                          ) ";
  1017.                         $stmt $em->getConnection()->prepare($get_sql);
  1018.                         $stmt->execute();
  1019.                         $entries $stmt->fetchAll();
  1020.                         $account_head_ids_by_client_type = [];
  1021.                         foreach ($entries as $entry) {
  1022.                             $has_payments 1;
  1023.                             $acHeadList[] = $entry['accounts_head_id'];
  1024.                             $acHeadDataById[$entry['accounts_head_id']]['name'] = $entry['name'];
  1025.                         }
  1026.                         $get_sql "SELECT acc_clients.*  FROM acc_clients
  1027.  WHERE acc_clients.company_id=" $companyId;
  1028.                         $stmt $em->getConnection()->prepare($get_sql);
  1029.                         $stmt->execute();
  1030.                         $entries $stmt->fetchAll();
  1031.                         $clientTypeListArray Client::ClientTypeList($em, [$companyId], true);
  1032.                         $clientTypesOfHeads = [];
  1033.                         foreach ($entries as $entry) {
  1034.                             if (!isset($account_head_ids_by_client_type[$entry['type']]))
  1035.                                 $account_head_ids_by_client_type[$entry['type']] = [];
  1036.                             $account_head_ids_by_client_type[$entry['type']][] = $entry['accounts_head_id'];
  1037.                             $clientTypesOfHeads[$entry['accounts_head_id']] = $entry['type'];
  1038.                             if ($entry['accounts_head_id'] != $entry['advance_head_id']) {
  1039.                                 $account_head_ids_by_client_type[$entry['type']][] = $entry['advance_head_id'];
  1040.                                 $clientTypesOfHeads[$entry['advance_head_id']] = $entry['type'];
  1041.                             }
  1042.                         }
  1043.                         //                        $get_sql = "SELECT * FROM acc_accounts_head WHERE acc_accounts_head.company_id=" . $companyId . "
  1044.                         //                        AND acc_accounts_head.head_level= 2 and acc_accounts_head.type='lib'";
  1045.                         //
  1046.                         //                        $stmt = $em->getConnection()->prepare($get_sql);
  1047.                         //                        $stmt->execute();
  1048.                         //                        $entries = $stmt->fetchAll();
  1049.                         //
  1050.                         //                        foreach ($entries as $entry) {
  1051.                         //                            $has_payments = 1;
  1052.                         //                            $cash_child_id_list[] = $entry['accounts_head_id'];
  1053.                         //                            $acHeadList[] = $entry['accounts_head_id'];
  1054.                         //                            $acHeadDataById[$entry['accounts_head_id']]['name'] = $entry['name'];
  1055.                         //                        }
  1056.                         $thisBalance_data Accounts::GetPeriodicDataByType($em$type 'ast'$level_to_group_by 2$parent_id_list = [], $expand_level 1$thisPeriodStartDate$thisPeriodEndDate'_during_', [], [], [], true);
  1057.                         $lastBalance_data Accounts::GetPeriodicDataByType($em$type 'ast'$level_to_group_by 2$parent_id_list = [], $expand_level 1$lastPeriodStartDate$lastPeriodEndDate'_during_', [], [], [], true);
  1058.                         $skipHeadIds = [];
  1059.                         $thisBalanceDataByClientType = [];
  1060.                         $lastBalanceDataByClientType = [];
  1061.                         foreach ($clientTypeListArray as $ct) {
  1062.                             $thisBalanceDataByClientType[$ct['id']] = 0;
  1063.                             $lastBalanceDataByClientType[$ct['id']] = 0;
  1064.                         }
  1065.                         foreach ($thisBalance_data as $parentHead => $balanceData) {
  1066.                             foreach ($balanceData['data'] as $acHead => $headData) {
  1067.                                 if (!(in_array($acHead$acHeadList)))
  1068.                                     continue;
  1069.                                 //                                if ($headData['head_level'] > 4)
  1070.                                 //                                    continue;
  1071.                                 $thisBalanceDataByAcHead[$acHead]['balance'] = $headData['end_balance']['balance'];
  1072.                                 if (isset($lastBalance_data[$parentHead])) {
  1073.                                     if (isset($lastBalance_data[$parentHead]['data'][$acHead]))
  1074.                                         $lastBalanceDataByAcHead[$acHead]['balance'] = $lastBalance_data[$parentHead]['data'][$acHead]['end_balance']['balance'];
  1075.                                     else
  1076.                                         $lastBalanceDataByAcHead[$acHead]['balance'] = 0;
  1077.                                 } else
  1078.                                     $lastBalanceDataByAcHead[$acHead]['balance'] = 0;
  1079.                                 if (!isset($thisBalanceDataByClientType[$clientTypesOfHeads[$acHead]]))
  1080.                                     $thisBalanceDataByClientType[$clientTypesOfHeads[$acHead]] = $headData['end_balance']['balance'];
  1081.                                 else
  1082.                                     $thisBalanceDataByClientType[$clientTypesOfHeads[$acHead]] += $headData['end_balance']['balance'];
  1083.                                 if (!isset($lastBalanceDataByClientType[$clientTypesOfHeads[$acHead]]))
  1084.                                     $lastBalanceDataByClientType[$clientTypesOfHeads[$acHead]] = 0;
  1085.                                 else
  1086.                                     $lastBalanceDataByClientType[$clientTypesOfHeads[$acHead]] += $lastBalance_data[$parentHead]['data'][$acHead]['end_balance']['balance'];
  1087.                                 $skipHeadIds[] = $acHead;
  1088.                             }
  1089.                         }
  1090.                         foreach ($lastBalance_data as $parentHead => $balanceData) {
  1091.                             foreach ($balanceData['data'] as $acHead => $headData) {
  1092.                                 if (in_array($acHead$skipHeadIds))
  1093.                                     continue;
  1094.                                 if (!in_array($acHead$acHeadList))
  1095.                                     continue;
  1096.                                 //                                if ($headData['head_level'] > 4)
  1097.                                 //                                    continue;
  1098.                                 $lastBalanceDataByAcHead[$acHead]['balance'] = $headData['end_balance']['balance'];
  1099.                                 if (isset($thisBalance_data[$parentHead])) {
  1100.                                     if (isset($thisBalance_data[$parentHead]['data'][$acHead]))
  1101.                                         $thisBalanceDataByAcHead[$acHead]['balance'] = $thisBalance_data[$parentHead]['data'][$acHead]['end_balance']['balance'];
  1102.                                     else
  1103.                                         $thisBalanceDataByAcHead[$acHead]['balance'] = 0;
  1104.                                 } else
  1105.                                     $thisBalanceDataByAcHead[$acHead]['balance'] = 0;
  1106.                                 if (!isset($lastBalanceDataByClientType[$clientTypesOfHeads[$acHead]]))
  1107.                                     $lastBalanceDataByClientType[$clientTypesOfHeads[$acHead]] = $headData['end_balance']['balance'];
  1108.                                 else
  1109.                                     $lastBalanceDataByClientType[$clientTypesOfHeads[$acHead]] += $headData['end_balance']['balance'];
  1110.                                 if (!isset($thisBalanceDataByClientType[$clientTypesOfHeads[$acHead]]))
  1111.                                     $thisBalanceDataByClientType[$clientTypesOfHeads[$acHead]] = 0;
  1112.                                 $skipHeadIds[] = $acHead;
  1113.                             }
  1114.                         }
  1115.                         $thisReportData = array(
  1116.                             //                            'accountsHeadList' => $acHeadList,
  1117.                             //                            'thisBalance_data' => $thisBalance_data,
  1118.                             //                            'confirmedHeadList' => $skipHeadIds,
  1119.                             //                            'acHeadDataById' => $acHeadDataById,
  1120.                             'thisBalance_data' => $thisBalance_data,
  1121.                             'lastBalance_data' => $lastBalance_data,
  1122.                             'thisBalanceDataByAcHead' => $thisBalanceDataByAcHead,
  1123.                             'lastBalanceDataByAcHead' => $lastBalanceDataByAcHead,
  1124.                             'clientTypeListArray' => $clientTypeListArray,
  1125.                             'thisBalanceDataByClientType' => $thisBalanceDataByClientType,
  1126.                             'lastBalanceDataByClientType' => $lastBalanceDataByClientType,
  1127.                         );
  1128.                         $data['receivable_position'][$app_company_index] = $thisReportData;
  1129.                         //                    $companyListData[] = Company::getCompanyListWithImage($em);
  1130.                     }
  1131.                     //Sales Position
  1132.                     if (in_array('sales_position'$reportsToGet)) {
  1133.                         $acHeadList = [];
  1134.                         $companyId explode('_'$app_company_index)[1];
  1135.                         $acHeadDataById = [];
  1136.                         $thisBalanceDataByClientType = [];
  1137.                         $lastBalanceDataByClientType = [];
  1138.                         $get_sql "SELECT sum(sales_invoice.invoice_amount) sales_amount,client_type.client_type_id, client_type.name, acc_clients.client_id, acc_clients.type
  1139.   FROM sales_invoice
  1140.   join acc_clients on acc_clients.client_id=sales_invoice.client_id
  1141.   join client_type on acc_clients.type=client_type.client_type_id
  1142.    WHERE sales_invoice.company_id=" $companyId " AND sales_invoice.approved=1
  1143.                           AND sales_invoice_date between '" $thisPeriodStartDate " 00:00:00' and '" $thisPeriodEndDate " 23:59:59.999'
  1144.                           GROUP BY client_type.client_type_id
  1145.                           ";
  1146.                         $stmt $em->getConnection()->prepare($get_sql);
  1147.                         $stmt->execute();
  1148.                         $entries $stmt->fetchAll();
  1149.                         $clientTypes = [];
  1150.                         $clientTypeNames = [];
  1151.                         $get_sql_1 $get_sql;
  1152.                         foreach ($entries as $entry) {
  1153.                             $has_payments 1;
  1154.                             $thisBalanceDataByClientType[$entry['client_type_id']] = $entry;
  1155.                             $lastBalanceDataByClientType[$entry['client_type_id']]['sales_amount'] = 0//just for the lulz
  1156.                             if (!in_array($entry['client_type_id'], $clientTypes)) {
  1157.                                 $clientTypes[] = $entry['client_type_id'];
  1158.                                 $clientTypeNames[$entry['client_type_id']] = $entry['name'];
  1159.                             }
  1160.                         }
  1161.                         $get_sql "SELECT sum(sales_invoice.invoice_amount) sales_amount,client_type.client_type_id, client_type.name, acc_clients.client_id, acc_clients.type
  1162.   FROM sales_invoice
  1163.   join acc_clients on acc_clients.client_id=sales_invoice.client_id
  1164.   join client_type on acc_clients.type=client_type.client_type_id
  1165.    WHERE sales_invoice.company_id=" $companyId " AND sales_invoice.approved=1
  1166.                           AND sales_invoice_date between '" $lastPeriodStartDate " 00:00:00' and '" $lastPeriodEndDate " 23:59:59.999'
  1167.                           GROUP BY client_type.client_type_id
  1168.                           ";
  1169.                         $stmt $em->getConnection()->prepare($get_sql);
  1170.                         $stmt->execute();
  1171.                         $entries $stmt->fetchAll();
  1172.                         foreach ($entries as $entry) {
  1173.                             $has_payments 1;
  1174.                             $lastBalanceDataByClientType[$entry['client_type_id']] = $entry;
  1175.                             if (!isset($thisBalanceDataByClientType[$entry['client_type_id']]))
  1176.                                 $thisBalanceDataByClientType[$entry['client_type_id']]['sales_amount'] = 0//just for the lulz
  1177.                             if (!in_array($entry['client_type_id'], $clientTypes)) {
  1178.                                 $clientTypes[] = $entry['client_type_id'];
  1179.                                 $clientTypeNames[$entry['client_type_id']] = $entry['name'];
  1180.                             }
  1181.                         }
  1182.                         $skipHeadIds = [];
  1183.                         $thisReportData = array(
  1184.                             'clientTypes' => $clientTypes,
  1185.                             //                            'get_sql_1' => $get_sql_1,
  1186.                             //                            'get_sql' => $get_sql,
  1187.                             'clientTypeNames' => $clientTypeNames,
  1188.                             'thisBalanceDataByClientType' => $thisBalanceDataByClientType,
  1189.                             'lastBalanceDataByClientType' => $lastBalanceDataByClientType,
  1190.                         );
  1191.                         $data['sales_position'][$app_company_index] = $thisReportData;
  1192.                         //                    $companyListData[] = Company::getCompanyListWithImage($em);
  1193.                     }
  1194.                     //Collection Position
  1195.                     if (in_array('collection_position'$reportsToGet)) {
  1196.                         $acHeadList = [];
  1197.                         $companyId explode('_'$app_company_index)[1];
  1198.                         $acHeadDataById = [];
  1199.                         $thisBalanceDataByClientType = [];
  1200.                         $lastBalanceDataByClientType = [];
  1201.                         $get_sql "SELECT SUM(CASE WHEN position = 'cr' THEN amount ELSE 0 END) positive_amount,
  1202. SUM(CASE WHEN position = 'dr' THEN amount ELSE 0 END) negative_amount,client_type.client_type_id, client_type.name, acc_clients.client_id, acc_clients.type
  1203.  FROM acc_transaction_details
  1204.    join acc_clients on acc_clients.accounts_head_id=acc_transaction_details.accounts_head_id or acc_clients.advance_head_id=acc_transaction_details.accounts_head_id
  1205.   join client_type on acc_clients.type=client_type.client_type_id
  1206.   WHERE acc_transaction_details.ledger_hit=1 AND acc_transaction_details.transaction_id in (select distinct transaction_id from acc_transactions where acc_transactions.document_type=6)  AND ledger_hit_date between '" $thisPeriodStartDate " 00:00:00' and '" $thisPeriodEndDate " 23:59:59.999'
  1207.                               GROUP BY client_type.client_type_id";
  1208.                         $stmt $em->getConnection()->prepare($get_sql);
  1209.                         $stmt->execute();
  1210.                         $entries $stmt->fetchAll();
  1211.                         $clientTypes = [];
  1212.                         $clientTypeNames = [];
  1213.                         foreach ($entries as $entry) {
  1214.                             $has_payments 1;
  1215.                             $thisBalanceDataByClientType[$entry['client_type_id']] = $entry;
  1216.                             $lastBalanceDataByClientType[$entry['client_type_id']]['collection_amount'] = 0//just for the lulz
  1217.                             $thisBalanceDataByClientType[$entry['client_type_id']]['collection_amount'] = $entry['positive_amount'] - $entry['negative_amount'];
  1218.                             if (!in_array($entry['client_type_id'], $clientTypes)) {
  1219.                                 $clientTypes[] = $entry['client_type_id'];
  1220.                                 $clientTypeNames[$entry['client_type_id']] = $entry['name'];
  1221.                             }
  1222.                         }
  1223.                         $get_sql "SELECT SUM(CASE WHEN position = 'cr' THEN amount ELSE 0 END) positive_amount,
  1224. SUM(CASE WHEN position = 'dr' THEN amount ELSE 0 END) negative_amount,client_type.client_type_id, client_type.name, acc_clients.client_id, acc_clients.type
  1225.  FROM acc_transaction_details
  1226.    join acc_clients on acc_clients.accounts_head_id=acc_transaction_details.accounts_head_id or acc_clients.advance_head_id=acc_transaction_details.accounts_head_id
  1227.   join client_type on acc_clients.type=client_type.client_type_id
  1228.   WHERE acc_transaction_details.ledger_hit=1 AND  acc_transaction_details.transaction_id in (select distinct transaction_id from acc_transactions where acc_transactions.document_type=6) AND ledger_hit_date between '" $lastPeriodStartDate " 00:00:00' and '" $lastPeriodEndDate " 23:59:59.999'
  1229.                               GROUP BY client_type.client_type_id";
  1230.                         $stmt $em->getConnection()->prepare($get_sql);
  1231.                         $stmt->execute();
  1232.                         $entries $stmt->fetchAll();
  1233.                         foreach ($entries as $entry) {
  1234.                             $has_payments 1;
  1235.                             $lastBalanceDataByClientType[$entry['client_type_id']] = $entry;
  1236.                             $lastBalanceDataByClientType[$entry['client_type_id']]['collection_amount'] = $entry['positive_amount'] - $entry['negative_amount'];
  1237.                             if (!isset($thisBalanceDataByClientType[$entry['client_type_id']]))
  1238.                                 $thisBalanceDataByClientType[$entry['client_type_id']]['collection_amount'] = 0//just for the lulz
  1239.                             if (!in_array($entry['client_type_id'], $clientTypes)) {
  1240.                                 $clientTypes[] = $entry['client_type_id'];
  1241.                                 $clientTypeNames[$entry['client_type_id']] = $entry['name'];
  1242.                             }
  1243.                         }
  1244.                         $skipHeadIds = [];
  1245.                         $thisReportData = array(
  1246.                             'clientTypes' => $clientTypes,
  1247.                             'clientTypeNames' => $clientTypeNames,
  1248.                             'thisBalanceDataByClientType' => $thisBalanceDataByClientType,
  1249.                             'lastBalanceDataByClientType' => $lastBalanceDataByClientType,
  1250.                         );
  1251.                         $data['collection_position'][$app_company_index] = $thisReportData;
  1252.                         //                    $companyListData[] = Company::getCompanyListWithImage($em);
  1253.                     }
  1254.                     //Return Position
  1255.                     if (in_array('market_return_position'$reportsToGet)) {
  1256.                         $acHeadList = [];
  1257.                         $companyId explode('_'$app_company_index)[1];
  1258.                         $acHeadDataById = [];
  1259.                         $thisBalanceDataByClientType = [];
  1260.                         $lastBalanceDataByClientType = [];
  1261.                         $get_sql "SELECT sum(irr_item.received_total_sales_price) return_amount,client_type.client_type_id, client_type.name, acc_clients.client_id, acc_clients.type
  1262.   FROM irr_item
  1263.   join item_received_replacement on item_received_replacement.irr_id=irr_item.irr_id
  1264.   join acc_clients on acc_clients.client_id=item_received_replacement.client_id
  1265.   join client_type on acc_clients.type=client_type.client_type_id
  1266.    WHERE item_received_replacement.company_id=" $companyId " AND item_received_replacement.approved=1
  1267.                           AND item_received_replacement.irr_date between '" $thisPeriodStartDate " 00:00:00' and '" $thisPeriodEndDate " 23:59:59.999'
  1268.                           GROUP BY client_type.client_type_id
  1269.                           ";
  1270.                         $stmt $em->getConnection()->prepare($get_sql);
  1271.                         $stmt->execute();
  1272.                         $entries $stmt->fetchAll();
  1273.                         $clientTypes = [];
  1274.                         $clientTypeNames = [];
  1275.                         $get_sql_1 $get_sql;
  1276.                         foreach ($entries as $entry) {
  1277.                             $has_payments 1;
  1278.                             $thisBalanceDataByClientType[$entry['client_type_id']] = $entry;
  1279.                             $lastBalanceDataByClientType[$entry['client_type_id']]['return_amount'] = 0//just for the lulz
  1280.                             if (!in_array($entry['client_type_id'], $clientTypes)) {
  1281.                                 $clientTypes[] = $entry['client_type_id'];
  1282.                                 $clientTypeNames[$entry['client_type_id']] = $entry['name'];
  1283.                             }
  1284.                         }
  1285.                         $get_sql "SELECT sum(irr_item.received_total_sales_price) return_amount,client_type.client_type_id, client_type.name, acc_clients.client_id, acc_clients.type
  1286.   FROM irr_item
  1287.   join item_received_replacement on item_received_replacement.irr_id=irr_item.irr_id
  1288.   join acc_clients on acc_clients.client_id=item_received_replacement.client_id
  1289.   join client_type on acc_clients.type=client_type.client_type_id
  1290.    WHERE item_received_replacement.company_id=" $companyId " AND item_received_replacement.approved=1
  1291.                           AND item_received_replacement.irr_date between '" $lastPeriodStartDate " 00:00:00' and '" $lastPeriodEndDate " 23:59:59.999'
  1292.                           GROUP BY client_type.client_type_id
  1293.                           ";
  1294.                         $stmt $em->getConnection()->prepare($get_sql);
  1295.                         $stmt->execute();
  1296.                         $entries $stmt->fetchAll();
  1297.                         foreach ($entries as $entry) {
  1298.                             $has_payments 1;
  1299.                             $lastBalanceDataByClientType[$entry['client_type_id']] = $entry;
  1300.                             if (!isset($thisBalanceDataByClientType[$entry['client_type_id']]))
  1301.                                 $thisBalanceDataByClientType[$entry['client_type_id']]['return_amount'] = 0//just for the lulz
  1302.                             if (!in_array($entry['client_type_id'], $clientTypes)) {
  1303.                                 $clientTypes[] = $entry['client_type_id'];
  1304.                                 $clientTypeNames[$entry['client_type_id']] = $entry['name'];
  1305.                             }
  1306.                         }
  1307.                         $skipHeadIds = [];
  1308.                         $thisReportData = array(
  1309.                             'clientTypes' => $clientTypes,
  1310.                             //                            'get_sql_1' => $get_sql_1,
  1311.                             //                            'get_sql' => $get_sql,
  1312.                             'clientTypeNames' => $clientTypeNames,
  1313.                             'thisBalanceDataByClientType' => $thisBalanceDataByClientType,
  1314.                             'lastBalanceDataByClientType' => $lastBalanceDataByClientType,
  1315.                         );
  1316.                         $data['market_return_position'][$app_company_index] = $thisReportData;
  1317.                         //                    $companyListData[] = Company::getCompanyListWithImage($em);
  1318.                     }
  1319.                     //order and client count
  1320.                     if (in_array('order_and_client_count'$reportsToGet)) {
  1321.                         $acHeadList = [];
  1322.                         $companyId explode('_'$app_company_index)[1];
  1323.                         $acHeadDataById = [];
  1324.                         $thisBalanceDataByAcHead = [];
  1325.                         $lastBalanceDataByAcHead = [];
  1326.                         $today = new \DateTime();
  1327.                         $get_sql "SELECT count(sales_order_id) total_so_count, sum(so_amount) total_so_amount, sum(invoice_amount) total_invoice_amount FROM sales_order WHERE sales_order.company_id=" $companyId " and  sales_order.sales_order_date between '" $thisPeriodStartDate " 00:00:00' and '" $thisPeriodEndDate " 23:59:59.999' ";
  1328.                         $stmt $em->getConnection()->prepare($get_sql);
  1329.                         $stmt->execute();
  1330.                         $entries1 $stmt->fetchAll();
  1331.                         $get_sql "SELECT count(client_id) total_clients FROM acc_clients WHERE acc_clients.company_id=" $companyId;
  1332.                         $stmt $em->getConnection()->prepare($get_sql);
  1333.                         $stmt->execute();
  1334.                         $entries2 $stmt->fetchAll();
  1335.                         $currCompanyData Company::getCompanyData($em$session->get(UserConstants::USER_COMPANY_ID$companyId));
  1336.                         $get_sql "SELECT SUM(CASE WHEN position = 'cr' THEN amount ELSE ((-1)*amount) END) total_collection_amount, acc_transactions.document_hash FROM acc_transaction_details
  1337.                         join acc_transactions on acc_transactions.transaction_id=acc_transaction_details.transaction_id
  1338.                         WHERE acc_transaction_details.ledger_hit=1 AND acc_transactions.document_type=6
  1339.                       AND (
  1340.                       accounts_head_id in(select distinct accounts_head_id from acc_clients WHERE acc_clients.company_id=" $companyId ")
  1341.                       or  accounts_head_id in(select distinct advance_head_id from acc_clients WHERE acc_clients.company_id=" $companyId ") )
  1342.                       AND acc_transactions.company_id=" $companyId " AND acc_transactions.approved=1 AND acc_transaction_details.ledger_hit_date between '" $thisPeriodStartDate " 00:00:00' and '" $thisPeriodEndDate " 23:59:59.999' ";
  1343.                         $stmt $em->getConnection()->prepare($get_sql);
  1344.                         $stmt->execute();
  1345.                         $entries3 $stmt->fetchAll();
  1346.                         //
  1347.                         //                        $get_sql = "SELECT (select  c.balance last_balance from inv_closing_balance c
  1348.                         //where c.product_id=a.product_id and c.warehouse_id=a.warehouse_id and c.action_tag_id=a.action_tag_id order by date desc limit 1) stock_amount
  1349.                         //from inv_closing_balance a
  1350.                         //                        where a.warehouse_id in (select distinct id from warehouse
  1351.                         //                        WHERE  warehouse.company_id=" . $companyId . ") and  a.date between '" . $thisPeriodStartDate . " 00:00:00' and '" . $thisPeriodEndDate . " 23:59:59.999' ";
  1352.                         $get_sql "SELECT a.* , (select  c.balance last_balance from inv_closing_balance c
  1353. where date <='" $thisPeriodEndDate " 00:00:00' and c.product_id=a.product_id and c.warehouse_id=a.warehouse_id and c.action_tag_id=a.action_tag_id order by date desc limit 1) last_balance
  1354. from inv_closing_balance a
  1355. where a.warehouse_id in (select distinct id from warehouse
  1356.                       WHERE  warehouse.company_id=" $companyId ") ";
  1357.                         $stmt $em->getConnection()->prepare($get_sql);
  1358.                         $stmt->execute();
  1359.                         $entries4 $stmt->fetchAll();
  1360.                         $currCompanyData Company::getCompanyData($em$session->get(UserConstants::USER_COMPANY_ID$companyId));
  1361.                         $total_stock_amount 0;
  1362.                         foreach ($entries4 as $ent) {
  1363.                             $total_stock_amount += $ent['last_balance'];
  1364.                         }
  1365.                         $thisReportData = array(
  1366.                             //                            'total_stock_amount' => empty($entries3) ? 0 : $entries4[0]['total_stock_amount'],
  1367.                             'total_stock_amount' => $total_stock_amount,
  1368.                             'total_collection_amount' => empty($entries3) ? $entries3[0]['total_collection_amount'],
  1369.                             'total_so_count' => empty($entries1) ? $entries1[0]['total_so_count'],
  1370.                             'total_so_amount' => empty($entries1) ? $entries1[0]['total_so_amount'],
  1371.                             'total_invoice_amount' => empty($entries1) ? $entries1[0]['total_invoice_amount'],
  1372.                             'total_receivable' => $currCompanyData->getReceivable(),
  1373.                             'total_payable' => $currCompanyData->getPayable(),
  1374.                             'total_clients' => empty($entries2) ? $entries2[0]['total_clients'],
  1375.                         );
  1376.                         $data['order_and_client_count'][$app_company_index] = $thisReportData;
  1377.                         //                    $companyListData[] = Company::getCompanyListWithImage($em);
  1378.                     }
  1379.                     //Inventory Position
  1380.                     if (in_array('inventory_position'$reportsToGet)) {
  1381.                         $acHeadList = [];
  1382.                         $companyId explode('_'$app_company_index)[1];
  1383.                         $acHeadDataById = [];
  1384.                         $thisBalanceDataByActionTag = [];
  1385.                         $lastBalanceDataByActionTag = [];
  1386.                         $warehouseList Inventory::warehouse_action_list($em$companyId$method 'object');
  1387.                         $get_sql "SELECT a.* , (select  c.balance last_balance from inv_closing_balance c
  1388. where date <='" $thisPeriodEndDate " 00:00:00' and c.product_id=a.product_id and c.warehouse_id=a.warehouse_id and c.action_tag_id=a.action_tag_id order by date desc limit 1) last_balance
  1389. from inv_closing_balance a
  1390. where a.warehouse_id in (select distinct id from warehouse
  1391.                        WHERE  warehouse.company_id=" $companyId ") ";
  1392.                         $stmt $em->getConnection()->prepare($get_sql);
  1393.                         $stmt->execute();
  1394.                         $entries $stmt->fetchAll();
  1395.                         $confirmed_action_ids = [];
  1396.                         $confirmed_action_names = [];
  1397.                         $get_sql_1 $get_sql;
  1398.                         foreach ($entries as $entry) {
  1399.                             $has_payments 1;
  1400.                             if (isset($thisBalanceDataByActionTag[$entry['action_tag_id']]))
  1401.                                 $thisBalanceDataByActionTag[$entry['action_tag_id']]['inventory_amount'] += $entry['last_balance'];
  1402.                             else
  1403.                                 $thisBalanceDataByActionTag[$entry['action_tag_id']]['inventory_amount'] = $entry['last_balance'];
  1404.                             if (!isset($lastBalanceDataByActionTag[$entry['action_tag_id']]))
  1405.                                 $lastBalanceDataByActionTag[$entry['action_tag_id']]['inventory_amount'] = 0;
  1406.                             if (!in_array($entry['action_tag_id'], $confirmed_action_ids)) {
  1407.                                 $confirmed_action_ids[] = $entry['action_tag_id'];
  1408.                                 $confirmed_action_names[$entry['action_tag_id']] = $warehouseList[$entry['action_tag_id']]['name'];
  1409.                             }
  1410.                         }
  1411.                         $get_sql "SELECT a.* , (select  c.balance last_balance from inv_closing_balance c
  1412. where date <='" $lastPeriodEndDate " 00:00:00' and c.product_id=a.product_id and c.warehouse_id=a.warehouse_id and c.action_tag_id=a.action_tag_id order by date desc limit 1) last_balance
  1413. from inv_closing_balance a
  1414. where a.warehouse_id in (select distinct id from warehouse
  1415.                        WHERE  warehouse.company_id=" $companyId ") ";
  1416.                         $stmt $em->getConnection()->prepare($get_sql);
  1417.                         $stmt->execute();
  1418.                         $entries $stmt->fetchAll();
  1419.                         foreach ($entries as $entry) {
  1420.                             $has_payments 1;
  1421.                             if (isset($lastBalanceDataByActionTag[$entry['action_tag_id']]))
  1422.                                 $lastBalanceDataByActionTag[$entry['action_tag_id']]['inventory_amount'] += $entry['last_balance'];
  1423.                             else
  1424.                                 $lastBalanceDataByActionTag[$entry['action_tag_id']]['inventory_amount'] = $entry['last_balance'];
  1425.                             if (!isset($thisBalanceDataByActionTag[$entry['action_tag_id']]))
  1426.                                 $thisBalanceDataByActionTag[$entry['action_tag_id']]['inventory_amount'] = 0;
  1427.                             if (!in_array($entry['action_tag_id'], $confirmed_action_ids)) {
  1428.                                 $confirmed_action_ids[] = $entry['action_tag_id'];
  1429.                                 $confirmed_action_names[$entry['action_tag_id']] = $warehouseList[$entry['action_tag_id']]['name'];
  1430.                             }
  1431.                         }
  1432.                         $skipHeadIds = [];
  1433.                         $thisReportData = array(
  1434.                             //                            'clientTypes' => $clientTypes,
  1435.                             //                            'get_sql_1' => $get_sql_1,
  1436.                             //                            'get_sql' => $get_sql,
  1437.                             'confirmed_action_ids' => $confirmed_action_ids,
  1438.                             'confirmed_action_names' => $confirmed_action_names,
  1439.                             'thisBalanceDataByActionTag' => $thisBalanceDataByActionTag,
  1440.                             'lastBalanceDataByActionTag' => $lastBalanceDataByActionTag,
  1441.                         );
  1442.                         $data['inventory_position'][$app_company_index] = $thisReportData;
  1443.                         //                    $companyListData[] = Company::getCompanyListWithImage($em);
  1444.                     }
  1445.                     //Production Position
  1446.                     if (in_array('production_position'$reportsToGet)) {
  1447.                         $acHeadList = [];
  1448.                         $companyId explode('_'$app_company_index)[1];
  1449.                         $acHeadDataById = [];
  1450.                         $thisBalanceDataByIgId = [];
  1451.                         $lastBalanceDataByIgId = [];
  1452.                         $itemGroups = [];
  1453.                         $itemGroupNames = [];
  1454.                         $get_sql "SELECT sum((case WHEN inv_products.curr_sales_price!=0 then inv_products.curr_sales_price else inv_products.curr_purchase_price END )*production_entry_item.produced_qty) production_amount,inv_item_group.id item_group_id ,inv_item_group.name item_group_name ,inv_products.id product_id
  1455.   FROM production_entry_item
  1456.   join production on production_entry_item.production_id=production.production_id
  1457.   join inv_products on production_entry_item.product_id=inv_products.id
  1458.   join inv_item_group on inv_item_group.id=inv_products.ig_id
  1459.    WHERE production.company_id=" $companyId " AND production.approved=1
  1460.                           AND production.production_date between '" $thisPeriodStartDate " 00:00:00' and '" $thisPeriodEndDate " 23:59:59.999'
  1461.                           GROUP BY inv_item_group.id
  1462.                           ";
  1463.                         //                        $get_sql = "SELECT sum(product_mrp.average_price*production_entry_item.produced_qty) production_amount,inv_item_group.id item_group_id ,inv_item_group.name item_group_name ,inv_products.id product_id
  1464.                         //  FROM production_entry_item
  1465.                         //  join production on production_entry_item.production_id=production.production_id
  1466.                         //  join inv_products on production_entry_item.product_id=inv_products.id
  1467.                         //  join product_mrp on production_entry_item.product_id=product_mrp.product_id
  1468.                         //  join inv_item_group on inv_item_group.id=inv_products.ig_id
  1469.                         //   WHERE production.company_id=" . $companyId . " AND production.approved=1
  1470.                         //                          AND production.production_date between '" . $thisPeriodStartDate . " 00:00:00' and '" . $thisPeriodEndDate . " 23:59:59.999'
  1471.                         //                          GROUP BY inv_item_group.id
  1472.                         //                          ";
  1473.                         $stmt $em->getConnection()->prepare($get_sql);
  1474.                         $stmt->execute();
  1475.                         $entries $stmt->fetchAll();
  1476.                         $get_sql_1 $get_sql;
  1477.                         foreach ($entries as $entry) {
  1478.                             $has_payments 1;
  1479.                             $thisBalanceDataByIgId[$entry['item_group_id']] = $entry;
  1480.                             $lastBalanceDataByIgId[$entry['item_group_id']]['production_amount'] = 0//just for the lulz
  1481.                             if (!in_array($entry['item_group_id'], $clientTypes)) {
  1482.                                 $itemGroups[] = $entry['item_group_id'];
  1483.                                 $itemGroupNames[$entry['item_group_id']] = $entry['item_group_name'];
  1484.                             }
  1485.                         }
  1486.                         $get_sql "SELECT sum(production_entry_item.price*production_entry_item.produced_qty) production_amount,inv_item_group.id item_group_id ,inv_item_group.name item_group_name ,inv_products.id product_id
  1487.   FROM production_entry_item
  1488.   join production on production_entry_item.production_id=production.production_id
  1489.   join inv_products on production_entry_item.product_id=inv_products.id
  1490.   join inv_item_group on inv_item_group.id=inv_products.ig_id
  1491.    WHERE production.company_id=" $companyId " AND production.approved=1
  1492.                           AND production.production_date between '" $lastPeriodStartDate " 00:00:00' and '" $lastPeriodEndDate " 23:59:59.999'
  1493.                           GROUP BY inv_item_group.id
  1494.                           ";
  1495.                         $stmt $em->getConnection()->prepare($get_sql);
  1496.                         $stmt->execute();
  1497.                         $entries $stmt->fetchAll();
  1498.                         foreach ($entries as $entry) {
  1499.                             $has_payments 1;
  1500.                             $lastBalanceDataByIgId[$entry['item_group_id']] = $entry;
  1501.                             if (!isset($thisBalanceDataByIgId[$entry['item_group_id']]))
  1502.                                 $thisBalanceDataByIgId[$entry['item_group_id']]['production_amount'] = 0//just for the lulz
  1503.                             if (!in_array($entry['item_group_id'], $clientTypes)) {
  1504.                                 $itemGroups[] = $entry['item_group_id'];
  1505.                                 $itemGroupNames[$entry['item_group_id']] = $entry['item_group_name'];
  1506.                             }
  1507.                         }
  1508.                         $skipHeadIds = [];
  1509.                         $thisReportData = array(
  1510.                             'itemGroups' => $itemGroups,
  1511.                             //                            'get_sql_1' => $get_sql_1,
  1512.                             //                            'get_sql' => $get_sql,
  1513.                             'itemGroupNames' => $itemGroupNames,
  1514.                             'thisBalanceDataByIgId' => $thisBalanceDataByIgId,
  1515.                             'lastBalanceDataByIgId' => $lastBalanceDataByIgId,
  1516.                         );
  1517.                         $data['production_position'][$app_company_index] = $thisReportData;
  1518.                         //                    $companyListData[] = Company::getCompanyListWithImage($em);
  1519.                     }
  1520.                     //Top Products
  1521.                     if (in_array('top_selling_item_position'$reportsToGet)) {
  1522.                         $acHeadList = [];
  1523.                         $companyId explode('_'$app_company_index)[1];
  1524.                         $acHeadDataById = [];
  1525.                         $thisBalanceDataByRelId = [];
  1526.                         $lastBalanceDataByRelId = [];
  1527.                         $clientIds = [];
  1528.                         $clientNames = [];
  1529.                         $productIds = [];
  1530.                         $productNames = [];
  1531.                         $get_sql "SELECT sum(sales_invoice_item.qty*sales_invoice_item.current_purchase_price) sales_amount, inv_products.id product_id, inv_products.name product_name, acc_clients.client_id, acc_clients.type
  1532.   FROM sales_invoice_item
  1533.   join sales_invoice on sales_invoice_item.sales_invoice_id=sales_invoice.sales_invoice_id
  1534.   join inv_products on sales_invoice_item.product_id=inv_products.id
  1535.   join acc_clients on acc_clients.client_id=sales_invoice.client_id
  1536.    WHERE sales_invoice.company_id=" $companyId " AND sales_invoice.approved=1
  1537.                           AND sales_invoice_date between '" $thisPeriodStartDate " 00:00:00' and '" $thisPeriodEndDate " 23:59:59.999'
  1538.                           GROUP BY sales_invoice_item.product_id
  1539.                           ORDER BY sales_amount DESC
  1540.                           LIMIT 10
  1541.                           ";
  1542.                         $stmt $em->getConnection()->prepare($get_sql);
  1543.                         $stmt->execute();
  1544.                         $entries $stmt->fetchAll();
  1545.                         $get_sql_1 $get_sql;
  1546.                         for ($k 0$k 10$k++) {
  1547.                             $has_payments 1;
  1548.                             if (!isset($entries[$k]))
  1549.                                 $entries[$k] = array(
  1550.                                     'sales_amount' => '',
  1551.                                     'product_name' => '',
  1552.                                     'client_name' => '',
  1553.                                 );
  1554.                             $has_payments 1;
  1555.                             $thisBalanceDataByRelId[$k] = $entries[$k];
  1556.                         }
  1557.                         $get_sql "SELECT sum(sales_invoice_item.qty*sales_invoice_item.current_purchase_price) sales_amount, inv_products.id product_id, inv_products.name product_name, acc_clients.client_id, acc_clients.type
  1558.   FROM sales_invoice_item
  1559.   join sales_invoice on sales_invoice_item.sales_invoice_id=sales_invoice.sales_invoice_id
  1560.   join inv_products on sales_invoice_item.product_id=inv_products.id
  1561.   join acc_clients on acc_clients.client_id=sales_invoice.client_id
  1562.    WHERE sales_invoice.company_id=" $companyId " AND sales_invoice.approved=1
  1563.                           AND sales_invoice_date between '" $lastPeriodStartDate " 00:00:00' and '" $lastPeriodEndDate " 23:59:59.999'
  1564.                           GROUP BY sales_invoice_item.product_id
  1565.                           ORDER BY sales_amount DESC
  1566.                           LIMIT 10
  1567.                           ";
  1568.                         $stmt $em->getConnection()->prepare($get_sql);
  1569.                         $stmt->execute();
  1570.                         $entries $stmt->fetchAll();
  1571.                         for ($k 0$k 10$k++) {
  1572.                             $has_payments 1;
  1573.                             if (!isset($entries[$k]))
  1574.                                 $entries[$k] = array(
  1575.                                     'sales_amount' => '',
  1576.                                     'product_name' => '',
  1577.                                     'client_name' => '',
  1578.                                 );
  1579.                             $lastBalanceDataByRelId[$k] = $entries[$k];
  1580.                         }
  1581.                         $skipHeadIds = [];
  1582.                         $thisReportData = array(
  1583.                             //                            'clientTypes' => $clientTypes,
  1584.                             ////                            'get_sql_1' => $get_sql_1,
  1585.                             ////                            'get_sql' => $get_sql,
  1586.                             //                            'clientTypeNames' => $clientTypeNames,
  1587.                             'thisBalanceDataByRelId' => $thisBalanceDataByRelId,
  1588.                             'lastBalanceDataByRelId' => $lastBalanceDataByRelId,
  1589.                         );
  1590.                         $data['top_selling_item_position'][$app_company_index] = $thisReportData;
  1591.                         //                    $companyListData[] = Company::getCompanyListWithImage($em);
  1592.                     }
  1593.                     //Top Products
  1594.                     if (in_array('top_selling_client_position'$reportsToGet)) {
  1595.                         $acHeadList = [];
  1596.                         $companyId explode('_'$app_company_index)[1];
  1597.                         $acHeadDataById = [];
  1598.                         $thisBalanceDataByRelId = [];
  1599.                         $lastBalanceDataByRelId = [];
  1600.                         $clientIds = [];
  1601.                         $clientNames = [];
  1602.                         $productIds = [];
  1603.                         $productNames = [];
  1604.                         $get_sql "SELECT sum(sales_invoice.invoice_amount) sales_amount,  acc_clients.client_id, acc_clients.client_name client_name
  1605.   FROM sales_invoice
  1606.   join acc_clients on acc_clients.client_id=sales_invoice.client_id
  1607.    WHERE sales_invoice.company_id=" $companyId " AND sales_invoice.approved=1
  1608.                           AND sales_invoice_date between '" $thisPeriodStartDate " 00:00:00' and '" $thisPeriodEndDate " 23:59:59.999'
  1609.                           GROUP BY sales_invoice.client_id
  1610.                           ORDER BY sales_amount DESC
  1611.                           LIMIT 10
  1612.                           ";
  1613.                         $stmt $em->getConnection()->prepare($get_sql);
  1614.                         $stmt->execute();
  1615.                         $entries $stmt->fetchAll();
  1616.                         $get_sql_1 $get_sql;
  1617.                         for ($k 0$k 10$k++) {
  1618.                             $has_payments 1;
  1619.                             if (!isset($entries[$k]))
  1620.                                 $entries[$k] = array(
  1621.                                     'sales_amount' => '',
  1622.                                     'product_name' => '',
  1623.                                     'client_name' => '',
  1624.                                 );
  1625.                             $has_payments 1;
  1626.                             $thisBalanceDataByRelId[$k] = $entries[$k];
  1627.                         }
  1628.                         $get_sql "SELECT sum(sales_invoice.invoice_amount) sales_amount,  acc_clients.client_id, acc_clients.client_name client_name
  1629.   FROM sales_invoice
  1630.   join acc_clients on acc_clients.client_id=sales_invoice.client_id
  1631.    WHERE sales_invoice.company_id=" $companyId " AND sales_invoice.approved=1
  1632.                           AND sales_invoice_date between '" $lastPeriodStartDate " 00:00:00' and '" $lastPeriodEndDate " 23:59:59.999'
  1633.                           GROUP BY sales_invoice.client_id
  1634.                           ORDER BY sales_amount DESC
  1635.                           LIMIT 10
  1636.                           ";
  1637.                         $stmt $em->getConnection()->prepare($get_sql);
  1638.                         $stmt->execute();
  1639.                         $entries $stmt->fetchAll();
  1640.                         for ($k 0$k 10$k++) {
  1641.                             $has_payments 1;
  1642.                             if (!isset($entries[$k]))
  1643.                                 $entries[$k] = array(
  1644.                                     'sales_amount' => '',
  1645.                                     'product_name' => '',
  1646.                                     'client_name' => '',
  1647.                                 );
  1648.                             $lastBalanceDataByRelId[$k] = $entries[$k];
  1649.                         }
  1650.                         $skipHeadIds = [];
  1651.                         $thisReportData = array(
  1652.                             //                            'clientTypes' => $clientTypes,
  1653.                             ////                            'get_sql_1' => $get_sql_1,
  1654.                             ////                            'get_sql' => $get_sql,
  1655.                             //                            'clientTypeNames' => $clientTypeNames,
  1656.                             'thisBalanceDataByRelId' => $thisBalanceDataByRelId,
  1657.                             'lastBalanceDataByRelId' => $lastBalanceDataByRelId,
  1658.                         );
  1659.                         $data['top_selling_client_position'][$app_company_index] = $thisReportData;
  1660.                         //                    $companyListData[] = Company::getCompanyListWithImage($em);
  1661.                     }
  1662.                 }
  1663.             }
  1664.         }
  1665.         return new JsonResponse(
  1666.             array(
  1667.                 'success' => true,
  1668.                 'data' => $data,
  1669.                 'companyListData' => $companyListData,
  1670.                 'dataToConnectList' => $dataToConnectList,
  1671.                 'periodType' => $periodType,
  1672.                 'queriedReportsToGet' => $request->request->get('reportsToGet'),
  1673.                 'reportsToGet' => $reportsToGet,
  1674.                 'thisPeriodStartDate' => $thisPeriodStartDate,
  1675.                 'thisPeriodEndDate' => $thisPeriodEndDate,
  1676.                 'lastPeriodStartDate' => $lastPeriodStartDate,
  1677.                 'lastPeriodEndDate' => $lastPeriodEndDate,
  1678.                 'companyIdListByAppId' => $companyIdListByAppId,
  1679.                 'companyNameListByAppId' => $companyNameListByAppId,
  1680.                 'companyImageListByAppId' => $companyImageListByAppId,
  1681.                 'appIdList' => $appIdList,
  1682.             )
  1683.         );
  1684.     }
  1685.     public function indexAction(Request $request$cgHash '')
  1686.     {
  1687.         $session $request->getSession();
  1688.         $systemType $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
  1689.         if ($systemType == '_ERP_') {
  1690.             //do nothing its default to dashboard index
  1691.         } else if ($systemType == '_BUDDYBEE_') {
  1692.             if ($cgHash != '')
  1693.                 $session->set('codeHash'$cgHash);
  1694.         }
  1695.         // Generic::debugMessage($session);
  1696.         $ROUTE_LIST json_decode($session->get(UserConstants::USER_ROUTE_LIST), true);
  1697.         if ($ROUTE_LIST == null)
  1698.             $ROUTE_LIST = [];
  1699.         $CurrentRoute $request->attributes->get('_route');
  1700.         if ($session->get(UserConstants::USER_ROUTE_LIST) == || in_array('management_dashboard'$ROUTE_LIST)) {
  1701.             // User is not authorized. send him to dashboard
  1702.             //                    $controller->addFlash(
  1703.             //                        'error',
  1704.             //                        'Sorry Couldnot insert Data.'
  1705.             //                    );
  1706.             //                    return $this->render('ApplicationBundle:pages/dashboard:advanced_management_dashboard.html.twig',
  1707.             if ($session->has('isMobile'))
  1708.                 if ($session->get('isMobile') == true) {
  1709.                     return $this->render(
  1710.                         'ApplicationBundle:pages/dashboard:index_finance_mobile.html.twig',
  1711.                         array(
  1712.                             'page_title' => 'Finance Dashboard',
  1713.                             'dashboardDataForUser' => []
  1714.                         )
  1715.                     );
  1716.                 }
  1717.             return $this->render(
  1718.                 'ApplicationBundle:pages/dashboard:advanced_management_dashboard.html.twig',
  1719.                 array(
  1720.                     'page_title' => 'Dashboard'
  1721.                 )
  1722.             );
  1723.         }
  1724.         if ($session->has('isMobile'))
  1725.             if ($session->get('isMobile') == true) {
  1726.                 if ($systemType == '_CENTRAL_') {
  1727.                     $defaultRoute 'central_landing';
  1728.                     return $this->redirectToRoute($defaultRoute);
  1729.                 }
  1730.                 elseif ($systemType == '_SOPHIA_') {
  1731.                     $defaultRoute 'sofia_dashboard_admin';
  1732.                     return $this->redirectToRoute($defaultRoute);
  1733.                 }else
  1734.                     return $this->render(
  1735.                         'ApplicationBundle:pages/dashboard:index_finance_mobile.html.twig',
  1736.                         array(
  1737.                             'page_title' => 'Finance Dashboard',
  1738.                             'dashboardDataForUser' => []
  1739.                         )
  1740.                     );
  1741.             }
  1742.         else {
  1743.                 //check if user has a default route if yes redirect to it
  1744.                 if ($session->get(UserConstants::USER_TYPE) == UserConstants::USER_TYPE_SUPPLIER)
  1745.                     $defaultRoute 'supplier_dashboard';
  1746.                 else if ($session->get(UserConstants::USER_TYPE) == UserConstants::USER_TYPE_CLIENT)
  1747.                     $defaultRoute 'client_dashboard';
  1748.                 else if ($session->get(UserConstants::USER_TYPE) == UserConstants::USER_TYPE_APPLICANT) {
  1749.                     if ($systemType == '_CENTRAL_') {
  1750.                         $defaultRoute 'central_landing';
  1751.                     }
  1752.                     elseif ($systemType == '_SOPHIA_') {
  1753.                         $defaultRoute 'sofia_dashboard_admin';
  1754.                     } else
  1755.                         $defaultRoute 'applicant_dashboard';
  1756.                 } else
  1757.                     $defaultRoute $session->get(UserConstants::USER_DEFAULT_ROUTE);
  1758.                 //            if(in_array($defaultRoute, $ROUTE_LIST))
  1759.                 if ($defaultRoute != '' && $defaultRoute != null)
  1760.                     return $this->redirectToRoute($defaultRoute);
  1761.                 else
  1762.                     return $this->render(
  1763.                         'ApplicationBundle:pages/dashboard:index.html.twig',
  1764.                         array(
  1765.                             'page_title' => 'Dashboard'
  1766.                         )
  1767.                     );
  1768.             }
  1769.     }
  1770.     public function indexSupplierAction(Request $request)
  1771.     {
  1772.         $session $request->getSession();
  1773.         $supplierId 3;
  1774.         if ($request->query->has('supplierId')) //for debug now
  1775.         {
  1776.             $session->set('supplierId'$request->query->get('supplierId'));
  1777.         }
  1778.         $supplierId $session->get('supplierId');  //////////////////////LATER
  1779.         $em $this->getDoctrine()->getManager();
  1780.         $companyId $this->getLoggedUserCompanyId($request);
  1781.         $userId $request->getSession()->get(UserConstants::USER_ID);
  1782.         $SD Supplier::GetSupplierProfileDetails($em$supplierId'SI');
  1783.         $dashboardDataForUser = [];
  1784.         return $this->render(
  1785.             'ApplicationBundle:pages/dashboard:index_supplier.html.twig',
  1786.             array(
  1787.                 'page_title' => 'Supplier Dashboard',
  1788.                 'dashboardDataForUser' => $dashboardDataForUser,
  1789.                 'data' => $SD,
  1790.                 'igList' => Inventory::ItemGroupList($em$companyId)
  1791.             )
  1792.         );
  1793.     }
  1794.     public function indexClientAction(Request $request)
  1795.     {
  1796.         $session $request->getSession();
  1797.         $clientId 3;
  1798.         if ($request->query->has('clientId')) //for debug now
  1799.         {
  1800.             $session->set('clientId'$request->query->get('clientId'));
  1801.         }
  1802.         $clientId $session->get('clientId');  //////////////////////LATER
  1803.         $em $this->getDoctrine()->getManager();
  1804.         $companyId $this->getLoggedUserCompanyId($request);
  1805.         $userId $request->getSession()->get(UserConstants::USER_ID);
  1806.         $SD Client::GetClientProfileDetails($em$clientId'CI');
  1807.         $dashboardDataForUser = [];
  1808.         return $this->render(
  1809.             'ApplicationBundle:pages/dashboard:index_client.html.twig',
  1810.             array(
  1811.                 'page_title' => 'Client Dashboard',
  1812.                 'dashboardDataForUser' => $dashboardDataForUser,
  1813.                 'data' => $SD,
  1814.                 'igList' => Inventory::ItemGroupList($em$companyId)
  1815.             )
  1816.         );
  1817.     }
  1818.     public function indexFinanceAction(Request $request)
  1819.     {
  1820.         $session $request->getSession();
  1821.         $dashboardDataForUser = [];
  1822.         $em $this->getDoctrine()->getManager();
  1823.         $companyId $this->getLoggedUserCompanyId($request);
  1824.         $userId $request->getSession()->get(UserConstants::USER_ID);
  1825.         $dbQuery $em->getRepository("ApplicationBundle:DashboardWidget")->findBy(
  1826.             array(
  1827.                 'CompanyId' => $companyId,
  1828.                 'userId' => $userId,
  1829.                 'status' => GeneralConstant::ACTIVE
  1830.             ),
  1831.             array(
  1832.                 'sequence' => 'ASC'
  1833.             )
  1834.         );
  1835.         if (empty($dbQuery))   ///now get the defaults
  1836.             $dbQuery $em->getRepository("ApplicationBundle:DashboardWidget")->findBy(
  1837.                 array(
  1838.                     'CompanyId' => $companyId,
  1839.                     //                    'userId'=>$userId,
  1840.                     'defaultBoxFlag' => 1,
  1841.                     'status' => GeneralConstant::ACTIVE
  1842.                 ),
  1843.                 array(
  1844.                     'sequence' => 'ASC'
  1845.                 )
  1846.             );
  1847.         foreach ($dbQuery as $entry) {
  1848.             $dashboardDataForUser[] = array(
  1849.                 'id' => $entry->getId(),
  1850.                 'widgetId' => $entry->getId(),
  1851.                 'widgetSequence' => $entry->getSequence(),
  1852.                 'widgetStatus' => $entry->getStatus(),
  1853.                 'widgetData' => json_decode($entry->getData(), true),
  1854.                 'defaultBoxFlag' => $entry->getDefaultBoxFlag(),
  1855.                 'widgetSizeTiny' => $entry->getSizeTiny(),
  1856.                 'widgetSizeSmall' => $entry->getSizeSmall(),
  1857.                 'widgetSizeMedium' => $entry->getSizeMedium(),
  1858.                 'widgetSizeLarge' => $entry->getSizeLarge(),
  1859.                 'refreshInterval' => $entry->getRefreshInterval(),
  1860.             );
  1861.         }
  1862.         if ($session->has('isMobile')) {
  1863.             if ($session->get('isMobile') == true) {
  1864.                 return $this->render(
  1865.                     'ApplicationBundle:pages/dashboard:index_finance_mobile.html.twig',
  1866.                     array(
  1867.                         'page_title' => 'Finance Dashboard',
  1868.                         'dashboardDataForUser' => $dashboardDataForUser
  1869.                     )
  1870.                 );
  1871.             } else {
  1872.             }
  1873.         }
  1874.         return $this->render(
  1875.             'ApplicationBundle:pages/dashboard:index_finance.html.twig',
  1876.             array(
  1877.                 'page_title' => 'Finance Dashboard',
  1878.                 'dashboardDataForUser' => $dashboardDataForUser
  1879.             )
  1880.         );
  1881.     }
  1882.     public function indexSalesAction(Request $request)
  1883.     {
  1884.         $session $request->getSession();
  1885.         $dashboardDataForUser = [];
  1886.         $em $this->getDoctrine()->getManager();
  1887.         $companyId $this->getLoggedUserCompanyId($request);
  1888.         $userId $request->getSession()->get(UserConstants::USER_ID);
  1889.         $dbQuery $em->getRepository("ApplicationBundle:DashboardWidget")->findBy(
  1890.             array(
  1891.                 'CompanyId' => $companyId,
  1892.                 'userId' => $userId,
  1893.                 'status' => GeneralConstant::ACTIVE
  1894.             ),
  1895.             array(
  1896.                 'sequence' => 'ASC'
  1897.             )
  1898.         );
  1899.         if (empty($dbQuery))   ///now get the defaults
  1900.             $dbQuery $em->getRepository("ApplicationBundle:DashboardWidget")->findBy(
  1901.                 array(
  1902.                     'CompanyId' => $companyId,
  1903.                     //                    'userId'=>$userId,
  1904.                     'defaultBoxFlag' => 1,
  1905.                     'status' => GeneralConstant::ACTIVE
  1906.                 ),
  1907.                 array(
  1908.                     'sequence' => 'ASC'
  1909.                 )
  1910.             );
  1911.         foreach ($dbQuery as $entry) {
  1912.             $dashboardDataForUser[] = array(
  1913.                 'id' => $entry->getId(),
  1914.                 'widgetId' => $entry->getId(),
  1915.                 'widgetSequence' => $entry->getSequence(),
  1916.                 'widgetStatus' => $entry->getStatus(),
  1917.                 'widgetData' => json_decode($entry->getData(), true),
  1918.                 'defaultBoxFlag' => $entry->getDefaultBoxFlag(),
  1919.                 'widgetSizeTiny' => $entry->getSizeTiny(),
  1920.                 'widgetSizeSmall' => $entry->getSizeSmall(),
  1921.                 'widgetSizeMedium' => $entry->getSizeMedium(),
  1922.                 'widgetSizeLarge' => $entry->getSizeLarge(),
  1923.                 'refreshInterval' => $entry->getRefreshInterval(),
  1924.             );
  1925.         }
  1926.         if ($session->has('isMobile')) {
  1927.             if ($session->get('isMobile') == true) {
  1928.                 return $this->render(
  1929.                     'ApplicationBundle:pages/dashboard:index_finance_mobile.html.twig',
  1930.                     array(
  1931.                         'page_title' => 'Finance Dashboard',
  1932.                         'dashboardDataForUser' => $dashboardDataForUser
  1933.                     )
  1934.                 );
  1935.             } else {
  1936.             }
  1937.         }
  1938.         return $this->render(
  1939.             'ApplicationBundle:pages/dashboard:index_sales.html.twig',
  1940.             array(
  1941.                 'page_title' => 'Sales Dashboard',
  1942.                 'dashboardDataForUser' => $dashboardDataForUser
  1943.             )
  1944.         );
  1945.     }
  1946.     public function indexPurchaseAction(Request $request)
  1947.     {
  1948.         $session $request->getSession();
  1949.         $dashboardDataForUser = [];
  1950.         $em $this->getDoctrine()->getManager();
  1951.         $companyId $this->getLoggedUserCompanyId($request);
  1952.         $userId $request->getSession()->get(UserConstants::USER_ID);
  1953.         $dbQuery $em->getRepository("ApplicationBundle:DashboardWidget")->findBy(
  1954.             array(
  1955.                 'CompanyId' => $companyId,
  1956.                 'userId' => $userId,
  1957.                 'status' => GeneralConstant::ACTIVE
  1958.             ),
  1959.             array(
  1960.                 'sequence' => 'ASC'
  1961.             )
  1962.         );
  1963.         if (empty($dbQuery))   ///now get the defaults
  1964.             $dbQuery $em->getRepository("ApplicationBundle:DashboardWidget")->findBy(
  1965.                 array(
  1966.                     'CompanyId' => $companyId,
  1967.                     //                    'userId'=>$userId,
  1968.                     'defaultBoxFlag' => 1,
  1969.                     'status' => GeneralConstant::ACTIVE
  1970.                 ),
  1971.                 array(
  1972.                     'sequence' => 'ASC'
  1973.                 )
  1974.             );
  1975.         foreach ($dbQuery as $entry) {
  1976.             $dashboardDataForUser[] = array(
  1977.                 'id' => $entry->getId(),
  1978.                 'widgetId' => $entry->getId(),
  1979.                 'widgetSequence' => $entry->getSequence(),
  1980.                 'widgetStatus' => $entry->getStatus(),
  1981.                 'widgetData' => json_decode($entry->getData(), true),
  1982.                 'defaultBoxFlag' => $entry->getDefaultBoxFlag(),
  1983.                 'widgetSizeTiny' => $entry->getSizeTiny(),
  1984.                 'widgetSizeSmall' => $entry->getSizeSmall(),
  1985.                 'widgetSizeMedium' => $entry->getSizeMedium(),
  1986.                 'widgetSizeLarge' => $entry->getSizeLarge(),
  1987.                 'refreshInterval' => $entry->getRefreshInterval(),
  1988.             );
  1989.         }
  1990.         return $this->render(
  1991.             'ApplicationBundle:pages/dashboard:index_sales.html.twig',
  1992.             array(
  1993.                 'page_title' => 'Sales Dashboard',
  1994.                 'dashboardDataForUser' => $dashboardDataForUser
  1995.             )
  1996.         );
  1997.     }
  1998.     public function indexDistributionAction(Request $request)
  1999.     {
  2000.         $session $request->getSession();
  2001.         $dashboardDataForUser = [];
  2002.         $em $this->getDoctrine()->getManager();
  2003.         $companyId $this->getLoggedUserCompanyId($request);
  2004.         $userId $request->getSession()->get(UserConstants::USER_ID);
  2005.         $dbQuery $em->getRepository("ApplicationBundle:DashboardWidget")->findBy(
  2006.             array(
  2007.                 'CompanyId' => $companyId,
  2008.                 'userId' => $userId,
  2009.                 'status' => GeneralConstant::ACTIVE
  2010.             ),
  2011.             array(
  2012.                 'sequence' => 'ASC'
  2013.             )
  2014.         );
  2015.         if (empty($dbQuery))   ///now get the defaults
  2016.             $dbQuery $em->getRepository("ApplicationBundle:DashboardWidget")->findBy(
  2017.                 array(
  2018.                     'CompanyId' => $companyId,
  2019.                     //                    'userId'=>$userId,
  2020.                     'defaultBoxFlag' => 1,
  2021.                     'status' => GeneralConstant::ACTIVE
  2022.                 ),
  2023.                 array(
  2024.                     'sequence' => 'ASC'
  2025.                 )
  2026.             );
  2027.         foreach ($dbQuery as $entry) {
  2028.             $dashboardDataForUser[] = array(
  2029.                 'id' => $entry->getId(),
  2030.                 'widgetId' => $entry->getId(),
  2031.                 'widgetSequence' => $entry->getSequence(),
  2032.                 'widgetStatus' => $entry->getStatus(),
  2033.                 'widgetData' => json_decode($entry->getData(), true),
  2034.                 'defaultBoxFlag' => $entry->getDefaultBoxFlag(),
  2035.                 'widgetSizeTiny' => $entry->getSizeTiny(),
  2036.                 'widgetSizeSmall' => $entry->getSizeSmall(),
  2037.                 'widgetSizeMedium' => $entry->getSizeMedium(),
  2038.                 'widgetSizeLarge' => $entry->getSizeLarge(),
  2039.                 'refreshInterval' => $entry->getRefreshInterval(),
  2040.             );
  2041.         }
  2042.         return $this->render(
  2043.             'ApplicationBundle:pages/dashboard:index_sales.html.twig',
  2044.             array(
  2045.                 'page_title' => 'Sales Dashboard',
  2046.                 'dashboardDataForUser' => $dashboardDataForUser
  2047.             )
  2048.         );
  2049.     }
  2050.     public function indexProductionAction(Request $request)
  2051.     {
  2052.         $session $request->getSession();
  2053.         $dashboardDataForUser = [];
  2054.         $em $this->getDoctrine()->getManager();
  2055.         $companyId $this->getLoggedUserCompanyId($request);
  2056.         $userId $request->getSession()->get(UserConstants::USER_ID);
  2057.         $dbQuery $em->getRepository("ApplicationBundle:DashboardWidget")->findBy(
  2058.             array(
  2059.                 'CompanyId' => $companyId,
  2060.                 'userId' => $userId,
  2061.                 'status' => GeneralConstant::ACTIVE
  2062.             ),
  2063.             array(
  2064.                 'sequence' => 'ASC'
  2065.             )
  2066.         );
  2067.         if (empty($dbQuery))   ///now get the defaults
  2068.             $dbQuery $em->getRepository("ApplicationBundle:DashboardWidget")->findBy(
  2069.                 array(
  2070.                     'CompanyId' => $companyId,
  2071.                     //                    'userId'=>$userId,
  2072.                     'defaultBoxFlag' => 1,
  2073.                     'status' => GeneralConstant::ACTIVE
  2074.                 ),
  2075.                 array(
  2076.                     'sequence' => 'ASC'
  2077.                 )
  2078.             );
  2079.         foreach ($dbQuery as $entry) {
  2080.             $dashboardDataForUser[] = array(
  2081.                 'id' => $entry->getId(),
  2082.                 'widgetId' => $entry->getId(),
  2083.                 'widgetSequence' => $entry->getSequence(),
  2084.                 'widgetStatus' => $entry->getStatus(),
  2085.                 'widgetData' => json_decode($entry->getData(), true),
  2086.                 'defaultBoxFlag' => $entry->getDefaultBoxFlag(),
  2087.                 'widgetSizeTiny' => $entry->getSizeTiny(),
  2088.                 'widgetSizeSmall' => $entry->getSizeSmall(),
  2089.                 'widgetSizeMedium' => $entry->getSizeMedium(),
  2090.                 'widgetSizeLarge' => $entry->getSizeLarge(),
  2091.                 'refreshInterval' => $entry->getRefreshInterval(),
  2092.             );
  2093.         }
  2094.         return $this->render(
  2095.             'ApplicationBundle:pages/dashboard:index_sales.html.twig',
  2096.             array(
  2097.                 'page_title' => 'Sales Dashboard',
  2098.                 'dashboardDataForUser' => $dashboardDataForUser
  2099.             )
  2100.         );
  2101.     }
  2102.     public function indexInventoryAction(Request $request)
  2103.     {
  2104.         $session $request->getSession();
  2105.         $dashboardDataForUser = [];
  2106.         $em $this->getDoctrine()->getManager();
  2107.         $companyId $this->getLoggedUserCompanyId($request);
  2108.         $userId $request->getSession()->get(UserConstants::USER_ID);
  2109.         $dbQuery $em->getRepository("ApplicationBundle:DashboardWidget")->findBy(
  2110.             array(
  2111.                 'CompanyId' => $companyId,
  2112.                 'userId' => $userId,
  2113.                 'status' => GeneralConstant::ACTIVE
  2114.             ),
  2115.             array(
  2116.                 'sequence' => 'ASC'
  2117.             )
  2118.         );
  2119.         if (empty($dbQuery))   ///now get the defaults
  2120.             $dbQuery $em->getRepository("ApplicationBundle:DashboardWidget")->findBy(
  2121.                 array(
  2122.                     'CompanyId' => $companyId,
  2123.                     //                    'userId'=>$userId,
  2124.                     'defaultBoxFlag' => 1,
  2125.                     'status' => GeneralConstant::ACTIVE
  2126.                 ),
  2127.                 array(
  2128.                     'sequence' => 'ASC'
  2129.                 )
  2130.             );
  2131.         foreach ($dbQuery as $entry) {
  2132.             $dashboardDataForUser[] = array(
  2133.                 'id' => $entry->getId(),
  2134.                 'widgetId' => $entry->getId(),
  2135.                 'widgetSequence' => $entry->getSequence(),
  2136.                 'widgetStatus' => $entry->getStatus(),
  2137.                 'widgetData' => json_decode($entry->getData(), true),
  2138.                 'defaultBoxFlag' => $entry->getDefaultBoxFlag(),
  2139.                 'widgetSizeTiny' => $entry->getSizeTiny(),
  2140.                 'widgetSizeSmall' => $entry->getSizeSmall(),
  2141.                 'widgetSizeMedium' => $entry->getSizeMedium(),
  2142.                 'widgetSizeLarge' => $entry->getSizeLarge(),
  2143.                 'refreshInterval' => $entry->getRefreshInterval(),
  2144.             );
  2145.         }
  2146.         return $this->render(
  2147.             'ApplicationBundle:pages/dashboard:index_sales.html.twig',
  2148.             array(
  2149.                 'page_title' => 'Sales Dashboard',
  2150.                 'dashboardDataForUser' => $dashboardDataForUser
  2151.             )
  2152.         );
  2153.     }
  2154.     public function indexServiceAction(Request $request)
  2155.     {
  2156.         $session $request->getSession();
  2157.         $dashboardDataForUser = [];
  2158.         $em $this->getDoctrine()->getManager();
  2159.         $companyId $this->getLoggedUserCompanyId($request);
  2160.         $userId $request->getSession()->get(UserConstants::USER_ID);
  2161.         $dbQuery $em->getRepository("ApplicationBundle:DashboardWidget")->findBy(
  2162.             array(
  2163.                 'CompanyId' => $companyId,
  2164.                 'userId' => $userId,
  2165.                 'status' => GeneralConstant::ACTIVE
  2166.             ),
  2167.             array(
  2168.                 'sequence' => 'ASC'
  2169.             )
  2170.         );
  2171.         if (empty($dbQuery))   ///now get the defaults
  2172.             $dbQuery $em->getRepository("ApplicationBundle:DashboardWidget")->findBy(
  2173.                 array(
  2174.                     'CompanyId' => $companyId,
  2175.                     //                    'userId'=>$userId,
  2176.                     'defaultBoxFlag' => 1,
  2177.                     'status' => GeneralConstant::ACTIVE
  2178.                 ),
  2179.                 array(
  2180.                     'sequence' => 'ASC'
  2181.                 )
  2182.             );
  2183.         foreach ($dbQuery as $entry) {
  2184.             $dashboardDataForUser[] = array(
  2185.                 'id' => $entry->getId(),
  2186.                 'widgetId' => $entry->getId(),
  2187.                 'widgetSequence' => $entry->getSequence(),
  2188.                 'widgetStatus' => $entry->getStatus(),
  2189.                 'widgetData' => json_decode($entry->getData(), true),
  2190.                 'defaultBoxFlag' => $entry->getDefaultBoxFlag(),
  2191.                 'widgetSizeTiny' => $entry->getSizeTiny(),
  2192.                 'widgetSizeSmall' => $entry->getSizeSmall(),
  2193.                 'widgetSizeMedium' => $entry->getSizeMedium(),
  2194.                 'widgetSizeLarge' => $entry->getSizeLarge(),
  2195.                 'refreshInterval' => $entry->getRefreshInterval(),
  2196.             );
  2197.         }
  2198.         return $this->render(
  2199.             'ApplicationBundle:pages/dashboard:index_sales.html.twig',
  2200.             array(
  2201.                 'page_title' => 'Sales Dashboard',
  2202.                 'dashboardDataForUser' => $dashboardDataForUser
  2203.             )
  2204.         );
  2205.     }
  2206.     public function modifyDashboardAction(Request $request)
  2207.     {
  2208.         $session $request->getSession();
  2209.         $em $this->getDoctrine()->getManager();
  2210.         $companyId $this->getLoggedUserCompanyId($request);
  2211.         $userId $request->getSession()->get(UserConstants::USER_ID);
  2212.         if ($request->isMethod('post')) {
  2213.             //update dashboard data
  2214.             if ($request->request->has('widgetId')) {
  2215.                 foreach ($request->request->get('widgetId') as $k => $v) {
  2216.                     if ($v != 0) {
  2217.                         //exists sso edit
  2218.                         $widget $em->getRepository("ApplicationBundle:DashboardWidget")->findOneBy(
  2219.                             array(
  2220.                                 'id' => $v,
  2221.                             )
  2222.                         );
  2223.                     } else
  2224.                         $widget = new DashboardWidget();
  2225.                     $widget->setData($request->request->get('widgetData')[$k]);
  2226.                     $widget->setSequence($request->request->get('widgetSequence')[$k]);
  2227.                     $widget->setStatus($request->request->has('widgetStatus') ? $request->request->get('widgetStatus')[$k] : GeneralConstant::ACTIVE);
  2228.                     $widget->setUserId($userId);
  2229.                     $widget->setCompanyId($companyId);
  2230.                     $widget->setDefaultBoxFlag($request->request->has('defaultBoxFlag') ? $request->request->get('defaultBoxFlag')[$k] : 0);
  2231.                     if ($v == 0)
  2232.                         $em->persist($widget);
  2233.                     $em->flush();
  2234.                 }
  2235.             }
  2236.         }
  2237.         $dashboardDataForUser = [];
  2238.         $dbQuery $em->getRepository("ApplicationBundle:DashboardWidget")->findBy(
  2239.             array(
  2240.                 'CompanyId' => $companyId,
  2241.                 'userId' => $userId,
  2242.                 'status' => GeneralConstant::ACTIVE
  2243.             )
  2244.         );
  2245.         if (empty($dbQuery))   ///now get the defaults
  2246.             $dbQuery $em->getRepository("ApplicationBundle:DashboardWidget")->findBy(
  2247.                 array(
  2248.                     'CompanyId' => $companyId,
  2249.                     //                    'userId'=>$userId,
  2250.                     'defaultBoxFlag' => 1,
  2251.                     'status' => GeneralConstant::ACTIVE
  2252.                 )
  2253.             );
  2254.         foreach ($dbQuery as $entry) {
  2255.             $dashboardDataForUser[] = array(
  2256.                 'id' => $entry->getId(),
  2257.                 'widgetId' => $entry->getId(),
  2258.                 'widgetSequence' => $entry->getSequence(),
  2259.                 'widgetStatus' => $entry->getStatus(),
  2260.                 'widgetData' => $entry->getData(),
  2261.                 'defaultBoxFlag' => $entry->getDefaultBoxFlag(),
  2262.                 'widgetSizeTiny' => $entry->getSizeTiny(),
  2263.                 'widgetSizeSmall' => $entry->getSizeSmall(),
  2264.                 'widgetSizeMedium' => $entry->getSizeMedium(),
  2265.                 'widgetSizeLarge' => $entry->getSizeLarge(),
  2266.                 'refreshInterval' => $entry->getRefreshInterval(),
  2267.             );
  2268.         }
  2269.         //1st try to see if any exists
  2270.         return $this->render(
  2271.             'ApplicationBundle:pages/dashboard:index_sales.html.twig',
  2272.             array(
  2273.                 'page_title' => 'Modify Dashboard'
  2274.             )
  2275.         );
  2276.     }
  2277.     public function ChangeCompanyDashboardAction(Request $request$id 1)
  2278.     {
  2279.         $session $request->getSession();
  2280.         if ($request->query->has('sys_admin_panel'))
  2281.             return $this->redirectToRoute('system_admin_dashboard');
  2282.         else {
  2283.             $session->set(UserConstants::USER_COMPANY_ID$id);
  2284.             return $this->redirectToRoute('dashboard');
  2285.         }
  2286.     }
  2287.     public function ChangeLeftPanelDisplayStatusAction(Request $request)
  2288.     {
  2289.         $session $request->getSession();
  2290.         $curr_status 1;
  2291.         if ($session->has('HIDE_LEFT_PANEL'))
  2292.             $curr_status $session->get('HIDE_LEFT_PANEL');
  2293.         if ($curr_status == 1)
  2294.             $curr_status 0;
  2295.         else
  2296.             $curr_status 1;
  2297.         $session->set('HIDE_LEFT_PANEL'$curr_status);
  2298.         //            return $this->redirectToRoute('dashboard');
  2299.         return new Response($curr_status);
  2300.     }
  2301.     public function PermissionDeniedAction(Request $request)
  2302.     {
  2303.         $session $request->getSession();
  2304.         // Generic::debugMessage($session);
  2305.         return $this->render(
  2306.             '@System/pages/permission_denied.html.twig',
  2307.             array(
  2308.                 'page_title' => 'Permission Denied'
  2309.             )
  2310.         );
  2311.     }
  2312.     public function MyDocumentsAction(Request $request)
  2313.     {
  2314.         $session $request->getSession();
  2315.         $em $this->getDoctrine()->getManager();
  2316.         $data MiscActions::getDocumentsByUserId($em$session->get(UserConstants::USER_ID));
  2317.         // Generic::debugMessage($session);
  2318.         return $this->render(
  2319.             'ApplicationBundle:pages/dashboard:my_documents.html.twig',
  2320.             array(
  2321.                 'page_title' => 'My Documents',
  2322.                 'data' => $data
  2323.             )
  2324.         );
  2325.     }
  2326.     //     public function MyDocumentsListForAppAction(Request $request)
  2327.     //     {
  2328.     //         $session = $request->getSession();
  2329.     //         $em = $this->getDoctrine()->getManager();
  2330.     //         $absoluteUrlList = [];
  2331.     //         foreach (GeneralConstant::$Entity_list_details as $e => $d) {
  2332.     //             if (isset($d['entity_print_route_path_name']))
  2333.     //                 $absoluteUrlList[$e] = $this->generateUrl($d['entity_print_route_path_name'], [], UrlGenerator::ABSOLUTE_URL);
  2334.     //         }
  2335.     //         $data = MiscActions::getDocumentsByUserIdForApp($em, $session->get(UserConstants::USER_ID), 1, $absoluteUrlList);
  2336.     //         // Generic::debugMessage($session);
  2337.     //         return new JsonResponse(array(
  2338.     //             'data' => $data
  2339.     //         ));
  2340.     // //        return $this->render('ApplicationBundle:pages/dashboard:my_documents.html.twig',
  2341.     // //            array(
  2342.     // //                'page_title' => 'My Documents',
  2343.     // //                'data' => $data
  2344.     // //            )
  2345.     // //        );
  2346.     //     }
  2347.     public function MyDocumentsListForAppAction(Request $request)
  2348.     {
  2349.         $session $request->getSession();
  2350.         $em $this->getDoctrine()->getManager();
  2351.         // Build absolute URL list
  2352.         $absoluteUrlList = [];
  2353.         foreach (GeneralConstant::$Entity_list_details as $e => $d) {
  2354.             if (isset($d['entity_print_route_path_name'])) {
  2355.                 $absoluteUrlList[$e] = $this->generateUrl($d['entity_print_route_path_name'], [], UrlGenerator::ABSOLUTE_URL);
  2356.             }
  2357.         }
  2358.         // Extract pagination parameters from the request
  2359.         $page $request->query->get('page''_UNSET_');
  2360.         $offset $request->query->get('offset'0);
  2361.         $limit $request->query->get('limit'10); // default limit is 10
  2362.         // Call the document list method with pagination
  2363.         return new JsonResponse(
  2364.             MiscActions::getDocumentsByUserIdForApp(
  2365.                 $em,
  2366.                 $session->get(UserConstants::USER_ID),
  2367.                 1,
  2368.                 $absoluteUrlList,
  2369.                 $page,
  2370.                 $offset,
  2371.                 $limit
  2372.             )
  2373.         );
  2374.     }
  2375.     public function ShowExceptionAction(Request $requestFlattenException $exceptionDebugLoggerInterface $logger null)
  2376.     {
  2377.         $session $request->getSession();
  2378.         $em $this->getDoctrine()->getManager();
  2379.         // Generic::debugMessage($session);
  2380.         //        $currentContent = $this->getAndCleanOutputBuffering($request->headers->get('X-Php-Ob-Level', -1));
  2381.         //        $showException = $request->attributes->get('showException', $this->debug); // As opposed to an additional parameter, this maintains BC
  2382.         $code $exception->getStatusCode();
  2383.         //        $data = MiscActions::getDocumentsByUserId($em, $session->get(UserConstants::USER_ID));
  2384.         return $this->render(
  2385.             'ApplicationBundle:pages/error:error_' $code '.html.twig',
  2386.             array(
  2387.                 'page_title' => 'Sorry',
  2388.                 //                'data' => $data
  2389.             )
  2390.         );
  2391.     }
  2392.     public function NotificationAction(Request $request)
  2393.     {
  2394.         $session $request->getSession();
  2395.         //'error', 'success', 'alert', 'information', 'warning', 'confirm'
  2396.         $themes = array(
  2397.             'error' => 'bg-red',
  2398.             'success' => 'bg-green',
  2399.             'alert' => 'bg-purple',
  2400.             'information' => 'bg-grey',
  2401.             'warning' => 'bg-orange',
  2402.             'confirm' => 'bg-blue',
  2403.         );
  2404.         $fa = array(
  2405.             'error' => 'fa fa-ban',
  2406.             'success' => 'fa fa-check',
  2407.             'alert' => 'fa fa-envelope',
  2408.             'information' => 'fa fa-comments',
  2409.             'warning' => 'fa fa-warning',
  2410.             'confirm' => 'fa fa-crosshairs',
  2411.         );
  2412.         // Generic::debugMessage($session);
  2413.         return $this->render(
  2414.             'ApplicationBundle:pages/dashboard:notification.html.twig',
  2415.             array(
  2416.                 'page_title' => 'Notifications',
  2417.                 'dt' => json_decode(System::GetAllNotification(
  2418.                     $this->container->getParameter('notification_enabled'),
  2419.                     $this->container->getParameter('notification_server'),
  2420.                     $request->getSession()->get(UserConstants::USER_ID),
  2421.                     $request->getSession()->get(UserConstants::USER_APP_ID),
  2422.                     $request->getSession()->get(UserConstants::USER_COMPANY_ID)
  2423.                 ), true),
  2424.                 //                'dt'=>System::GetAllNotification(
  2425.                 //                    $this->container->getParameter('notification_enabled'),
  2426.                 //                    $request->getSession()->get(UserConstants::USER_ID),
  2427.                 //                    $request->getSession()->get(UserConstants::USER_APP_ID),
  2428.                 //                    $request->getSession()->get(UserConstants::USER_COMPANY_ID)
  2429.                 //                ),
  2430.                 'themes' => $themes,
  2431.                 'fa' => $fa,
  2432.                 't' => curl_init()
  2433.             )
  2434.         );
  2435.     }
  2436.     public function EditAccountAction(Request $request)
  2437.     {
  2438.         $session $request->getSession();
  2439.         //'error', 'success', 'alert', 'information', 'warning', 'confirm'
  2440.         $themes = array(
  2441.             'error' => 'bg-red',
  2442.             'success' => 'bg-green',
  2443.             'alert' => 'bg-purple',
  2444.             'information' => 'bg-aqua',
  2445.             'warning' => 'bg-orange',
  2446.             'confirm' => 'bg-blue',
  2447.         );
  2448.         $fa = array(
  2449.             'error' => 'fa fa-ban',
  2450.             'success' => 'fa fa-check',
  2451.             'alert' => 'fa fa-envelope',
  2452.             'information' => 'fa fa-comments',
  2453.             'warning' => 'fa fa-warning',
  2454.             'confirm' => 'fa fa-crosshairs',
  2455.         );
  2456.         $em $this->getDoctrine()->getManager();
  2457.         $g_path '';
  2458.         if ($request->isMethod('POST')) {
  2459.             $post $request->request;
  2460.             $path "";
  2461.             foreach ($request->files as $uploadedFile) {
  2462.                 if ($uploadedFile != null) {
  2463.                     $fileName md5(uniqid()) . '.' $uploadedFile->guessExtension();
  2464.                     $path $fileName;
  2465.                     $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/FileUploads/' $request->request->get('userId') . '/';
  2466.                     if (!file_exists($upl_dir)) {
  2467.                         mkdir($upl_dir0777true);
  2468.                     }
  2469.                     $file $uploadedFile->move($upl_dir$path);
  2470.                 }
  2471.             }
  2472.             if ($path != "")
  2473.                 $file_path 'uploads/FileUploads/' $request->request->get('userId') . '/' $path;
  2474.             $g_path $this->container->getParameter('kernel.root_dir') . '/../web/uploads/FileUploads/' $request->request->get('userId') . '/' $path;
  2475.             //            $img_file = file_get_contents($g_path);
  2476.             //            $image_data=base64_encode($img_file);
  2477.             //            $encoded_data=System::encryptSignature($image_data,$request->request->get('approvalHash'));
  2478.             $query_here $this->getDoctrine()
  2479.                 ->getRepository('ApplicationBundle:SysUser')
  2480.                 ->findOneBy(
  2481.                     array('userId' => $request->request->get('userId'))
  2482.                 );
  2483.             if ($query_here) {
  2484.                 $new $query_here;
  2485.                 if ($path != "") {
  2486.                     if ($request->request->has('check_pp')) {
  2487.                         $new->setImage($file_path);
  2488.                         $session->set(UserConstants::USER_IMAGE$new->getImage());
  2489.                     } else
  2490.                         $new->setImage('');
  2491.                 }
  2492.                 $new->setName($request->request->get('name'));
  2493.                 $session->set(UserConstants::USER_NAME$request->request->get('name'));
  2494.                 //now password
  2495.                 if ($request->request->get('oldPass') != '') {
  2496.                     //1st check if old pass valid
  2497.                     if (!$this->container->get('sha256salted_encoder')->isPasswordValid($new->getPassword(), $request->request->get('oldPass'), $new->getSalt())) {
  2498.                         $this->addFlash(
  2499.                             'error',
  2500.                             'Your Old Password Was Wrong'
  2501.                         );
  2502.                     } else {
  2503.                         //old pass valid so now check if neww passes matches
  2504.                         if ($request->request->get('newPass') == $request->request->get('newPassAgain')) {
  2505.                             $new->setSalt(uniqid(mt_rand()));
  2506.                             $password $this->container->get('sha256salted_encoder')->encodePassword($request->request->get('newPass'), $new->getSalt());
  2507.                             $new->setPassword($password);
  2508.                             $em->flush();
  2509.                         } else {
  2510.                             $this->addFlash(
  2511.                                 'error',
  2512.                                 'Passwords Did not Match'
  2513.                             );
  2514.                         }
  2515.                     }
  2516.                 }
  2517.             } else {
  2518.                 //                    $new=new EncryptedSignature();
  2519.                 //                    $new->setData($encoded_data);
  2520.                 //                    $new->setUserId($request->request->get('userId'));
  2521.                 //                    $em->persist($new);
  2522.             }
  2523.             $em->flush();
  2524.             //            now deleting the file
  2525.         }
  2526.         $user_data Users::getUserInfoByLoginId($em$this->getLoggedUserLoginId($request));
  2527.         // Generic::debugMessage($session);
  2528.         return $this->render(
  2529.             '@System/pages/settings/edit_account.html.twig',
  2530.             array(
  2531.                 'page_title' => 'Edit Account',
  2532.                 'user_data' => $user_data,
  2533.                 //                'dt'=>json_decode(System::GetAllNotification($request->getSession()->get(UserConstants::USER_ID)),true),
  2534.                 'themes' => $themes,
  2535.                 'fa' => $fa,
  2536.             )
  2537.         );
  2538.     }
  2539.     public function indexApplicantAction(Request $request)
  2540.     {
  2541.         $systemType $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
  2542.         $twig_file 'ApplicationBundle:pages/login:applicant_login.html.twig';
  2543.         $session $request->getSession();
  2544.         if ($systemType == '_BUDDYBEE_') {
  2545.             if ($session->get('buddybeeAdminLevel'0) > 1)
  2546.                 return $this->redirectToRoute("buddybee_admin_dashboard", []);
  2547.             elseif ($session->get('isConsultant') == 1)
  2548.                 return $this->redirectToRoute("consultant_dashboard", []);
  2549.             else
  2550.                 return $this->redirectToRoute("student_dashboard", []);
  2551.         } elseif ($systemType == '_CENTRAL_') {
  2552.             return $this->render(
  2553.                 'ApplicationBundle:pages/dashboard:index_applicant.html.twig',
  2554.                 array(
  2555.                     'page_title' => 'Applicant Dashboard'
  2556.                 )
  2557.             );
  2558.         } else
  2559.             return $this->render(
  2560.                 'ApplicationBundle:pages/dashboard:consultant_dashboard.html.twig',
  2561.                 array(
  2562.                     'page_title' => 'Applicant Dashboard'
  2563.                 )
  2564.             );
  2565.     }
  2566.     public function indexCentralLandingAction(Request $request)
  2567.     {
  2568.         $session $request->getSession();
  2569.         $userAccessList $session->get('userAccessList', []);
  2570.         $companyNames array_map(function ($company) {
  2571.             return $company['companyName'];
  2572.         }, $userAccessList);
  2573.         if ($request->isMethod('POST')) {
  2574.             $employeeId $request->request->get('employee_id');
  2575.             $companyName $request->request->get('company_name');
  2576.             if ($employeeId && $companyName) {
  2577.                 return new JsonResponse([
  2578.                     'status' => 'success',
  2579.                     'message' => 'Data received successfully',
  2580.                     'employee_id' => $employeeId,
  2581.                     'company_name' => $companyName,
  2582.                 ]);
  2583.             } else {
  2584.                 return new JsonResponse([
  2585.                     'status' => 'error',
  2586.                     'message' => 'Employee ID or Company Name is missing',
  2587.                 ]);
  2588.             }
  2589.         }
  2590.         // If the request is not a POST request, render the normal page
  2591.         return $this->render(
  2592.             'ApplicationBundle:pages/dashboard:index_central_landing.html.twig',
  2593.             [
  2594.                 'page_title' => 'Central Landing',
  2595.                 'companyNames' => $companyNames
  2596.             ]
  2597.         );
  2598.     }
  2599.     public function HummanResourceAction()
  2600.     {
  2601.         $em $this->getDoctrine()->getManager();
  2602.         $currentTime = new \Datetime();
  2603.         $currDate $currentTime->format('Y-m-d');
  2604.         $queryBuilder $em->createQueryBuilder();
  2605.         $queryBuilder->select('A.employeeId''A.entry''A.lastIn''A.lastOut''A.currentLocation','A.createdAt''E.name','E.image','D.positionName')
  2606.             ->from('ApplicationBundle:EmployeeAttendance''A')
  2607.             ->where('A.createdAt >=  :date')
  2608.             ->andWhere('A.createdAt <=  :date_end')
  2609.             ->leftJoin('ApplicationBundle:Employee''E''WITH''A.employeeId = E.employeeId')
  2610.             ->leftJoin('ApplicationBundle:SysDepartmentPosition''D''WITH''E.positionId = D.positionId')
  2611.             ->setParameter('date'$currDate)
  2612.             ->setParameter('date_end'$currDate ' 23:59:59')
  2613.             ->orderBy('A.createdAt''DESC'// latest records first
  2614.             ->setMaxResults(5); // limit to 5 records
  2615.         $data $queryBuilder->getQuery()->getResult();
  2616.         $formattedData array_map(function($item) {
  2617.             return [
  2618.                 'employeeId' => $item['employeeId'],
  2619.                 'entry' => $item['entry'] ? $item['entry']->format('Y-m-d H:i:s') : null,
  2620.                 'lastIn' => $item['lastIn'] ? $item['lastIn']->format('Y-m-d H:i:s') : null,
  2621.                 'lastOut' => $item['lastOut'] ? $item['lastOut']->format('Y-m-d H:i:s') : null,
  2622.                 'currentLocation' => $item['currentLocation'],
  2623.                 'createdAt' => $item['createdAt'] ? $item['createdAt']->format('Y-m-d H:i:s') : null,
  2624.                 'name' => $item['name'],
  2625.                 'image' => $item['image'],
  2626.                 'positionName' => $item['positionName'],
  2627.             ];
  2628.         }, $data);
  2629.         $totalEmployees $em->getRepository('ApplicationBundle:EmployeeDetails')
  2630.             ->createQueryBuilder('E')
  2631.             ->select('COUNT(E.emp_status)')
  2632.             ->where('E.emp_status = 1')
  2633.             ->getQuery()
  2634.             ->getSingleScalarResult();
  2635.         $maleCount $em->getRepository('ApplicationBundle:EmployeeDetails')
  2636.             ->createQueryBuilder('E')
  2637.             ->select('COUNT(E.id)')
  2638.             ->where('E.sex = 1')
  2639.             ->getQuery()
  2640.             ->getSingleScalarResult();
  2641.         $femaleCount $em->getRepository('ApplicationBundle:EmployeeDetails')
  2642.             ->createQueryBuilder('E')
  2643.             ->select('COUNT(E.id)')
  2644.             ->where('E.sex = 2')
  2645.             ->getQuery()
  2646.             ->getSingleScalarResult();
  2647.         $fullTime $em->getRepository('ApplicationBundle:EmployeeDetails')
  2648.             ->createQueryBuilder('E')
  2649.             ->select('COUNT(E.id)')
  2650.             ->where('E.empType = 1')
  2651.             ->getQuery()
  2652.             ->getSingleScalarResult();
  2653.         $partTime $em->getRepository('ApplicationBundle:EmployeeDetails')
  2654.             ->createQueryBuilder('E')
  2655.             ->select('COUNT(E.id)')
  2656.             ->where('E.empType = 2')
  2657.             ->getQuery()
  2658.             ->getSingleScalarResult();
  2659.         $intern $em->getRepository('ApplicationBundle:EmployeeDetails')
  2660.             ->createQueryBuilder('E')
  2661.             ->select('COUNT(E.id)')
  2662.             ->where('E.empType = 3')
  2663.             ->getQuery()
  2664.             ->getSingleScalarResult();
  2665.         $temporary $em->getRepository('ApplicationBundle:EmployeeDetails')
  2666.             ->createQueryBuilder('E')
  2667.             ->select('COUNT(E.id)')
  2668.             ->where('E.empType = 4')
  2669.             ->getQuery()
  2670.             ->getSingleScalarResult();
  2671.         $contractual $em->getRepository('ApplicationBundle:EmployeeDetails')
  2672.             ->createQueryBuilder('E')
  2673.             ->select('COUNT(E.id)')
  2674.             ->where('E.empType = 5')
  2675.             ->getQuery()
  2676.             ->getSingleScalarResult();
  2677.         return $this->render(
  2678.             'ApplicationBundle:pages/dashboard:humanResource.html.twig',
  2679.             [
  2680.                 'page_title' => 'Human Resource Dashboard',
  2681.                 'attendanceDetails' => $formattedData,
  2682.                 'totalEmployee' => $totalEmployees,
  2683.                 'maleCount' => $maleCount,
  2684.                 'femaleCount' => $femaleCount,
  2685.                 'fullTime' => $fullTime,
  2686.                 'partTime' => $partTime,
  2687.                 'temporary' => $temporary,
  2688.                 'contractual' => $contractual,
  2689.                 'intern' => $intern,
  2690.             ]
  2691.         );
  2692.     }
  2693.     public function projectCashFlowReportAction()
  2694.     {
  2695.         return $this->render(
  2696.             'ApplicationBundle:pages/dashboard:cash_flow_report.html.twig',
  2697.             array(
  2698.                 'page_title' => 'Cash Flow Report'
  2699.             )
  2700.         );
  2701.     }
  2702.     public function PerformanceReviewDashboardAction()
  2703.     {
  2704.         return $this->render(
  2705.             'ApplicationBundle:pages/dashboard:performance_review_dashboard.html.twig',
  2706.             array(
  2707.                 'page_title' => 'Performance Review Dashboard'
  2708.             )
  2709.         );
  2710.     }
  2711.     public function RecruitmentDashboardAction()
  2712.     {
  2713.         return $this->render(
  2714.             'ApplicationBundle:pages/dashboard:recruitment_dashboard.html.twig',
  2715.             array(
  2716.                 'page_title' => 'Recruitment Dashboard'
  2717.             )
  2718.         );
  2719.     }
  2720.     public function TalentManagementDashboardAction()
  2721.     {
  2722.         return $this->render(
  2723.             'ApplicationBundle:pages/dashboard:talent_management_dashboard.html.twig',
  2724.             array(
  2725.                 'page_title' => 'Talent Management Dashboard'
  2726.             )
  2727.         );
  2728.     }
  2729.     public function CreateCompanyAction(Request $request)
  2730.     {
  2731.         $systemType $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
  2732.         $appId $request->get('app_id'0);
  2733.         $post $request;
  2734.         $session $request->getSession();
  2735.         if ($request->isMethod('POST')) {
  2736.             if ($systemType == '_CENTRAL_') {
  2737.                 $em_goc $this->getDoctrine()->getManager('company_group');
  2738.                 $em_goc->getConnection()->connect();
  2739.                 $connected $em_goc->getConnection()->isConnected();
  2740.                 $gocDataList = [];
  2741.                 if ($connected) {
  2742.                     $goc null;
  2743.                     $serverList GeneralConstant::$serverListById;
  2744.                     $companyGroupHash $post->get('company_short_code''');
  2745.                     $defaultUsageDate = new \DateTime();
  2746.                     $defaultUsageDate->modify('+1 year');
  2747.                     $usageValidUpto = new \DateTime($post->get('usage_valid_upto_dt_str'$defaultUsageDate->format('Y-m-d')));
  2748.                     $companyGroupServerId $post->get('server_id'1);
  2749.                     $companyGroupServerAddress $serverList[$companyGroupServerId]['absoluteUrl'];
  2750.                     $companyGroupServerPort $serverList[$companyGroupServerId]['port'];
  2751.                     $companyGroupServerHash $serverList[$companyGroupServerId]['serverMarker'];
  2752.                     //                $dbUser=
  2753.                     if ($appId != 0)
  2754.                         $goc $this->getDoctrine()->getManager('company_group')
  2755.                             ->getRepository("CompanyGroupBundle:CompanyGroup")
  2756.                             ->findOneBy(array(
  2757.                                 'appId' => $appId
  2758.                             ));
  2759.                     if (!$goc)
  2760.                         $goc = new CompanyGroup();
  2761.                     if ($appId == 0) {
  2762.                         $biggestAppIdCg $this->getDoctrine()->getManager('company_group')
  2763.                             ->getRepository("CompanyGroupBundle:CompanyGroup")
  2764.                             ->findOneBy(array( //                            'appId' => $appId
  2765.                             ), array(
  2766.                                 'appId' => 'desc'
  2767.                             ));
  2768.                         if ($biggestAppIdCg)
  2769.                             $appId $biggestAppIdCg->getAppId();
  2770.                     }
  2771.                     $goc->setName($post->get('company_name'));
  2772.                     $goc->setCompanyGroupHash($companyGroupHash);
  2773.                     $goc->setAppId($appId);
  2774.                     $goc->setActive(1);
  2775.                     $goc->setAddress($post->get('address'));
  2776.                     $goc->setShippingAddress($post->get('s_address'));
  2777.                     $goc->setBillingAddress($post->get('b_address'));
  2778.                     $goc->setMotto($post->get('motto'));
  2779.                     $goc->setInitiateFlag($post->get('initiate_flag'2));
  2780.                     $goc->setInvoiceFooter($post->get('i_footer'));
  2781.                     $goc->setGeneralFooter($post->get('g_footer'));
  2782.                     $goc->setCompanyReg($post->get('company_reg'''));
  2783.                     $goc->setCompanyTin($post->get('company_tin'''));
  2784.                     $goc->setCompanyBin($post->get('company_bin'''));
  2785.                     $goc->setCompanyTl($post->get('company_tl'''));
  2786.                     $goc->setCompanyType($post->get('company_type'''));
  2787.                     $goc->setCurrentSubscriptionPackageId($post->get('package'''));
  2788.                     $goc->setUsageValidUptoDate($usageValidUpto);
  2789.                     $goc->setUsageValidUptoDateTs($usageValidUpto->format('U'));
  2790.                     //                $goc->setCu($post->get('package', ''));
  2791.                     $goc->setAdminUserAllowed($post->get('number_of_admin_user'1));
  2792.                     $goc->setUserAllowed($post->get('number_of_user'2));
  2793.                     $goc->setSubscriptionMonth($post->get('subscription_month'1));
  2794.                     $goc->setCompanyDescription($post->get('company_description'''));
  2795.                     $goc->setDbUser($post->get('db_user'));
  2796.                     $goc->setDbPass($post->get('db_pass'));
  2797.                     $goc->setDbHost($post->get('db_host'));
  2798.                     $goc->setCompanyGroupServerId($companyGroupServerId);
  2799.                     $goc->setCompanyGroupServerAddress($companyGroupServerAddress);
  2800.                     $goc->setCompanyGroupServerPort($companyGroupServerPort);
  2801.                     $goc->setCompanyGroupServerHash($companyGroupServerHash);
  2802.                     foreach ($request->files as $uploadedFile) {
  2803.                         if ($uploadedFile != null) {
  2804.                             $fileName 'company_image' $appId '.' $uploadedFile->guessExtension();
  2805.                             $path $fileName;
  2806.                             $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/CompanyImage/';
  2807.                             if ($goc->getImage() != null && $goc->getImage() != '' && file_exists($this->container->getParameter('kernel.root_dir') . '/../web' $goc->getImage())) {
  2808.                                 unlink($this->container->getParameter('kernel.root_dir') . '/../web' $goc->getImage());
  2809.                             }
  2810.                             if (!file_exists($upl_dir)) {
  2811.                                 mkdir($upl_dir0777true);
  2812.                             }
  2813.                             $file $uploadedFile->move($upl_dir$path);
  2814.                             if ($path != "")
  2815.                                 $goc->setImage('/uploads/CompanyImage/' $path);
  2816.                         }
  2817.                     }
  2818.                     $em_goc->persist($goc);
  2819.                     $em_goc->flush();
  2820.                     $goc->setDbName('cg_' $appId '_' $companyGroupHash);
  2821.                     $goc->setDbUser($serverList[$companyGroupServerId]['dbUser']);
  2822.                     $goc->setDbPass($serverList[$companyGroupServerId]['dbPass']);
  2823.                     $goc->setDbHost('localhost');
  2824.                     $em_goc->flush();
  2825.                     $centralUser $this->getDoctrine()->getManager('company_group')
  2826.                         ->getRepository("CompanyGroupBundle:EntityApplicantDetails")
  2827.                         ->findOneBy(array(
  2828.                             'applicantId' => $session->get(UserConstants::USER_ID0)
  2829.                         ));
  2830.                     if ($centralUser) {
  2831.                         $userAppIds json_decode($centralUser->getUserAppIds(), true);
  2832.                         $userTypesByAppIds json_decode($centralUser->getUserTypesByAppIds(), true);
  2833.                         if ($userAppIds == null$userAppIds = [];
  2834.                         if ($userTypesByAppIds == null$userTypesByAppIds = [];
  2835.                         $userAppIds array_merge($userAppIdsarray_diff([$appId], $userAppIds));
  2836.                         if (!isset($userTypesByAppIds[$appId])) {
  2837.                             $userTypesByAppIds[$appId] = [];
  2838.                         }
  2839.                         $userTypesByAppIds[$appId] = array_merge($userTypesByAppIds[$appId], array_diff([UserConstants::USER_TYPE_SYSTEM], $userTypesByAppIds[$appId]));
  2840.                         $centralUser->setUserAppIds(json_encode($userAppIds));
  2841.                         $centralUser->setUserTypesByAppIds(json_encode($userTypesByAppIds));
  2842.                         $em_goc->flush();
  2843.                     }
  2844.                     $accessList $session->get('userAccessList', []);
  2845.                     $d = array(
  2846.                         'userType' => UserConstants::USER_TYPE_SYSTEM,
  2847.                         'globalId' => $session->get(UserConstants::USER_ID0),
  2848.                         'serverId' => $companyGroupServerId,
  2849.                         'serverUrl' => $companyGroupServerAddress,
  2850.                         'serverPort' => $companyGroupServerPort,
  2851.                         'systemType' => '_ERP_',
  2852.                         'companyId' => 1,
  2853.                         'appId' => $appId,
  2854.                         'companyLogoUrl' => $goc->getImage(),
  2855.                         'companyName' => $goc->getName(),
  2856.                         'authenticationStr' => $this->get('url_encryptor')->encrypt(
  2857.                             json_encode(
  2858.                                 array(
  2859.                                     'globalId' => $session->get(UserConstants::USER_ID0),
  2860.                                     'appId' => $appId,
  2861.                                     'authenticate' => 1,
  2862.                                     'userType' => UserConstants::USER_TYPE_SYSTEM
  2863.                                 )
  2864.                             )
  2865.                         ),
  2866.                         'userCompanyList' => []
  2867.                     );
  2868.                     $accessList[] = $d;
  2869.                     MiscActions::UpdateCompanyListInSession($em_goc$centralUser->getApplicantId(), 111$d);
  2870.                     $session->set('userAccessList'$accessList);
  2871.                 }
  2872.                 return new JsonResponse(array(
  2873.                     'success' => true,
  2874.                     "message" => "Company Created Successfully",
  2875.                     'user_access_data' => $d,
  2876.                     'app_id' => $appId
  2877.                 ));
  2878.             }
  2879.         }
  2880.         return $this->render('@HoneybeeWeb/pages/create_company.html.twig', array(
  2881.             'page_title' => 'Company',
  2882.             'serverList' => GeneralConstant::$serverListById
  2883.         ));
  2884.     }
  2885.     public function GetSessionDataForAppAction(
  2886.         Request $request,
  2887.                 $remoteVerify 0,
  2888.                 $version 'latest',
  2889.                 $identifier '_default_',
  2890.                 $refRoute '',
  2891.                 $apiKey '_ignore_'
  2892.     )
  2893.     {
  2894.         $message "";
  2895.         $gocList = [];
  2896.         $session $request->getSession();
  2897.         if ($request->request->has('token')) {
  2898.             $em_goc $this->getDoctrine()->getManager('company_group');
  2899.             $to_set_session_data MiscActions::GetSessionDataFromToken($em_goc$request->request->get('token'))['sessionData'];
  2900.             if ($to_set_session_data != null) {
  2901.                 foreach ($to_set_session_data as $k => $d) {
  2902.                     //check if mobile
  2903.                     $session->set($k$d);
  2904.                 }
  2905.             }
  2906.         }
  2907.         if ($request->request->has('sessionData')) {
  2908.             $to_set_session_data $request->request->get('sessionData');
  2909.             foreach ($to_set_session_data as $k => $d) {
  2910.                 //check if mobile
  2911.                 $session->set($k$d);
  2912.             }
  2913.         }
  2914.         if ($version !== 'latest') {
  2915.             $session_data = array(
  2916.                 'oAuthToken' => $session->get('oAuthToken'),
  2917.                 'locale' => $session->get('locale'),
  2918.                 'firebaseToken' => $session->get('firebaseToken'),
  2919.                 'token' => $session->get('token'),
  2920.                 UserConstants::USER_EMPLOYEE_ID => $session->get(UserConstants::USER_EMPLOYEE_ID),
  2921.                 UserConstants::USER_ID => $session->get(UserConstants::USER_ID),
  2922.                 UserConstants::LAST_SETTINGS_UPDATED_TS => $session->get(UserConstants::LAST_SETTINGS_UPDATED_TS),
  2923.                 UserConstants::USER_LOGIN_ID => $session->get(UserConstants::USER_LOGIN_ID),
  2924.                 UserConstants::USER_EMAIL => $session->get(UserConstants::USER_EMAIL),
  2925.                 UserConstants::USER_TYPE => $session->get(UserConstants::USER_TYPE),
  2926.                 UserConstants::USER_IMAGE => $session->get(UserConstants::USER_IMAGE),
  2927.                 UserConstants::USER_DEFAULT_ROUTE => $session->get(UserConstants::USER_DEFAULT_ROUTE),
  2928.                 UserConstants::USER_NAME => $session->get(UserConstants::USER_NAME),
  2929.                 UserConstants::USER_COMPANY_ID => $session->get(UserConstants::USER_COMPANY_ID),
  2930.                 UserConstants::USER_COMPANY_ID_LIST => $session->get(UserConstants::USER_COMPANY_ID_LIST),
  2931.                 UserConstants::USER_COMPANY_NAME_LIST => $session->get(UserConstants::USER_COMPANY_NAME_LIST),
  2932.                 UserConstants::USER_COMPANY_IMAGE_LIST => $session->get(UserConstants::USER_COMPANY_IMAGE_LIST),
  2933.                 UserConstants::USER_APP_ID => $session->get(UserConstants::USER_APP_ID),
  2934.                 UserConstants::USER_POSITION_LIST => $session->get(UserConstants::USER_POSITION_LIST),
  2935.                 UserConstants::USER_CURRENT_POSITION => $session->get(UserConstants::USER_CURRENT_POSITION),
  2936.                 UserConstants::ALL_MODULE_ACCESS_FLAG => $session->get(UserConstants::ALL_MODULE_ACCESS_FLAG),
  2937.                 UserConstants::USER_GOC_ID => $session->get(UserConstants::USER_GOC_ID),
  2938.                 UserConstants::USER_NOTIFICATION_ENABLED => GeneralConstant::NOTIFICATION_ENABLED == ? ($this->getParameter('notification_enabled') == 0) : 0,
  2939.                 UserConstants::USER_NOTIFICATION_SERVER => $this->getParameter('notification_server'),
  2940.                 UserConstants::PRODUCT_NAME_DISPLAY_TYPE => $session->get(UserConstants::PRODUCT_NAME_DISPLAY_TYPE),
  2941.                 UserConstants::APPLICATION_SECRET => $session->get(UserConstants::APPLICATION_SECRET),
  2942.                 //new addition
  2943.                 'appIdList' => $session->get('appIdList'),
  2944.                 'branchIdList' => $session->get('branchIdList'null),
  2945.                 'branchId' => $session->get('branchId'null),
  2946.                 'companyIdListByAppId' => $session->get('companyIdListByAppId'),
  2947.                 'companyNameListByAppId' => $session->get('companyNameListByAppId'),
  2948.                 'companyImageListByAppId' => $session->get('companyImageListByAppId'),
  2949.                 'userAccessList' => $session->get('userAccessList'),
  2950.                 'csToken' => $session->get('csToken'),
  2951.             );
  2952.         } else {
  2953.             $session_data = array(
  2954.                 'oAuthToken' => $session->get('oAuthToken'),
  2955.                 'locale' => $session->get('locale'),
  2956.                 'firebaseToken' => $session->get('firebaseToken'),
  2957.                 'token' => $session->get('token'),
  2958.                 UserConstants::USER_EMPLOYEE_ID => $session->get(UserConstants::USER_EMPLOYEE_ID),
  2959.                 UserConstants::USER_ID => $session->get(UserConstants::USER_ID),
  2960.                 UserConstants::LAST_SETTINGS_UPDATED_TS => $session->get(UserConstants::LAST_SETTINGS_UPDATED_TS),
  2961.                 UserConstants::USER_LOGIN_ID => $session->get(UserConstants::USER_LOGIN_ID),
  2962.                 UserConstants::USER_EMAIL => $session->get(UserConstants::USER_EMAIL),
  2963.                 UserConstants::USER_TYPE => $session->get(UserConstants::USER_TYPE),
  2964.                 UserConstants::USER_IMAGE => $session->get(UserConstants::USER_IMAGE),
  2965.                 UserConstants::USER_DEFAULT_ROUTE => $session->get(UserConstants::USER_DEFAULT_ROUTE),
  2966.                 UserConstants::USER_NAME => $session->get(UserConstants::USER_NAME),
  2967.                 UserConstants::USER_COMPANY_ID => $session->get(UserConstants::USER_COMPANY_ID),
  2968.                 UserConstants::USER_COMPANY_ID_LIST => $session->get(UserConstants::USER_COMPANY_ID_LIST),
  2969.                 UserConstants::USER_COMPANY_NAME_LIST => $session->get(UserConstants::USER_COMPANY_NAME_LIST),
  2970.                 UserConstants::USER_COMPANY_IMAGE_LIST => $session->get(UserConstants::USER_COMPANY_IMAGE_LIST),
  2971.                 UserConstants::USER_APP_ID => $session->get(UserConstants::USER_APP_ID),
  2972.                 UserConstants::USER_POSITION_LIST => $session->get(UserConstants::USER_POSITION_LIST),
  2973.                 UserConstants::USER_CURRENT_POSITION => $session->get(UserConstants::USER_CURRENT_POSITION),
  2974.                 UserConstants::ALL_MODULE_ACCESS_FLAG => $session->get(UserConstants::ALL_MODULE_ACCESS_FLAG),
  2975.                 UserConstants::USER_GOC_ID => $session->get(UserConstants::USER_GOC_ID),
  2976.                 UserConstants::USER_DB_NAME => $session->get(UserConstants::USER_DB_NAME),
  2977.                 UserConstants::USER_DB_USER => $session->get(UserConstants::USER_DB_USER),
  2978.                 UserConstants::USER_DB_HOST => $session->get(UserConstants::USER_DB_HOST),
  2979.                 UserConstants::USER_DB_PASS => $session->get(UserConstants::USER_DB_PASS),
  2980.                 UserConstants::USER_NOTIFICATION_ENABLED => GeneralConstant::NOTIFICATION_ENABLED == ? ($this->getParameter('notification_enabled') == 0) : 0,
  2981.                 UserConstants::USER_NOTIFICATION_SERVER => $this->getParameter('notification_server'),
  2982.                 UserConstants::PRODUCT_NAME_DISPLAY_TYPE => $session->get(UserConstants::PRODUCT_NAME_DISPLAY_TYPE),
  2983.                 UserConstants::APPLICATION_SECRET => $session->get(UserConstants::APPLICATION_SECRET),
  2984.                 //new addition
  2985.                 'appIdList' => $session->get('appIdList'),
  2986.                 'branchIdList' => $session->get('branchIdList'null),
  2987.                 'branchId' => $session->get('branchId'null),
  2988.                 'companyIdListByAppId' => $session->get('companyIdListByAppId'),
  2989.                 'companyNameListByAppId' => $session->get('companyNameListByAppId'),
  2990.                 'companyImageListByAppId' => $session->get('companyImageListByAppId'),
  2991.                 'userAccessList' => $session->get('userAccessList'),
  2992.                 'csToken' => $session->get('csToken'),
  2993.             );
  2994.         }
  2995.         $response = new JsonResponse(array(
  2996.             "success" => empty($session->get(UserConstants::USER_ID)) ? false true,
  2997.             //            'session'=>$request->getSession(),
  2998.             'session_data' => $session_data,
  2999.             //            'session2'=>$_SESSION,
  3000.         ));
  3001.         $response->headers->set('Access-Control-Allow-Origin''*, null');
  3002.         $response->headers->set('Access-Control-Allow-Methods''POST');
  3003.         //        $response->setCallback('FUNCTION_CALLBACK_NAME');
  3004.         return $response;
  3005.     }
  3006.     public function EmployeeAddUsingQrCodeCentralAction(Request $request)
  3007.     {
  3008.         $session $request->getSession();
  3009.         if ($request->isMethod('post')) {
  3010.             $em_goc $this->getDoctrine()->getManager('company_group');
  3011.             $entityApplicant $em_goc->getRepository("CompanyGroupBundle:EntityApplicantDetails")
  3012.                 ->findOneBy(
  3013.                     array(
  3014.                         'applicantId' => $request->request->get('userId'),
  3015.                     )
  3016.                 );
  3017.             $app $em_goc->getRepository("CompanyGroupBundle:CompanyGroup")
  3018.                 ->findOneBy(
  3019.                     array(
  3020.                         'appId' => $request->request->get('appId'),
  3021.                     )
  3022.                 );
  3023.             $userType $request->request->get('userType');
  3024.             $currAccessData json_decode($entityApplicant->getUserTypesByAppIds(), true);
  3025.             if ($currAccessData == null$currAccessData = [];
  3026.             if (!isset($currAccessData[$request->request->get('appId')]))
  3027.                 $currAccessData[$request->request->get('appId')] = [];
  3028.             $currAccessData[$request->request->get('appId')] = array_merge($currAccessData[$request->request->get('appId')], array_diff([$request->request->get('userType'$userType)], $currAccessData[$request->request->get('appId')]));
  3029.             $entityApplicant->setUserTypesByAppIds(json_encode($currAccessData));
  3030.             $em_goc->flush();
  3031.             $postData = [];
  3032.             $postData['globalId'] = $entityApplicant->getApplicantId();
  3033.             $postData['username'] = $entityApplicant->getUsername();
  3034.             $postData['email'] = $entityApplicant->getEmail();
  3035.             $postData['firstname'] = $entityApplicant->getFirstname();
  3036.             $postData['lastname'] = $entityApplicant->getLastname();
  3037.             $postData['appId'] = $request->request->get('appId');
  3038.             $postData['companyId'] = $request->request->get('companyId');
  3039.             $postData['userType'] = $userType;
  3040.             $urlToCall $app->getCompanyGroupServerAddress() . '/add_employee_by_qr_erp';
  3041.             $userFiles $postData;
  3042.             $curl curl_init();
  3043.             curl_setopt_array($curl, array(
  3044.                 CURLOPT_RETURNTRANSFER => 1,
  3045.                 CURLOPT_POST => 1,
  3046.                 CURLOPT_URL => $urlToCall,
  3047.                 CURLOPT_CONNECTTIMEOUT => 10,
  3048.                 CURLOPT_SSL_VERIFYPEER => false,
  3049.                 CURLOPT_SSL_VERIFYHOST => false,
  3050.                 CURLOPT_HTTPHEADER => array( //              "Accept: multipart/form-data",
  3051.                 ),
  3052.                 //                            ),
  3053.                 CURLOPT_POSTFIELDS => $userFiles
  3054.             ));
  3055.             $retData curl_exec($curl);
  3056.             $errData curl_error($curl);
  3057.             curl_close($curl);
  3058.             if ($errData) {
  3059. //                $returnData['message']='';
  3060.             } else {
  3061.                 $retDataObj json_decode($retDatatrue);
  3062.                 if ($retDataObj['status'] == 'success') {
  3063.                     $newAccess = [
  3064.                         'userType' => 1,
  3065.                         'userTypeName' => 'Admin',
  3066.                         'globalId' => $entityApplicant->getApplicantId(),
  3067.                         'serverId' => $app->getCompanyGroupServerId(),
  3068.                         'serverUrl' => $app->getCompanyGroupServerAddress(),
  3069.                         'serverPort' => $app->getCompanyGroupServerPort(),
  3070.                         'systemType' => '_ERP_',
  3071.                         'companyId' => 1,
  3072.                         'appId' => $app->getAppId(),
  3073.                         'companyLogoUrl' => '/uploads/CompanyImage/company_image' $request->request->get('appId') . '.png',
  3074.                         'companyName' => $app->getName(),
  3075.                         'authenticationStr' => $this->get('url_encryptor')->encrypt(json_encode(
  3076.                                 array(
  3077.                                     'globalId' => $entityApplicant->getApplicantId(),
  3078.                                     'appId' => $app->getAppId(),
  3079.                                     'authenticate' => 1,
  3080.                                     'userType' => $userType,
  3081.                                     'userTypeName' => UserConstants::$userTypeName[$userType]
  3082.                                 )
  3083.                             )
  3084.                         ),
  3085.                         'userCompanyList' => [],
  3086.                     ];
  3087. //            $token = $session->get('token');
  3088. //            $em_goc = $this->getDoctrine()->getManager('company_group');
  3089.                     $to_set_session_data MiscActions::GetSessionDataFromToken($em_goc$session->get(UserConstants::USER_TOKEN''))['sessionData'];
  3090.                     $currentUserAccessListInSession $to_set_session_data['userAccessList'];
  3091.                     $isAlreadyJoined false;
  3092.                     foreach ($currentUserAccessListInSession as $acc) {
  3093.                         if (isset($acc['appId']) && $acc['appId'] == $request->request->get('appId')) {
  3094.                             $isAlreadyJoined true;
  3095.                             break;
  3096.                         }
  3097.                     }
  3098. //                    if(isset($currentUserAccessListInSession[$request->request->get('appId')]))
  3099. //                        $isAlreadyJoined=true;
  3100.                     if ($isAlreadyJoined) {
  3101.                         return new JsonResponse([
  3102.                             'status' => 'false',
  3103.                             'message' => 'Already joined.',
  3104.                             'currentUserAccessListInSession'  => $currentUserAccessListInSession
  3105.                         ]);
  3106.                     }else{
  3107.                         $currentUserAccessListInSession[] = $newAccess;
  3108.                         $session->set('userAccessList'$currentUserAccessListInSession);
  3109.                         $to_set_session_data['userAccessList'] = $currentUserAccessListInSession;
  3110.                         $updatedToken MiscActions::CreateTokenFromSessionData($em_goc,
  3111.                             $to_set_session_data,
  3112.                             1,
  3113.                             1,
  3114.                             11
  3115.                         );
  3116.                         return new JsonResponse([
  3117.                             'status' => 'success',
  3118.                             'message' => 'User successfully added to company.',
  3119.                             'currentUserAccessListInSession'  => $currentUserAccessListInSession
  3120.                         ]);
  3121.                     }
  3122.                 }
  3123.             }
  3124. //            MiscActions::UpdateCompanyListInSession($em_goc, $entityApplicant->getApplicantId(), 1, 1, 1, $newAccess);
  3125.         } else {
  3126.             $company $request->get('company');
  3127.             return new JsonResponse(array(
  3128.                 'status' => 'error',
  3129.                 'message' => 'Something went wrong while onboarding.'
  3130.             ));
  3131.         }
  3132.         return new JsonResponse(array(
  3133.             'status' => 'error',
  3134.             'message' => 'Something went wrong while onboarding.'
  3135.         ));
  3136.     }
  3137.     public function EmployeeAddUsingQrCodeAction(Request $request)
  3138.     {
  3139.         $post $request;
  3140.         $em $this->getDoctrine()->getManager('company_group');
  3141.         $appid $request->query->get('appid'$request->request->get('appid'null));
  3142.         $session $request->getSession();
  3143.         $CurrentRoute $request->attributes->get('_route');
  3144.         $systemType $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
  3145.         if ($request->isMethod('POST')) {
  3146.             $userId $request->request->get('userId'null);
  3147.             if ($userId === null) {
  3148.                 $companyId $request->request->get('company',1);
  3149.                 $email $request->request->get('email');
  3150.                 $qrImage $request->files->get('qr_image');
  3151.                 if (!$email) {
  3152.                     return new JsonResponse(['status' => 'error''message' => 'Invalid request'], 400);
  3153.                 }
  3154.                 if ($qrImage) {
  3155.                     $uploadsDir $this->getParameter('kernel.project_dir') . '/public/uploads/';
  3156.                     $fileName 'qr_' $companyId '_' time() . '.png';
  3157.                     $qrImage->move($uploadsDir$fileName);
  3158.                     $qrImagePath $uploadsDir $fileName;
  3159.                     $bodyTemplate 'ApplicationBundle:email/user:applicant_confirm.html.twig';
  3160.                     $bodyData = [
  3161.                         'name' => $email,
  3162.                         'companyData' => $companyId,
  3163.                         'companyName' => $request->request->get('company'),
  3164.                         'userType' => 2,
  3165.                         'appId' => $appid,
  3166.                         //                        'qr_code_url' => '/uploads/' . $fileName
  3167.                     ];
  3168.                     $userAccessList $session->get('userAccessList', []);
  3169.                     $companyName array_map(function ($company) {
  3170.                         return $company['companyName'];
  3171.                     }, $userAccessList);
  3172.                     $new_mail $this->get('mail_module');
  3173.                     $new_mail->sendMyMail([
  3174.                         'senderHash' => '_CUSTOM_',
  3175.                         'forwardToMailAddress' => $email,
  3176.                         'fromAddress' => 'no-reply@ourhoneybee.eu',
  3177.                         'userName' => 'no-reply@ourhoneybee.eu',
  3178.                         'password' => 'Honeybee@0112',
  3179.                         'smtpServer' => 'smtp.hostinger.com',
  3180.                         'smtpPort' => 465,
  3181.                         'subject' => 'User Registration on HoneyBee Ecosystem under Entity ',
  3182.                         'toAddress' => $email,
  3183.                         'mailTemplate' => $bodyTemplate,
  3184.                         'templateData' => $bodyData,
  3185.                         'companyId' => $companyId,
  3186.                     ]);
  3187.                     return $this->render(
  3188.                         'ApplicationBundle:pages/dashboard:index_central_landing.html.twig',
  3189.                         [
  3190.                             'page_title' => 'Central Landing',
  3191.                             'companyNames' => $companyName
  3192.                         ]
  3193.                     );
  3194.                 } else {
  3195.                     $userAccessList $session->get('userAccessList', []);
  3196.                     $companyName array_map(function ($company) {
  3197.                         return $company['companyName'];
  3198.                     }, $userAccessList);
  3199.                     return $this->render(
  3200.                         'ApplicationBundle:pages/dashboard:index_central_landing.html.twig',
  3201.                         [
  3202.                             'page_title' => 'Central Landing',
  3203.                             'companyNames' => $companyName
  3204.                         ]
  3205.                     );
  3206.                 }
  3207.             } else {
  3208.                 if ($systemType == '_CENTRAL_') {
  3209.                     $userAccessList $session->get('userAccessList', []);
  3210.                     $companyName array_map(function ($company) {
  3211.                         return $company['companyName'];
  3212.                     }, $userAccessList);
  3213.                     $modifiedRequest $request->duplicate(
  3214.                         null,
  3215.                         array_merge($request->request->all(), ['appId' => $request->request->get('appid')])
  3216.                     );
  3217.                     $response $this->EmployeeAddUsingQrCodeCentralAction($modifiedRequest);
  3218. //                    if ($CurrentRoute == 'employee_add_by_qr_api')
  3219.                     {
  3220.                         return $response;
  3221.                     }
  3222. //                    return $this->render(
  3223. //                        'ApplicationBundle:pages/dashboard:index_central_landing.html.twig',
  3224. //                        [
  3225. //                            'page_title' => 'Central Landing',
  3226. //                            'companyNames' => $companyName
  3227. //                        ]
  3228. //                    );
  3229.                 }
  3230.             }
  3231.         } else {
  3232.             $company $request->get('company');
  3233.             $em_goc $this->getDoctrine()->getManager('company_group');
  3234.             $company $em_goc->getRepository("CompanyGroupBundle:CompanyGroup")->findOneBy(['appId' => $request->get('appid')]);
  3235.             return $this->render(
  3236.                 'ApplicationBundle:pages/dashboard:employee_add_by_qr.html.twig',
  3237.                 [
  3238.                     'page_title' => 'Company Invitation',
  3239.                     'company' => $company
  3240.                 ]
  3241.             );
  3242.         }
  3243.     }
  3244.     public function EmployeeOnboardUsingQrAction(Request $request): JsonResponse
  3245.     {
  3246.         $email $request->get('email');
  3247.         $isAjax $request->isXmlHttpRequest();
  3248.         $currentRoute $request->attributes->get('_route');
  3249.         if (!$email) {
  3250.             if ($isAjax) {
  3251.                 return new JsonResponse(['status' => 'error''message' => 'Email is required.']);
  3252.             } else {
  3253.                 throw $this->createNotFoundException("Email is missing.");
  3254.             }
  3255.         }
  3256.         $em_goc $this->getDoctrine()->getManager('company_group');
  3257.         $user $em_goc->getRepository("CompanyGroupBundle:EntityApplicantDetails")->findOneBy(['email' => $email]);
  3258.         if (!$user) {
  3259.             if ($isAjax) {
  3260.                 return new JsonResponse(['status' => 'error''message' => 'Applicant not found.']);
  3261.             } else {
  3262.                 throw $this->createNotFoundException("Applicant not found.");
  3263.             }
  3264.         }
  3265.         $payloadUrl $this->generateUrl('employee_onboard_by_qr_api', [
  3266.             'email' => $user->getEmail(),
  3267.             'applicantId' => $user->getApplicantId(),
  3268.             'employeeQr' => 1
  3269.         ], UrlGeneratorInterface::ABSOLUTE_URL);
  3270.         if ($currentRoute === 'employee_onboard') {
  3271.             return new JsonResponse([
  3272.                 'status' => 'success',
  3273.                 'data' => [
  3274.                     'applicantId' => $user->getApplicantId(),
  3275.                     'username' => $user->getUsername(),
  3276.                     'email' => $user->getEmail(),
  3277.                     'firstName' => $user->getFirstname(),
  3278.                     'lastName' => $user->getLastname(),
  3279.                     'link' => $payloadUrl
  3280.                 ]
  3281.             ]);
  3282.         }
  3283.         if ($isAjax) {
  3284.             return new JsonResponse([
  3285.                 'status' => 'success',
  3286.                 'data' => [
  3287.                     'id' => $user->getApplicantId(),
  3288.                     'email' => $user->getEmail(),
  3289.                     'name' => $user->getFirstname() . ' ' $user->getLastname(),
  3290.                     'dob' => $user->getDob() ? $user->getDob()->format('Y-m-d') : null,
  3291.                 ]
  3292.             ]);
  3293.         }
  3294.         $companies $request->getSession()->get('userAccessList', []);
  3295.         return $this->render('ApplicationBundle:pages/dashboard:qr_onboard_result.html.twig', [
  3296.             'page_title' => 'Onboarding',
  3297.             'applicant' => $user,
  3298.             'companies' => $companies
  3299.         ]);
  3300.     }
  3301.     public function OnboardUserToCompanyAction(Request $request)
  3302.     {
  3303.         $systemType $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
  3304.         $currentRoute $request->attributes->get('_route');
  3305.         if ($systemType !== '_CENTRAL_') {
  3306.             throw new \Exception("This action must be called from CENTRAL system.");
  3307.         }
  3308.         $email $request->request->get('email');
  3309.         $applicantId $request->request->get('applicant_id');
  3310.         $appId $request->request->get('company_id');
  3311.         $userType $request->request->get('user_type');
  3312.         if (!$email || !$appId || !$userType) {
  3313.             $this->addFlash('error''Missing required fields.');
  3314.             return new JsonResponse(['status' => 'error''message' => 'Missing required fields.']);
  3315.         }
  3316.         $em $this->getDoctrine()->getManager('company_group');
  3317.         $applicant $em->getRepository("CompanyGroupBundle:EntityApplicantDetails")->findOneBy(['email' => $email]);
  3318.         if (!$applicant) {
  3319.             $this->addFlash('error''Applicant not found.');
  3320.             return $this->redirectToRoute('central_landing');
  3321.         }
  3322.         $userAppIds json_decode($applicant->getUserAppIds(), true);
  3323.         if (!is_array($userAppIds)) {
  3324.             $userAppIds = [];
  3325.         }
  3326.         if (!in_array($appId$userAppIds)) {
  3327.             $userAppIds[] = $appId;
  3328.             $applicant->setUserAppIds(json_encode($userAppIds));
  3329.         }
  3330.         $userTypesByAppIds json_decode($applicant->getUserTypesByAppIds(), true) ?: [];
  3331.         $userTypesByAppIds[$appId] = array((int)$userType);
  3332.         $applicant->setUserTypesByAppIds(json_encode($userTypesByAppIds));
  3333.         $em->persist($applicant);
  3334.         $em->flush();
  3335.         $companyRepo $this->getDoctrine()->getManager('company_group')->getRepository("CompanyGroupBundle:CompanyGroup");
  3336.         $targetCompany $companyRepo->findOneBy(['appId' => $appId]);
  3337.         if (!$targetCompany) {
  3338.             $this->addFlash('error''Target company not found.');
  3339.             return $this->redirectToRoute('central_landing');
  3340.         }
  3341.         $serverList GeneralConstant::$serverListById;
  3342.         $serverId $targetCompany->getCompanyGroupServerId();
  3343.         $appId $targetCompany->getAppId();
  3344.         if (!isset($serverList[$serverId])) {
  3345.             $this->addFlash('error''Server configuration not found.');
  3346.             return $this->redirectToRoute('central_landing');
  3347.         }
  3348.         // Find correct companyId from session userAccessList using appId
  3349.         $session $request->getSession();
  3350.         $userAccessList $session->get('userAccessList', []);
  3351.         $resolvedCompanyId null;
  3352.         foreach ($userAccessList as $access) {
  3353.             if (isset($access['appId']) && $access['appId'] == $appId) {
  3354.                 $resolvedCompanyId $access['companyId'];
  3355.                 break;
  3356.             }
  3357.         }
  3358.         if (!$resolvedCompanyId) {
  3359.             $this->addFlash('error''Could not resolve companyId from session for the given appId.');
  3360.             return $this->redirectToRoute('central_landing');
  3361.         }
  3362.         $imagePath $this->container->getParameter('kernel.root_dir') . '/../web/' $applicant->getImage();
  3363.         $imageFile null;
  3364.         if ($applicant->getImage() && file_exists($imagePath)) {
  3365.             $mime mime_content_type($imagePath);
  3366.             $name pathinfo($imagePathPATHINFO_BASENAME);
  3367.             $imageFile = new \CURLFile($imagePath$mime$name);
  3368.         }
  3369.         // Prepare userData
  3370.         $userData = [];
  3371.         $getters array_filter(get_class_methods($applicant), function ($method) {
  3372.             return strpos($method'get') === 0;
  3373.         });
  3374.         foreach ($getters as $getter) {
  3375.             if (in_array($getter, ['getCreatedAt''getUpdatedAt''getImage'])) continue;
  3376.             $value $applicant->$getter();
  3377.             $userData[$getter] = $value instanceof \DateTime $value->format('Y-m-d') : $value;
  3378.         }
  3379.         $userData['getUserAppIds'] = json_encode($userAppIds);
  3380.         $userData['getUserTypesByAppIds'] = json_encode($userTypesByAppIds);
  3381.         $postFields = [
  3382.             'userData' => json_encode([$userData]),
  3383.             'appIds' => $appId,
  3384.             'userIds' => $applicantId,
  3385.             'companyId' => $resolvedCompanyId,
  3386.             'userType' => $userType,
  3387.             'imageFile' => $imageFile
  3388.         ];
  3389.         if ($imageFile) {
  3390.             $postFields['file_' $applicant->getApplicantId()] = $imageFile;
  3391.         }
  3392.         $url $serverList[$serverId]['absoluteUrl'] . '/OnBoardCentralUserToErp';
  3393.         $curl curl_init();
  3394.         curl_setopt_array($curl, [
  3395.             CURLOPT_RETURNTRANSFER => 1,
  3396.             CURLOPT_POST => 1,
  3397.             CURLOPT_URL => $url,
  3398.             CURLOPT_POSTFIELDS => $postFields,
  3399.             CURLOPT_CONNECTTIMEOUT => 10,
  3400.             CURLOPT_SSL_VERIFYPEER => false,
  3401.             CURLOPT_SSL_VERIFYHOST => false,
  3402.         ]);
  3403.         $response curl_exec($curl);
  3404.         $curlError curl_error($curl);
  3405.         curl_close($curl);
  3406.         $responseObj json_decode($responsetrue);
  3407.         if ($currentRoute === 'employee_onboard_api') {
  3408.             return new JsonResponse(
  3409.                 $responseObj
  3410.             );
  3411.         }
  3412.         if (!empty($responseObj['success'])) {
  3413.             $this->addFlash('success''Applicant onboarded and synced to ERP.');
  3414.         } else {
  3415.             $this->addFlash('warning''Onboarded, but ERP sync may have failed. Check logs.');
  3416.         }
  3417.         return $this->redirectToRoute('central_landing');
  3418.     }
  3419.     public function OnBoardCentralUserToErpAction(Request $request)
  3420.     {
  3421.         $systemType $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
  3422.         if ($systemType === '_CENTRAL_') {
  3423.             return new JsonResponse(['success' => false'message' => 'Invalid system type.']);
  3424.         }
  3425.         $userDataJson $request->get('userData');
  3426.         $userDataList json_decode($userDataJsontrue);
  3427.         if (!$userDataList || !is_array($userDataList)) {
  3428.             return new JsonResponse(['success' => false'message' => 'Invalid or missing userData.']);
  3429.         }
  3430.         $userData $userDataList[0] ?? null;
  3431.         if (!$userData || empty($userData['getApplicantId'])) {
  3432.             return new JsonResponse(['success' => false'message' => 'Missing applicant ID.']);
  3433.         }
  3434.         $em_goc $this->getDoctrine()->getManager('company_group');
  3435.         $globalId $userData['getApplicantId'];
  3436.         $appIds $request->get('appIds');
  3437.         $userIds $request->get('userIds');
  3438.         $companyId $request->get('companyId');
  3439.         $company $em_goc->getRepository("CompanyGroupBundle:CompanyGroup")->findOneBy(['appId' => $appIds]);
  3440.         if (!$company) {
  3441.             return new JsonResponse(['success' => false'message' => 'Target company not found.']);
  3442.         }
  3443.         $connector $this->container->get('application_connector');
  3444.         $connector->resetConnection(
  3445.             'default',
  3446.             $company->getDbName(),
  3447.             $company->getDbUser(),
  3448.             $company->getDbPass(),
  3449.             $company->getDbHost(),
  3450.             true
  3451.         );
  3452.         $em $this->getDoctrine()->getManager();
  3453.         $user $em->getRepository('ApplicationBundle:SysUser')->findOneBy([
  3454.             'globalId' => $globalId
  3455.         ]);
  3456.         if (!$user) {
  3457.             $user = new \ApplicationBundle\Entity\SysUser();
  3458.             $user->setGlobalId($globalId);
  3459.         } else {
  3460.             return new JsonResponse([
  3461.                 'status' => 'info',
  3462.                 'message' => 'User is already onboarded',
  3463.                 'userId' => $user->getUserId(),
  3464.                 'redirectUrl' => 'dashboard'
  3465.             ]);
  3466.         }
  3467.         $setterMap = [
  3468.             'getUsername' => 'setUserName',
  3469.             'getEmail' => 'setEmail',
  3470.             'getPassword' => 'setPassword',
  3471.             'getDeviceId' => 'setDeviceId',
  3472.             'getDeviceIdLockedFlag' => 'setDeviceIdLockedFlag',
  3473.             'getLockDeviceIdOnNextLoginFlag' => 'setLockDeviceIdOnNextLoginFlag',
  3474.             'getOAuthUniqueId' => 'setOAuthUniqueId',
  3475.             'getOAuthEmail' => 'setOAuthEmail',
  3476.             'getSyncFlag' => 'setSyncFlag',
  3477.             'getFirstname' => 'setName',
  3478.         ];
  3479.         $user->setUserAppId($appIds);
  3480.         $user->setUserAppIdList(json_encode([$appIds]));
  3481.         $user->setStatus(1);
  3482.         foreach ($setterMap as $getter => $setter) {
  3483.             if (isset($userData[$getter]) && method_exists($user$setter)) {
  3484.                 $user->$setter($userData[$getter]);
  3485.             }
  3486.         }
  3487.         $fullName trim(($userData['getFirstname'] ?? '') . ' ' . ($userData['getLastname'] ?? ''));
  3488.         if (!empty($fullName)) {
  3489.             $user->setName($fullName);
  3490.         }
  3491.         $imagePathToSet '';
  3492.         $uploadedFile $request->files->get('file_' $globalId);
  3493.         if ($uploadedFile) {
  3494.             $uploadDir $this->getParameter('kernel.project_dir') . '/web/uploads/UserImage/';
  3495.             if (!file_exists($uploadDir)) {
  3496.                 mkdir($uploadDir0777true);
  3497.             }
  3498.             $filename 'user_' $globalId '.' $uploadedFile->guessExtension();
  3499.             $uploadedFile->move($uploadDir$filename);
  3500.             $imagePathToSet 'uploads/UserImage/' $filename;
  3501.             $user->setImage($imagePathToSet);
  3502.         }
  3503.         $user->setUserType(1);
  3504.         $em->persist($user);
  3505.         $em->flush();
  3506.         $employee $em->getRepository('ApplicationBundle:Employee')->findOneBy([
  3507.             'userId' => $user->getUserId()
  3508.         ]);
  3509.         if (!$employee) {
  3510.             $employee = new \ApplicationBundle\Entity\Employee();
  3511.             $employee->setUserId($user->getUserId());
  3512.             $employee->setDateOfAddition(new \DateTime());
  3513.         }
  3514.         $employee->setFirstName($userData['getFirstname'] ?? null);
  3515.         $employee->setLastName($userData['getLastname'] ?? null);
  3516.         $employee->setName(trim(($userData['getFirstname'] ?? '') . ' ' . ($userData['getLastname'] ?? '')));
  3517.         $employee->setEmail($userData['getEmail'] ?? null);
  3518.         $employee->setEmmContact($userData['getEmmContact'] ?? null);
  3519.         $employee->setCurrentAddress($userData['getCurrAddr'] ?? null);
  3520.         $employee->setPermanentAddress($userData['getPermAddr'] ?? null);
  3521.         $employee->setCompanyId((int)$companyId);
  3522.         $employee->setDepartmentId($userData['getDept'] ?? null);
  3523.         $employee->setBranchId($userData['getBranch'] ?? null);
  3524.         $employee->setPositionId($userData['getDesg'] ?? null);
  3525.         $employee->setSupervisorId($userData['getSupervisor'] ?? null);
  3526.         if (!empty($imagePathToSet)) {
  3527.             $employee->setImage($imagePathToSet);
  3528.         }
  3529.         $employee->setStatus("1");
  3530.         $employee->setLastModifiedDate(new \DateTime());
  3531.         $em->persist($employee);
  3532.         $em->flush();
  3533.         $employeeDetails $em->getRepository('ApplicationBundle:EmployeeDetails')
  3534.             ->findOneBy(['userId' => $user->getUserId()]);
  3535.         if (!$employeeDetails) {
  3536.             $employeeDetails = new \ApplicationBundle\Entity\EmployeeDetails();
  3537.             $employeeDetails->setUserId($user->getUserId());
  3538.         }
  3539.         $employeeDetails->setId($employee->getEmployeeId());
  3540.         $employeeDetails->setFirstname($userData['getFirstname'] ?? null);
  3541.         $employeeDetails->setLastname($userData['getLastname'] ?? null);
  3542.         $employeeDetails->setUsername($userData['getUsername'] ?? null);
  3543.         $employeeDetails->setEmail($userData['getEmail'] ?? null);
  3544.         $employeeDetails->setPassword($userData['getPassword'] ?? null);
  3545.         $employeeDetails->setNid($userData['getNid'] ?? null);
  3546.         $employeeDetails->setSex($userData['getSex'] ?? null);
  3547.         $employeeDetails->setFather($userData['getFather'] ?? null);
  3548.         $employeeDetails->setMother($userData['getMother'] ?? null);
  3549.         $employeeDetails->setSpouse($userData['getSpouse'] ?? null);
  3550.         $employeeDetails->setChild1($userData['getChild1'] ?? null);
  3551.         $employeeDetails->setChild2($userData['getChild2'] ?? null);
  3552.         $employeeDetails->setPhone($userData['getPhone'] ?? null);
  3553.         $employeeDetails->setOfficialPhone($userData['getOfficailPhone'] ?? null);
  3554.         $employeeDetails->setCurrAddr($userData['getCurrAddr'] ?? null);
  3555.         $employeeDetails->setPermAddr($userData['getPermAddr'] ?? null);
  3556.         $employeeDetails->setEmmContact($userData['getEmmContact'] ?? null);
  3557.         if (!empty($userData['getDob'])) {
  3558.             $employeeDetails->setDob(new \DateTime($userData['getDob']));
  3559.         }
  3560.         if (!empty($userData['getJoiningDate'])) {
  3561.             $employeeDetails->setJoiningDate(new \DateTime($userData['getJoiningDate']));
  3562.         }
  3563.         if (!empty($userData['getEmpValidTill'])) {
  3564.             $employeeDetails->setEmpValidTill(new \DateTime($userData['getEmpValidTill']));
  3565.         }
  3566.         if (!empty($userData['getTinValidTill'])) {
  3567.             $employeeDetails->setTinValidTill(new \DateTime($userData['getTinValidTill']));
  3568.         }
  3569.         if (!empty($userData['getMedInsValidTill'])) {
  3570.             $employeeDetails->setMedInsValidTill(new \DateTime($userData['getMedInsValidTill']));
  3571.         }
  3572.         $employeeDetails->setEmpType($userData['getEmpType'] ?? null);
  3573.         $employeeDetails->setEmpCode($userData['getEmpCode'] ?? null);
  3574.         $employeeDetails->setEmployeeLevel($userData['getEmployeeLevel'] ?? null);
  3575.         $employeeDetails->setTin($userData['getTin'] ?? null);
  3576.         $employeeDetails->setSkill($userData['getSkill'] ?? null);
  3577.         $employeeDetails->setEducationData($userData['getEducationData'] ?? null);
  3578.         $employeeDetails->setWorkExperienceData($userData['getWorkExperienceData'] ?? null);
  3579.         $employeeDetails->setApplicationText($userData['getApplicationText'] ?? null);
  3580.         $employeeDetails->setCurrentEmployment($userData['getCurrentEmployment'] ?? null);
  3581.         $employeeDetails->setEmergencyContactNumber($userData['getEmergencyContactNumber'] ?? null);
  3582.         $employeeDetails->setPostalCode($userData['getPostalCode'] ?? null);
  3583.         $employeeDetails->setCountry($userData['getCountry'] ?? null);
  3584.         if (!empty($imagePathToSet)) {
  3585.             $employeeDetails->setImage($imagePathToSet);
  3586.         }
  3587.         $em->persist($employeeDetails);
  3588.         $em->flush();
  3589.         $uploadedFile $request->files->get('file_' $globalId);
  3590.         return new JsonResponse([
  3591.             'success' => true,
  3592.             'globalId' => $globalId,
  3593.             'appIds' => $appIds,
  3594.             'userIds' => $userIds,
  3595.             'hasFile' => $uploadedFile !== null,
  3596.         ]);
  3597.     }
  3598.     public function getIndustryListForAppAction()
  3599.     {
  3600.         $industryList GeneralConstant::$industryList;
  3601.         return new JsonResponse($industryList);
  3602.     }
  3603.     public function getFeatureListAction()
  3604.     {
  3605.         $featureList GeneralConstant::$featureList;
  3606.         return new JsonResponse($featureList);
  3607.     }
  3608.     public function chooseYourPlanAction()
  3609.     {
  3610.         $plan GeneralConstant::$chooseYourPlan;
  3611.         return new JsonResponse($plan);
  3612.     }
  3613. //    public function getLogindataFromTokenAction(Request $request)
  3614. //    {
  3615. //        $em_goc = $this->getDoctrine()->getManager('company_group');
  3616. //        $sessionData = MiscActions::GetSessionDataFromToken($em_goc, $request->query->get('hbeeSessionToken'))['sessionData'];
  3617. //        return new JsonResponse($sessionData);
  3618. //        $sessionDataa = MiscActions::GetSessionDataFromToken($em_goc, $request->query->get('hbeeSessionToken'))['sessionData'];
  3619. //        return new JsonResponse($sessionDataa);
  3620. //    }
  3621.     public function getLogindataFromTokenAction(Request $request)
  3622.     {
  3623.         $em_goc $this->getDoctrine()->getManager('company_group');
  3624.         $token $request->query->get('hbeeSessionToken');
  3625.         if (!$token) {
  3626.             return new JsonResponse(['error' => 'Missing session token'], 400);
  3627.         }
  3628.         $sessionResult MiscActions::GetSessionDataFromToken($em_goc$token);
  3629.         if (!$sessionResult || !isset($sessionResult['sessionData'])) {
  3630.             return new JsonResponse(['error' => 'Invalid session token or session not found'], 401);
  3631.         }
  3632.         $sessionData $sessionResult['sessionData'];
  3633.         return new JsonResponse($sessionData);
  3634.     }
  3635.    public function packageDetailsAction()
  3636. {
  3637.     $packageDetails GeneralConstant::$packageDetails;
  3638.     return new JsonResponse([
  3639.         'success' => true,
  3640.         'message' => 'Data fetched successfully.',
  3641.         'data' => $packageDetails
  3642.     ]);
  3643. }
  3644.     public function employeeRangeAction()
  3645.     {
  3646.         $employeeRangeForApp GeneralConstant::$employeeRange;
  3647.         return new JsonResponse($employeeRangeForApp);
  3648.     }
  3649.     public function paymentMethodAction()
  3650.     {
  3651.         $paymentMethod GeneralConstant::$paymentMethod;
  3652.         return new JsonResponse($paymentMethod);
  3653.     }
  3654.     public function companyTypeAction()
  3655.     {
  3656.         $companyType GeneralConstant::$companyType;
  3657.         return new JsonResponse(
  3658.             [
  3659.                 'status' => 'success',
  3660.                 'message' => 'Company types retrieved successfully.',
  3661.                 'data' => $companyType,
  3662.             ]
  3663.          );
  3664.     }
  3665.     public function getCountryListAction()
  3666.     {
  3667.         $em_goc $this->getDoctrine()->getManager('company_group');
  3668.         $countryList $em_goc->getRepository('CompanyGroupBundle:EntityCountries')
  3669.             ->createQueryBuilder('C')
  3670.             ->select('C.CountryId''C.code''C.nameEn')
  3671.             ->getQuery()
  3672.             ->getArrayResult();
  3673.         // $formattedList = array_map(function ($country) {
  3674.         //     return [
  3675.         //         'countryId' => $country['countryId'],
  3676.         //         'countryName' => $country['nameEn'],
  3677.         //         'countryCode' => $country['code'],
  3678.         //     ];
  3679.         // }, $countryList);
  3680.         return new JsonResponse([
  3681.             'status' => true,
  3682.             'message' => 'Country list fetched successfully',
  3683.             'data' => $countryList,
  3684.         ]);
  3685.     }
  3686. public function spotLightSearchAction(Request $request,$queryStr ''){
  3687.     
  3688.     $em $this->getDoctrine()->getManager();
  3689.     $data = [];
  3690.     $data_by_id = [];
  3691.     $session $request->getSession();
  3692.     $entityDetails GeneralConstant::$Entity_list_details
  3693.     if ($queryStr == '_DEFAULT_')
  3694.         $queryStr '';
  3695.     if ($request->request->has('query') && $queryStr == '')
  3696.         $queryStr $request->request->get('queryStr');
  3697.     if ($queryStr == '_DEFAULT_')
  3698.         $queryStr '';
  3699.     //module
  3700.     $filterQryForCriteria "select * from sys_module where 1=1 and module_name  like '%" $queryStr "%'  limit 10";
  3701.     $get_kids_sql $filterQryForCriteria;
  3702.     $stmt $em->getConnection()->prepare($get_kids_sql);
  3703.     $stmt->execute();
  3704.     $get_kids $stmt->fetchAll();
  3705.     $productId 0;
  3706.     $absoluteUrl $this->generateUrl('dashboard', [], UrlGenerator::ABSOLUTE_URL);
  3707.     if (!empty($get_kids)) {
  3708.         foreach ($get_kids as $product) {
  3709.             $pa = array();
  3710.             $pa['id'] = $product['module_id'];
  3711.             $pa['name'] = $product['module_name'] ;
  3712.             $pa['moduleRoute'] =$product['module_route'];
  3713.             $pa['url'] = $absoluteUrl'/' .$product['module_route'];;
  3714.             $data[] = $pa;;
  3715.         }
  3716.     }
  3717.     //supplier
  3718.     $filterQryForCriteria "select * from acc_suppliers where 1=1 and supplier_name  like '%" $queryStr "%'  limit 10";
  3719.     $get_kids_sql $filterQryForCriteria;
  3720.     $stmt $em->getConnection()->prepare($get_kids_sql);
  3721.     $stmt->execute();
  3722.     $get_kids $stmt->fetchAll();
  3723.     $productId 0;
  3724.     $absoluteUrl $this->generateUrl('dashboard', [], UrlGenerator::ABSOLUTE_URL);
  3725.     $url $this->generateUrl(
  3726.         'create_supplier'
  3727.     );
  3728.     if (!empty($get_kids)) {
  3729.         foreach ($get_kids as $product) {
  3730.             $pa = array();
  3731.             $pa['id'] = $product['supplier_id'];
  3732.             $pa['name'] = $product['supplier_name'] ;
  3733.             $pa['url'] = rtrim($absoluteUrl'/') . '/' ltrim($url'/') . '?ex_s_id=' $product['supplier_id'];
  3734.             $data[] = $pa;;
  3735.         }
  3736.     }
  3737.     //client
  3738.     $filterQryForCriteria "select * from acc_clients where 1=1 and client_name  like '%" $queryStr "%'  limit 10";
  3739.     $get_kids_sql $filterQryForCriteria;
  3740.     $stmt $em->getConnection()->prepare($get_kids_sql);
  3741.     $stmt->execute();
  3742.     $get_kids $stmt->fetchAll();
  3743.     $productId 0;
  3744.     $absoluteUrl $this->generateUrl('dashboard', [], UrlGenerator::ABSOLUTE_URL);
  3745.     $url $this->generateUrl(
  3746.         'create_client'
  3747.     );
  3748.     if (!empty($get_kids)) {
  3749.         foreach ($get_kids as $product) {
  3750.             $pa = array();
  3751.             $pa['id'] = $product['client_id'];
  3752.             $pa['name'] = $product['client_name'] ;
  3753.             $pa['url'] = rtrim($absoluteUrl'/') . '/' trim($url'/') . '/' $product['client_id'];
  3754.             $data[] = $pa;;
  3755.         }
  3756.     }
  3757.     //document
  3758.     $filterQryForCriteria "select * from approval where 1=1 and document_hash  like '%" $queryStr "%'  limit 10";
  3759.     $get_kids_sql $filterQryForCriteria;
  3760.     $stmt $em->getConnection()->prepare($get_kids_sql);
  3761.     $stmt->execute();
  3762.     $get_kids $stmt->fetchAll();
  3763.     $productId 0;
  3764.     $absoluteUrl $this->generateUrl('dashboard', [], UrlGenerator::ABSOLUTE_URL);
  3765.     
  3766.     if (!empty($get_kids)) {
  3767.         foreach ($get_kids as $product) {
  3768.             $url $this->generateUrl(
  3769.                 $entityDetails[$product['entity']]['entity_view_route_path_name']
  3770.             );
  3771.             $pa = array();
  3772.             $pa['id'] = $product['id'];
  3773.             $pa['name'] = $product['document_hash'] ;
  3774.             $pa['url'] = rtrim($absoluteUrl'/') . '/' trim($url'/') . '/' $product['entity_id'];
  3775.             $data[] = $pa;;
  3776.         }
  3777.     }
  3778.     {
  3779.         return new JsonResponse(
  3780.             array(
  3781.                 'success' => true,
  3782.                 'data' => $data,
  3783.             )
  3784.         );
  3785.     }
  3786. }
  3787.     public function getMlDataAction()
  3788.     {
  3789.         $data GeneralConstant::$dataFromMl;
  3790.         return new JsonResponse($data);
  3791.     }
  3792.     public function UploadDocumentsAction(Request $request)
  3793.     {
  3794.         $session $request->getSession();
  3795.         $em $this->getDoctrine()->getManager();
  3796.         return $this->render(
  3797.             'ApplicationBundle:pages/dashboard:upload_documents.html.twig',
  3798.             array(
  3799.                 'page_title' => 'Upload Documents',
  3800.             )
  3801.         );
  3802.     }
  3803. }