src/ApplicationBundle/Controller/DashboardController.php line 35

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