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.             'ApplicationBundle:pages/login: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.                 } else
  1730.                     return $this->render(
  1731.                         'ApplicationBundle:pages/dashboard:index_finance_mobile.html.twig',
  1732.                         array(
  1733.                             'page_title' => 'Finance Dashboard',
  1734.                             'dashboardDataForUser' => []
  1735.                         )
  1736.                     );
  1737.             } else {
  1738.                 //check if user has a default route if yes redirect to it
  1739.                 if ($session->get(UserConstants::USER_TYPE) == UserConstants::USER_TYPE_SUPPLIER)
  1740.                     $defaultRoute 'supplier_dashboard';
  1741.                 else if ($session->get(UserConstants::USER_TYPE) == UserConstants::USER_TYPE_CLIENT)
  1742.                     $defaultRoute 'client_dashboard';
  1743.                 else if ($session->get(UserConstants::USER_TYPE) == UserConstants::USER_TYPE_APPLICANT) {
  1744.                     if ($systemType == '_CENTRAL_') {
  1745.                         $defaultRoute 'central_landing';
  1746.                     } else
  1747.                         $defaultRoute 'applicant_dashboard';
  1748.                 } else
  1749.                     $defaultRoute $session->get(UserConstants::USER_DEFAULT_ROUTE);
  1750.                 //            if(in_array($defaultRoute, $ROUTE_LIST))
  1751.                 if ($defaultRoute != '' && $defaultRoute != null)
  1752.                     return $this->redirectToRoute($defaultRoute);
  1753.                 else
  1754.                     return $this->render(
  1755.                         'ApplicationBundle:pages/dashboard:index.html.twig',
  1756.                         array(
  1757.                             'page_title' => 'Dashboard'
  1758.                         )
  1759.                     );
  1760.             }
  1761.     }
  1762.     public function indexSupplierAction(Request $request)
  1763.     {
  1764.         $session $request->getSession();
  1765.         $supplierId 3;
  1766.         if ($request->query->has('supplierId')) //for debug now
  1767.         {
  1768.             $session->set('supplierId'$request->query->get('supplierId'));
  1769.         }
  1770.         $supplierId $session->get('supplierId');  //////////////////////LATER
  1771.         $em $this->getDoctrine()->getManager();
  1772.         $companyId $this->getLoggedUserCompanyId($request);
  1773.         $userId $request->getSession()->get(UserConstants::USER_ID);
  1774.         $SD Supplier::GetSupplierProfileDetails($em$supplierId'SI');
  1775.         $dashboardDataForUser = [];
  1776.         return $this->render(
  1777.             'ApplicationBundle:pages/dashboard:index_supplier.html.twig',
  1778.             array(
  1779.                 'page_title' => 'Supplier Dashboard',
  1780.                 'dashboardDataForUser' => $dashboardDataForUser,
  1781.                 'data' => $SD,
  1782.                 'igList' => Inventory::ItemGroupList($em$companyId)
  1783.             )
  1784.         );
  1785.     }
  1786.     public function indexClientAction(Request $request)
  1787.     {
  1788.         $session $request->getSession();
  1789.         $clientId 3;
  1790.         if ($request->query->has('clientId')) //for debug now
  1791.         {
  1792.             $session->set('clientId'$request->query->get('clientId'));
  1793.         }
  1794.         $clientId $session->get('clientId');  //////////////////////LATER
  1795.         $em $this->getDoctrine()->getManager();
  1796.         $companyId $this->getLoggedUserCompanyId($request);
  1797.         $userId $request->getSession()->get(UserConstants::USER_ID);
  1798.         $SD Client::GetClientProfileDetails($em$clientId'CI');
  1799.         $dashboardDataForUser = [];
  1800.         return $this->render(
  1801.             'ApplicationBundle:pages/dashboard:index_client.html.twig',
  1802.             array(
  1803.                 'page_title' => 'Client Dashboard',
  1804.                 'dashboardDataForUser' => $dashboardDataForUser,
  1805.                 'data' => $SD,
  1806.                 'igList' => Inventory::ItemGroupList($em$companyId)
  1807.             )
  1808.         );
  1809.     }
  1810.     public function indexFinanceAction(Request $request)
  1811.     {
  1812.         $session $request->getSession();
  1813.         $dashboardDataForUser = [];
  1814.         $em $this->getDoctrine()->getManager();
  1815.         $companyId $this->getLoggedUserCompanyId($request);
  1816.         $userId $request->getSession()->get(UserConstants::USER_ID);
  1817.         $dbQuery $em->getRepository("ApplicationBundle:DashboardWidget")->findBy(
  1818.             array(
  1819.                 'CompanyId' => $companyId,
  1820.                 'userId' => $userId,
  1821.                 'status' => GeneralConstant::ACTIVE
  1822.             ),
  1823.             array(
  1824.                 'sequence' => 'ASC'
  1825.             )
  1826.         );
  1827.         if (empty($dbQuery))   ///now get the defaults
  1828.             $dbQuery $em->getRepository("ApplicationBundle:DashboardWidget")->findBy(
  1829.                 array(
  1830.                     'CompanyId' => $companyId,
  1831.                     //                    'userId'=>$userId,
  1832.                     'defaultBoxFlag' => 1,
  1833.                     'status' => GeneralConstant::ACTIVE
  1834.                 ),
  1835.                 array(
  1836.                     'sequence' => 'ASC'
  1837.                 )
  1838.             );
  1839.         foreach ($dbQuery as $entry) {
  1840.             $dashboardDataForUser[] = array(
  1841.                 'id' => $entry->getId(),
  1842.                 'widgetId' => $entry->getId(),
  1843.                 'widgetSequence' => $entry->getSequence(),
  1844.                 'widgetStatus' => $entry->getStatus(),
  1845.                 'widgetData' => json_decode($entry->getData(), true),
  1846.                 'defaultBoxFlag' => $entry->getDefaultBoxFlag(),
  1847.                 'widgetSizeTiny' => $entry->getSizeTiny(),
  1848.                 'widgetSizeSmall' => $entry->getSizeSmall(),
  1849.                 'widgetSizeMedium' => $entry->getSizeMedium(),
  1850.                 'widgetSizeLarge' => $entry->getSizeLarge(),
  1851.                 'refreshInterval' => $entry->getRefreshInterval(),
  1852.             );
  1853.         }
  1854.         if ($session->has('isMobile')) {
  1855.             if ($session->get('isMobile') == true) {
  1856.                 return $this->render(
  1857.                     'ApplicationBundle:pages/dashboard:index_finance_mobile.html.twig',
  1858.                     array(
  1859.                         'page_title' => 'Finance Dashboard',
  1860.                         'dashboardDataForUser' => $dashboardDataForUser
  1861.                     )
  1862.                 );
  1863.             } else {
  1864.             }
  1865.         }
  1866.         return $this->render(
  1867.             'ApplicationBundle:pages/dashboard:index_finance.html.twig',
  1868.             array(
  1869.                 'page_title' => 'Finance Dashboard',
  1870.                 'dashboardDataForUser' => $dashboardDataForUser
  1871.             )
  1872.         );
  1873.     }
  1874.     public function indexSalesAction(Request $request)
  1875.     {
  1876.         $session $request->getSession();
  1877.         $dashboardDataForUser = [];
  1878.         $em $this->getDoctrine()->getManager();
  1879.         $companyId $this->getLoggedUserCompanyId($request);
  1880.         $userId $request->getSession()->get(UserConstants::USER_ID);
  1881.         $dbQuery $em->getRepository("ApplicationBundle:DashboardWidget")->findBy(
  1882.             array(
  1883.                 'CompanyId' => $companyId,
  1884.                 'userId' => $userId,
  1885.                 'status' => GeneralConstant::ACTIVE
  1886.             ),
  1887.             array(
  1888.                 'sequence' => 'ASC'
  1889.             )
  1890.         );
  1891.         if (empty($dbQuery))   ///now get the defaults
  1892.             $dbQuery $em->getRepository("ApplicationBundle:DashboardWidget")->findBy(
  1893.                 array(
  1894.                     'CompanyId' => $companyId,
  1895.                     //                    'userId'=>$userId,
  1896.                     'defaultBoxFlag' => 1,
  1897.                     'status' => GeneralConstant::ACTIVE
  1898.                 ),
  1899.                 array(
  1900.                     'sequence' => 'ASC'
  1901.                 )
  1902.             );
  1903.         foreach ($dbQuery as $entry) {
  1904.             $dashboardDataForUser[] = array(
  1905.                 'id' => $entry->getId(),
  1906.                 'widgetId' => $entry->getId(),
  1907.                 'widgetSequence' => $entry->getSequence(),
  1908.                 'widgetStatus' => $entry->getStatus(),
  1909.                 'widgetData' => json_decode($entry->getData(), true),
  1910.                 'defaultBoxFlag' => $entry->getDefaultBoxFlag(),
  1911.                 'widgetSizeTiny' => $entry->getSizeTiny(),
  1912.                 'widgetSizeSmall' => $entry->getSizeSmall(),
  1913.                 'widgetSizeMedium' => $entry->getSizeMedium(),
  1914.                 'widgetSizeLarge' => $entry->getSizeLarge(),
  1915.                 'refreshInterval' => $entry->getRefreshInterval(),
  1916.             );
  1917.         }
  1918.         if ($session->has('isMobile')) {
  1919.             if ($session->get('isMobile') == true) {
  1920.                 return $this->render(
  1921.                     'ApplicationBundle:pages/dashboard:index_finance_mobile.html.twig',
  1922.                     array(
  1923.                         'page_title' => 'Finance Dashboard',
  1924.                         'dashboardDataForUser' => $dashboardDataForUser
  1925.                     )
  1926.                 );
  1927.             } else {
  1928.             }
  1929.         }
  1930.         return $this->render(
  1931.             'ApplicationBundle:pages/dashboard:index_sales.html.twig',
  1932.             array(
  1933.                 'page_title' => 'Sales Dashboard',
  1934.                 'dashboardDataForUser' => $dashboardDataForUser
  1935.             )
  1936.         );
  1937.     }
  1938.     public function indexPurchaseAction(Request $request)
  1939.     {
  1940.         $session $request->getSession();
  1941.         $dashboardDataForUser = [];
  1942.         $em $this->getDoctrine()->getManager();
  1943.         $companyId $this->getLoggedUserCompanyId($request);
  1944.         $userId $request->getSession()->get(UserConstants::USER_ID);
  1945.         $dbQuery $em->getRepository("ApplicationBundle:DashboardWidget")->findBy(
  1946.             array(
  1947.                 'CompanyId' => $companyId,
  1948.                 'userId' => $userId,
  1949.                 'status' => GeneralConstant::ACTIVE
  1950.             ),
  1951.             array(
  1952.                 'sequence' => 'ASC'
  1953.             )
  1954.         );
  1955.         if (empty($dbQuery))   ///now get the defaults
  1956.             $dbQuery $em->getRepository("ApplicationBundle:DashboardWidget")->findBy(
  1957.                 array(
  1958.                     'CompanyId' => $companyId,
  1959.                     //                    'userId'=>$userId,
  1960.                     'defaultBoxFlag' => 1,
  1961.                     'status' => GeneralConstant::ACTIVE
  1962.                 ),
  1963.                 array(
  1964.                     'sequence' => 'ASC'
  1965.                 )
  1966.             );
  1967.         foreach ($dbQuery as $entry) {
  1968.             $dashboardDataForUser[] = array(
  1969.                 'id' => $entry->getId(),
  1970.                 'widgetId' => $entry->getId(),
  1971.                 'widgetSequence' => $entry->getSequence(),
  1972.                 'widgetStatus' => $entry->getStatus(),
  1973.                 'widgetData' => json_decode($entry->getData(), true),
  1974.                 'defaultBoxFlag' => $entry->getDefaultBoxFlag(),
  1975.                 'widgetSizeTiny' => $entry->getSizeTiny(),
  1976.                 'widgetSizeSmall' => $entry->getSizeSmall(),
  1977.                 'widgetSizeMedium' => $entry->getSizeMedium(),
  1978.                 'widgetSizeLarge' => $entry->getSizeLarge(),
  1979.                 'refreshInterval' => $entry->getRefreshInterval(),
  1980.             );
  1981.         }
  1982.         return $this->render(
  1983.             'ApplicationBundle:pages/dashboard:index_sales.html.twig',
  1984.             array(
  1985.                 'page_title' => 'Sales Dashboard',
  1986.                 'dashboardDataForUser' => $dashboardDataForUser
  1987.             )
  1988.         );
  1989.     }
  1990.     public function indexDistributionAction(Request $request)
  1991.     {
  1992.         $session $request->getSession();
  1993.         $dashboardDataForUser = [];
  1994.         $em $this->getDoctrine()->getManager();
  1995.         $companyId $this->getLoggedUserCompanyId($request);
  1996.         $userId $request->getSession()->get(UserConstants::USER_ID);
  1997.         $dbQuery $em->getRepository("ApplicationBundle:DashboardWidget")->findBy(
  1998.             array(
  1999.                 'CompanyId' => $companyId,
  2000.                 'userId' => $userId,
  2001.                 'status' => GeneralConstant::ACTIVE
  2002.             ),
  2003.             array(
  2004.                 'sequence' => 'ASC'
  2005.             )
  2006.         );
  2007.         if (empty($dbQuery))   ///now get the defaults
  2008.             $dbQuery $em->getRepository("ApplicationBundle:DashboardWidget")->findBy(
  2009.                 array(
  2010.                     'CompanyId' => $companyId,
  2011.                     //                    'userId'=>$userId,
  2012.                     'defaultBoxFlag' => 1,
  2013.                     'status' => GeneralConstant::ACTIVE
  2014.                 ),
  2015.                 array(
  2016.                     'sequence' => 'ASC'
  2017.                 )
  2018.             );
  2019.         foreach ($dbQuery as $entry) {
  2020.             $dashboardDataForUser[] = array(
  2021.                 'id' => $entry->getId(),
  2022.                 'widgetId' => $entry->getId(),
  2023.                 'widgetSequence' => $entry->getSequence(),
  2024.                 'widgetStatus' => $entry->getStatus(),
  2025.                 'widgetData' => json_decode($entry->getData(), true),
  2026.                 'defaultBoxFlag' => $entry->getDefaultBoxFlag(),
  2027.                 'widgetSizeTiny' => $entry->getSizeTiny(),
  2028.                 'widgetSizeSmall' => $entry->getSizeSmall(),
  2029.                 'widgetSizeMedium' => $entry->getSizeMedium(),
  2030.                 'widgetSizeLarge' => $entry->getSizeLarge(),
  2031.                 'refreshInterval' => $entry->getRefreshInterval(),
  2032.             );
  2033.         }
  2034.         return $this->render(
  2035.             'ApplicationBundle:pages/dashboard:index_sales.html.twig',
  2036.             array(
  2037.                 'page_title' => 'Sales Dashboard',
  2038.                 'dashboardDataForUser' => $dashboardDataForUser
  2039.             )
  2040.         );
  2041.     }
  2042.     public function indexProductionAction(Request $request)
  2043.     {
  2044.         $session $request->getSession();
  2045.         $dashboardDataForUser = [];
  2046.         $em $this->getDoctrine()->getManager();
  2047.         $companyId $this->getLoggedUserCompanyId($request);
  2048.         $userId $request->getSession()->get(UserConstants::USER_ID);
  2049.         $dbQuery $em->getRepository("ApplicationBundle:DashboardWidget")->findBy(
  2050.             array(
  2051.                 'CompanyId' => $companyId,
  2052.                 'userId' => $userId,
  2053.                 'status' => GeneralConstant::ACTIVE
  2054.             ),
  2055.             array(
  2056.                 'sequence' => 'ASC'
  2057.             )
  2058.         );
  2059.         if (empty($dbQuery))   ///now get the defaults
  2060.             $dbQuery $em->getRepository("ApplicationBundle:DashboardWidget")->findBy(
  2061.                 array(
  2062.                     'CompanyId' => $companyId,
  2063.                     //                    'userId'=>$userId,
  2064.                     'defaultBoxFlag' => 1,
  2065.                     'status' => GeneralConstant::ACTIVE
  2066.                 ),
  2067.                 array(
  2068.                     'sequence' => 'ASC'
  2069.                 )
  2070.             );
  2071.         foreach ($dbQuery as $entry) {
  2072.             $dashboardDataForUser[] = array(
  2073.                 'id' => $entry->getId(),
  2074.                 'widgetId' => $entry->getId(),
  2075.                 'widgetSequence' => $entry->getSequence(),
  2076.                 'widgetStatus' => $entry->getStatus(),
  2077.                 'widgetData' => json_decode($entry->getData(), true),
  2078.                 'defaultBoxFlag' => $entry->getDefaultBoxFlag(),
  2079.                 'widgetSizeTiny' => $entry->getSizeTiny(),
  2080.                 'widgetSizeSmall' => $entry->getSizeSmall(),
  2081.                 'widgetSizeMedium' => $entry->getSizeMedium(),
  2082.                 'widgetSizeLarge' => $entry->getSizeLarge(),
  2083.                 'refreshInterval' => $entry->getRefreshInterval(),
  2084.             );
  2085.         }
  2086.         return $this->render(
  2087.             'ApplicationBundle:pages/dashboard:index_sales.html.twig',
  2088.             array(
  2089.                 'page_title' => 'Sales Dashboard',
  2090.                 'dashboardDataForUser' => $dashboardDataForUser
  2091.             )
  2092.         );
  2093.     }
  2094.     public function indexInventoryAction(Request $request)
  2095.     {
  2096.         $session $request->getSession();
  2097.         $dashboardDataForUser = [];
  2098.         $em $this->getDoctrine()->getManager();
  2099.         $companyId $this->getLoggedUserCompanyId($request);
  2100.         $userId $request->getSession()->get(UserConstants::USER_ID);
  2101.         $dbQuery $em->getRepository("ApplicationBundle:DashboardWidget")->findBy(
  2102.             array(
  2103.                 'CompanyId' => $companyId,
  2104.                 'userId' => $userId,
  2105.                 'status' => GeneralConstant::ACTIVE
  2106.             ),
  2107.             array(
  2108.                 'sequence' => 'ASC'
  2109.             )
  2110.         );
  2111.         if (empty($dbQuery))   ///now get the defaults
  2112.             $dbQuery $em->getRepository("ApplicationBundle:DashboardWidget")->findBy(
  2113.                 array(
  2114.                     'CompanyId' => $companyId,
  2115.                     //                    'userId'=>$userId,
  2116.                     'defaultBoxFlag' => 1,
  2117.                     'status' => GeneralConstant::ACTIVE
  2118.                 ),
  2119.                 array(
  2120.                     'sequence' => 'ASC'
  2121.                 )
  2122.             );
  2123.         foreach ($dbQuery as $entry) {
  2124.             $dashboardDataForUser[] = array(
  2125.                 'id' => $entry->getId(),
  2126.                 'widgetId' => $entry->getId(),
  2127.                 'widgetSequence' => $entry->getSequence(),
  2128.                 'widgetStatus' => $entry->getStatus(),
  2129.                 'widgetData' => json_decode($entry->getData(), true),
  2130.                 'defaultBoxFlag' => $entry->getDefaultBoxFlag(),
  2131.                 'widgetSizeTiny' => $entry->getSizeTiny(),
  2132.                 'widgetSizeSmall' => $entry->getSizeSmall(),
  2133.                 'widgetSizeMedium' => $entry->getSizeMedium(),
  2134.                 'widgetSizeLarge' => $entry->getSizeLarge(),
  2135.                 'refreshInterval' => $entry->getRefreshInterval(),
  2136.             );
  2137.         }
  2138.         return $this->render(
  2139.             'ApplicationBundle:pages/dashboard:index_sales.html.twig',
  2140.             array(
  2141.                 'page_title' => 'Sales Dashboard',
  2142.                 'dashboardDataForUser' => $dashboardDataForUser
  2143.             )
  2144.         );
  2145.     }
  2146.     public function indexServiceAction(Request $request)
  2147.     {
  2148.         $session $request->getSession();
  2149.         $dashboardDataForUser = [];
  2150.         $em $this->getDoctrine()->getManager();
  2151.         $companyId $this->getLoggedUserCompanyId($request);
  2152.         $userId $request->getSession()->get(UserConstants::USER_ID);
  2153.         $dbQuery $em->getRepository("ApplicationBundle:DashboardWidget")->findBy(
  2154.             array(
  2155.                 'CompanyId' => $companyId,
  2156.                 'userId' => $userId,
  2157.                 'status' => GeneralConstant::ACTIVE
  2158.             ),
  2159.             array(
  2160.                 'sequence' => 'ASC'
  2161.             )
  2162.         );
  2163.         if (empty($dbQuery))   ///now get the defaults
  2164.             $dbQuery $em->getRepository("ApplicationBundle:DashboardWidget")->findBy(
  2165.                 array(
  2166.                     'CompanyId' => $companyId,
  2167.                     //                    'userId'=>$userId,
  2168.                     'defaultBoxFlag' => 1,
  2169.                     'status' => GeneralConstant::ACTIVE
  2170.                 ),
  2171.                 array(
  2172.                     'sequence' => 'ASC'
  2173.                 )
  2174.             );
  2175.         foreach ($dbQuery as $entry) {
  2176.             $dashboardDataForUser[] = array(
  2177.                 'id' => $entry->getId(),
  2178.                 'widgetId' => $entry->getId(),
  2179.                 'widgetSequence' => $entry->getSequence(),
  2180.                 'widgetStatus' => $entry->getStatus(),
  2181.                 'widgetData' => json_decode($entry->getData(), true),
  2182.                 'defaultBoxFlag' => $entry->getDefaultBoxFlag(),
  2183.                 'widgetSizeTiny' => $entry->getSizeTiny(),
  2184.                 'widgetSizeSmall' => $entry->getSizeSmall(),
  2185.                 'widgetSizeMedium' => $entry->getSizeMedium(),
  2186.                 'widgetSizeLarge' => $entry->getSizeLarge(),
  2187.                 'refreshInterval' => $entry->getRefreshInterval(),
  2188.             );
  2189.         }
  2190.         return $this->render(
  2191.             'ApplicationBundle:pages/dashboard:index_sales.html.twig',
  2192.             array(
  2193.                 'page_title' => 'Sales Dashboard',
  2194.                 'dashboardDataForUser' => $dashboardDataForUser
  2195.             )
  2196.         );
  2197.     }
  2198.     public function modifyDashboardAction(Request $request)
  2199.     {
  2200.         $session $request->getSession();
  2201.         $em $this->getDoctrine()->getManager();
  2202.         $companyId $this->getLoggedUserCompanyId($request);
  2203.         $userId $request->getSession()->get(UserConstants::USER_ID);
  2204.         if ($request->isMethod('post')) {
  2205.             //update dashboard data
  2206.             if ($request->request->has('widgetId')) {
  2207.                 foreach ($request->request->get('widgetId') as $k => $v) {
  2208.                     if ($v != 0) {
  2209.                         //exists sso edit
  2210.                         $widget $em->getRepository("ApplicationBundle:DashboardWidget")->findOneBy(
  2211.                             array(
  2212.                                 'id' => $v,
  2213.                             )
  2214.                         );
  2215.                     } else
  2216.                         $widget = new DashboardWidget();
  2217.                     $widget->setData($request->request->get('widgetData')[$k]);
  2218.                     $widget->setSequence($request->request->get('widgetSequence')[$k]);
  2219.                     $widget->setStatus($request->request->has('widgetStatus') ? $request->request->get('widgetStatus')[$k] : GeneralConstant::ACTIVE);
  2220.                     $widget->setUserId($userId);
  2221.                     $widget->setCompanyId($companyId);
  2222.                     $widget->setDefaultBoxFlag($request->request->has('defaultBoxFlag') ? $request->request->get('defaultBoxFlag')[$k] : 0);
  2223.                     if ($v == 0)
  2224.                         $em->persist($widget);
  2225.                     $em->flush();
  2226.                 }
  2227.             }
  2228.         }
  2229.         $dashboardDataForUser = [];
  2230.         $dbQuery $em->getRepository("ApplicationBundle:DashboardWidget")->findBy(
  2231.             array(
  2232.                 'CompanyId' => $companyId,
  2233.                 'userId' => $userId,
  2234.                 'status' => GeneralConstant::ACTIVE
  2235.             )
  2236.         );
  2237.         if (empty($dbQuery))   ///now get the defaults
  2238.             $dbQuery $em->getRepository("ApplicationBundle:DashboardWidget")->findBy(
  2239.                 array(
  2240.                     'CompanyId' => $companyId,
  2241.                     //                    'userId'=>$userId,
  2242.                     'defaultBoxFlag' => 1,
  2243.                     'status' => GeneralConstant::ACTIVE
  2244.                 )
  2245.             );
  2246.         foreach ($dbQuery as $entry) {
  2247.             $dashboardDataForUser[] = array(
  2248.                 'id' => $entry->getId(),
  2249.                 'widgetId' => $entry->getId(),
  2250.                 'widgetSequence' => $entry->getSequence(),
  2251.                 'widgetStatus' => $entry->getStatus(),
  2252.                 'widgetData' => $entry->getData(),
  2253.                 'defaultBoxFlag' => $entry->getDefaultBoxFlag(),
  2254.                 'widgetSizeTiny' => $entry->getSizeTiny(),
  2255.                 'widgetSizeSmall' => $entry->getSizeSmall(),
  2256.                 'widgetSizeMedium' => $entry->getSizeMedium(),
  2257.                 'widgetSizeLarge' => $entry->getSizeLarge(),
  2258.                 'refreshInterval' => $entry->getRefreshInterval(),
  2259.             );
  2260.         }
  2261.         //1st try to see if any exists
  2262.         return $this->render(
  2263.             'ApplicationBundle:pages/dashboard:index_sales.html.twig',
  2264.             array(
  2265.                 'page_title' => 'Modify Dashboard'
  2266.             )
  2267.         );
  2268.     }
  2269.     public function ChangeCompanyDashboardAction(Request $request$id 1)
  2270.     {
  2271.         $session $request->getSession();
  2272.         if ($request->query->has('sys_admin_panel'))
  2273.             return $this->redirectToRoute('system_admin_dashboard');
  2274.         else {
  2275.             $session->set(UserConstants::USER_COMPANY_ID$id);
  2276.             return $this->redirectToRoute('dashboard');
  2277.         }
  2278.     }
  2279.     public function ChangeLeftPanelDisplayStatusAction(Request $request)
  2280.     {
  2281.         $session $request->getSession();
  2282.         $curr_status 1;
  2283.         if ($session->has('HIDE_LEFT_PANEL'))
  2284.             $curr_status $session->get('HIDE_LEFT_PANEL');
  2285.         if ($curr_status == 1)
  2286.             $curr_status 0;
  2287.         else
  2288.             $curr_status 1;
  2289.         $session->set('HIDE_LEFT_PANEL'$curr_status);
  2290.         //            return $this->redirectToRoute('dashboard');
  2291.         return new Response($curr_status);
  2292.     }
  2293.     public function PermissionDeniedAction(Request $request)
  2294.     {
  2295.         $session $request->getSession();
  2296.         // Generic::debugMessage($session);
  2297.         return $this->render(
  2298.             '@System/pages/permission_denied.html.twig',
  2299.             array(
  2300.                 'page_title' => 'Permission Denied'
  2301.             )
  2302.         );
  2303.     }
  2304.     public function MyDocumentsAction(Request $request)
  2305.     {
  2306.         $session $request->getSession();
  2307.         $em $this->getDoctrine()->getManager();
  2308.         $data MiscActions::getDocumentsByUserId($em$session->get(UserConstants::USER_ID));
  2309.         // Generic::debugMessage($session);
  2310.         return $this->render(
  2311.             'ApplicationBundle:pages/dashboard:my_documents.html.twig',
  2312.             array(
  2313.                 'page_title' => 'My Documents',
  2314.                 'data' => $data
  2315.             )
  2316.         );
  2317.     }
  2318.     //     public function MyDocumentsListForAppAction(Request $request)
  2319.     //     {
  2320.     //         $session = $request->getSession();
  2321.     //         $em = $this->getDoctrine()->getManager();
  2322.     //         $absoluteUrlList = [];
  2323.     //         foreach (GeneralConstant::$Entity_list_details as $e => $d) {
  2324.     //             if (isset($d['entity_print_route_path_name']))
  2325.     //                 $absoluteUrlList[$e] = $this->generateUrl($d['entity_print_route_path_name'], [], UrlGenerator::ABSOLUTE_URL);
  2326.     //         }
  2327.     //         $data = MiscActions::getDocumentsByUserIdForApp($em, $session->get(UserConstants::USER_ID), 1, $absoluteUrlList);
  2328.     //         // Generic::debugMessage($session);
  2329.     //         return new JsonResponse(array(
  2330.     //             'data' => $data
  2331.     //         ));
  2332.     // //        return $this->render('ApplicationBundle:pages/dashboard:my_documents.html.twig',
  2333.     // //            array(
  2334.     // //                'page_title' => 'My Documents',
  2335.     // //                'data' => $data
  2336.     // //            )
  2337.     // //        );
  2338.     //     }
  2339.     public function MyDocumentsListForAppAction(Request $request)
  2340.     {
  2341.         $session $request->getSession();
  2342.         $em $this->getDoctrine()->getManager();
  2343.         // Build absolute URL list
  2344.         $absoluteUrlList = [];
  2345.         foreach (GeneralConstant::$Entity_list_details as $e => $d) {
  2346.             if (isset($d['entity_print_route_path_name'])) {
  2347.                 $absoluteUrlList[$e] = $this->generateUrl($d['entity_print_route_path_name'], [], UrlGenerator::ABSOLUTE_URL);
  2348.             }
  2349.         }
  2350.         // Extract pagination parameters from the request
  2351.         $page $request->query->get('page''_UNSET_');
  2352.         $offset $request->query->get('offset'0);
  2353.         $limit $request->query->get('limit'10); // default limit is 10
  2354.         // Call the document list method with pagination
  2355.         return new JsonResponse(
  2356.             MiscActions::getDocumentsByUserIdForApp(
  2357.                 $em,
  2358.                 $session->get(UserConstants::USER_ID),
  2359.                 1,
  2360.                 $absoluteUrlList,
  2361.                 $page,
  2362.                 $offset,
  2363.                 $limit
  2364.             )
  2365.         );
  2366.     }
  2367.     public function ShowExceptionAction(Request $requestFlattenException $exceptionDebugLoggerInterface $logger null)
  2368.     {
  2369.         $session $request->getSession();
  2370.         $em $this->getDoctrine()->getManager();
  2371.         // Generic::debugMessage($session);
  2372.         //        $currentContent = $this->getAndCleanOutputBuffering($request->headers->get('X-Php-Ob-Level', -1));
  2373.         //        $showException = $request->attributes->get('showException', $this->debug); // As opposed to an additional parameter, this maintains BC
  2374.         $code $exception->getStatusCode();
  2375.         //        $data = MiscActions::getDocumentsByUserId($em, $session->get(UserConstants::USER_ID));
  2376.         return $this->render(
  2377.             'ApplicationBundle:pages/error:error_' $code '.html.twig',
  2378.             array(
  2379.                 'page_title' => 'Sorry',
  2380.                 //                'data' => $data
  2381.             )
  2382.         );
  2383.     }
  2384.     public function NotificationAction(Request $request)
  2385.     {
  2386.         $session $request->getSession();
  2387.         //'error', 'success', 'alert', 'information', 'warning', 'confirm'
  2388.         $themes = array(
  2389.             'error' => 'bg-red',
  2390.             'success' => 'bg-green',
  2391.             'alert' => 'bg-purple',
  2392.             'information' => 'bg-grey',
  2393.             'warning' => 'bg-orange',
  2394.             'confirm' => 'bg-blue',
  2395.         );
  2396.         $fa = array(
  2397.             'error' => 'fa fa-ban',
  2398.             'success' => 'fa fa-check',
  2399.             'alert' => 'fa fa-envelope',
  2400.             'information' => 'fa fa-comments',
  2401.             'warning' => 'fa fa-warning',
  2402.             'confirm' => 'fa fa-crosshairs',
  2403.         );
  2404.         // Generic::debugMessage($session);
  2405.         return $this->render(
  2406.             'ApplicationBundle:pages/dashboard:notification.html.twig',
  2407.             array(
  2408.                 'page_title' => 'Notifications',
  2409.                 'dt' => json_decode(System::GetAllNotification(
  2410.                     $this->container->getParameter('notification_enabled'),
  2411.                     $this->container->getParameter('notification_server'),
  2412.                     $request->getSession()->get(UserConstants::USER_ID),
  2413.                     $request->getSession()->get(UserConstants::USER_APP_ID),
  2414.                     $request->getSession()->get(UserConstants::USER_COMPANY_ID)
  2415.                 ), true),
  2416.                 //                'dt'=>System::GetAllNotification(
  2417.                 //                    $this->container->getParameter('notification_enabled'),
  2418.                 //                    $request->getSession()->get(UserConstants::USER_ID),
  2419.                 //                    $request->getSession()->get(UserConstants::USER_APP_ID),
  2420.                 //                    $request->getSession()->get(UserConstants::USER_COMPANY_ID)
  2421.                 //                ),
  2422.                 'themes' => $themes,
  2423.                 'fa' => $fa,
  2424.                 't' => curl_init()
  2425.             )
  2426.         );
  2427.     }
  2428.     public function EditAccountAction(Request $request)
  2429.     {
  2430.         $session $request->getSession();
  2431.         //'error', 'success', 'alert', 'information', 'warning', 'confirm'
  2432.         $themes = array(
  2433.             'error' => 'bg-red',
  2434.             'success' => 'bg-green',
  2435.             'alert' => 'bg-purple',
  2436.             'information' => 'bg-aqua',
  2437.             'warning' => 'bg-orange',
  2438.             'confirm' => 'bg-blue',
  2439.         );
  2440.         $fa = array(
  2441.             'error' => 'fa fa-ban',
  2442.             'success' => 'fa fa-check',
  2443.             'alert' => 'fa fa-envelope',
  2444.             'information' => 'fa fa-comments',
  2445.             'warning' => 'fa fa-warning',
  2446.             'confirm' => 'fa fa-crosshairs',
  2447.         );
  2448.         $em $this->getDoctrine()->getManager();
  2449.         $g_path '';
  2450.         if ($request->isMethod('POST')) {
  2451.             $post $request->request;
  2452.             $path "";
  2453.             foreach ($request->files as $uploadedFile) {
  2454.                 if ($uploadedFile != null) {
  2455.                     $fileName md5(uniqid()) . '.' $uploadedFile->guessExtension();
  2456.                     $path $fileName;
  2457.                     $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/FileUploads/' $request->request->get('userId') . '/';
  2458.                     if (!file_exists($upl_dir)) {
  2459.                         mkdir($upl_dir0777true);
  2460.                     }
  2461.                     $file $uploadedFile->move($upl_dir$path);
  2462.                 }
  2463.             }
  2464.             if ($path != "")
  2465.                 $file_path 'uploads/FileUploads/' $request->request->get('userId') . '/' $path;
  2466.             $g_path $this->container->getParameter('kernel.root_dir') . '/../web/uploads/FileUploads/' $request->request->get('userId') . '/' $path;
  2467.             //            $img_file = file_get_contents($g_path);
  2468.             //            $image_data=base64_encode($img_file);
  2469.             //            $encoded_data=System::encryptSignature($image_data,$request->request->get('approvalHash'));
  2470.             $query_here $this->getDoctrine()
  2471.                 ->getRepository('ApplicationBundle:SysUser')
  2472.                 ->findOneBy(
  2473.                     array('userId' => $request->request->get('userId'))
  2474.                 );
  2475.             if ($query_here) {
  2476.                 $new $query_here;
  2477.                 if ($path != "") {
  2478.                     if ($request->request->has('check_pp')) {
  2479.                         $new->setImage($file_path);
  2480.                         $session->set(UserConstants::USER_IMAGE$new->getImage());
  2481.                     } else
  2482.                         $new->setImage('');
  2483.                 }
  2484.                 $new->setName($request->request->get('name'));
  2485.                 $session->set(UserConstants::USER_NAME$request->request->get('name'));
  2486.                 //now password
  2487.                 if ($request->request->get('oldPass') != '') {
  2488.                     //1st check if old pass valid
  2489.                     if (!$this->container->get('sha256salted_encoder')->isPasswordValid($new->getPassword(), $request->request->get('oldPass'), $new->getSalt())) {
  2490.                         $this->addFlash(
  2491.                             'error',
  2492.                             'Your Old Password Was Wrong'
  2493.                         );
  2494.                     } else {
  2495.                         //old pass valid so now check if neww passes matches
  2496.                         if ($request->request->get('newPass') == $request->request->get('newPassAgain')) {
  2497.                             $new->setSalt(uniqid(mt_rand()));
  2498.                             $password $this->container->get('sha256salted_encoder')->encodePassword($request->request->get('newPass'), $new->getSalt());
  2499.                             $new->setPassword($password);
  2500.                             $em->flush();
  2501.                         } else {
  2502.                             $this->addFlash(
  2503.                                 'error',
  2504.                                 'Passwords Did not Match'
  2505.                             );
  2506.                         }
  2507.                     }
  2508.                 }
  2509.             } else {
  2510.                 //                    $new=new EncryptedSignature();
  2511.                 //                    $new->setData($encoded_data);
  2512.                 //                    $new->setUserId($request->request->get('userId'));
  2513.                 //                    $em->persist($new);
  2514.             }
  2515.             $em->flush();
  2516.             //            now deleting the file
  2517.         }
  2518.         $user_data Users::getUserInfoByLoginId($em$this->getLoggedUserLoginId($request));
  2519.         // Generic::debugMessage($session);
  2520.         return $this->render(
  2521.             '@System/pages/settings/edit_account.html.twig',
  2522.             array(
  2523.                 'page_title' => 'Edit Account',
  2524.                 'user_data' => $user_data,
  2525.                 //                'dt'=>json_decode(System::GetAllNotification($request->getSession()->get(UserConstants::USER_ID)),true),
  2526.                 'themes' => $themes,
  2527.                 'fa' => $fa,
  2528.             )
  2529.         );
  2530.     }
  2531.     public function indexApplicantAction(Request $request)
  2532.     {
  2533.         $systemType $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
  2534.         $twig_file 'ApplicationBundle:pages/login:applicant_login.html.twig';
  2535.         $session $request->getSession();
  2536.         if ($systemType == '_BUDDYBEE_') {
  2537.             if ($session->get('buddybeeAdminLevel'0) > 1)
  2538.                 return $this->redirectToRoute("buddybee_admin_dashboard", []);
  2539.             elseif ($session->get('isConsultant') == 1)
  2540.                 return $this->redirectToRoute("consultant_dashboard", []);
  2541.             else
  2542.                 return $this->redirectToRoute("student_dashboard", []);
  2543.         } elseif ($systemType == '_CENTRAL_') {
  2544.             return $this->render(
  2545.                 'ApplicationBundle:pages/dashboard:index_applicant.html.twig',
  2546.                 array(
  2547.                     'page_title' => 'Applicant Dashboard'
  2548.                 )
  2549.             );
  2550.         } else
  2551.             return $this->render(
  2552.                 'ApplicationBundle:pages/dashboard:consultant_dashboard.html.twig',
  2553.                 array(
  2554.                     'page_title' => 'Applicant Dashboard'
  2555.                 )
  2556.             );
  2557.     }
  2558.     public function indexCentralLandingAction(Request $request)
  2559.     {
  2560.         $session $request->getSession();
  2561.         $userAccessList $session->get('userAccessList', []);
  2562.         $companyNames array_map(function ($company) {
  2563.             return $company['companyName'];
  2564.         }, $userAccessList);
  2565.         if ($request->isMethod('POST')) {
  2566.             $employeeId $request->request->get('employee_id');
  2567.             $companyName $request->request->get('company_name');
  2568.             if ($employeeId && $companyName) {
  2569.                 return new JsonResponse([
  2570.                     'status' => 'success',
  2571.                     'message' => 'Data received successfully',
  2572.                     'employee_id' => $employeeId,
  2573.                     'company_name' => $companyName,
  2574.                 ]);
  2575.             } else {
  2576.                 return new JsonResponse([
  2577.                     'status' => 'error',
  2578.                     'message' => 'Employee ID or Company Name is missing',
  2579.                 ]);
  2580.             }
  2581.         }
  2582.         // If the request is not a POST request, render the normal page
  2583.         return $this->render(
  2584.             'ApplicationBundle:pages/dashboard:index_central_landing.html.twig',
  2585.             [
  2586.                 'page_title' => 'Central Landing',
  2587.                 'companyNames' => $companyNames
  2588.             ]
  2589.         );
  2590.     }
  2591.     public function HummanResourceAction()
  2592.     {
  2593.         return $this->render(
  2594.             'ApplicationBundle:pages/dashboard:humanResource.html.twig',
  2595.             array(
  2596.                 'page_title' => 'Human Resource Dashboard'
  2597.             )
  2598.         );
  2599.     }
  2600.     public function projectCashFlowReportAction()
  2601.     {
  2602.         return $this->render(
  2603.             'ApplicationBundle:pages/dashboard:cash_flow_report.html.twig',
  2604.             array(
  2605.                 'page_title' => 'Cash Flow Report'
  2606.             )
  2607.         );
  2608.     }
  2609.     public function PerformanceReviewDashboardAction()
  2610.     {
  2611.         return $this->render(
  2612.             'ApplicationBundle:pages/dashboard:performance_review_dashboard.html.twig',
  2613.             array(
  2614.                 'page_title' => 'Performance Review Dashboard'
  2615.             )
  2616.         );
  2617.     }
  2618.     public function RecruitmentDashboardAction()
  2619.     {
  2620.         return $this->render(
  2621.             'ApplicationBundle:pages/dashboard:recruitment_dashboard.html.twig',
  2622.             array(
  2623.                 'page_title' => 'Recruitment Dashboard'
  2624.             )
  2625.         );
  2626.     }
  2627.     public function TalentManagementDashboardAction()
  2628.     {
  2629.         return $this->render(
  2630.             'ApplicationBundle:pages/dashboard:talent_management_dashboard.html.twig',
  2631.             array(
  2632.                 'page_title' => 'Talent Management Dashboard'
  2633.             )
  2634.         );
  2635.     }
  2636.     public function CreateCompanyAction(Request $request)
  2637.     {
  2638.         $systemType $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
  2639.         $appId $request->get('app_id'0);
  2640.         $post $request;
  2641.         $session $request->getSession();
  2642.         if ($request->isMethod('POST')) {
  2643.             if ($systemType == '_CENTRAL_') {
  2644.                 $em_goc $this->getDoctrine()->getManager('company_group');
  2645.                 $em_goc->getConnection()->connect();
  2646.                 $connected $em_goc->getConnection()->isConnected();
  2647.                 $gocDataList = [];
  2648.                 if ($connected) {
  2649.                     $goc null;
  2650.                     $serverList GeneralConstant::$serverListById;
  2651.                     $companyGroupHash $post->get('company_short_code''');
  2652.                     $defaultUsageDate = new \DateTime();
  2653.                     $defaultUsageDate->modify('+1 year');
  2654.                     $usageValidUpto = new \DateTime($post->get('usage_valid_upto_dt_str'$defaultUsageDate->format('Y-m-d')));
  2655.                     $companyGroupServerId $post->get('server_id'1);
  2656.                     $companyGroupServerAddress $serverList[$companyGroupServerId]['absoluteUrl'];
  2657.                     $companyGroupServerPort $serverList[$companyGroupServerId]['port'];
  2658.                     $companyGroupServerHash $serverList[$companyGroupServerId]['serverMarker'];
  2659.                     //                $dbUser=
  2660.                     if ($appId != 0)
  2661.                         $goc $this->getDoctrine()->getManager('company_group')
  2662.                             ->getRepository("CompanyGroupBundle:CompanyGroup")
  2663.                             ->findOneBy(array(
  2664.                                 'appId' => $appId
  2665.                             ));
  2666.                     if (!$goc)
  2667.                         $goc = new CompanyGroup();
  2668.                     if ($appId == 0) {
  2669.                         $biggestAppIdCg $this->getDoctrine()->getManager('company_group')
  2670.                             ->getRepository("CompanyGroupBundle:CompanyGroup")
  2671.                             ->findOneBy(array( //                            'appId' => $appId
  2672.                             ), array(
  2673.                                 'appId' => 'desc'
  2674.                             ));
  2675.                         if ($biggestAppIdCg)
  2676.                             $appId $biggestAppIdCg->getAppId();
  2677.                     }
  2678.                     $goc->setName($post->get('company_name'));
  2679.                     $goc->setCompanyGroupHash($companyGroupHash);
  2680.                     $goc->setAppId($appId);
  2681.                     $goc->setActive(1);
  2682.                     $goc->setAddress($post->get('address'));
  2683.                     $goc->setShippingAddress($post->get('s_address'));
  2684.                     $goc->setBillingAddress($post->get('b_address'));
  2685.                     $goc->setMotto($post->get('motto'));
  2686.                     $goc->setInitiateFlag($post->get('initiate_flag'2));
  2687.                     $goc->setInvoiceFooter($post->get('i_footer'));
  2688.                     $goc->setGeneralFooter($post->get('g_footer'));
  2689.                     $goc->setCompanyReg($post->get('company_reg'''));
  2690.                     $goc->setCompanyTin($post->get('company_tin'''));
  2691.                     $goc->setCompanyBin($post->get('company_bin'''));
  2692.                     $goc->setCompanyTl($post->get('company_tl'''));
  2693.                     $goc->setCompanyType($post->get('company_type'''));
  2694.                     $goc->setCurrentSubscriptionPackageId($post->get('package'''));
  2695.                     $goc->setUsageValidUptoDate($usageValidUpto);
  2696.                     $goc->setUsageValidUptoDateTs($usageValidUpto->format('U'));
  2697.                     //                $goc->setCu($post->get('package', ''));
  2698.                     $goc->setAdminUserAllowed($post->get('number_of_admin_user'1));
  2699.                     $goc->setUserAllowed($post->get('number_of_user'2));
  2700.                     $goc->setSubscriptionMonth($post->get('subscription_month'1));
  2701.                     $goc->setCompanyDescription($post->get('company_description'''));
  2702.                     $goc->setDbUser($post->get('db_user'));
  2703.                     $goc->setDbPass($post->get('db_pass'));
  2704.                     $goc->setDbHost($post->get('db_host'));
  2705.                     $goc->setCompanyGroupServerId($companyGroupServerId);
  2706.                     $goc->setCompanyGroupServerAddress($companyGroupServerAddress);
  2707.                     $goc->setCompanyGroupServerPort($companyGroupServerPort);
  2708.                     $goc->setCompanyGroupServerHash($companyGroupServerHash);
  2709.                     foreach ($request->files as $uploadedFile) {
  2710.                         if ($uploadedFile != null) {
  2711.                             $fileName 'company_image' $appId '.' $uploadedFile->guessExtension();
  2712.                             $path $fileName;
  2713.                             $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/CompanyImage/';
  2714.                             if ($goc->getImage() != null && $goc->getImage() != '' && file_exists($this->container->getParameter('kernel.root_dir') . '/../web' $goc->getImage())) {
  2715.                                 unlink($this->container->getParameter('kernel.root_dir') . '/../web' $goc->getImage());
  2716.                             }
  2717.                             if (!file_exists($upl_dir)) {
  2718.                                 mkdir($upl_dir0777true);
  2719.                             }
  2720.                             $file $uploadedFile->move($upl_dir$path);
  2721.                             if ($path != "")
  2722.                                 $goc->setImage('/uploads/CompanyImage/' $path);
  2723.                         }
  2724.                     }
  2725.                     $em_goc->persist($goc);
  2726.                     $em_goc->flush();
  2727.                     $goc->setDbName('cg_' $appId '_' $companyGroupHash);
  2728.                     $goc->setDbUser($serverList[$companyGroupServerId]['dbUser']);
  2729.                     $goc->setDbPass($serverList[$companyGroupServerId]['dbPass']);
  2730.                     $goc->setDbHost('localhost');
  2731.                     $em_goc->flush();
  2732.                     $centralUser $this->getDoctrine()->getManager('company_group')
  2733.                         ->getRepository("CompanyGroupBundle:EntityApplicantDetails")
  2734.                         ->findOneBy(array(
  2735.                             'applicantId' => $session->get(UserConstants::USER_ID0)
  2736.                         ));
  2737.                     if ($centralUser) {
  2738.                         $userAppIds json_decode($centralUser->getUserAppIds(), true);
  2739.                         $userTypesByAppIds json_decode($centralUser->getUserTypesByAppIds(), true);
  2740.                         if ($userAppIds == null$userAppIds = [];
  2741.                         if ($userTypesByAppIds == null$userTypesByAppIds = [];
  2742.                         $userAppIds array_merge($userAppIdsarray_diff([$appId], $userAppIds));
  2743.                         if (!isset($userTypesByAppIds[$appId])) {
  2744.                             $userTypesByAppIds[$appId] = [];
  2745.                         }
  2746.                         $userTypesByAppIds[$appId] = array_merge($userTypesByAppIds[$appId], array_diff([UserConstants::USER_TYPE_SYSTEM], $userTypesByAppIds[$appId]));
  2747.                         $centralUser->setUserAppIds(json_encode($userAppIds));
  2748.                         $centralUser->setUserTypesByAppIds(json_encode($userTypesByAppIds));
  2749.                         $em_goc->flush();
  2750.                     }
  2751.                     $accessList $session->get('userAccessList', []);
  2752.                     $d = array(
  2753.                         'userType' => UserConstants::USER_TYPE_SYSTEM,
  2754.                         'globalId' => $session->get(UserConstants::USER_ID0),
  2755.                         'serverId' => $companyGroupServerId,
  2756.                         'serverUrl' => $companyGroupServerAddress,
  2757.                         'serverPort' => $companyGroupServerPort,
  2758.                         'systemType' => '_ERP_',
  2759.                         'companyId' => 1,
  2760.                         'appId' => $appId,
  2761.                         'companyLogoUrl' => $goc->getImage(),
  2762.                         'companyName' => $goc->getName(),
  2763.                         'authenticationStr' => $this->get('url_encryptor')->encrypt(
  2764.                             json_encode(
  2765.                                 array(
  2766.                                     'globalId' => $session->get(UserConstants::USER_ID0),
  2767.                                     'appId' => $appId,
  2768.                                     'authenticate' => 1,
  2769.                                     'userType' => UserConstants::USER_TYPE_SYSTEM
  2770.                                 )
  2771.                             )
  2772.                         ),
  2773.                         'userCompanyList' => []
  2774.                     );
  2775.                     $accessList[] = $d;
  2776.                     $session->set('userAccessList'$accessList);
  2777.                 }
  2778.                 return new JsonResponse(array(
  2779.                     'user_access_data' => $d,
  2780.                     'app_id' => $appId
  2781.                 ));
  2782.             }
  2783.         }
  2784.         return $this->render('@HoneybeeWeb/pages/create_company.html.twig', array(
  2785.             'page_title' => 'Company',
  2786.             'serverList' => GeneralConstant::$serverListById
  2787.         ));
  2788.     }
  2789.     public function GetSessionDataForAppAction(
  2790.         Request $request,
  2791.                 $remoteVerify 0,
  2792.                 $version 'latest',
  2793.                 $identifier '_default_',
  2794.                 $refRoute '',
  2795.                 $apiKey '_ignore_'
  2796.     )
  2797.     {
  2798.         $message "";
  2799.         $gocList = [];
  2800.         $session $request->getSession();
  2801.         if ($request->request->has('token')) {
  2802.             $em_goc $this->getDoctrine()->getManager('company_group');
  2803.             $to_set_session_data MiscActions::GetSessionDataFromToken($em_goc$request->request->get('token'))['sessionData'];
  2804.             if ($to_set_session_data != null) {
  2805.                 foreach ($to_set_session_data as $k => $d) {
  2806.                     //check if mobile
  2807.                     $session->set($k$d);
  2808.                 }
  2809.             }
  2810.         }
  2811.         if ($request->request->has('sessionData')) {
  2812.             $to_set_session_data $request->request->get('sessionData');
  2813.             foreach ($to_set_session_data as $k => $d) {
  2814.                 //check if mobile
  2815.                 $session->set($k$d);
  2816.             }
  2817.         }
  2818.         if ($version !== 'latest') {
  2819.             $session_data = array(
  2820.                 'oAuthToken' => $session->get('oAuthToken'),
  2821.                 'locale' => $session->get('locale'),
  2822.                 'firebaseToken' => $session->get('firebaseToken'),
  2823.                 'token' => $session->get('token'),
  2824.                 UserConstants::USER_EMPLOYEE_ID => $session->get(UserConstants::USER_EMPLOYEE_ID),
  2825.                 UserConstants::USER_ID => $session->get(UserConstants::USER_ID),
  2826.                 UserConstants::LAST_SETTINGS_UPDATED_TS => $session->get(UserConstants::LAST_SETTINGS_UPDATED_TS),
  2827.                 UserConstants::USER_LOGIN_ID => $session->get(UserConstants::USER_LOGIN_ID),
  2828.                 UserConstants::USER_EMAIL => $session->get(UserConstants::USER_EMAIL),
  2829.                 UserConstants::USER_TYPE => $session->get(UserConstants::USER_TYPE),
  2830.                 UserConstants::USER_IMAGE => $session->get(UserConstants::USER_IMAGE),
  2831.                 UserConstants::USER_DEFAULT_ROUTE => $session->get(UserConstants::USER_DEFAULT_ROUTE),
  2832.                 UserConstants::USER_NAME => $session->get(UserConstants::USER_NAME),
  2833.                 UserConstants::USER_COMPANY_ID => $session->get(UserConstants::USER_COMPANY_ID),
  2834.                 UserConstants::USER_COMPANY_ID_LIST => $session->get(UserConstants::USER_COMPANY_ID_LIST),
  2835.                 UserConstants::USER_COMPANY_NAME_LIST => $session->get(UserConstants::USER_COMPANY_NAME_LIST),
  2836.                 UserConstants::USER_COMPANY_IMAGE_LIST => $session->get(UserConstants::USER_COMPANY_IMAGE_LIST),
  2837.                 UserConstants::USER_APP_ID => $session->get(UserConstants::USER_APP_ID),
  2838.                 UserConstants::USER_POSITION_LIST => $session->get(UserConstants::USER_POSITION_LIST),
  2839.                 UserConstants::USER_CURRENT_POSITION => $session->get(UserConstants::USER_CURRENT_POSITION),
  2840.                 UserConstants::ALL_MODULE_ACCESS_FLAG => $session->get(UserConstants::ALL_MODULE_ACCESS_FLAG),
  2841.                 UserConstants::USER_GOC_ID => $session->get(UserConstants::USER_GOC_ID),
  2842.                 UserConstants::USER_NOTIFICATION_ENABLED => GeneralConstant::NOTIFICATION_ENABLED == ? ($this->getParameter('notification_enabled') == 0) : 0,
  2843.                 UserConstants::USER_NOTIFICATION_SERVER => $this->getParameter('notification_server'),
  2844.                 UserConstants::PRODUCT_NAME_DISPLAY_TYPE => $session->get(UserConstants::PRODUCT_NAME_DISPLAY_TYPE),
  2845.                 UserConstants::APPLICATION_SECRET => $session->get(UserConstants::APPLICATION_SECRET),
  2846.                 //new addition
  2847.                 'appIdList' => $session->get('appIdList'),
  2848.                 'branchIdList' => $session->get('branchIdList'null),
  2849.                 'branchId' => $session->get('branchId'null),
  2850.                 'companyIdListByAppId' => $session->get('companyIdListByAppId'),
  2851.                 'companyNameListByAppId' => $session->get('companyNameListByAppId'),
  2852.                 'companyImageListByAppId' => $session->get('companyImageListByAppId'),
  2853.                 'userAccessList' => $session->get('userAccessList'),
  2854.                 'csToken' => $session->get('csToken'),
  2855.             );
  2856.         } else {
  2857.             $session_data = array(
  2858.                 'oAuthToken' => $session->get('oAuthToken'),
  2859.                 'locale' => $session->get('locale'),
  2860.                 'firebaseToken' => $session->get('firebaseToken'),
  2861.                 'token' => $session->get('token'),
  2862.                 UserConstants::USER_EMPLOYEE_ID => $session->get(UserConstants::USER_EMPLOYEE_ID),
  2863.                 UserConstants::USER_ID => $session->get(UserConstants::USER_ID),
  2864.                 UserConstants::LAST_SETTINGS_UPDATED_TS => $session->get(UserConstants::LAST_SETTINGS_UPDATED_TS),
  2865.                 UserConstants::USER_LOGIN_ID => $session->get(UserConstants::USER_LOGIN_ID),
  2866.                 UserConstants::USER_EMAIL => $session->get(UserConstants::USER_EMAIL),
  2867.                 UserConstants::USER_TYPE => $session->get(UserConstants::USER_TYPE),
  2868.                 UserConstants::USER_IMAGE => $session->get(UserConstants::USER_IMAGE),
  2869.                 UserConstants::USER_DEFAULT_ROUTE => $session->get(UserConstants::USER_DEFAULT_ROUTE),
  2870.                 UserConstants::USER_NAME => $session->get(UserConstants::USER_NAME),
  2871.                 UserConstants::USER_COMPANY_ID => $session->get(UserConstants::USER_COMPANY_ID),
  2872.                 UserConstants::USER_COMPANY_ID_LIST => $session->get(UserConstants::USER_COMPANY_ID_LIST),
  2873.                 UserConstants::USER_COMPANY_NAME_LIST => $session->get(UserConstants::USER_COMPANY_NAME_LIST),
  2874.                 UserConstants::USER_COMPANY_IMAGE_LIST => $session->get(UserConstants::USER_COMPANY_IMAGE_LIST),
  2875.                 UserConstants::USER_APP_ID => $session->get(UserConstants::USER_APP_ID),
  2876.                 UserConstants::USER_POSITION_LIST => $session->get(UserConstants::USER_POSITION_LIST),
  2877.                 UserConstants::USER_CURRENT_POSITION => $session->get(UserConstants::USER_CURRENT_POSITION),
  2878.                 UserConstants::ALL_MODULE_ACCESS_FLAG => $session->get(UserConstants::ALL_MODULE_ACCESS_FLAG),
  2879.                 UserConstants::USER_GOC_ID => $session->get(UserConstants::USER_GOC_ID),
  2880.                 UserConstants::USER_DB_NAME => $session->get(UserConstants::USER_DB_NAME),
  2881.                 UserConstants::USER_DB_USER => $session->get(UserConstants::USER_DB_USER),
  2882.                 UserConstants::USER_DB_HOST => $session->get(UserConstants::USER_DB_HOST),
  2883.                 UserConstants::USER_DB_PASS => $session->get(UserConstants::USER_DB_PASS),
  2884.                 UserConstants::USER_NOTIFICATION_ENABLED => GeneralConstant::NOTIFICATION_ENABLED == ? ($this->getParameter('notification_enabled') == 0) : 0,
  2885.                 UserConstants::USER_NOTIFICATION_SERVER => $this->getParameter('notification_server'),
  2886.                 UserConstants::PRODUCT_NAME_DISPLAY_TYPE => $session->get(UserConstants::PRODUCT_NAME_DISPLAY_TYPE),
  2887.                 UserConstants::APPLICATION_SECRET => $session->get(UserConstants::APPLICATION_SECRET),
  2888.                 //new addition
  2889.                 'appIdList' => $session->get('appIdList'),
  2890.                 'branchIdList' => $session->get('branchIdList'null),
  2891.                 'branchId' => $session->get('branchId'null),
  2892.                 'companyIdListByAppId' => $session->get('companyIdListByAppId'),
  2893.                 'companyNameListByAppId' => $session->get('companyNameListByAppId'),
  2894.                 'companyImageListByAppId' => $session->get('companyImageListByAppId'),
  2895.                 'userAccessList' => $session->get('userAccessList'),
  2896.                 'csToken' => $session->get('csToken'),
  2897.             );
  2898.         }
  2899.         $response = new JsonResponse(array(
  2900.             "success" => empty($session->get(UserConstants::USER_ID)) ? false true,
  2901.             //            'session'=>$request->getSession(),
  2902.             'session_data' => $session_data,
  2903.             //            'session2'=>$_SESSION,
  2904.         ));
  2905.         $response->headers->set('Access-Control-Allow-Origin''*, null');
  2906.         $response->headers->set('Access-Control-Allow-Methods''POST');
  2907.         //        $response->setCallback('FUNCTION_CALLBACK_NAME');
  2908.         return $response;
  2909.     }
  2910.     public function EmployeeAddUsingQrCodeCentralAction(Request $request)
  2911.     {
  2912.         if ($request->isMethod('post')) {
  2913.             $em_goc $this->getDoctrine()->getManager('company_group');
  2914.             $entityApplicant $em_goc->getRepository("CompanyGroupBundle:EntityApplicantDetails")
  2915.                 ->findOneBy(
  2916.                     array(
  2917.                         'applicantId' => $request->request->get('userId'),
  2918.                     )
  2919.                 );
  2920.             $app $em_goc->getRepository("CompanyGroupBundle:CompanyGroup")
  2921.                 ->findOneBy(
  2922.                     array(
  2923.                         'appId' => $request->request->get('appId'),
  2924.                     )
  2925.                 );
  2926.             $userType $request->request->get('userType');
  2927.             $currAccessData json_decode($entityApplicant->getUserTypesByAppIds(), true);
  2928.             if ($currAccessData == null$currAccessData = [];
  2929.             if (!isset($currAccessData[$request->request->get('appId')]))
  2930.                 $currAccessData[$request->request->get('appId')] = [];
  2931.             $currAccessData[$request->request->get('appId')] = array_merge($currAccessData[$request->request->get('appId')], array_diff([$request->request->get('userType'$userType)], $currAccessData[$request->request->get('appId')]));
  2932.             $entityApplicant->setUserTypesByAppIds(json_encode($currAccessData));
  2933.             $em_goc->flush();
  2934.             $postData = [];
  2935.             $postData['globalId'] = $entityApplicant->getApplicantId();
  2936.             $postData['username'] = $entityApplicant->getUsername();
  2937.             $postData['email'] = $entityApplicant->getEmail();
  2938.             $postData['firstname'] = $entityApplicant->getFirstname();
  2939.             $postData['lastname'] = $entityApplicant->getLastname();
  2940.             $postData['appId'] = $request->request->get('appId');
  2941.             $postData['companyId'] = $request->request->get('companyId');
  2942.             $postData['userType'] = $userType;
  2943.             $urlToCall $app->getCompanyGroupServerAddress() . '/add_employee_by_qr_erp';
  2944.             $userFiles $postData;
  2945.             $curl curl_init();
  2946.             curl_setopt_array($curl, array(
  2947.                 CURLOPT_RETURNTRANSFER => 1,
  2948.                 CURLOPT_POST => 1,
  2949.                 CURLOPT_URL => $urlToCall,
  2950.                 CURLOPT_CONNECTTIMEOUT => 10,
  2951.                 CURLOPT_SSL_VERIFYPEER => false,
  2952.                 CURLOPT_SSL_VERIFYHOST => false,
  2953.                 CURLOPT_HTTPHEADER => array( //              "Accept: multipart/form-data",
  2954.                 ),
  2955.                 //                            ),
  2956.                 CURLOPT_POSTFIELDS => $userFiles
  2957.             ));
  2958.             $retData curl_exec($curl);
  2959.             $errData curl_error($curl);
  2960.             curl_close($curl);
  2961.             $retDataObj json_decode($retDatatrue);
  2962.         } else {
  2963.             $company $request->get('company');
  2964.             return new JsonResponse(array(
  2965.                 "success" => false,
  2966.             ));
  2967.         }
  2968.         return new JsonResponse([
  2969.             'status' => 'success',
  2970.             'message' => 'User successfully added to company or already joined.'
  2971.         ]);
  2972.     }
  2973.     public function EmployeeAddUsingQrCodeErpServerAction(Request $request)
  2974.     {
  2975.         $em_goc $this->getDoctrine()->getManager('company_group');
  2976.         $app $em_goc->getRepository("CompanyGroupBundle:CompanyGroup")
  2977.             ->findOneBy(
  2978.                 array(
  2979.                     'appId' => $request->request->get('appId'),
  2980.                 )
  2981.             );
  2982.         $connector $this->container->get('application_connector');
  2983.         $connector->resetConnection(
  2984.             'default',
  2985.             $app->getDbName(),
  2986.             $app->getDbUser(),
  2987.             $app->getDbPass(),
  2988.             $app->getDbHost(),
  2989.             true
  2990.         );
  2991.         $em $this->getDoctrine()->getManager();
  2992.         $user $em->getRepository('ApplicationBundle:SysUser')
  2993.             ->findOneBy(
  2994.                 array(
  2995.                     'globalId' => $request->request->get('globalId'),
  2996.                 )
  2997.             );
  2998.         if (!$user)
  2999.             $user = new SysUser();
  3000.         $user->setGlobalId($request->request->get('globalId'));
  3001.         $user->setUsername($request->request->get('username'));
  3002.         $user->setEmail($request->request->get('email'));
  3003.         $user->setName($request->request->get('firstname'));
  3004.         $user->setUserType($request->request->get('userType'));
  3005.         $user->setUserAppId($request->request->get('appId'));
  3006.         $user->setUserCompanyId(1);
  3007.         $user->setStatus(1);
  3008.         $user->setDefaultRoute('sales_dashboard');
  3009.         $em->persist($user);
  3010.         $em->flush();
  3011.         $employee $em->getRepository('ApplicationBundle:Employee')
  3012.             ->findOneBy(
  3013.                 array(
  3014.                     'userId' => $user->getUserId(),
  3015.                 )
  3016.             );
  3017.         if (!$employee) {
  3018.             $employee = new Employee();
  3019.             if ($request->request->get('email') && $request->request->get('firstname') && $request->request->get('lastname')) {
  3020.                 $employee->setEmail($request->request->get('email'));
  3021.                 $employee->setFirstName($request->request->get('firstname'));
  3022.                 $employee->setLastName($request->request->get('lastname'));
  3023.                 $employee->setCompanyId($request->request->get('companyId'));
  3024.                 $employee->setStatus(1);
  3025.                 $employee->setUserId($user->getUserId());
  3026.                 $em->persist($employee);
  3027.                 $em->flush();
  3028.             } else {
  3029.                 return new JsonResponse([
  3030.                     'status' => 'error',
  3031.                     'message' => 'Missing employee data',
  3032.                 ]);
  3033.             }
  3034.         }
  3035.         $employeeDetails $em->getRepository('ApplicationBundle:EmployeeDetails')
  3036.             ->findOneBy(
  3037.                 array(
  3038.                     'userId' => $user->getUserId(),
  3039.                 )
  3040.             );
  3041.         if (!$employeeDetails) {
  3042.             $employeeDetails = new EmployeeDetails();
  3043.             if ($request->request->get('email') && $request->request->get('firstname') && $request->request->get('lastname')) {
  3044.                 $employeeDetails->setId($employee->getEmployeeId());
  3045.                 $employeeDetails->setEmail($request->request->get('email'));
  3046.                 $employeeDetails->setFirstName($request->request->get('firstname'));
  3047.                 $employeeDetails->setLastName($request->request->get('lastname'));
  3048.                 $employeeDetails->setUsername($request->request->get('username'));
  3049.                 $employeeDetails->setUserId($employee->getUserId());
  3050.                 $employeeDetails->setEmpStatus(1);
  3051.                 $em->persist($employeeDetails);
  3052.                 $em->flush();
  3053.             } else {
  3054.                 return new JsonResponse([
  3055.                     'status' => 'error',
  3056.                     'message' => 'Missing employee data',
  3057.                 ]);
  3058.             }
  3059.         }
  3060.         return $this->render(
  3061.             'ApplicationBundle:pages/dashboard:index_central_landing.html.twig',
  3062.             [
  3063.                 'page_title' => 'Central Landing',
  3064.             ]
  3065.         );
  3066.     }
  3067.     public function EmployeeAddUsingQrCodeAction(Request $request)
  3068.     {
  3069.         $post $request;
  3070.         $em $this->getDoctrine()->getManager('company_group');
  3071.         $appid $request->query->get('appid'$request->request->get('appid'null));
  3072.         $session $request->getSession();
  3073.         $CurrentRoute $request->attributes->get('_route');
  3074.         $systemType $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
  3075.         if ($request->isMethod('POST')) {
  3076.             $userId $request->request->get('userId'null);
  3077.             if ($userId === null) {
  3078.                 $companyId $request->request->get('company');
  3079.                 $email $request->request->get('email');
  3080.                 $qrImage $request->files->get('qr_image');
  3081.                 if (!$email) {
  3082.                     return new JsonResponse(['status' => 'error''message' => 'Invalid request'], 400);
  3083.                 }
  3084.                 if ($qrImage) {
  3085.                     $uploadsDir $this->getParameter('kernel.project_dir') . '/public/uploads/';
  3086.                     $fileName 'qr_' $companyId '_' time() . '.png';
  3087.                     $qrImage->move($uploadsDir$fileName);
  3088.                     $qrImagePath $uploadsDir $fileName;
  3089.                     $bodyTemplate 'ApplicationBundle:email/user:applicant_confirm.html.twig';
  3090.                     $bodyData = [
  3091.                         'name' => $email,
  3092.                         'companyData' => $companyId,
  3093.                         'companyName' => $request->request->get('company'),
  3094.                         'userType' => 2,
  3095.                         'appId' => $appid,
  3096.                         //                        'qr_code_url' => '/uploads/' . $fileName
  3097.                     ];
  3098.                     $userAccessList $session->get('userAccessList', []);
  3099.                     $companyName array_map(function ($company) {
  3100.                         return $company['companyName'];
  3101.                     }, $userAccessList);
  3102.                     $new_mail $this->get('mail_module');
  3103.                     $new_mail->sendMyMail([
  3104.                         'senderHash' => '_CUSTOM_',
  3105.                         'forwardToMailAddress' => $email,
  3106.                         'fromAddress' => 'no-reply@ourhoneybee.eu',
  3107.                         'userName' => 'no-reply@ourhoneybee.eu',
  3108.                         'password' => 'Honeybee@0112',
  3109.                         'smtpServer' => 'smtp.hostinger.com',
  3110.                         'smtpPort' => 465,
  3111.                         'subject' => 'User Registration on HoneyBee Ecosystem under Entity ',
  3112.                         'toAddress' => $email,
  3113.                         'mailTemplate' => $bodyTemplate,
  3114.                         'templateData' => $bodyData,
  3115.                         'companyId' => $companyId,
  3116.                     ]);
  3117.                     return $this->render(
  3118.                         'ApplicationBundle:pages/dashboard:index_central_landing.html.twig',
  3119.                         [
  3120.                             'page_title' => 'Central Landing',
  3121.                             'companyNames' => $companyName
  3122.                         ]
  3123.                     );
  3124.                 } else {
  3125.                     $userAccessList $session->get('userAccessList', []);
  3126.                     $companyName array_map(function ($company) {
  3127.                         return $company['companyName'];
  3128.                     }, $userAccessList);
  3129.                     return $this->render(
  3130.                         'ApplicationBundle:pages/dashboard:index_central_landing.html.twig',
  3131.                         [
  3132.                             'page_title' => 'Central Landing',
  3133.                             'companyNames' => $companyName
  3134.                         ]
  3135.                     );
  3136.                 }
  3137.             } else {
  3138.                 if ($systemType == '_CENTRAL_') {
  3139.                     $userAccessList $session->get('userAccessList', []);
  3140.                     $companyName array_map(function ($company) {
  3141.                         return $company['companyName'];
  3142.                     }, $userAccessList);
  3143.                     $modifiedRequest $request->duplicate(
  3144.                         null,
  3145.                         array_merge($request->request->all(), ['appId' => $request->request->get('appid')])
  3146.                     );
  3147.                     $response $this->EmployeeAddUsingQrCodeCentralAction($modifiedRequest);
  3148.                     if ($CurrentRoute == 'employee_add_by_qr_api') {
  3149.                         return $response;
  3150.                     }
  3151.                     return $this->render(
  3152.                         'ApplicationBundle:pages/dashboard:index_central_landing.html.twig',
  3153.                         [
  3154.                             'page_title' => 'Central Landing',
  3155.                             'companyNames' => $companyName
  3156.                         ]
  3157.                     );
  3158.                 }
  3159.             }
  3160.         } else {
  3161.             $company $request->get('company');
  3162.             return $this->render(
  3163.                 'ApplicationBundle:pages/dashboard:employee_add_by_qr.html.twig',
  3164.                 [
  3165.                     'page_title' => 'Central Landing',
  3166.                     'companyNames' => $company
  3167.                 ]
  3168.             );
  3169.         }
  3170.     }
  3171.     public function EmployeeOnboardUsingQrAction(Request $request)
  3172.     {
  3173.         $email $request->get('email');
  3174.         $isAjax $request->isXmlHttpRequest();
  3175.         $currentRoute $request->attributes->get('_route');
  3176.         if (!$email) {
  3177.             if ($isAjax) {
  3178.                 return new JsonResponse(['status' => 'error''message' => 'Email is required.']);
  3179.             } else {
  3180.                 throw $this->createNotFoundException("Email is missing.");
  3181.             }
  3182.         }
  3183.         $em_goc $this->getDoctrine()->getManager('company_group');
  3184.         $user $em_goc->getRepository("CompanyGroupBundle:EntityApplicantDetails")->findOneBy(['email' => $email]);
  3185.         if (!$user) {
  3186.             if ($isAjax) {
  3187.                 return new JsonResponse(['status' => 'error''message' => 'Applicant not found.']);
  3188.             } else {
  3189.                 throw $this->createNotFoundException("Applicant not found.");
  3190.             }
  3191.         }
  3192.         $payloadUrl $this->generateUrl('employee_onboard_by_qr_api', [
  3193.             'email' => $user->getEmail(),
  3194.             'applicantId' => $user->getApplicantId(),
  3195.             'employeeQr'=>1
  3196.         ], UrlGeneratorInterface::ABSOLUTE_URL);
  3197.         if ($currentRoute === 'employee_onboard') {
  3198.             return new JsonResponse([
  3199.                 'status' => 'success',
  3200.                 'data' => [
  3201.                     'applicantId' => $user->getApplicantId(),
  3202.                     'username' => $user->getUsername(),
  3203.                     'email' => $user->getEmail(),
  3204.                     'firstName'=> $user->getFirstname(),
  3205.                     'lastName' => $user->getLastname(),
  3206.                     'link' => $payloadUrl
  3207.                 ]
  3208.             ]);
  3209.         }
  3210.         if ($isAjax) {
  3211.             return new JsonResponse([
  3212.                 'status' => 'success',
  3213.                 'data' => [
  3214.                     'id' => $user->getApplicantId(),
  3215.                     'email' => $user->getEmail(),
  3216.                     'name' => $user->getFirstname() . ' ' $user->getLastname(),
  3217.                     'dob' => $user->getDob() ? $user->getDob()->format('Y-m-d') : null,
  3218.                 ]
  3219.             ]);
  3220.         }
  3221.         $companies $request->getSession()->get('userAccessList', []);
  3222.         return $this->render('ApplicationBundle:pages/dashboard:qr_onboard_result.html.twig', [
  3223.             'page_title' => 'Onboarding',
  3224.             'applicant' => $user,
  3225.             'companies' => $companies
  3226.         ]);
  3227.     }
  3228.     public function OnboardUserToCompanyAction(Request $request)
  3229.     {
  3230.         $systemType $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
  3231.         $currentRoute $request->attributes->get('_route');
  3232.         if ($systemType !== '_CENTRAL_') {
  3233.             throw new \Exception("This action must be called from CENTRAL system.");
  3234.         }
  3235.         $email $request->request->get('email');
  3236.         $applicantId $request->request->get('applicant_id');
  3237.         $appId $request->request->get('company_id');
  3238.         $userType $request->request->get('user_type');
  3239.         if (!$email || !$appId || !$userType) {
  3240.             $this->addFlash('error''Missing required fields.');
  3241.             return new JsonResponse(['status' => 'error''message' => 'Missing required fields.']);
  3242.         }
  3243.         $em $this->getDoctrine()->getManager('company_group');
  3244.         $applicant $em->getRepository("CompanyGroupBundle:EntityApplicantDetails")->findOneBy(['email' => $email]);
  3245.         if (!$applicant) {
  3246.             $this->addFlash('error''Applicant not found.');
  3247.             return $this->redirectToRoute('central_landing');
  3248.         }
  3249.         $userAppIds json_decode($applicant->getUserAppIds(), true);
  3250.         if (!is_array($userAppIds)) {
  3251.             $userAppIds = [];
  3252.         }
  3253.         if (!in_array($appId$userAppIds)) {
  3254.             $userAppIds[] = $appId;
  3255.             $applicant->setUserAppIds(json_encode($userAppIds));
  3256.         }
  3257.         $userTypesByAppIds json_decode($applicant->getUserTypesByAppIds(), true) ?: [];
  3258.         $userTypesByAppIds[$appId] = array((int) $userType);
  3259.         $applicant->setUserTypesByAppIds(json_encode($userTypesByAppIds));
  3260.         $em->persist($applicant);
  3261.         $em->flush();
  3262.         $companyRepo $this->getDoctrine()->getManager('company_group')->getRepository("CompanyGroupBundle:CompanyGroup");
  3263.         $targetCompany $companyRepo->findOneBy(['appId' => $appId]);
  3264.         if (!$targetCompany) {
  3265.             $this->addFlash('error''Target company not found.');
  3266.             return $this->redirectToRoute('central_landing');
  3267.         }
  3268.         $serverList GeneralConstant::$serverListById;
  3269.         $serverId $targetCompany->getCompanyGroupServerId();
  3270.         $appId $targetCompany->getAppId();
  3271.         if (!isset($serverList[$serverId])) {
  3272.             $this->addFlash('error''Server configuration not found.');
  3273.             return $this->redirectToRoute('central_landing');
  3274.         }
  3275.         // Find correct companyId from session userAccessList using appId
  3276.         $session $request->getSession();
  3277.         $userAccessList $session->get('userAccessList', []);
  3278.         $resolvedCompanyId null;
  3279.         foreach ($userAccessList as $access) {
  3280.             if (isset($access['appId']) && $access['appId'] == $appId) {
  3281.                 $resolvedCompanyId $access['companyId'];
  3282.                 break;
  3283.             }
  3284.         }
  3285.         if (!$resolvedCompanyId) {
  3286.             $this->addFlash('error''Could not resolve companyId from session for the given appId.');
  3287.             return $this->redirectToRoute('central_landing');
  3288.         }
  3289.         $imagePath $this->container->getParameter('kernel.root_dir') . '/../web/' $applicant->getImage();
  3290.         $imageFile null;
  3291.         if ($applicant->getImage() && file_exists($imagePath)) {
  3292.             $mime mime_content_type($imagePath);
  3293.             $name pathinfo($imagePathPATHINFO_BASENAME);
  3294.             $imageFile = new \CURLFile($imagePath$mime$name);
  3295.         }
  3296.         // Prepare userData
  3297.         $userData = [];
  3298.         $getters array_filter(get_class_methods($applicant), function ($method) {
  3299.             return strpos($method'get') === 0;
  3300.         });
  3301.         foreach ($getters as $getter) {
  3302.             if (in_array($getter, ['getCreatedAt''getUpdatedAt''getImage'])) continue;
  3303.             $value $applicant->$getter();
  3304.             $userData[$getter] = $value instanceof \DateTime $value->format('Y-m-d') : $value;
  3305.         }
  3306.         $userData['getUserAppIds'] = json_encode($userAppIds);
  3307.         $userData['getUserTypesByAppIds'] = json_encode($userTypesByAppIds);
  3308.         $postFields = [
  3309.             'userData' => json_encode([$userData]),
  3310.             'appIds' => $appId,
  3311.             'userIds' => $applicantId,
  3312.             'companyId' => $resolvedCompanyId,
  3313.             'userType' => $userType,
  3314.             'imageFile' => $imageFile
  3315.         ];
  3316.         if ($imageFile) {
  3317.             $postFields['file_' $applicant->getApplicantId()] = $imageFile;
  3318.         }
  3319.         $url $serverList[$serverId]['absoluteUrl'] . '/OnBoardCentralUserToErp';
  3320.         $curl curl_init();
  3321.         curl_setopt_array($curl, [
  3322.             CURLOPT_RETURNTRANSFER => 1,
  3323.             CURLOPT_POST => 1,
  3324.             CURLOPT_URL => $url,
  3325.             CURLOPT_POSTFIELDS => $postFields,
  3326.             CURLOPT_CONNECTTIMEOUT => 10,
  3327.             CURLOPT_SSL_VERIFYPEER => false,
  3328.             CURLOPT_SSL_VERIFYHOST => false,
  3329.         ]);
  3330.         $response curl_exec($curl);
  3331.         $curlError curl_error($curl);
  3332.         curl_close($curl);
  3333.         $responseObj json_decode($responsetrue);
  3334.         if ($currentRoute === 'employee_onboard_api') {
  3335.             return new JsonResponse(
  3336.                 $responseObj
  3337.             );
  3338.         }
  3339.         if (!empty($responseObj['success'])) {
  3340.             $this->addFlash('success''Applicant onboarded and synced to ERP.');
  3341.         } else {
  3342.             $this->addFlash('warning''Onboarded, but ERP sync may have failed. Check logs.');
  3343.         }
  3344.         return $this->redirectToRoute('central_landing');
  3345.     }
  3346.     public function OnBoardCentralUserToErpAction(Request $request)
  3347.     {
  3348.         $systemType $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
  3349.         if ($systemType === '_CENTRAL_') {
  3350.             return new JsonResponse(['success' => false'message' => 'Invalid system type.']);
  3351.         }
  3352.         $userDataJson $request->get('userData');
  3353.         $userDataList json_decode($userDataJsontrue);
  3354.         if (!$userDataList || !is_array($userDataList)) {
  3355.             return new JsonResponse(['success' => false'message' => 'Invalid or missing userData.']);
  3356.         }
  3357.         $userData $userDataList[0] ?? null;
  3358.         if (!$userData || empty($userData['getApplicantId'])) {
  3359.             return new JsonResponse(['success' => false'message' => 'Missing applicant ID.']);
  3360.         }
  3361.         $em_goc $this->getDoctrine()->getManager('company_group');
  3362.         $globalId $userData['getApplicantId'];
  3363.         $appIds $request->get('appIds');
  3364.         $userIds $request->get('userIds');
  3365.         $companyId $request->get('companyId');
  3366.         $company $em_goc->getRepository("CompanyGroupBundle:CompanyGroup")->findOneBy(['appId' => $appIds]);
  3367.         if (!$company) {
  3368.             return new JsonResponse(['success' => false'message' => 'Target company not found.']);
  3369.         }
  3370.         $connector $this->container->get('application_connector');
  3371.         $connector->resetConnection(
  3372.             'default',
  3373.             $company->getDbName(),
  3374.             $company->getDbUser(),
  3375.             $company->getDbPass(),
  3376.             $company->getDbHost(),
  3377.             true
  3378.         );
  3379.         $em $this->getDoctrine()->getManager();
  3380.         $user $em->getRepository('ApplicationBundle:SysUser')->findOneBy([
  3381.             'globalId' => $globalId
  3382.         ]);
  3383.         if (!$user) {
  3384.             $user = new \ApplicationBundle\Entity\SysUser();
  3385.             $user->setGlobalId($globalId);
  3386.         }
  3387.         $setterMap = [
  3388.             'getUsername' => 'setUserName',
  3389.             'getEmail' => 'setEmail',
  3390.             'getPassword' => 'setPassword',
  3391.             'getDeviceId' => 'setDeviceId',
  3392.             'getDeviceIdLockedFlag' => 'setDeviceIdLockedFlag',
  3393.             'getLockDeviceIdOnNextLoginFlag' => 'setLockDeviceIdOnNextLoginFlag',
  3394.             'getOAuthUniqueId' => 'setOAuthUniqueId',
  3395.             'getOAuthEmail' => 'setOAuthEmail',
  3396.             'getSyncFlag' => 'setSyncFlag',
  3397.             'getFirstname' => 'setName',
  3398.         ];
  3399.         $user->setUserAppId($appIds);
  3400.         $user->setUserAppIdList(json_encode([$appIds]));
  3401.         $user->setStatus(1);
  3402.         foreach ($setterMap as $getter => $setter) {
  3403.             if (isset($userData[$getter]) && method_exists($user$setter)) {
  3404.                 $user->$setter($userData[$getter]);
  3405.             }
  3406.         }
  3407.         $fullName trim(($userData['getFirstname'] ?? '') . ' ' . ($userData['getLastname'] ?? ''));
  3408.         if (!empty($fullName)) {
  3409.             $user->setName($fullName);
  3410.         }
  3411.         $imagePathToSet '';
  3412.         $uploadedFile $request->files->get('file_' $globalId);
  3413.         if ($uploadedFile) {
  3414.             $uploadDir $this->getParameter('kernel.project_dir') . '/web/uploads/UserImage/';
  3415.             if (!file_exists($uploadDir)) {
  3416.                 mkdir($uploadDir0777true);
  3417.             }
  3418.             $filename 'user_' $globalId '.' $uploadedFile->guessExtension();
  3419.             $uploadedFile->move($uploadDir$filename);
  3420.             $imagePathToSet 'uploads/UserImage/' $filename;
  3421.             $user->setImage($imagePathToSet);
  3422.         }
  3423.         $user->setUserType(1);
  3424.         $em->persist($user);
  3425.         $em->flush();
  3426.         $employee $em->getRepository('ApplicationBundle:Employee')->findOneBy([
  3427.             'userId' => $user->getUserId()
  3428.         ]);
  3429.         if (!$employee) {
  3430.             $employee = new \ApplicationBundle\Entity\Employee();
  3431.             $employee->setUserId($user->getUserId());
  3432.             $employee->setDateOfAddition(new \DateTime());
  3433.         }
  3434.         $employee->setFirstName($userData['getFirstname'] ?? null);
  3435.         $employee->setLastName($userData['getLastname'] ?? null);
  3436.         $employee->setName(trim(($userData['getFirstname'] ?? '') . ' ' . ($userData['getLastname'] ?? '')));
  3437.         $employee->setEmail($userData['getEmail'] ?? null);
  3438.         $employee->setEmmContact($userData['getEmmContact'] ?? null);
  3439.         $employee->setCurrentAddress($userData['getCurrAddr'] ?? null);
  3440.         $employee->setPermanentAddress($userData['getPermAddr'] ?? null);
  3441.         $employee->setCompanyId((int) $companyId);
  3442.         $employee->setDepartmentId($userData['getDept'] ?? null);
  3443.         $employee->setBranchId($userData['getBranch'] ?? null);
  3444.         $employee->setPositionId($userData['getDesg'] ?? null);
  3445.         $employee->setSupervisorId($userData['getSupervisor'] ?? null);
  3446.         if (!empty($imagePathToSet)) {
  3447.             $employee->setImage($imagePathToSet);
  3448.         }
  3449.         $employee->setStatus("1");
  3450.         $employee->setLastModifiedDate(new \DateTime());
  3451.         $em->persist($employee);
  3452.         $em->flush();
  3453.         $employeeDetails $em->getRepository('ApplicationBundle:EmployeeDetails')
  3454.             ->findOneBy(['userId' => $user->getUserId()]);
  3455.         if (!$employeeDetails) {
  3456.             $employeeDetails = new \ApplicationBundle\Entity\EmployeeDetails();
  3457.             $employeeDetails->setUserId($user->getUserId());
  3458.         }
  3459.         $employeeDetails->setId($employee->getEmployeeId());
  3460.         $employeeDetails->setFirstname($userData['getFirstname'] ?? null);
  3461.         $employeeDetails->setLastname($userData['getLastname'] ?? null);
  3462.         $employeeDetails->setUsername($userData['getUsername'] ?? null);
  3463.         $employeeDetails->setEmail($userData['getEmail'] ?? null);
  3464.         $employeeDetails->setPassword($userData['getPassword'] ?? null);
  3465.         $employeeDetails->setNid($userData['getNid'] ?? null);
  3466.         $employeeDetails->setSex($userData['getSex'] ?? null);
  3467.         $employeeDetails->setFather($userData['getFather'] ?? null);
  3468.         $employeeDetails->setMother($userData['getMother'] ?? null);
  3469.         $employeeDetails->setSpouse($userData['getSpouse'] ?? null);
  3470.         $employeeDetails->setChild1($userData['getChild1'] ?? null);
  3471.         $employeeDetails->setChild2($userData['getChild2'] ?? null);
  3472.         $employeeDetails->setPhone($userData['getPhone'] ?? null);
  3473.         $employeeDetails->setOfficialPhone($userData['getOfficailPhone'] ?? null);
  3474.         $employeeDetails->setCurrAddr($userData['getCurrAddr'] ?? null);
  3475.         $employeeDetails->setPermAddr($userData['getPermAddr'] ?? null);
  3476.         $employeeDetails->setEmmContact($userData['getEmmContact'] ?? null);
  3477.         if (!empty($userData['getDob'])) {
  3478.             $employeeDetails->setDob(new \DateTime($userData['getDob']));
  3479.         }
  3480.         if (!empty($userData['getJoiningDate'])) {
  3481.             $employeeDetails->setJoiningDate(new \DateTime($userData['getJoiningDate']));
  3482.         }
  3483.         if (!empty($userData['getEmpValidTill'])) {
  3484.             $employeeDetails->setEmpValidTill(new \DateTime($userData['getEmpValidTill']));
  3485.         }
  3486.         if (!empty($userData['getTinValidTill'])) {
  3487.             $employeeDetails->setTinValidTill(new \DateTime($userData['getTinValidTill']));
  3488.         }
  3489.         if (!empty($userData['getMedInsValidTill'])) {
  3490.             $employeeDetails->setMedInsValidTill(new \DateTime($userData['getMedInsValidTill']));
  3491.         }
  3492.         $employeeDetails->setEmpType($userData['getEmpType'] ?? null);
  3493.         $employeeDetails->setEmpCode($userData['getEmpCode'] ?? null);
  3494.         $employeeDetails->setEmployeeLevel($userData['getEmployeeLevel'] ?? null);
  3495.         $employeeDetails->setTin($userData['getTin'] ?? null);
  3496.         $employeeDetails->setSkill($userData['getSkill'] ?? null);
  3497.         $employeeDetails->setEducationData($userData['getEducationData'] ?? null);
  3498.         $employeeDetails->setWorkExperienceData($userData['getWorkExperienceData'] ?? null);
  3499.         $employeeDetails->setApplicationText($userData['getApplicationText'] ?? null);
  3500.         $employeeDetails->setCurrentEmployment($userData['getCurrentEmployment'] ?? null);
  3501.         $employeeDetails->setEmergencyContactNumber($userData['getEmergencyContactNumber'] ?? null);
  3502.         $employeeDetails->setPostalCode($userData['getPostalCode'] ?? null);
  3503.         $employeeDetails->setCountry($userData['getCountry'] ?? null);
  3504.         if (!empty($imagePathToSet)) {
  3505.             $employeeDetails->setImage($imagePathToSet);
  3506.         }
  3507.         $em->persist($employeeDetails);
  3508.         $em->flush();
  3509.         $uploadedFile $request->files->get('file_' $globalId);
  3510.         return new JsonResponse([
  3511.             'success' => true,
  3512.             'globalId' => $globalId,
  3513.             'appIds' => $appIds,
  3514.             'userIds' => $userIds,
  3515.             'hasFile' => $uploadedFile !== null,
  3516.         ]);
  3517.     }
  3518.     public function getIndustryListForAppAction()
  3519.     {
  3520.         $industryList GeneralConstant::$industryList;
  3521.         return new JsonResponse($industryList);
  3522.     }
  3523.     public function getFeatureListAction()
  3524.     {
  3525.         $featureList GeneralConstant::$featureList;
  3526.         return new JsonResponse($featureList);
  3527.     }
  3528.     public function chooseYourPlanAction()
  3529.     {
  3530.         $plan GeneralConstant::$chooseYourPlan;
  3531.         return new JsonResponse($plan);
  3532.     }
  3533. //    public function getLogindataFromTokenAction(Request $request)
  3534. //    {
  3535. //        $em_goc = $this->getDoctrine()->getManager('company_group');
  3536. //        $sessionData = MiscActions::GetSessionDataFromToken($em_goc, $request->query->get('hbeeSessionToken'))['sessionData'];
  3537. //        return new JsonResponse($sessionData);
  3538. //        $sessionDataa = MiscActions::GetSessionDataFromToken($em_goc, $request->query->get('hbeeSessionToken'))['sessionData'];
  3539. //        return new JsonResponse($sessionDataa);
  3540. //    }
  3541.     public function getLogindataFromTokenAction(Request $request)
  3542.     {
  3543.         $em_goc $this->getDoctrine()->getManager('company_group');
  3544.         $token $request->query->get('hbeeSessionToken');
  3545.         if (!$token) {
  3546.             return new JsonResponse(['error' => 'Missing session token'], 400);
  3547.         }
  3548.         $sessionResult MiscActions::GetSessionDataFromToken($em_goc$token);
  3549.         if (!$sessionResult || !isset($sessionResult['sessionData'])) {
  3550.             return new JsonResponse(['error' => 'Invalid session token or session not found'], 401);
  3551.         }
  3552.         $sessionData $sessionResult['sessionData'];
  3553.         return new JsonResponse($sessionData);
  3554.     }
  3555.     public function packageDetailsAction()
  3556.     {
  3557.         $packageDetails GeneralConstant::$packageDetails;
  3558.         return new JsonResponse($packageDetails);
  3559.     }
  3560.     public function employeeRangeAction()
  3561.     {
  3562.         $employeeRangeForApp GeneralConstant::$employeeRange;
  3563.         return new JsonResponse($employeeRangeForApp);
  3564.     }
  3565.     public function paymentMethodAction()
  3566.     {
  3567.         $paymentMethod GeneralConstant::$paymentMethod;
  3568.         return new JsonResponse($paymentMethod);
  3569.     }
  3570. }