src/ApplicationBundle/Controller/DashboardController.php line 2267

Open in your IDE?
  1. <?php
  2. namespace ApplicationBundle\Controller;
  3. use ApplicationBundle\Constants\GeneralConstant;
  4. use ApplicationBundle\Entity\DashboardWidget;
  5. use ApplicationBundle\Modules\User\Position;
  6. use CompanyGroupBundle\Entity\EntityItemGroup;
  7. use CompanyGroupBundle\Entity\EntityProductCategories;
  8. use CompanyGroupBundle\Entity\EntityProductSubCategories;
  9. use CompanyGroupBundle\Entity\EntityProductSpecifications;
  10. use CompanyGroupBundle\Entity\EntityBrandCompany;
  11. use CompanyGroupBundle\Entity\EntityUnitType;
  12. use CompanyGroupBundle\Entity\EntityProducts;
  13. use ApplicationBundle\Helper\Generic;
  14. use ApplicationBundle\Interfaces\SessionCheckInterface;
  15. use ApplicationBundle\Constants\UserConstants;
  16. use ApplicationBundle\Modules\Accounts\Accounts;
  17. use ApplicationBundle\Modules\System\MiscActions;
  18. use ApplicationBundle\Modules\System\System;
  19. use ApplicationBundle\Modules\User\Users;
  20. use ApplicationBundle\Modules\Purchase\Supplier;
  21. use ApplicationBundle\Modules\Inventory\Inventory;
  22. use CompanyGroupBundle\Entity\EntityUser;
  23. use Symfony\Component\BrowserKit\Client as BrowserClientKit;
  24. use ApplicationBundle\Modules\Sales\Client;
  25. use ApplicationBundle\Modules\User\Company;
  26. use Symfony\Component\HttpFoundation\Request;
  27. use Symfony\Component\HttpFoundation\Response;
  28. use Symfony\Component\Debug\Exception\FlattenException;
  29. use Symfony\Component\HttpKernel\Log\DebugLoggerInterface;
  30. use Symfony\Component\HttpFoundation\JsonResponse;
  31. use Twig\Environment;
  32. use Twig\Error\LoaderError;
  33. use Twig\Loader\ExistsLoaderInterface;
  34. use Twig\Loader\SourceContextLoaderInterface;
  35. class DashboardController extends GenericController implements SessionCheckInterface
  36. {
  37.     public function doLoginAsAction(Request $request)
  38.     {
  39.         $session $request->getSession();
  40.         if ($request->isMethod('POST')) {
  41.             $session->set(UserConstants::USER_CURRENT_POSITION$request->request->get('position'));
  42.             $curr_position_id $request->request->get('position');
  43.             if ($session->get(UserConstants::USER_LOGIN_ID) != 0) {
  44.                 $loginID $this->get('user_module')->addUserLoginLog(
  45.                     $session->get(UserConstants::USER_ID),
  46.                     $request->server->get("REMOTE_ADDR"),
  47.                     $request->request->get('position'),
  48.                     '',
  49.                     '',
  50.                     '',
  51.                     $session->get(UserConstants::USER_LOGIN_ID)
  52.                 );
  53.             } else $loginID $this->get('user_module')->addUserLoginLog(
  54.                 $session->get(UserConstants::USER_ID),
  55.                 $request->server->get("REMOTE_ADDR"),
  56.                 $request->request->get('position'),
  57.                 '',
  58.                 '',
  59.                 '',
  60.                 0
  61.             );
  62.             if ($session->get(UserConstants::ALL_MODULE_ACCESS_FLAG) == 1)
  63.                 $prohibit_list_array = [];
  64.             else if ($curr_position_id != 0)
  65.                 $prohibit_list_array Position::getUserProhibitRouteArray($this->getDoctrine()->getManager(), $curr_position_id$session->get(UserConstants::USER_ID));
  66.             $session->set(UserConstants::USER_LOGIN_ID$loginID);
  67.             $session->set(UserConstants::USER_PROHIBIT_LISTjson_encode($prohibit_list_array));
  68.             $session->set(UserConstants::USER_ROUTE_LISTjson_encode(Position::getUserRouteArray($this->getDoctrine()->getManager(), $request->request->get('position'), $session->get(UserConstants::USER_ID))));
  69.             return $this->redirectToRoute("dashboard");
  70.         }
  71.         $message "";
  72.         $PositionList = array();
  73.         $PL json_decode($session->get(UserConstants::USER_POSITION_LIST), true);
  74.         foreach ($PL as &$positionID) {
  75.             $PositionList[$positionID] = Position::getPositionName($this->getDoctrine()->getManager(), $positionID);
  76.         }
  77.         return $this->render(
  78.             'ApplicationBundle:pages/login:login_position.html.twig',
  79.             array(
  80.                 "message" => $message,
  81.                 'page_title' => 'Users',
  82.                 'position_list' => $PositionList
  83.             )
  84.         );
  85.     }
  86. //    protected $twig;
  87. //    protected $debug;
  88. //
  89. //    /**
  90. //     * @param bool $debug Show error (false) or exception (true) pages by default
  91. //     */
  92. //    public function __construct(Environment $twig, $debug)
  93. //    {
  94. //        $this->twig = $twig;
  95. //        $this->debug = $debug;
  96. //    }
  97.     public function TestSmsAction(Request $request)
  98.     {
  99.         $em $this->getDoctrine()->getManager();
  100.         $session $request->getSession();
  101.         $em $this->getDoctrine()->getManager();
  102.         $userAppId $session->get('userAppId');
  103.         $companyId $session->get('userCompanyId');
  104.         if (GeneralConstant::SMS_ENABLED == 1) {
  105.             $company $em->getRepository('ApplicationBundle:Company')->findOneBy(
  106.                 array(
  107.                     'id' => $companyId///material
  108.                 )
  109.             );
  110.             if ($company->getSmsNotificationEnabled() == 1) {
  111.                 $smsData = [];
  112.                 $smsSettings json_decode($company->getSmsSettings(), true);
  113.                 if ($smsSettings != null && !empty($smsSettings)) {
  114.                     $method = isset($smsSettings['method']) ? $smsSettings['method'] : 'GET';
  115.                     $destination_url = isset($smsSettings['destination_url']) ? $smsSettings['destination_url'] : 'http://172.105.70.96:1234';
  116.                     $user_name = isset($smsSettings['user_name']) ? $smsSettings['user_name'] : 'test';
  117.                     $user_name_var = isset($smsSettings['user_name_var']) ? $smsSettings['user_name_var'] : 'Username';
  118.                     $password_var = isset($smsSettings['password_var']) ? $smsSettings['password_var'] : 'Password';
  119.                     $password = isset($smsSettings['password']) ? $smsSettings['password'] : '';
  120.                     $from_number_var = isset($smsSettings['from_number_var']) ? $smsSettings['from_number_var'] : 'From';
  121.                     $from_number = isset($smsSettings['from_number']) ? $smsSettings['from_number'] : '';
  122.                     $to_number_var = isset($smsSettings['to_number_var']) ? $smsSettings['to_number_var'] : 'To';
  123.                     $to_number $request->query->has('To') ? $request->query->get('To') : '01911706483';
  124.                     $text_var = isset($smsSettings['text_var']) ? $smsSettings['text_var'] : 'Message';
  125.                     $text $request->query->has('Message') ? $request->query->get('Message') : 'Test message';
  126.                     return new JsonResponse(System::sendSms(1$method$destination_url,
  127.                         $user_name_var$user_name,
  128.                         $password_var$password,
  129.                         $from_number_var$from_number,
  130.                         $to_number_var$to_number,
  131.                         $text_var$text,
  132.                         $viewlink ""));
  133.                 }
  134.             }
  135.             return new JsonResponse([
  136.                     'companyId' => $companyId,
  137.                     'companyName' => $company->getName(),
  138.                     'enabled' => $company->getSmsNotificationEnabled(),
  139. //                    'smsSettings'=>$smsSettings
  140.                 ]
  141.             );
  142.         }
  143.         return new JsonResponse([
  144.                 'success' => false
  145.             ]
  146.         );
  147.     }
  148.     public function SyncCompanyProductToEntityProductAction(Request $request)
  149.     {
  150.         $gocId $request->query->has('gocId') ? $request->query->get('gocId') : 0;
  151.         $companyId $request->query->has('companyId') ? $request->query->get('companyId') : 1;
  152.         $genQueryArray = [];
  153.         $em_goc $this->getDoctrine()->getManager('company_group');
  154.         $em_goc->getConnection()->connect();
  155.         $em $this->getDoctrine()->getManager();
  156.         if ($request->query->has('forceRefresh')) {
  157.             $genQueryArray = [];
  158.             $query "
  159.             TRUNCATE `entity_brand_company`;
  160.             TRUNCATE `entity_item_group`;
  161.             TRUNCATE `entity_products`;
  162.             TRUNCATE `entity_product_categories`;
  163.             TRUNCATE `entity_product_specifications`;
  164.             TRUNCATE `entity_product_sub_categories`;
  165.             TRUNCATE `entity_specification_types`;
  166.             TRUNCATE `entity_unit_type`;
  167.             SELECT * from `entity_unit_type`;";
  168.             $stmt $em_goc->getConnection()->prepare($query);
  169.             $stmt->execute();
  170. //            $Transactions = $stmt->fetchAll();
  171.             $get_kids_sql 'select * from acc_accounts_head where accounts_head_id not in (select distinct parent_id from acc_accounts_head) ;';
  172. //UPDATE company SET sales=0, expense=0, payable=0 ,net_worth=0, monthly_growth=0 WHERE 1;';
  173.             $stmt $em->getConnection()->prepare($get_kids_sql);
  174.             $stmt->execute();
  175.             $query $stmt->fetchAll();
  176.         } else
  177.             $genQueryArray = ['globalId' => [0null]];
  178.         //1st step get all company item ids and then check for global id null if its null then the
  179.         // item group is not present in entity so add it
  180.         $company_wise_entities = [
  181.             'Currencies',
  182.             'UnitType',
  183.             'BrandCompany',
  184.             'InvItemGroup',
  185.             'InvProductCategories',
  186.             'InvProductSubCategories',
  187.             'InvProductSpecifications',
  188.             'InvSpecificationTypes',
  189.             'InvProducts'
  190.         ];
  191.         $entity_wise_entities = [
  192.             'EntityCurrencies',
  193.             'EntityUnitType',
  194.             'EntityBrandCompany',
  195.             'EntityItemGroup',
  196.             'EntityProductCategories',
  197.             'EntityProductSubCategories',
  198.             'EntityProductSpecifications',
  199.             'EntitySpecificationTypes',
  200.             'EntityProducts'
  201.         ];
  202.         ////ITEMGROUPS
  203.         foreach ($company_wise_entities as $k => $cwa) {
  204.             $dataOnCompany $em
  205.                 ->getRepository("ApplicationBundle:" $cwa)
  206.                 ->findBy(
  207.                     $genQueryArray
  208.                 );
  209.             $match_cid_gid_itemgroup = [];  //[cid=>gid]
  210.             $match_cid_gid_itemgroup = [];  //[cid=>gid]
  211.             foreach ($dataOnCompany as $data) {
  212.                 $newClass "\\CompanyGroupBundle\\Entity\\" $entity_wise_entities[$k];
  213.                 $new = new $newClass();
  214. //                $new = new \CompanyGroupBundle\Entity\EntityItemGroup();
  215.                 $getters array_filter(get_class_methods($data), function ($method) {
  216.                     return 'get' === substr($method03);
  217.                 });
  218.                 foreach ($getters as $getter) {
  219.                     if ($getter == 'getGlobalId')
  220.                         continue;
  221. //                    if ($getter == 'getId')
  222. //                        continue;
  223.                     $setMethod str_replace('get''set'$getter);
  224.                     if (method_exists($new$setMethod))
  225.                         $new->{$setMethod}($data->{$getter}()); // `foo!`
  226.                 }
  227.                 $em_goc->persist($new);
  228.                 $em_goc->flush();
  229.                 if ($cwa == 'Currencies') {
  230.                     $data->setGlobalId($new->getCurrencyId());
  231.                     $new->setGlobalId($new->getCurrencyId());
  232.                 } else {
  233.                     $data->setGlobalId($new->getId());
  234.                     $new->setGlobalId($new->getId());
  235.                 }
  236.                 $em->flush();
  237.                 $em_goc->flush();
  238. //                $match_cid_gid_itemgroup[$data->getId()] = $new->getId();
  239.             }
  240.         }
  241.         return new JsonResponse(
  242.             array(
  243.                 'data' => $entity_wise_entities
  244.             )
  245.         );
  246.     }
  247.     public function SyncEntityProductToCompanyProductAction(Request $request)
  248.     {
  249.         $gocId $request->query->has('gocId') ? $request->query->get('gocId') : 0;
  250.         $companyId $request->query->has('companyId') ? $request->query->get('companyId') : 1;
  251.         $genQueryArray = [];
  252.         $em_goc $this->getDoctrine()->getManager('company_group');
  253.         $em_goc->getConnection()->connect();
  254.         $em $this->getDoctrine()->getManager();
  255.         if ($request->query->has('forceRefresh')) {
  256.             $genQueryArray = [];
  257.             $query "
  258.             TRUNCATE `brand_company`;
  259.             TRUNCATE `inv_item_group`;
  260.             TRUNCATE `inv_products`;
  261.             TRUNCATE `inv_product_categories`;
  262.             TRUNCATE `inv_product_specifications`;
  263.             TRUNCATE `inv_product_sub_categories`;
  264.             TRUNCATE `inv_specification_types`;
  265.             TRUNCATE `unit_type`;
  266.             SELECT * from `unit_type`;";
  267.             $stmt $em->getConnection()->prepare($query);
  268.             $stmt->execute();
  269. //            $Transactions = $stmt->fetchAll();
  270.             $get_kids_sql 'select * from acc_accounts_head where accounts_head_id not in (select distinct parent_id from acc_accounts_head) ;';
  271. //UPDATE company SET sales=0, expense=0, payable=0 ,net_worth=0, monthly_growth=0 WHERE 1;';
  272.             $stmt $em->getConnection()->prepare($get_kids_sql);
  273.             $stmt->execute();
  274.             $query $stmt->fetchAll();
  275.         } else {
  276. //            $genQueryArray = ['globalId' => [0, null]];
  277.         }
  278.         //1st step get all company item ids and then check for global id null if its null then the
  279.         // item group is not present in entity so add it
  280.         $company_wise_entities = [
  281.             'Currencies',
  282.             'UnitType',
  283.             'BrandCompany',
  284.             'InvItemGroup',
  285.             'InvProductCategories',
  286.             'InvProductSubCategories',
  287.             'InvProductSpecifications',
  288.             'InvSpecificationTypes',
  289.             'InvProducts'
  290.         ];
  291.         $entity_wise_entities = [
  292.             'EntityCurrencies',
  293.             'EntityUnitType',
  294.             'EntityBrandCompany',
  295.             'EntityItemGroup',
  296.             'EntityProductCategories',
  297.             'EntityProductSubCategories',
  298.             'EntityProductSpecifications',
  299.             'EntitySpecificationTypes',
  300.             'EntityProducts'
  301.         ];
  302.         foreach ($entity_wise_entities as $k => $ewa) {
  303.             $dataOnEntity $em_goc
  304.                 ->getRepository("CompanyGroupBundle:" $ewa)
  305.                 ->findBy(
  306.                     $genQueryArray
  307.                 );
  308.             $match_cid_gid_itemgroup = [];  //[cid=>gid]
  309.             $match_cid_gid_itemgroup = [];  //[cid=>gid]
  310.             foreach ($dataOnEntity as $data) {
  311.                 $newClass "\\ApplicationBundle\\Entity\\" $company_wise_entities[$k];
  312.                 $rec_exists 0;
  313.                 $new $em
  314.                     ->getRepository("ApplicationBundle:" $company_wise_entities[$k])
  315.                     ->findOneBy(
  316.                         array(
  317.                             'globalId' => $data->getGlobalId()
  318.                         )
  319.                     );
  320.                 if ($new) {
  321.                     $rec_exists 1;
  322.                 } else
  323.                     $new = new $newClass();
  324. //                $new = new \CompanyGroupBundle\Entity\EntityItemGroup();
  325.                 $getters array_filter(get_class_methods($data), function ($method) {
  326.                     return 'get' === substr($method03);
  327.                 });
  328.                 foreach ($getters as $getter) {
  329.                     if ($getter == 'getId')
  330.                         continue;
  331.                     $setMethod str_replace('get''set'$getter);
  332.                     if (method_exists($new$setMethod)) {
  333.                         if ($ewa == 'EntityProducts') {
  334.                             if ($rec_exists == 1) {
  335.                                 if (in_array($setMethod, [
  336.                                     'setPurchasePrice',
  337.                                     'setPurchasePriceWoExpense',
  338.                                     'setQty',
  339.                                     'setReorderLevel',
  340.                                     'setBookingQty',
  341.                                     'setNonSalesInvoicedQty',
  342.                                     'setNonSalesReturnReceivedQty',
  343.                                     'setBookingQty',
  344.                                     'setPhysicalQty',
  345.                                 ])) {
  346.                                     continue;
  347.                                 }
  348.                             }
  349.                         }
  350.                         $new->{$setMethod}($data->{$getter}()); // `foo!`
  351.                     }
  352.                 }
  353.                 if ($rec_exists == 0)
  354.                     $em->persist($new);
  355.                 $em->flush();
  356.                 if ($ewa == 'EntityCurrencies') {
  357.                     $new->setGlobalId($data->getCurrencyId());
  358.                 } else {
  359.                     $new->setGlobalId($data->getId());
  360.                 }
  361.                 $em->flush();
  362. //                $match_cid_gid_itemgroup[$data->getId()] = $new->getId();
  363.             }
  364.         }
  365.         return new JsonResponse(
  366.             array(
  367.                 'data' => $company_wise_entities
  368.             )
  369.         );
  370.     }
  371.     public function getAppGeneralDashboardDataAction(Request $request)
  372.     {
  373.         $dataFor 'client';
  374.         $personId 0;
  375.         if ($request->query->has('dataFor'))
  376.             $dataFor $request->query->get('dataFor');
  377.         if ($request->request->has('dataFor'))
  378.             $dataFor $request->request->get('dataFor');
  379.         if ($request->query->has('personId'))
  380.             $personId $request->query->get('personId');
  381.         if ($request->request->has('personId'))
  382.             $personId $request->request->get('personId');
  383.         if ($personId == 0)
  384.             return new JsonResponse(
  385.                 array(
  386.                     'success' => false,
  387.                     'data' => [],
  388.                 )
  389.             );
  390.         $session $request->getSession();
  391.         $em $this->getDoctrine()->getManager();
  392.         $userAppId $session->get('userAppId');
  393.         $companyId $session->get('userCompanyId');
  394.         $dataToConnectList = [];
  395.         $appIdList $session->get('appIdList');
  396.         $companyIdListByAppId $session->get('companyIdListByAppId');
  397.         $companyNameListByAppId $session->get('companyNameListByAppId');
  398.         $companyImageListByAppId $session->get('companyImageListByAppId');
  399.         $gocEnabled 0;
  400.         if ($this->container->hasParameter('entity_group_enabled'))
  401.             $gocEnabled $this->container->getParameter('entity_group_enabled');
  402.         $connector $this->container->get('application_connector');
  403.         $connector->resetConnection(
  404.             'default',
  405.             $session->get('gocDbName'),
  406.             $session->get('gocDbUser'),
  407.             $session->get('gocDbPass'),
  408.             $session->get('gocDbHost'),
  409.             $reset true
  410.         );
  411.         $em $this->getDoctrine()->getManager();
  412.         $data = [];
  413.         if ($dataFor == 'client') {
  414.             //get order_count, order_amount,bill_count, bill_amount, collection_amount, due_amount
  415.             $data = [
  416.                 'order_count' => 0,
  417.                 'order_amount' => 0,
  418.                 'invoice_count' => 0,
  419.                 'invoice_amount' => 0,
  420.                 'collection_amount' => 0,
  421.                 'due_amount' => 0,
  422.                 'client_count' => 1,
  423.             ];
  424.             $clientIds = [$personId];
  425.             //order count and amount
  426.             $get_sql "SELECT count(sales_order_id) order_count, sum(so_amount) order_amount
  427. FROM sales_order WHERE approved=1 and sales_order.company_id=" $companyId "  and sales_order.client_id in (" implode(','$clientIds) . ");";
  428.             $stmt $em->getConnection()->prepare($get_sql);
  429.             $stmt->execute();
  430.             $entries $stmt->fetchAll();
  431.             if (!empty($entries)) {
  432.                 $data['order_count'] = $entries[0]['order_count'];
  433.                 $data['order_amount'] = $entries[0]['order_amount'];
  434.             }
  435.             //invoice
  436.             $get_sql "SELECT count(sales_invoice_id) invoice_count, sum(invoice_amount) invoice_amount
  437. FROM sales_invoice WHERE approved=1 and sales_invoice.company_id=" $companyId "  and sales_invoice.client_id in (" implode(','$clientIds) . ");";
  438.             $stmt $em->getConnection()->prepare($get_sql);
  439.             $stmt->execute();
  440.             $entries $stmt->fetchAll();
  441.             if (!empty($entries)) {
  442.                 $data['invoice_count'] = $entries[0]['invoice_count'];
  443.                 $data['invoice_amount'] = $entries[0]['invoice_amount'];
  444.             }
  445.             //now collection
  446.             $get_sql "SELECT SUM(CASE WHEN position = 'cr' THEN amount ELSE 0 END) positive_amount,
  447. 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
  448.  FROM acc_transaction_details
  449.    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
  450.   join client_type on acc_clients.type=client_type.client_type_id
  451.   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) . ") ";
  452.             $stmt $em->getConnection()->prepare($get_sql);
  453.             $stmt->execute();
  454.             $entries $stmt->fetchAll();
  455.             $clientTypes = [];
  456.             $clientTypeNames = [];
  457.             $alreadyCids = [];
  458.             foreach ($entries as $entry) {
  459.                 $data['collection_amount'] += (* ($entry['positive_amount'] - $entry['negative_amount']));
  460.                 if (!in_array($entry['client_id'], $alreadyCids)) {
  461.                     $data['due_amount'] += ($entry['client_due']);
  462.                     $alreadyCids[] = $entry['client_id'];
  463.                 }
  464.             }
  465.         }
  466.         if ($dataFor == 'sales_user') {
  467.             //get order_count, order_amount,bill_count, bill_amount, collection_amount, due_amount
  468.             $data = [
  469.                 'order_count' => 0,
  470.                 'order_amount' => 0,
  471.                 'invoice_count' => 0,
  472.                 'invoice_amount' => 0,
  473.                 'collection_amount' => 0,
  474.                 'due_amount' => 0,
  475.                 'client_count' => 0,
  476.             ];
  477.             $clientIds = [];
  478.             $salesPersonIds = [];
  479.             $allSalespersonFlag 1//temp
  480.             if ($allSalespersonFlag != 1) {
  481.                 $query $em->getRepository('ApplicationBundle:Employee')->findOneBy(
  482.                     array(
  483.                         'userId' => $personId
  484.                     )
  485.                 );
  486.                 if ($query)
  487.                     $salesPersonIds[] = $query->getEmployeeId();
  488.             }
  489.             //Client count
  490.             $get_sql "SELECT  client_id
  491. FROM acc_clients WHERE  acc_clients.company_id=" $companyId " ";
  492.             if ($allSalespersonFlag != 1)
  493.                 $get_sql .= " and acc_clients.sales_person_id in (" implode(','$salesPersonIds) . ");";
  494.             else
  495.                 $get_sql .= " ;";
  496.             $stmt $em->getConnection()->prepare($get_sql);
  497.             $stmt->execute();
  498.             $entries $stmt->fetchAll();
  499.             if (!empty($entries)) {
  500.                 foreach ($entries as $entry) {
  501.                     $data['client_count'] += 1;
  502.                     $clientIds[] = $entry['client_id'];
  503.                 }
  504.             }
  505.             //order count and amount
  506.             if (!empty($clientIds)) {
  507.                 $get_sql "SELECT count(sales_order_id) order_count, sum(so_amount) order_amount
  508. FROM sales_order WHERE approved=1 and sales_order.company_id=" $companyId "  and sales_order.client_id in (" implode(','$clientIds) . ");";
  509.                 $stmt $em->getConnection()->prepare($get_sql);
  510.                 $stmt->execute();
  511.                 $entries $stmt->fetchAll();
  512.                 if (!empty($entries)) {
  513.                     $data['order_count'] = $entries[0]['order_count'];
  514.                     $data['order_amount'] = $entries[0]['order_amount'];
  515.                 }
  516.                 //invoice
  517.                 $get_sql "SELECT count(sales_invoice_id) invoice_count, sum(invoice_amount) invoice_amount
  518. FROM sales_invoice WHERE approved=1 and sales_invoice.company_id=" $companyId "  and sales_invoice.client_id in (" implode(','$clientIds) . ");";
  519.                 $stmt $em->getConnection()->prepare($get_sql);
  520.                 $stmt->execute();
  521.                 $entries $stmt->fetchAll();
  522.                 if (!empty($entries)) {
  523.                     $data['invoice_count'] = $entries[0]['invoice_count'];
  524.                     $data['invoice_amount'] = $entries[0]['invoice_amount'];
  525.                 }
  526.                 //now collection
  527.                 $get_sql "SELECT SUM(CASE WHEN position = 'cr' THEN amount ELSE 0 END) positive_amount,
  528. 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
  529.  FROM acc_transaction_details
  530.    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
  531.   join client_type on acc_clients.type=client_type.client_type_id
  532.   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) . ") ";
  533.                 $stmt $em->getConnection()->prepare($get_sql);
  534.                 $stmt->execute();
  535.                 $entries $stmt->fetchAll();
  536.                 $clientTypes = [];
  537.                 $clientTypeNames = [];
  538.                 $alreadyCids = [];
  539.                 foreach ($entries as $entry) {
  540.                     $data['collection_amount'] += (* ($entry['positive_amount'] - $entry['negative_amount']));
  541.                     if (!in_array($entry['client_id'], $alreadyCids)) {
  542.                         $data['due_amount'] += ($entry['client_due']);
  543.                         $alreadyCids[] = $entry['client_id'];
  544.                     }
  545.                 }
  546.             }
  547.         }
  548.         if ($dataFor == 'user') {
  549.             //get order_count, payment_amount,
  550.         }
  551.         return new JsonResponse(
  552.             array(
  553.                 'success' => true,
  554.                 'data' => $data,
  555.                 'dataFor' => $dataFor,
  556.                 'personId' => $personId,
  557.             )
  558.         );
  559.     }
  560.     public function getManagementDashboardDataAction(Request $request)
  561.     {
  562.         $session $request->getSession();
  563.         $data = array(
  564.             'cash_and_bank_position' => [],
  565.             'order_and_client_count' => [],
  566.             'expense_vs_revenue' => [],
  567.             'receivable_position' => [],
  568.             'payable_position' => [],
  569.             'expense_position' => [],
  570.             'inventory_position' => [],
  571.             'production_position' => [],
  572.             'sales_position' => [],
  573.             'collection_position' => [],
  574.             'market_return_position' => [],
  575.             'top_selling_item_position' => [],
  576.             'top_selling_client_position' => [],
  577.         );
  578.         $em $this->getDoctrine()->getManager();
  579.         $reportsToGet = [
  580.             'cash_and_bank_position',
  581.             'order_and_client_count',
  582.             'expense_vs_revenue',
  583.             'receivable_position',
  584.             'payable_position',
  585.             'expense_position',
  586.             'inventory_position',
  587.             'production_position',
  588.             'sales_position',
  589.             'collection_position',
  590.             'market_return_position',
  591.             'top_selling_item_position',
  592.             'top_selling_client_position',
  593.         ];
  594. //        $periodType='day'; //day,month,week,year,quarter etc
  595.         $periodType 'month'//day,month,week,year,quarter etc
  596.         if ($request->request->has('reportsToGet')) {
  597.             if ($request->request->get('reportsToGet') != 'all' && !in_array('all'$request->request->get('reportsToGet'))) {
  598.                 $reportsToGet $request->request->get('reportsToGet');
  599.             }
  600.         }
  601.         if ($request->request->has('periodType')) {
  602.             $periodType $request->request->get('periodType');
  603.         }
  604.         $userAppId $session->get('userAppId');
  605.         $dataToConnectList = [];
  606.         $appIdList $session->get('appIdList');
  607.         $companyIdListByAppId $session->get('companyIdListByAppId');
  608.         $companyNameListByAppId $session->get('companyNameListByAppId');
  609.         $companyImageListByAppId $session->get('companyImageListByAppId');
  610.         $gocEnabled 0;
  611.         if ($this->container->hasParameter('entity_group_enabled'))
  612.             $gocEnabled $this->container->getParameter('entity_group_enabled');
  613.         $thisPeriodStartDate '';
  614.         $lastPeriodStartDate '';
  615.         $thisPeriodEndDate '';
  616.         $lastPeriodEndDate '';
  617.         $today = new \DateTime();
  618.         if ($periodType == 'month') {
  619.             $thisPeriodEndDate $today->format('Y-m-d');
  620.             $thisPeriodStartDate $today->format('Y-m-') . '01';
  621.             $currDate = new \DateTime($thisPeriodStartDate);
  622.             $currDate->modify('-1 day');
  623.             $lastPeriodEndDate $currDate->format('Y-m-d');
  624.             $lastPeriodStartDate $currDate->format('Y-m-') . '01';
  625.         } else if ($periodType == 'week') {
  626.             $thisPeriodEndDate $today->format('Y-m-d');
  627.             $thisWeekStartDate date("Y-m-d"strtotime("previous saturday"));
  628.             $thisPeriodStartDate date("Y-m-d"strtotime("previous saturday"));
  629.             $currDate = new \DateTime($thisPeriodStartDate);
  630.             $currDate->modify('-1 day');
  631.             $lastPeriodEndDate $currDate->format('Y-m-d');
  632.             $currDate->modify('-6 day');
  633.             $lastPeriodStartDate $currDate->format('Y-m-d');
  634.         } else if ($periodType == 'quarter') {
  635.             $thisPeriodEndDate $today->format('Y-m-d');
  636.             $thisWeekStartDate date("Y-m-d"strtotime("previous saturday"));
  637.             $thisPeriodStartDate date("Y-m-d"strtotime("previous saturday"));
  638.             $currDate = new \DateTime($thisPeriodStartDate);
  639.             $currDate->modify('-1 day');
  640.             $lastPeriodEndDate $currDate->format('Y-m-d');
  641.             $currDate->modify('-6 day');
  642.             $lastPeriodStartDate $currDate->format('Y-m-d');
  643.         } else if ($periodType == 'year') {
  644.             $thisPeriodEndDate $today->format('Y-m-d');
  645. //            $thisWeekStartDate = date("Y-m-d", strtotime("previous saturday"));
  646.             $thisPeriodStartDate = ($today->format('Y')) . '-01-01';
  647.             $currDate = new \DateTime($thisPeriodStartDate);
  648.             $currDate->modify('-1 day');
  649.             $lastPeriodEndDate $currDate->format('Y-m-d');
  650.             $lastPeriodStartDate = ($currDate->format('Y')) . '-01-01';;
  651.         }
  652.         $companyListData = [];
  653.         foreach ($appIdList as $appId) {
  654.             //queryonly if mor ethan one app id
  655.             $skip 0;
  656.             if ($appId == $userAppId) {
  657.                 $connector $this->container->get('application_connector');
  658.                 $connector->resetConnection(
  659.                     'default',
  660.                     $session->get('gocDbName'),
  661.                     $session->get('gocDbUser'),
  662.                     $session->get('gocDbPass'),
  663.                     $session->get('gocDbHost'),
  664.                     $reset true
  665.                 );
  666.                 $em $this->getDoctrine()->getManager();
  667.             } else {
  668.                 $dataToConnect System::changeDoctrineManagerByAppId($this->getDoctrine()->getManager('company_group'), $gocEnabled$appId);
  669.                 $dataToConnectList[] = $dataToConnect;
  670.                 if (!empty($dataToConnect)) {
  671.                     $connector $this->container->get('application_connector');
  672.                     $connector->resetConnection(
  673.                         'default',
  674.                         $dataToConnect['dbName'],
  675.                         $dataToConnect['dbUser'],
  676.                         $dataToConnect['dbPass'],
  677.                         $dataToConnect['dbHost'],
  678.                         $reset true
  679.                     );
  680.                     $em $this->getDoctrine()->getManager();
  681.                 } else {
  682.                     $skip 1;
  683.                 }
  684.             }
  685.             if ($skip == 1)
  686.                 continue;
  687. //                $companyListData[] = Company::getCompanyListWithImage($em);
  688. //                $get_sql = "SELECT * FROM company ";
  689. //                $stmt = $em->getConnection()->prepare($get_sql);
  690. //                $stmt->execute();
  691. //                $entries = $stmt->fetchAll();
  692. //                $companyListData[] = $entries;
  693. //                foreach ($companyIdListByAppId as $app_company_index)
  694.             if (isset ($companyIdListByAppId[$appId])) {
  695.                 foreach ($companyIdListByAppId[$appId] as $app_company_index) {
  696.                     //exp vs rev
  697.                     if (in_array('expense_vs_revenue'$reportsToGet)) {
  698.                         $acHeadList = [];
  699.                         $companyId explode('_'$app_company_index)[1];
  700.                         $acHeadDataById = [];
  701.                         $thisBalanceDataByAcHead = [];
  702.                         $lastBalanceDataByAcHead = [];
  703.                         $mon_names = ["""January""February""March""April""May""June""July""August""September""October""November""December"];
  704.                         $limit 12;
  705.                         $get_kids_sql "SELECT expense, revenue, `date` summ_date
  706.                           FROM monthly_summary
  707.                             where monthly_summary.company_id=$companyId
  708.                             AND ( monthly_summary.branch_id=0 or monthly_summary.branch_id is null) ";
  709. //                               GROUP BY monthly_summary.`date`
  710.                         $get_kids_sql .= " ORDER BY monthly_summary.`date` DESC  limit " $limit;
  711.                         $stmt $em->getConnection()->prepare($get_kids_sql);
  712.                         $stmt->execute();
  713.                         $pl $stmt->fetchAll();
  714.                         $curr_date = new \DateTime();
  715.                         $curr_mon = ($curr_date->format('m'));
  716.                         $curr_year = ($curr_date->format('Y'));
  717.                         $object_list = [];
  718.                         $debug_list = [];
  719.                         $list = [];
  720.                         $timeStampList = [];
  721. //        $first
  722.                         foreach ($pl as $key => $entry) {
  723.                             $qryDate = new \DateTime($entry['summ_date']);
  724.                             $qrMon $qryDate->format('m');;
  725.                             $qrYr $qryDate->format('Y');;
  726.                             $object_list[$qrYr '_' $qrMon] = $entry;
  727.                         }
  728.                         for ($k 0$k 11$k++) {
  729.                             $debug_list[$k] = $curr_year '_' $curr_mon;
  730.                             $currTimeStamp strtotime($curr_year "-" $curr_mon '-1');
  731.                             $currTimeStampMili $currTimeStamp 1000;
  732.                             $cashAddition 0;
  733.                             $bankAddition 0;
  734.                             if (isset($object_list[$curr_year '_' $curr_mon])) {
  735.                                 $entry $object_list[$curr_year '_' $curr_mon];
  736.                                 $list['monthList'][] = $mon_names[$curr_mon];
  737.                                 $list['revenue'][] = round($entry['revenue']);
  738.                                 $list['tsCommaRevenue'][] = [$currTimeStampMiliround($entry['revenue'])];
  739.                                 $list['expense'][] = round($entry['expense']);
  740.                                 $list['tsCommaExpense'][] = [$currTimeStampMiliround($entry['expense'])];
  741.                             } else {
  742.                                 $list['monthList'][] = $mon_names[($curr_mon)];
  743.                                 $list['revenue'][] = 0;
  744.                                 $list['expense'][] = 0;
  745.                                 $list['tsCommaRevenue'][] = [$currTimeStampMili0];
  746.                                 $list['tsCommaExpense'][] = [$currTimeStampMili0];
  747.                             }
  748.                             $curr_mon--;
  749.                             if ($curr_mon <= 0) {
  750.                                 $curr_mon 12;
  751.                                 $curr_year--;
  752.                             }
  753.                             //new end
  754.                         }
  755.                         $data['expense_vs_revenue'][$app_company_index] = $list;
  756.                     }
  757.                     //cash and bank position
  758.                     if (in_array('cash_and_bank_position'$reportsToGet)) {
  759.                         $acHeadList = [];
  760.                         $companyId explode('_'$app_company_index)[1];
  761.                         $acHeadDataById = [];
  762.                         $thisBalanceDataByAcHead = [];
  763.                         $lastBalanceDataByAcHead = [];
  764.                         $bank_settings $em->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
  765.                             'name' => 'bank_parents',
  766. //                        'CompanyId'=>$companyId
  767.                         ));
  768.                         $bank_id_list = [];
  769.                         if ($bank_settings)
  770.                             $bank_id_list json_decode($bank_settings->getData());
  771.                         $bank_child_id_list = [];
  772.                         $likeQuery '';
  773.                         foreach ($bank_id_list as $p) {
  774.                             $likeQuery .= "OR path_tree like '%/" $p "%/' ";
  775.                         }
  776.                         $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 ") ";
  777.                         $stmt $em->getConnection()->prepare($get_sql);
  778.                         $stmt->execute();
  779.                         $entries $stmt->fetchAll();
  780.                         foreach ($entries as $entry) {
  781.                             $has_payments 1;
  782.                             $bank_child_id_list[] = $entry['accounts_head_id'];
  783.                             $acHeadList[] = $entry['accounts_head_id'];
  784.                             $acHeadDataById[$entry['accounts_head_id']]['name'] = $entry['name'];
  785.                         }
  786.                         $cash_settings $em->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
  787.                             'name' => 'cash_parents'
  788. //                        'CompanyId'=>$companyId
  789.                         ));
  790.                         $cash_id_list = [];
  791.                         if ($cash_settings)
  792.                             $cash_id_list json_decode($cash_settings->getData());
  793.                         $cash_child_id_list = [];
  794.                         $likeQuery '';
  795.                         foreach ($cash_id_list as $p) {
  796.                             $likeQuery .= "OR path_tree like '%/" $p "%/' ";
  797.                         }
  798.                         $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 ") ";
  799.                         $stmt $em->getConnection()->prepare($get_sql);
  800.                         $stmt->execute();
  801.                         $entries $stmt->fetchAll();
  802.                         foreach ($entries as $entry) {
  803.                             $has_payments 1;
  804.                             $cash_child_id_list[] = $entry['accounts_head_id'];
  805.                             $acHeadList[] = $entry['accounts_head_id'];
  806.                             $acHeadDataById[$entry['accounts_head_id']]['name'] = $entry['name'];
  807.                         }
  808.                         $thisBalance_data Accounts::GetBalanceOnDate($em$thisPeriodEndDate, []);
  809.                         $lastBalance_data Accounts::GetBalanceOnDate($em$lastPeriodEndDate, []);
  810.                         foreach ($acHeadList as $acHead) {
  811.                             $thisBalanceDataByAcHead[$acHead]['balance'] = $thisBalance_data[$acHead]['end_balance']['balance'];
  812.                             $lastBalanceDataByAcHead[$acHead]['balance'] = $lastBalance_data[$acHead]['end_balance']['balance'];
  813.                         }
  814.                         $thisReportData = array(
  815.                             'accountsHeadList' => $acHeadList,
  816.                             'acHeadDataById' => $acHeadDataById,
  817.                             'cash_child_id_list' => $cash_child_id_list,
  818.                             'bank_child_id_list' => $bank_child_id_list,
  819.                             'thisBalanceDataByAcHead' => $thisBalanceDataByAcHead,
  820.                             'lastBalanceDataByAcHead' => $lastBalanceDataByAcHead,
  821.                         );
  822.                         $data['cash_and_bank_position'][$app_company_index] = $thisReportData;
  823. //                    $companyListData[] = Company::getCompanyListWithImage($em);
  824.                     }
  825.                     //Expense Position
  826.                     if (in_array('expense_position'$reportsToGet)) {
  827.                         $acHeadList = [];
  828.                         $companyId explode('_'$app_company_index)[1];
  829.                         $acHeadDataById = [];
  830.                         $thisBalanceDataByAcHead = [];
  831.                         $lastBalanceDataByAcHead = [];
  832.                         $get_sql "SELECT * FROM acc_accounts_head WHERE acc_accounts_head.company_id=" $companyId "
  833.                         AND acc_accounts_head.head_level= 2 ";
  834.                         $stmt $em->getConnection()->prepare($get_sql);
  835.                         $stmt->execute();
  836.                         $entries $stmt->fetchAll();
  837.                         foreach ($entries as $entry) {
  838.                             $has_payments 1;
  839.                             $cash_child_id_list[] = $entry['accounts_head_id'];
  840.                             $acHeadList[] = $entry['accounts_head_id'];
  841.                             $acHeadDataById[$entry['accounts_head_id']]['name'] = $entry['name'];
  842.                         }
  843.                         $thisBalance_data Accounts:: GetPeriodicDataByType($em$type 'exp'$level_to_group_by 1$parent_id_list = [], $expand_level 1$thisPeriodStartDate$thisPeriodEndDate'_during_', [], [], [], false);
  844.                         $lastBalance_data Accounts:: GetPeriodicDataByType($em$type 'exp'$level_to_group_by 1$parent_id_list = [], $expand_level 1$lastPeriodStartDate$lastPeriodEndDate'_during_', [], [], [], false);
  845.                         $skipHeadIds = [];
  846.                         foreach ($thisBalance_data as $parentHead => $balanceData) {
  847.                             foreach ($balanceData['data'] as $acHead => $headData) {
  848.                                 if (!in_array($acHead$acHeadList))
  849.                                     continue;
  850.                                 $thisBalanceDataByAcHead[$acHead]['balance'] = $headData['head_balance'];
  851.                                 if (isset($lastBalance_data[$parentHead])) {
  852.                                     if (isset($lastBalance_data[$parentHead]['data'][$acHead]))
  853.                                         $lastBalanceDataByAcHead[$acHead]['balance'] = $lastBalance_data[$parentHead]['data'][$acHead]['head_balance'];
  854.                                     else
  855.                                         $lastBalanceDataByAcHead[$acHead]['balance'] = 0;
  856.                                 } else
  857.                                     $lastBalanceDataByAcHead[$acHead]['balance'] = 0;
  858.                                 $skipHeadIds[] = $acHead;
  859.                             }
  860.                         }
  861.                         foreach ($lastBalance_data as $parentHead => $balanceData) {
  862.                             foreach ($balanceData['data'] as $acHead => $headData) {
  863.                                 if (in_array($acHead$skipHeadIds))
  864.                                     continue;
  865.                                 if (!in_array($acHead$acHeadList))
  866.                                     continue;
  867.                                 $lastBalanceDataByAcHead[$acHead]['balance'] = $headData['head_balance'];
  868.                                 if (isset($thisBalance_data[$parentHead])) {
  869.                                     if (isset($thisBalance_data[$parentHead]['data'][$acHead]))
  870.                                         $thisBalanceDataByAcHead[$acHead]['balance'] = $thisBalance_data[$parentHead]['data'][$acHead]['head_balance'];
  871.                                     else
  872.                                         $thisBalanceDataByAcHead[$acHead]['balance'] = 0;
  873.                                 } else
  874.                                     $thisBalanceDataByAcHead[$acHead]['balance'] = 0;
  875.                                 $skipHeadIds[] = $acHead;
  876.                             }
  877.                         }
  878.                         $thisReportData = array(
  879.                             'accountsHeadList' => $acHeadList,
  880. //                            'thisBalance_data' => $thisBalance_data,
  881.                             'confirmedHeadList' => $skipHeadIds,
  882.                             'acHeadDataById' => $acHeadDataById,
  883.                             'thisBalanceDataByAcHead' => $thisBalanceDataByAcHead,
  884.                             'lastBalanceDataByAcHead' => $lastBalanceDataByAcHead,
  885.                         );
  886.                         $data['expense_position'][$app_company_index] = $thisReportData;
  887. //                    $companyListData[] = Company::getCompanyListWithImage($em);
  888.                     }
  889.                     //Payable Position
  890.                     if (in_array('payable_position'$reportsToGet)) {
  891.                         $acHeadList = [];
  892.                         $companyId explode('_'$app_company_index)[1];
  893.                         $acHeadDataById = [];
  894.                         $thisBalanceDataByAcHead = [];
  895.                         $lastBalanceDataByAcHead = [];
  896.                         $filter_settings $em->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
  897.                             'name' => 'payable_parents',
  898. //                        'CompanyId'=>$companyId
  899.                         ));
  900.                         $filter_head_parents_id_list = [];
  901.                         if ($filter_settings)
  902.                             $filter_head_parents_id_list json_decode($filter_settings->getData());
  903.                         $likeQuery '';
  904.                         foreach ($filter_head_parents_id_list as $p) {
  905.                             $likeQuery .= "OR path_tree like '%/" $p "%/' ";
  906.                         }
  907.                         $get_sql "SELECT * FROM acc_accounts_head WHERE acc_accounts_head.company_id=" $companyId "
  908.                          and (1=0 " $likeQuery ") ";
  909.                         $stmt $em->getConnection()->prepare($get_sql);
  910.                         $stmt->execute();
  911.                         $entries $stmt->fetchAll();
  912.                         foreach ($entries as $entry) {
  913.                             $has_payments 1;
  914.                             $acHeadList[] = $entry['accounts_head_id'];
  915.                             $acHeadDataById[$entry['accounts_head_id']]['name'] = $entry['name'];
  916.                         }
  917. //                        $get_sql = "SELECT * FROM acc_accounts_head WHERE acc_accounts_head.company_id=" . $companyId . "
  918. //                        AND acc_accounts_head.head_level= 2 and acc_accounts_head.type='lib'";
  919. //
  920. //                        $stmt = $em->getConnection()->prepare($get_sql);
  921. //                        $stmt->execute();
  922. //                        $entries = $stmt->fetchAll();
  923. //
  924. //                        foreach ($entries as $entry) {
  925. //                            $has_payments = 1;
  926. //                            $cash_child_id_list[] = $entry['accounts_head_id'];
  927. //                            $acHeadList[] = $entry['accounts_head_id'];
  928. //                            $acHeadDataById[$entry['accounts_head_id']]['name'] = $entry['name'];
  929. //                        }
  930.                         $thisBalance_data Accounts:: GetPeriodicDataByType($em$type 'lib'$level_to_group_by 2$parent_id_list = [], $expand_level 1$thisPeriodStartDate$thisPeriodEndDate'_during_', [], [], [], false);
  931.                         $lastBalance_data Accounts:: GetPeriodicDataByType($em$type 'lib'$level_to_group_by 2$parent_id_list = [], $expand_level 1$lastPeriodStartDate$lastPeriodEndDate'_during_', [], [], [], false);
  932.                         $skipHeadIds = [];
  933.                         foreach ($thisBalance_data as $parentHead => $balanceData) {
  934.                             foreach ($balanceData['data'] as $acHead => $headData) {
  935.                                 if (!(in_array($acHead$acHeadList)))
  936.                                     continue;
  937.                                 if ($headData['head_level'] > 4)
  938.                                     continue;
  939. //                                $thisBalanceDataByAcHead[$acHead]['balance'] = $headData['head_balance'];
  940.                                 $thisBalanceDataByAcHead[$acHead]['balance'] = $headData['end_balance']['balance'];
  941.                                 if (isset($lastBalance_data[$parentHead])) {
  942.                                     if (isset($lastBalance_data[$parentHead]['data'][$acHead]))
  943. //                                        $lastBalanceDataByAcHead[$acHead]['balance'] = $lastBalance_data[$parentHead]['data'][$acHead]['head_balance'];
  944.                                         $lastBalanceDataByAcHead[$acHead]['balance'] = $lastBalance_data[$parentHead]['data'][$acHead]['end_balance']['balance'];
  945.                                     else
  946.                                         $lastBalanceDataByAcHead[$acHead]['balance'] = 0;
  947.                                 } else
  948.                                     $lastBalanceDataByAcHead[$acHead]['balance'] = 0;
  949.                                 $skipHeadIds[] = $acHead;
  950.                             }
  951.                         }
  952.                         foreach ($lastBalance_data as $parentHead => $balanceData) {
  953.                             foreach ($balanceData['data'] as $acHead => $headData) {
  954.                                 if (in_array($acHead$skipHeadIds))
  955.                                     continue;
  956.                                 if (!in_array($acHead$acHeadList))
  957.                                     continue;
  958.                                 if ($headData['head_level'] > 4)
  959.                                     continue;
  960.                                 $lastBalanceDataByAcHead[$acHead]['balance'] = $headData['end_balance']['balance'];
  961.                                 if (isset($thisBalance_data[$parentHead])) {
  962.                                     if (isset($thisBalance_data[$parentHead]['data'][$acHead]))
  963.                                         $thisBalanceDataByAcHead[$acHead]['balance'] = $thisBalance_data[$parentHead]['data'][$acHead]['end_balance']['balance'];
  964.                                     else
  965.                                         $thisBalanceDataByAcHead[$acHead]['balance'] = 0;
  966.                                 } else
  967.                                     $thisBalanceDataByAcHead[$acHead]['balance'] = 0;
  968.                                 $skipHeadIds[] = $acHead;
  969.                             }
  970.                         }
  971.                         $thisReportData = array(
  972.                             'accountsHeadList' => $acHeadList,
  973. //                            'thisBalance_data' => $thisBalance_data,
  974.                             'confirmedHeadList' => $skipHeadIds,
  975.                             'acHeadDataById' => $acHeadDataById,
  976.                             'thisBalanceDataByAcHead' => $thisBalanceDataByAcHead,
  977.                             'lastBalanceDataByAcHead' => $lastBalanceDataByAcHead,
  978.                         );
  979.                         $data['payable_position'][$app_company_index] = $thisReportData;
  980. //                    $companyListData[] = Company::getCompanyListWithImage($em);
  981.                     }
  982.                     //Receivable Position
  983.                     if (in_array('receivable_position'$reportsToGet)) {
  984.                         $acHeadList = [];
  985.                         $companyId explode('_'$app_company_index)[1];
  986.                         $acHeadDataById = [];
  987.                         $thisBalanceDataByAcHead = [];
  988.                         $lastBalanceDataByAcHead = [];
  989. //                        $filter_settings = $em->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
  990. //                            'name' => 'receivable_parents',
  991. ////                        'CompanyId'=>$companyId
  992. //                        ));
  993. //                        $filter_head_parents_id_list = [];
  994. //                        if ($filter_settings)
  995. //                            $filter_head_parents_id_list = json_decode($filter_settings->getData());
  996. //                        $likeQuery = '';
  997. //                        foreach ($filter_head_parents_id_list as $p) {
  998. //                            $likeQuery .= "OR path_tree like '%/" . $p . "%/' ";
  999. //                        }
  1000. //                        $get_sql = "SELECT * FROM acc_accounts_head WHERE acc_accounts_head.company_id=" . $companyId . "
  1001. //                         and (1=0 " . $likeQuery . ") ";
  1002.                         $get_sql "SELECT acc_accounts_head.*  FROM acc_accounts_head
  1003.  WHERE acc_accounts_head.company_id=" $companyId "
  1004.                          and  ( acc_accounts_head.accounts_head_id in (select distinct accounts_head_id from acc_clients)
  1005.                           OR acc_accounts_head.accounts_head_id in (select distinct advance_head_id from acc_clients)
  1006.                          ) ";
  1007.                         $stmt $em->getConnection()->prepare($get_sql);
  1008.                         $stmt->execute();
  1009.                         $entries $stmt->fetchAll();
  1010.                         $account_head_ids_by_client_type = [];
  1011.                         foreach ($entries as $entry) {
  1012.                             $has_payments 1;
  1013.                             $acHeadList[] = $entry['accounts_head_id'];
  1014.                             $acHeadDataById[$entry['accounts_head_id']]['name'] = $entry['name'];
  1015.                         }
  1016.                         $get_sql "SELECT acc_clients.*  FROM acc_clients
  1017.  WHERE acc_clients.company_id=" $companyId;
  1018.                         $stmt $em->getConnection()->prepare($get_sql);
  1019.                         $stmt->execute();
  1020.                         $entries $stmt->fetchAll();
  1021.                         $clientTypeListArray Client::ClientTypeList($em, [$companyId], true);
  1022.                         $clientTypesOfHeads = [];
  1023.                         foreach ($entries as $entry) {
  1024.                             if (!isset($account_head_ids_by_client_type[$entry['type']]))
  1025.                                 $account_head_ids_by_client_type[$entry['type']] = [];
  1026.                             $account_head_ids_by_client_type[$entry['type']][] = $entry['accounts_head_id'];
  1027.                             $clientTypesOfHeads[$entry['accounts_head_id']] = $entry['type'];
  1028.                             if ($entry['accounts_head_id'] != $entry['advance_head_id']) {
  1029.                                 $account_head_ids_by_client_type[$entry['type']][] = $entry['advance_head_id'];
  1030.                                 $clientTypesOfHeads[$entry['advance_head_id']] = $entry['type'];
  1031.                             }
  1032.                         }
  1033. //                        $get_sql = "SELECT * FROM acc_accounts_head WHERE acc_accounts_head.company_id=" . $companyId . "
  1034. //                        AND acc_accounts_head.head_level= 2 and acc_accounts_head.type='lib'";
  1035. //
  1036. //                        $stmt = $em->getConnection()->prepare($get_sql);
  1037. //                        $stmt->execute();
  1038. //                        $entries = $stmt->fetchAll();
  1039. //
  1040. //                        foreach ($entries as $entry) {
  1041. //                            $has_payments = 1;
  1042. //                            $cash_child_id_list[] = $entry['accounts_head_id'];
  1043. //                            $acHeadList[] = $entry['accounts_head_id'];
  1044. //                            $acHeadDataById[$entry['accounts_head_id']]['name'] = $entry['name'];
  1045. //                        }
  1046.                         $thisBalance_data Accounts:: GetPeriodicDataByType($em$type 'ast'$level_to_group_by 2$parent_id_list = [], $expand_level 1$thisPeriodStartDate$thisPeriodEndDate'_during_', [], [], [], true);
  1047.                         $lastBalance_data Accounts:: GetPeriodicDataByType($em$type 'ast'$level_to_group_by 2$parent_id_list = [], $expand_level 1$lastPeriodStartDate$lastPeriodEndDate'_during_', [], [], [], true);
  1048.                         $skipHeadIds = [];
  1049.                         $thisBalanceDataByClientType = [];
  1050.                         $lastBalanceDataByClientType = [];
  1051.                         foreach ($clientTypeListArray as $ct) {
  1052.                             $thisBalanceDataByClientType[$ct['id']] = 0;
  1053.                             $lastBalanceDataByClientType[$ct['id']] = 0;
  1054.                         }
  1055.                         foreach ($thisBalance_data as $parentHead => $balanceData) {
  1056.                             foreach ($balanceData['data'] as $acHead => $headData) {
  1057.                                 if (!(in_array($acHead$acHeadList)))
  1058.                                     continue;
  1059. //                                if ($headData['head_level'] > 4)
  1060. //                                    continue;
  1061.                                 $thisBalanceDataByAcHead[$acHead]['balance'] = $headData['end_balance']['balance'];
  1062.                                 if (isset($lastBalance_data[$parentHead])) {
  1063.                                     if (isset($lastBalance_data[$parentHead]['data'][$acHead]))
  1064.                                         $lastBalanceDataByAcHead[$acHead]['balance'] = $lastBalance_data[$parentHead]['data'][$acHead]['end_balance']['balance'];
  1065.                                     else
  1066.                                         $lastBalanceDataByAcHead[$acHead]['balance'] = 0;
  1067.                                 } else
  1068.                                     $lastBalanceDataByAcHead[$acHead]['balance'] = 0;
  1069.                                 if (!isset($thisBalanceDataByClientType[$clientTypesOfHeads[$acHead]]))
  1070.                                     $thisBalanceDataByClientType[$clientTypesOfHeads[$acHead]] = $headData['end_balance']['balance'];
  1071.                                 else
  1072.                                     $thisBalanceDataByClientType[$clientTypesOfHeads[$acHead]] += $headData['end_balance']['balance'];
  1073.                                 if (!isset($lastBalanceDataByClientType[$clientTypesOfHeads[$acHead]]))
  1074.                                     $lastBalanceDataByClientType[$clientTypesOfHeads[$acHead]] = 0;
  1075.                                 else
  1076.                                     $lastBalanceDataByClientType[$clientTypesOfHeads[$acHead]] += $lastBalance_data[$parentHead]['data'][$acHead]['end_balance']['balance'];
  1077.                                 $skipHeadIds[] = $acHead;
  1078.                             }
  1079.                         }
  1080.                         foreach ($lastBalance_data as $parentHead => $balanceData) {
  1081.                             foreach ($balanceData['data'] as $acHead => $headData) {
  1082.                                 if (in_array($acHead$skipHeadIds))
  1083.                                     continue;
  1084.                                 if (!in_array($acHead$acHeadList))
  1085.                                     continue;
  1086. //                                if ($headData['head_level'] > 4)
  1087. //                                    continue;
  1088.                                 $lastBalanceDataByAcHead[$acHead]['balance'] = $headData['end_balance']['balance'];
  1089.                                 if (isset($thisBalance_data[$parentHead])) {
  1090.                                     if (isset($thisBalance_data[$parentHead]['data'][$acHead]))
  1091.                                         $thisBalanceDataByAcHead[$acHead]['balance'] = $thisBalance_data[$parentHead]['data'][$acHead]['end_balance']['balance'];
  1092.                                     else
  1093.                                         $thisBalanceDataByAcHead[$acHead]['balance'] = 0;
  1094.                                 } else
  1095.                                     $thisBalanceDataByAcHead[$acHead]['balance'] = 0;
  1096.                                 if (!isset($lastBalanceDataByClientType[$clientTypesOfHeads[$acHead]]))
  1097.                                     $lastBalanceDataByClientType[$clientTypesOfHeads[$acHead]] = $headData['end_balance']['balance'];
  1098.                                 else
  1099.                                     $lastBalanceDataByClientType[$clientTypesOfHeads[$acHead]] += $headData['end_balance']['balance'];
  1100.                                 if (!isset($thisBalanceDataByClientType[$clientTypesOfHeads[$acHead]]))
  1101.                                     $thisBalanceDataByClientType[$clientTypesOfHeads[$acHead]] = 0;
  1102.                                 $skipHeadIds[] = $acHead;
  1103.                             }
  1104.                         }
  1105.                         $thisReportData = array(
  1106. //                            'accountsHeadList' => $acHeadList,
  1107. //                            'thisBalance_data' => $thisBalance_data,
  1108. //                            'confirmedHeadList' => $skipHeadIds,
  1109. //                            'acHeadDataById' => $acHeadDataById,
  1110.                             'thisBalance_data' => $thisBalance_data,
  1111.                             'lastBalance_data' => $lastBalance_data,
  1112.                             'thisBalanceDataByAcHead' => $thisBalanceDataByAcHead,
  1113.                             'lastBalanceDataByAcHead' => $lastBalanceDataByAcHead,
  1114.                             'clientTypeListArray' => $clientTypeListArray,
  1115.                             'thisBalanceDataByClientType' => $thisBalanceDataByClientType,
  1116.                             'lastBalanceDataByClientType' => $lastBalanceDataByClientType,
  1117.                         );
  1118.                         $data['receivable_position'][$app_company_index] = $thisReportData;
  1119. //                    $companyListData[] = Company::getCompanyListWithImage($em);
  1120.                     }
  1121.                     //Sales Position
  1122.                     if (in_array('sales_position'$reportsToGet)) {
  1123.                         $acHeadList = [];
  1124.                         $companyId explode('_'$app_company_index)[1];
  1125.                         $acHeadDataById = [];
  1126.                         $thisBalanceDataByClientType = [];
  1127.                         $lastBalanceDataByClientType = [];
  1128.                         $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
  1129.   FROM sales_invoice
  1130.   join acc_clients on acc_clients.client_id=sales_invoice.client_id
  1131.   join client_type on acc_clients.type=client_type.client_type_id
  1132.    WHERE sales_invoice.company_id=" $companyId " AND sales_invoice.approved=1
  1133.                           AND sales_invoice_date between '" $thisPeriodStartDate " 00:00:00' and '" $thisPeriodEndDate " 23:59:59.999'
  1134.                           GROUP BY client_type.client_type_id
  1135.                           ";
  1136.                         $stmt $em->getConnection()->prepare($get_sql);
  1137.                         $stmt->execute();
  1138.                         $entries $stmt->fetchAll();
  1139.                         $clientTypes = [];
  1140.                         $clientTypeNames = [];
  1141.                         $get_sql_1 $get_sql;
  1142.                         foreach ($entries as $entry) {
  1143.                             $has_payments 1;
  1144.                             $thisBalanceDataByClientType[$entry['client_type_id']] = $entry;
  1145.                             $lastBalanceDataByClientType[$entry['client_type_id']]['sales_amount'] = 0//just for the lulz
  1146.                             if (!in_array($entry['client_type_id'], $clientTypes)) {
  1147.                                 $clientTypes[] = $entry['client_type_id'];
  1148.                                 $clientTypeNames[$entry['client_type_id']] = $entry['name'];
  1149.                             }
  1150.                         }
  1151.                         $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
  1152.   FROM sales_invoice
  1153.   join acc_clients on acc_clients.client_id=sales_invoice.client_id
  1154.   join client_type on acc_clients.type=client_type.client_type_id
  1155.    WHERE sales_invoice.company_id=" $companyId " AND sales_invoice.approved=1
  1156.                           AND sales_invoice_date between '" $lastPeriodStartDate " 00:00:00' and '" $lastPeriodEndDate " 23:59:59.999'
  1157.                           GROUP BY client_type.client_type_id
  1158.                           ";
  1159.                         $stmt $em->getConnection()->prepare($get_sql);
  1160.                         $stmt->execute();
  1161.                         $entries $stmt->fetchAll();
  1162.                         foreach ($entries as $entry) {
  1163.                             $has_payments 1;
  1164.                             $lastBalanceDataByClientType[$entry['client_type_id']] = $entry;
  1165.                             if (!isset($thisBalanceDataByClientType[$entry['client_type_id']]))
  1166.                                 $thisBalanceDataByClientType[$entry['client_type_id']]['sales_amount'] = 0//just for the lulz
  1167.                             if (!in_array($entry['client_type_id'], $clientTypes)) {
  1168.                                 $clientTypes[] = $entry['client_type_id'];
  1169.                                 $clientTypeNames[$entry['client_type_id']] = $entry['name'];
  1170.                             }
  1171.                         }
  1172.                         $skipHeadIds = [];
  1173.                         $thisReportData = array(
  1174.                             'clientTypes' => $clientTypes,
  1175. //                            'get_sql_1' => $get_sql_1,
  1176. //                            'get_sql' => $get_sql,
  1177.                             'clientTypeNames' => $clientTypeNames,
  1178.                             'thisBalanceDataByClientType' => $thisBalanceDataByClientType,
  1179.                             'lastBalanceDataByClientType' => $lastBalanceDataByClientType,
  1180.                         );
  1181.                         $data['sales_position'][$app_company_index] = $thisReportData;
  1182. //                    $companyListData[] = Company::getCompanyListWithImage($em);
  1183.                     }
  1184.                     //Collection Position
  1185.                     if (in_array('collection_position'$reportsToGet)) {
  1186.                         $acHeadList = [];
  1187.                         $companyId explode('_'$app_company_index)[1];
  1188.                         $acHeadDataById = [];
  1189.                         $thisBalanceDataByClientType = [];
  1190.                         $lastBalanceDataByClientType = [];
  1191.                         $get_sql "SELECT SUM(CASE WHEN position = 'cr' THEN amount ELSE 0 END) positive_amount,
  1192. 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
  1193.  FROM acc_transaction_details
  1194.    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
  1195.   join client_type on acc_clients.type=client_type.client_type_id
  1196.   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'
  1197.                               GROUP BY client_type.client_type_id";
  1198.                         $stmt $em->getConnection()->prepare($get_sql);
  1199.                         $stmt->execute();
  1200.                         $entries $stmt->fetchAll();
  1201.                         $clientTypes = [];
  1202.                         $clientTypeNames = [];
  1203.                         foreach ($entries as $entry) {
  1204.                             $has_payments 1;
  1205.                             $thisBalanceDataByClientType[$entry['client_type_id']] = $entry;
  1206.                             $lastBalanceDataByClientType[$entry['client_type_id']]['collection_amount'] = 0//just for the lulz
  1207.                             $thisBalanceDataByClientType[$entry['client_type_id']]['collection_amount'] = $entry['positive_amount'] - $entry['negative_amount'];
  1208.                             if (!in_array($entry['client_type_id'], $clientTypes)) {
  1209.                                 $clientTypes[] = $entry['client_type_id'];
  1210.                                 $clientTypeNames[$entry['client_type_id']] = $entry['name'];
  1211.                             }
  1212.                         }
  1213.                         $get_sql "SELECT SUM(CASE WHEN position = 'cr' THEN amount ELSE 0 END) positive_amount,
  1214. 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
  1215.  FROM acc_transaction_details
  1216.    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
  1217.   join client_type on acc_clients.type=client_type.client_type_id
  1218.   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'
  1219.                               GROUP BY client_type.client_type_id";
  1220.                         $stmt $em->getConnection()->prepare($get_sql);
  1221.                         $stmt->execute();
  1222.                         $entries $stmt->fetchAll();
  1223.                         foreach ($entries as $entry) {
  1224.                             $has_payments 1;
  1225.                             $lastBalanceDataByClientType[$entry['client_type_id']] = $entry;
  1226.                             $lastBalanceDataByClientType[$entry['client_type_id']]['collection_amount'] = $entry['positive_amount'] - $entry['negative_amount'];
  1227.                             if (!isset($thisBalanceDataByClientType[$entry['client_type_id']]))
  1228.                                 $thisBalanceDataByClientType[$entry['client_type_id']]['collection_amount'] = 0//just for the lulz
  1229.                             if (!in_array($entry['client_type_id'], $clientTypes)) {
  1230.                                 $clientTypes[] = $entry['client_type_id'];
  1231.                                 $clientTypeNames[$entry['client_type_id']] = $entry['name'];
  1232.                             }
  1233.                         }
  1234.                         $skipHeadIds = [];
  1235.                         $thisReportData = array(
  1236.                             'clientTypes' => $clientTypes,
  1237.                             'clientTypeNames' => $clientTypeNames,
  1238.                             'thisBalanceDataByClientType' => $thisBalanceDataByClientType,
  1239.                             'lastBalanceDataByClientType' => $lastBalanceDataByClientType,
  1240.                         );
  1241.                         $data['collection_position'][$app_company_index] = $thisReportData;
  1242. //                    $companyListData[] = Company::getCompanyListWithImage($em);
  1243.                     }
  1244.                     //Return Position
  1245.                     if (in_array('market_return_position'$reportsToGet)) {
  1246.                         $acHeadList = [];
  1247.                         $companyId explode('_'$app_company_index)[1];
  1248.                         $acHeadDataById = [];
  1249.                         $thisBalanceDataByClientType = [];
  1250.                         $lastBalanceDataByClientType = [];
  1251.                         $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
  1252.   FROM irr_item
  1253.   join item_received_replacement on item_received_replacement.irr_id=irr_item.irr_id
  1254.   join acc_clients on acc_clients.client_id=item_received_replacement.client_id
  1255.   join client_type on acc_clients.type=client_type.client_type_id
  1256.    WHERE item_received_replacement.company_id=" $companyId " AND item_received_replacement.approved=1
  1257.                           AND item_received_replacement.irr_date between '" $thisPeriodStartDate " 00:00:00' and '" $thisPeriodEndDate " 23:59:59.999'
  1258.                           GROUP BY client_type.client_type_id
  1259.                           ";
  1260.                         $stmt $em->getConnection()->prepare($get_sql);
  1261.                         $stmt->execute();
  1262.                         $entries $stmt->fetchAll();
  1263.                         $clientTypes = [];
  1264.                         $clientTypeNames = [];
  1265.                         $get_sql_1 $get_sql;
  1266.                         foreach ($entries as $entry) {
  1267.                             $has_payments 1;
  1268.                             $thisBalanceDataByClientType[$entry['client_type_id']] = $entry;
  1269.                             $lastBalanceDataByClientType[$entry['client_type_id']]['return_amount'] = 0//just for the lulz
  1270.                             if (!in_array($entry['client_type_id'], $clientTypes)) {
  1271.                                 $clientTypes[] = $entry['client_type_id'];
  1272.                                 $clientTypeNames[$entry['client_type_id']] = $entry['name'];
  1273.                             }
  1274.                         }
  1275.                         $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
  1276.   FROM irr_item
  1277.   join item_received_replacement on item_received_replacement.irr_id=irr_item.irr_id
  1278.   join acc_clients on acc_clients.client_id=item_received_replacement.client_id
  1279.   join client_type on acc_clients.type=client_type.client_type_id
  1280.    WHERE item_received_replacement.company_id=" $companyId " AND item_received_replacement.approved=1
  1281.                           AND item_received_replacement.irr_date between '" $lastPeriodStartDate " 00:00:00' and '" $lastPeriodEndDate " 23:59:59.999'
  1282.                           GROUP BY client_type.client_type_id
  1283.                           ";
  1284.                         $stmt $em->getConnection()->prepare($get_sql);
  1285.                         $stmt->execute();
  1286.                         $entries $stmt->fetchAll();
  1287.                         foreach ($entries as $entry) {
  1288.                             $has_payments 1;
  1289.                             $lastBalanceDataByClientType[$entry['client_type_id']] = $entry;
  1290.                             if (!isset($thisBalanceDataByClientType[$entry['client_type_id']]))
  1291.                                 $thisBalanceDataByClientType[$entry['client_type_id']]['return_amount'] = 0//just for the lulz
  1292.                             if (!in_array($entry['client_type_id'], $clientTypes)) {
  1293.                                 $clientTypes[] = $entry['client_type_id'];
  1294.                                 $clientTypeNames[$entry['client_type_id']] = $entry['name'];
  1295.                             }
  1296.                         }
  1297.                         $skipHeadIds = [];
  1298.                         $thisReportData = array(
  1299.                             'clientTypes' => $clientTypes,
  1300. //                            'get_sql_1' => $get_sql_1,
  1301. //                            'get_sql' => $get_sql,
  1302.                             'clientTypeNames' => $clientTypeNames,
  1303.                             'thisBalanceDataByClientType' => $thisBalanceDataByClientType,
  1304.                             'lastBalanceDataByClientType' => $lastBalanceDataByClientType,
  1305.                         );
  1306.                         $data['market_return_position'][$app_company_index] = $thisReportData;
  1307. //                    $companyListData[] = Company::getCompanyListWithImage($em);
  1308.                     }
  1309.                     //order and client count
  1310.                     if (in_array('order_and_client_count'$reportsToGet)) {
  1311.                         $acHeadList = [];
  1312.                         $companyId explode('_'$app_company_index)[1];
  1313.                         $acHeadDataById = [];
  1314.                         $thisBalanceDataByAcHead = [];
  1315.                         $lastBalanceDataByAcHead = [];
  1316.                         $today = new \DateTime();
  1317.                         $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' ";
  1318.                         $stmt $em->getConnection()->prepare($get_sql);
  1319.                         $stmt->execute();
  1320.                         $entries1 $stmt->fetchAll();
  1321.                         $get_sql "SELECT count(client_id) total_clients FROM acc_clients WHERE acc_clients.company_id=" $companyId;
  1322.                         $stmt $em->getConnection()->prepare($get_sql);
  1323.                         $stmt->execute();
  1324.                         $entries2 $stmt->fetchAll();
  1325.                         $currCompanyData Company::getCompanyData($em$session->get(UserConstants::USER_COMPANY_ID$companyId));
  1326.                         $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
  1327.                         join acc_transactions on acc_transactions.transaction_id=acc_transaction_details.transaction_id
  1328.                         WHERE acc_transaction_details.ledger_hit=1 AND acc_transactions.document_type=6
  1329.                       AND (
  1330.                       accounts_head_id in(select distinct accounts_head_id from acc_clients WHERE acc_clients.company_id=" $companyId ")
  1331.                       or  accounts_head_id in(select distinct advance_head_id from acc_clients WHERE acc_clients.company_id=" $companyId ") )
  1332.                       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' ";
  1333.                         $stmt $em->getConnection()->prepare($get_sql);
  1334.                         $stmt->execute();
  1335.                         $entries3 $stmt->fetchAll();
  1336. //
  1337. //                        $get_sql = "SELECT (select  c.balance last_balance from inv_closing_balance c
  1338. //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
  1339. //from inv_closing_balance a
  1340. //                        where a.warehouse_id in (select distinct id from warehouse
  1341. //                        WHERE  warehouse.company_id=" . $companyId . ") and  a.date between '" . $thisPeriodStartDate . " 00:00:00' and '" . $thisPeriodEndDate . " 23:59:59.999' ";
  1342.                         $get_sql "SELECT a.* , (select  c.balance last_balance from inv_closing_balance c
  1343. 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
  1344. from inv_closing_balance a
  1345. where a.warehouse_id in (select distinct id from warehouse
  1346.                       WHERE  warehouse.company_id=" $companyId ") ";
  1347.                         $stmt $em->getConnection()->prepare($get_sql);
  1348.                         $stmt->execute();
  1349.                         $entries4 $stmt->fetchAll();
  1350.                         $currCompanyData Company::getCompanyData($em$session->get(UserConstants::USER_COMPANY_ID$companyId));
  1351.                         $total_stock_amount 0;
  1352.                         foreach ($entries4 as $ent) {
  1353.                             $total_stock_amount += $ent['last_balance'];
  1354.                         }
  1355.                         $thisReportData = array(
  1356. //                            'total_stock_amount' => empty($entries3) ? 0 : $entries4[0]['total_stock_amount'],
  1357.                             'total_stock_amount' => $total_stock_amount,
  1358.                             'total_collection_amount' => empty($entries3) ? $entries3[0]['total_collection_amount'],
  1359.                             'total_so_count' => empty($entries1) ? $entries1[0]['total_so_count'],
  1360.                             'total_so_amount' => empty($entries1) ? $entries1[0]['total_so_amount'],
  1361.                             'total_invoice_amount' => empty($entries1) ? $entries1[0]['total_invoice_amount'],
  1362.                             'total_receivable' => $currCompanyData->getReceivable(),
  1363.                             'total_payable' => $currCompanyData->getPayable(),
  1364.                             'total_clients' => empty($entries2) ? $entries2[0]['total_clients'],
  1365.                         );
  1366.                         $data['order_and_client_count'][$app_company_index] = $thisReportData;
  1367. //                    $companyListData[] = Company::getCompanyListWithImage($em);
  1368.                     }
  1369.                     //Inventory Position
  1370.                     if (in_array('inventory_position'$reportsToGet)) {
  1371.                         $acHeadList = [];
  1372.                         $companyId explode('_'$app_company_index)[1];
  1373.                         $acHeadDataById = [];
  1374.                         $thisBalanceDataByActionTag = [];
  1375.                         $lastBalanceDataByActionTag = [];
  1376.                         $warehouseList Inventory::warehouse_action_list($em$companyId$method 'object');
  1377.                         $get_sql "SELECT a.* , (select  c.balance last_balance from inv_closing_balance c
  1378. 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
  1379. from inv_closing_balance a
  1380. where a.warehouse_id in (select distinct id from warehouse
  1381.                        WHERE  warehouse.company_id=" $companyId ") ";
  1382.                         $stmt $em->getConnection()->prepare($get_sql);
  1383.                         $stmt->execute();
  1384.                         $entries $stmt->fetchAll();
  1385.                         $confirmed_action_ids = [];
  1386.                         $confirmed_action_names = [];
  1387.                         $get_sql_1 $get_sql;
  1388.                         foreach ($entries as $entry) {
  1389.                             $has_payments 1;
  1390.                             if (isset($thisBalanceDataByActionTag[$entry['action_tag_id']]))
  1391.                                 $thisBalanceDataByActionTag[$entry['action_tag_id']]['inventory_amount'] += $entry['last_balance'];
  1392.                             else
  1393.                                 $thisBalanceDataByActionTag[$entry['action_tag_id']]['inventory_amount'] = $entry['last_balance'];
  1394.                             if (!isset($lastBalanceDataByActionTag[$entry['action_tag_id']]))
  1395.                                 $lastBalanceDataByActionTag[$entry['action_tag_id']]['inventory_amount'] = 0;
  1396.                             if (!in_array($entry['action_tag_id'], $confirmed_action_ids)) {
  1397.                                 $confirmed_action_ids[] = $entry['action_tag_id'];
  1398.                                 $confirmed_action_names[$entry['action_tag_id']] = $warehouseList[$entry['action_tag_id']]['name'];
  1399.                             }
  1400.                         }
  1401.                         $get_sql "SELECT a.* , (select  c.balance last_balance from inv_closing_balance c
  1402. 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
  1403. from inv_closing_balance a
  1404. where a.warehouse_id in (select distinct id from warehouse
  1405.                        WHERE  warehouse.company_id=" $companyId ") ";
  1406.                         $stmt $em->getConnection()->prepare($get_sql);
  1407.                         $stmt->execute();
  1408.                         $entries $stmt->fetchAll();
  1409.                         foreach ($entries as $entry) {
  1410.                             $has_payments 1;
  1411.                             if (isset($lastBalanceDataByActionTag[$entry['action_tag_id']]))
  1412.                                 $lastBalanceDataByActionTag[$entry['action_tag_id']]['inventory_amount'] += $entry['last_balance'];
  1413.                             else
  1414.                                 $lastBalanceDataByActionTag[$entry['action_tag_id']]['inventory_amount'] = $entry['last_balance'];
  1415.                             if (!isset($thisBalanceDataByActionTag[$entry['action_tag_id']]))
  1416.                                 $thisBalanceDataByActionTag[$entry['action_tag_id']]['inventory_amount'] = 0;
  1417.                             if (!in_array($entry['action_tag_id'], $confirmed_action_ids)) {
  1418.                                 $confirmed_action_ids[] = $entry['action_tag_id'];
  1419.                                 $confirmed_action_names[$entry['action_tag_id']] = $warehouseList[$entry['action_tag_id']]['name'];
  1420.                             }
  1421.                         }
  1422.                         $skipHeadIds = [];
  1423.                         $thisReportData = array(
  1424. //                            'clientTypes' => $clientTypes,
  1425. //                            'get_sql_1' => $get_sql_1,
  1426. //                            'get_sql' => $get_sql,
  1427.                             'confirmed_action_ids' => $confirmed_action_ids,
  1428.                             'confirmed_action_names' => $confirmed_action_names,
  1429.                             'thisBalanceDataByActionTag' => $thisBalanceDataByActionTag,
  1430.                             'lastBalanceDataByActionTag' => $lastBalanceDataByActionTag,
  1431.                         );
  1432.                         $data['inventory_position'][$app_company_index] = $thisReportData;
  1433. //                    $companyListData[] = Company::getCompanyListWithImage($em);
  1434.                     }
  1435.                     //Production Position
  1436.                     if (in_array('production_position'$reportsToGet)) {
  1437.                         $acHeadList = [];
  1438.                         $companyId explode('_'$app_company_index)[1];
  1439.                         $acHeadDataById = [];
  1440.                         $thisBalanceDataByIgId = [];
  1441.                         $lastBalanceDataByIgId = [];
  1442.                         $itemGroups = [];
  1443.                         $itemGroupNames = [];
  1444.                         $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
  1445.   FROM production_entry_item
  1446.   join production on production_entry_item.production_id=production.production_id
  1447.   join inv_products on production_entry_item.product_id=inv_products.id
  1448.   join inv_item_group on inv_item_group.id=inv_products.ig_id
  1449.    WHERE production.company_id=" $companyId " AND production.approved=1
  1450.                           AND production.production_date between '" $thisPeriodStartDate " 00:00:00' and '" $thisPeriodEndDate " 23:59:59.999'
  1451.                           GROUP BY inv_item_group.id
  1452.                           ";
  1453. //                        $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
  1454. //  FROM production_entry_item
  1455. //  join production on production_entry_item.production_id=production.production_id
  1456. //  join inv_products on production_entry_item.product_id=inv_products.id
  1457. //  join product_mrp on production_entry_item.product_id=product_mrp.product_id
  1458. //  join inv_item_group on inv_item_group.id=inv_products.ig_id
  1459. //   WHERE production.company_id=" . $companyId . " AND production.approved=1
  1460. //                          AND production.production_date between '" . $thisPeriodStartDate . " 00:00:00' and '" . $thisPeriodEndDate . " 23:59:59.999'
  1461. //                          GROUP BY inv_item_group.id
  1462. //                          ";
  1463.                         $stmt $em->getConnection()->prepare($get_sql);
  1464.                         $stmt->execute();
  1465.                         $entries $stmt->fetchAll();
  1466.                         $get_sql_1 $get_sql;
  1467.                         foreach ($entries as $entry) {
  1468.                             $has_payments 1;
  1469.                             $thisBalanceDataByIgId[$entry['item_group_id']] = $entry;
  1470.                             $lastBalanceDataByIgId[$entry['item_group_id']]['production_amount'] = 0//just for the lulz
  1471.                             if (!in_array($entry['item_group_id'], $clientTypes)) {
  1472.                                 $itemGroups[] = $entry['item_group_id'];
  1473.                                 $itemGroupNames[$entry['item_group_id']] = $entry['item_group_name'];
  1474.                             }
  1475.                         }
  1476.                         $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
  1477.   FROM production_entry_item
  1478.   join production on production_entry_item.production_id=production.production_id
  1479.   join inv_products on production_entry_item.product_id=inv_products.id
  1480.   join inv_item_group on inv_item_group.id=inv_products.ig_id
  1481.    WHERE production.company_id=" $companyId " AND production.approved=1
  1482.                           AND production.production_date between '" $lastPeriodStartDate " 00:00:00' and '" $lastPeriodEndDate " 23:59:59.999'
  1483.                           GROUP BY inv_item_group.id
  1484.                           ";
  1485.                         $stmt $em->getConnection()->prepare($get_sql);
  1486.                         $stmt->execute();
  1487.                         $entries $stmt->fetchAll();
  1488.                         foreach ($entries as $entry) {
  1489.                             $has_payments 1;
  1490.                             $lastBalanceDataByIgId[$entry['item_group_id']] = $entry;
  1491.                             if (!isset($thisBalanceDataByIgId[$entry['item_group_id']]))
  1492.                                 $thisBalanceDataByIgId[$entry['item_group_id']]['production_amount'] = 0//just for the lulz
  1493.                             if (!in_array($entry['item_group_id'], $clientTypes)) {
  1494.                                 $itemGroups[] = $entry['item_group_id'];
  1495.                                 $itemGroupNames[$entry['item_group_id']] = $entry['item_group_name'];
  1496.                             }
  1497.                         }
  1498.                         $skipHeadIds = [];
  1499.                         $thisReportData = array(
  1500.                             'itemGroups' => $itemGroups,
  1501. //                            'get_sql_1' => $get_sql_1,
  1502. //                            'get_sql' => $get_sql,
  1503.                             'itemGroupNames' => $itemGroupNames,
  1504.                             'thisBalanceDataByIgId' => $thisBalanceDataByIgId,
  1505.                             'lastBalanceDataByIgId' => $lastBalanceDataByIgId,
  1506.                         );
  1507.                         $data['production_position'][$app_company_index] = $thisReportData;
  1508. //                    $companyListData[] = Company::getCompanyListWithImage($em);
  1509.                     }
  1510.                     //Top Products
  1511.                     if (in_array('top_selling_item_position'$reportsToGet)) {
  1512.                         $acHeadList = [];
  1513.                         $companyId explode('_'$app_company_index)[1];
  1514.                         $acHeadDataById = [];
  1515.                         $thisBalanceDataByRelId = [];
  1516.                         $lastBalanceDataByRelId = [];
  1517.                         $clientIds = [];
  1518.                         $clientNames = [];
  1519.                         $productIds = [];
  1520.                         $productNames = [];
  1521.                         $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
  1522.   FROM sales_invoice_item
  1523.   join sales_invoice on sales_invoice_item.sales_invoice_id=sales_invoice.sales_invoice_id
  1524.   join inv_products on sales_invoice_item.product_id=inv_products.id
  1525.   join acc_clients on acc_clients.client_id=sales_invoice.client_id
  1526.    WHERE sales_invoice.company_id=" $companyId " AND sales_invoice.approved=1
  1527.                           AND sales_invoice_date between '" $thisPeriodStartDate " 00:00:00' and '" $thisPeriodEndDate " 23:59:59.999'
  1528.                           GROUP BY sales_invoice_item.product_id
  1529.                           ORDER BY sales_amount DESC
  1530.                           LIMIT 10
  1531.                           ";
  1532.                         $stmt $em->getConnection()->prepare($get_sql);
  1533.                         $stmt->execute();
  1534.                         $entries $stmt->fetchAll();
  1535.                         $get_sql_1 $get_sql;
  1536.                         for ($k 0$k 10$k++) {
  1537.                             $has_payments 1;
  1538.                             if (!isset($entries[$k]))
  1539.                                 $entries[$k] = array(
  1540.                                     'sales_amount' => '',
  1541.                                     'product_name' => '',
  1542.                                     'client_name' => '',
  1543.                                 );
  1544.                             $has_payments 1;
  1545.                             $thisBalanceDataByRelId[$k] = $entries[$k];
  1546.                         }
  1547.                         $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
  1548.   FROM sales_invoice_item
  1549.   join sales_invoice on sales_invoice_item.sales_invoice_id=sales_invoice.sales_invoice_id
  1550.   join inv_products on sales_invoice_item.product_id=inv_products.id
  1551.   join acc_clients on acc_clients.client_id=sales_invoice.client_id
  1552.    WHERE sales_invoice.company_id=" $companyId " AND sales_invoice.approved=1
  1553.                           AND sales_invoice_date between '" $lastPeriodStartDate " 00:00:00' and '" $lastPeriodEndDate " 23:59:59.999'
  1554.                           GROUP BY sales_invoice_item.product_id
  1555.                           ORDER BY sales_amount DESC
  1556.                           LIMIT 10
  1557.                           ";
  1558.                         $stmt $em->getConnection()->prepare($get_sql);
  1559.                         $stmt->execute();
  1560.                         $entries $stmt->fetchAll();
  1561.                         for ($k 0$k 10$k++) {
  1562.                             $has_payments 1;
  1563.                             if (!isset($entries[$k]))
  1564.                                 $entries[$k] = array(
  1565.                                     'sales_amount' => '',
  1566.                                     'product_name' => '',
  1567.                                     'client_name' => '',
  1568.                                 );
  1569.                             $lastBalanceDataByRelId[$k] = $entries[$k];
  1570.                         }
  1571.                         $skipHeadIds = [];
  1572.                         $thisReportData = array(
  1573. //                            'clientTypes' => $clientTypes,
  1574. ////                            'get_sql_1' => $get_sql_1,
  1575. ////                            'get_sql' => $get_sql,
  1576. //                            'clientTypeNames' => $clientTypeNames,
  1577.                             'thisBalanceDataByRelId' => $thisBalanceDataByRelId,
  1578.                             'lastBalanceDataByRelId' => $lastBalanceDataByRelId,
  1579.                         );
  1580.                         $data['top_selling_item_position'][$app_company_index] = $thisReportData;
  1581. //                    $companyListData[] = Company::getCompanyListWithImage($em);
  1582.                     }
  1583.                     //Top Products
  1584.                     if (in_array('top_selling_client_position'$reportsToGet)) {
  1585.                         $acHeadList = [];
  1586.                         $companyId explode('_'$app_company_index)[1];
  1587.                         $acHeadDataById = [];
  1588.                         $thisBalanceDataByRelId = [];
  1589.                         $lastBalanceDataByRelId = [];
  1590.                         $clientIds = [];
  1591.                         $clientNames = [];
  1592.                         $productIds = [];
  1593.                         $productNames = [];
  1594.                         $get_sql "SELECT sum(sales_invoice.invoice_amount) sales_amount,  acc_clients.client_id, acc_clients.client_name client_name
  1595.   FROM sales_invoice
  1596.   join acc_clients on acc_clients.client_id=sales_invoice.client_id
  1597.    WHERE sales_invoice.company_id=" $companyId " AND sales_invoice.approved=1
  1598.                           AND sales_invoice_date between '" $thisPeriodStartDate " 00:00:00' and '" $thisPeriodEndDate " 23:59:59.999'
  1599.                           GROUP BY sales_invoice.client_id
  1600.                           ORDER BY sales_amount DESC
  1601.                           LIMIT 10
  1602.                           ";
  1603.                         $stmt $em->getConnection()->prepare($get_sql);
  1604.                         $stmt->execute();
  1605.                         $entries $stmt->fetchAll();
  1606.                         $get_sql_1 $get_sql;
  1607.                         for ($k 0$k 10$k++) {
  1608.                             $has_payments 1;
  1609.                             if (!isset($entries[$k]))
  1610.                                 $entries[$k] = array(
  1611.                                     'sales_amount' => '',
  1612.                                     'product_name' => '',
  1613.                                     'client_name' => '',
  1614.                                 );
  1615.                             $has_payments 1;
  1616.                             $thisBalanceDataByRelId[$k] = $entries[$k];
  1617.                         }
  1618.                         $get_sql "SELECT sum(sales_invoice.invoice_amount) sales_amount,  acc_clients.client_id, acc_clients.client_name client_name
  1619.   FROM sales_invoice
  1620.   join acc_clients on acc_clients.client_id=sales_invoice.client_id
  1621.    WHERE sales_invoice.company_id=" $companyId " AND sales_invoice.approved=1
  1622.                           AND sales_invoice_date between '" $lastPeriodStartDate " 00:00:00' and '" $lastPeriodEndDate " 23:59:59.999'
  1623.                           GROUP BY sales_invoice.client_id
  1624.                           ORDER BY sales_amount DESC
  1625.                           LIMIT 10
  1626.                           ";
  1627.                         $stmt $em->getConnection()->prepare($get_sql);
  1628.                         $stmt->execute();
  1629.                         $entries $stmt->fetchAll();
  1630.                         for ($k 0$k 10$k++) {
  1631.                             $has_payments 1;
  1632.                             if (!isset($entries[$k]))
  1633.                                 $entries[$k] = array(
  1634.                                     'sales_amount' => '',
  1635.                                     'product_name' => '',
  1636.                                     'client_name' => '',
  1637.                                 );
  1638.                             $lastBalanceDataByRelId[$k] = $entries[$k];
  1639.                         }
  1640.                         $skipHeadIds = [];
  1641.                         $thisReportData = array(
  1642. //                            'clientTypes' => $clientTypes,
  1643. ////                            'get_sql_1' => $get_sql_1,
  1644. ////                            'get_sql' => $get_sql,
  1645. //                            'clientTypeNames' => $clientTypeNames,
  1646.                             'thisBalanceDataByRelId' => $thisBalanceDataByRelId,
  1647.                             'lastBalanceDataByRelId' => $lastBalanceDataByRelId,
  1648.                         );
  1649.                         $data['top_selling_client_position'][$app_company_index] = $thisReportData;
  1650. //                    $companyListData[] = Company::getCompanyListWithImage($em);
  1651.                     }
  1652.                 }
  1653.             }
  1654.         }
  1655.         return new JsonResponse(
  1656.             array(
  1657.                 'success' => true,
  1658.                 'data' => $data,
  1659.                 'companyListData' => $companyListData,
  1660.                 'dataToConnectList' => $dataToConnectList,
  1661.                 'periodType' => $periodType,
  1662.                 'queriedReportsToGet' => $request->request->get('reportsToGet'),
  1663.                 'reportsToGet' => $reportsToGet,
  1664.                 'thisPeriodStartDate' => $thisPeriodStartDate,
  1665.                 'thisPeriodEndDate' => $thisPeriodEndDate,
  1666.                 'lastPeriodStartDate' => $lastPeriodStartDate,
  1667.                 'lastPeriodEndDate' => $lastPeriodEndDate,
  1668.                 'companyIdListByAppId' => $companyIdListByAppId,
  1669.                 'companyNameListByAppId' => $companyNameListByAppId,
  1670.                 'companyImageListByAppId' => $companyImageListByAppId,
  1671.                 'appIdList' => $appIdList,
  1672.             )
  1673.         );
  1674.     }
  1675.     public function indexAction(Request $request$cgHash '')
  1676.     {
  1677.         $session $request->getSession();
  1678.         $systemType $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
  1679.         if ($systemType == '_ERP_') {
  1680.             //do nothing its default to dashboard index
  1681.         } else if ($systemType == '_BUDDYBEE_') {
  1682.             if ($cgHash != '')
  1683.                 $session->set('codeHash'$cgHash);
  1684.         }
  1685.         // Generic::debugMessage($session);
  1686.         $ROUTE_LIST json_decode($session->get(UserConstants::USER_ROUTE_LIST), true);
  1687.         if ($ROUTE_LIST == null)
  1688.             $ROUTE_LIST = [];
  1689.         $CurrentRoute $request->attributes->get('_route');
  1690.         if ($session->get(UserConstants::USER_ROUTE_LIST) == || in_array('management_dashboard'$ROUTE_LIST)) {
  1691.             // User is not authorized. send him to dashboard
  1692. //                    $controller->addFlash(
  1693. //                        'error',
  1694. //                        'Sorry Couldnot insert Data.'
  1695. //                    );
  1696. //                    return $this->render('ApplicationBundle:pages/dashboard:advanced_management_dashboard.html.twig',
  1697.             if ($session->has('isMobile'))
  1698.                 if ($session->get('isMobile') == true) {
  1699.                     return $this->render('ApplicationBundle:pages/dashboard:index_finance_mobile.html.twig',
  1700.                         array(
  1701.                             'page_title' => 'Finance Dashboard',
  1702.                             'dashboardDataForUser' => []
  1703.                         )
  1704.                     );
  1705.                 }
  1706.             return $this->render('ApplicationBundle:pages/dashboard:advanced_management_dashboard.html.twig',
  1707.                 array(
  1708.                     'page_title' => 'Dashboard'
  1709.                 )
  1710.             );
  1711.         }
  1712.         if ($session->has('isMobile'))
  1713.             if ($session->get('isMobile') == true) {
  1714.                 if ($systemType == '_CENTRAL_') {
  1715.                     $defaultRoute 'central_landing';
  1716.                     return $this->redirectToRoute($defaultRoute);
  1717.                 } else
  1718.                 return $this->render('ApplicationBundle:pages/dashboard:index_finance_mobile.html.twig',
  1719.                     array(
  1720.                         'page_title' => 'Finance Dashboard',
  1721.                         'dashboardDataForUser' => []
  1722.                     )
  1723.                 );
  1724.             } else {
  1725.                 //check if user has a default route if yes redirect to it
  1726.                 if ($session->get(UserConstants::USER_TYPE) == UserConstants::USER_TYPE_SUPPLIER)
  1727.                     $defaultRoute 'supplier_dashboard';
  1728.                 else if ($session->get(UserConstants::USER_TYPE) == UserConstants::USER_TYPE_CLIENT)
  1729.                     $defaultRoute 'client_dashboard';
  1730.                 else if ($session->get(UserConstants::USER_TYPE) == UserConstants::USER_TYPE_APPLICANT) {
  1731.                     if ($systemType == '_CENTRAL_') {
  1732.                         $defaultRoute 'central_landing';
  1733.                     } else
  1734.                         $defaultRoute 'applicant_dashboard';
  1735.                 } else
  1736.                     $defaultRoute $session->get(UserConstants::USER_DEFAULT_ROUTE);
  1737. //            if(in_array($defaultRoute, $ROUTE_LIST))
  1738.                 if ($defaultRoute != '' && $defaultRoute != null)
  1739.                     return $this->redirectToRoute($defaultRoute);
  1740.                 else
  1741.                     return $this->render('ApplicationBundle:pages/dashboard:index.html.twig',
  1742.                         array(
  1743.                             'page_title' => 'Dashboard'
  1744.                         )
  1745.                     );
  1746.             }
  1747.     }
  1748.     public function indexSupplierAction(Request $request)
  1749.     {
  1750.         $session $request->getSession();
  1751.         $supplierId 3;
  1752.         if ($request->query->has('supplierId'))//for debug now
  1753.         {
  1754.             $session->set('supplierId'$request->query->get('supplierId'));
  1755.         }
  1756.         $supplierId $session->get('supplierId');  //////////////////////LATER
  1757.         $em $this->getDoctrine()->getManager();
  1758.         $companyId $this->getLoggedUserCompanyId($request);
  1759.         $userId $request->getSession()->get(UserConstants::USER_ID);
  1760.         $SD Supplier::GetSupplierProfileDetails($em$supplierId'SI');
  1761.         $dashboardDataForUser = [];
  1762.         return $this->render('ApplicationBundle:pages/dashboard:index_supplier.html.twig',
  1763.             array(
  1764.                 'page_title' => 'Supplier Dashboard',
  1765.                 'dashboardDataForUser' => $dashboardDataForUser,
  1766.                 'data' => $SD,
  1767.                 'igList' => Inventory::ItemGroupList($em$companyId)
  1768.             )
  1769.         );
  1770.     }
  1771.     public function indexClientAction(Request $request)
  1772.     {
  1773.         $session $request->getSession();
  1774.         $clientId 3;
  1775.         if ($request->query->has('clientId'))//for debug now
  1776.         {
  1777.             $session->set('clientId'$request->query->get('clientId'));
  1778.         }
  1779.         $clientId $session->get('clientId');  //////////////////////LATER
  1780.         $em $this->getDoctrine()->getManager();
  1781.         $companyId $this->getLoggedUserCompanyId($request);
  1782.         $userId $request->getSession()->get(UserConstants::USER_ID);
  1783.         $SD Client::GetClientProfileDetails($em$clientId'CI');
  1784.         $dashboardDataForUser = [];
  1785.         return $this->render('ApplicationBundle:pages/dashboard:index_client.html.twig',
  1786.             array(
  1787.                 'page_title' => 'Client Dashboard',
  1788.                 'dashboardDataForUser' => $dashboardDataForUser,
  1789.                 'data' => $SD,
  1790.                 'igList' => Inventory::ItemGroupList($em$companyId)
  1791.             )
  1792.         );
  1793.     }
  1794.     public function indexFinanceAction(Request $request)
  1795.     {
  1796.         $session $request->getSession();
  1797.         $dashboardDataForUser = [];
  1798.         $em $this->getDoctrine()->getManager();
  1799.         $companyId $this->getLoggedUserCompanyId($request);
  1800.         $userId $request->getSession()->get(UserConstants::USER_ID);
  1801.         $dbQuery $em->getRepository("ApplicationBundle:DashboardWidget")->findBy(
  1802.             array(
  1803.                 'CompanyId' => $companyId,
  1804.                 'userId' => $userId,
  1805.                 'status' => GeneralConstant::ACTIVE
  1806.             ),
  1807.             array(
  1808.                 'sequence' => 'ASC'
  1809.             )
  1810.         );
  1811.         if (empty($dbQuery))   ///now get the defaults
  1812.             $dbQuery $em->getRepository("ApplicationBundle:DashboardWidget")->findBy(
  1813.                 array(
  1814.                     'CompanyId' => $companyId,
  1815. //                    'userId'=>$userId,
  1816.                     'defaultBoxFlag' => 1,
  1817.                     'status' => GeneralConstant::ACTIVE
  1818.                 ),
  1819.                 array(
  1820.                     'sequence' => 'ASC'
  1821.                 )
  1822.             );
  1823.         foreach ($dbQuery as $entry) {
  1824.             $dashboardDataForUser[] = array(
  1825.                 'id' => $entry->getId(),
  1826.                 'widgetId' => $entry->getId(),
  1827.                 'widgetSequence' => $entry->getSequence(),
  1828.                 'widgetStatus' => $entry->getStatus(),
  1829.                 'widgetData' => json_decode($entry->getData(), true),
  1830.                 'defaultBoxFlag' => $entry->getDefaultBoxFlag(),
  1831.                 'widgetSizeTiny' => $entry->getSizeTiny(),
  1832.                 'widgetSizeSmall' => $entry->getSizeSmall(),
  1833.                 'widgetSizeMedium' => $entry->getSizeMedium(),
  1834.                 'widgetSizeLarge' => $entry->getSizeLarge(),
  1835.                 'refreshInterval' => $entry->getRefreshInterval(),
  1836.             );
  1837.         }
  1838.         if ($session->has('isMobile')) {
  1839.             if ($session->get('isMobile') == true) {
  1840.                 return $this->render('ApplicationBundle:pages/dashboard:index_finance_mobile.html.twig',
  1841.                     array(
  1842.                         'page_title' => 'Finance Dashboard',
  1843.                         'dashboardDataForUser' => $dashboardDataForUser
  1844.                     )
  1845.                 );
  1846.             } else {
  1847.             }
  1848.         }
  1849.         return $this->render('ApplicationBundle:pages/dashboard:index_finance.html.twig',
  1850.             array(
  1851.                 'page_title' => 'Finance Dashboard',
  1852.                 'dashboardDataForUser' => $dashboardDataForUser
  1853.             )
  1854.         );
  1855.     }
  1856.     public function indexSalesAction(Request $request)
  1857.     {
  1858.         $session $request->getSession();
  1859.         $dashboardDataForUser = [];
  1860.         $em $this->getDoctrine()->getManager();
  1861.         $companyId $this->getLoggedUserCompanyId($request);
  1862.         $userId $request->getSession()->get(UserConstants::USER_ID);
  1863.         $dbQuery $em->getRepository("ApplicationBundle:DashboardWidget")->findBy(
  1864.             array(
  1865.                 'CompanyId' => $companyId,
  1866.                 'userId' => $userId,
  1867.                 'status' => GeneralConstant::ACTIVE
  1868.             ),
  1869.             array(
  1870.                 'sequence' => 'ASC'
  1871.             )
  1872.         );
  1873.         if (empty($dbQuery))   ///now get the defaults
  1874.             $dbQuery $em->getRepository("ApplicationBundle:DashboardWidget")->findBy(
  1875.                 array(
  1876.                     'CompanyId' => $companyId,
  1877. //                    'userId'=>$userId,
  1878.                     'defaultBoxFlag' => 1,
  1879.                     'status' => GeneralConstant::ACTIVE
  1880.                 ),
  1881.                 array(
  1882.                     'sequence' => 'ASC'
  1883.                 )
  1884.             );
  1885.         foreach ($dbQuery as $entry) {
  1886.             $dashboardDataForUser[] = array(
  1887.                 'id' => $entry->getId(),
  1888.                 'widgetId' => $entry->getId(),
  1889.                 'widgetSequence' => $entry->getSequence(),
  1890.                 'widgetStatus' => $entry->getStatus(),
  1891.                 'widgetData' => json_decode($entry->getData(), true),
  1892.                 'defaultBoxFlag' => $entry->getDefaultBoxFlag(),
  1893.                 'widgetSizeTiny' => $entry->getSizeTiny(),
  1894.                 'widgetSizeSmall' => $entry->getSizeSmall(),
  1895.                 'widgetSizeMedium' => $entry->getSizeMedium(),
  1896.                 'widgetSizeLarge' => $entry->getSizeLarge(),
  1897.                 'refreshInterval' => $entry->getRefreshInterval(),
  1898.             );
  1899.         }
  1900.         if ($session->has('isMobile')) {
  1901.             if ($session->get('isMobile') == true) {
  1902.                 return $this->render('ApplicationBundle:pages/dashboard:index_finance_mobile.html.twig',
  1903.                     array(
  1904.                         'page_title' => 'Finance Dashboard',
  1905.                         'dashboardDataForUser' => $dashboardDataForUser
  1906.                     )
  1907.                 );
  1908.             } else {
  1909.             }
  1910.         }
  1911.         return $this->render('ApplicationBundle:pages/dashboard:index_sales.html.twig',
  1912.             array(
  1913.                 'page_title' => 'Sales Dashboard',
  1914.                 'dashboardDataForUser' => $dashboardDataForUser
  1915.             )
  1916.         );
  1917.     }
  1918.     public function indexPurchaseAction(Request $request)
  1919.     {
  1920.         $session $request->getSession();
  1921.         $dashboardDataForUser = [];
  1922.         $em $this->getDoctrine()->getManager();
  1923.         $companyId $this->getLoggedUserCompanyId($request);
  1924.         $userId $request->getSession()->get(UserConstants::USER_ID);
  1925.         $dbQuery $em->getRepository("ApplicationBundle:DashboardWidget")->findBy(
  1926.             array(
  1927.                 'CompanyId' => $companyId,
  1928.                 'userId' => $userId,
  1929.                 'status' => GeneralConstant::ACTIVE
  1930.             ),
  1931.             array(
  1932.                 'sequence' => 'ASC'
  1933.             )
  1934.         );
  1935.         if (empty($dbQuery))   ///now get the defaults
  1936.             $dbQuery $em->getRepository("ApplicationBundle:DashboardWidget")->findBy(
  1937.                 array(
  1938.                     'CompanyId' => $companyId,
  1939. //                    'userId'=>$userId,
  1940.                     'defaultBoxFlag' => 1,
  1941.                     'status' => GeneralConstant::ACTIVE
  1942.                 ),
  1943.                 array(
  1944.                     'sequence' => 'ASC'
  1945.                 )
  1946.             );
  1947.         foreach ($dbQuery as $entry) {
  1948.             $dashboardDataForUser[] = array(
  1949.                 'id' => $entry->getId(),
  1950.                 'widgetId' => $entry->getId(),
  1951.                 'widgetSequence' => $entry->getSequence(),
  1952.                 'widgetStatus' => $entry->getStatus(),
  1953.                 'widgetData' => json_decode($entry->getData(), true),
  1954.                 'defaultBoxFlag' => $entry->getDefaultBoxFlag(),
  1955.                 'widgetSizeTiny' => $entry->getSizeTiny(),
  1956.                 'widgetSizeSmall' => $entry->getSizeSmall(),
  1957.                 'widgetSizeMedium' => $entry->getSizeMedium(),
  1958.                 'widgetSizeLarge' => $entry->getSizeLarge(),
  1959.                 'refreshInterval' => $entry->getRefreshInterval(),
  1960.             );
  1961.         }
  1962.         return $this->render('ApplicationBundle:pages/dashboard:index_sales.html.twig',
  1963.             array(
  1964.                 'page_title' => 'Sales Dashboard',
  1965.                 'dashboardDataForUser' => $dashboardDataForUser
  1966.             )
  1967.         );
  1968.     }
  1969.     public function indexDistributionAction(Request $request)
  1970.     {
  1971.         $session $request->getSession();
  1972.         $dashboardDataForUser = [];
  1973.         $em $this->getDoctrine()->getManager();
  1974.         $companyId $this->getLoggedUserCompanyId($request);
  1975.         $userId $request->getSession()->get(UserConstants::USER_ID);
  1976.         $dbQuery $em->getRepository("ApplicationBundle:DashboardWidget")->findBy(
  1977.             array(
  1978.                 'CompanyId' => $companyId,
  1979.                 'userId' => $userId,
  1980.                 'status' => GeneralConstant::ACTIVE
  1981.             ),
  1982.             array(
  1983.                 'sequence' => 'ASC'
  1984.             )
  1985.         );
  1986.         if (empty($dbQuery))   ///now get the defaults
  1987.             $dbQuery $em->getRepository("ApplicationBundle:DashboardWidget")->findBy(
  1988.                 array(
  1989.                     'CompanyId' => $companyId,
  1990. //                    'userId'=>$userId,
  1991.                     'defaultBoxFlag' => 1,
  1992.                     'status' => GeneralConstant::ACTIVE
  1993.                 ),
  1994.                 array(
  1995.                     'sequence' => 'ASC'
  1996.                 )
  1997.             );
  1998.         foreach ($dbQuery as $entry) {
  1999.             $dashboardDataForUser[] = array(
  2000.                 'id' => $entry->getId(),
  2001.                 'widgetId' => $entry->getId(),
  2002.                 'widgetSequence' => $entry->getSequence(),
  2003.                 'widgetStatus' => $entry->getStatus(),
  2004.                 'widgetData' => json_decode($entry->getData(), true),
  2005.                 'defaultBoxFlag' => $entry->getDefaultBoxFlag(),
  2006.                 'widgetSizeTiny' => $entry->getSizeTiny(),
  2007.                 'widgetSizeSmall' => $entry->getSizeSmall(),
  2008.                 'widgetSizeMedium' => $entry->getSizeMedium(),
  2009.                 'widgetSizeLarge' => $entry->getSizeLarge(),
  2010.                 'refreshInterval' => $entry->getRefreshInterval(),
  2011.             );
  2012.         }
  2013.         return $this->render('ApplicationBundle:pages/dashboard:index_sales.html.twig',
  2014.             array(
  2015.                 'page_title' => 'Sales Dashboard',
  2016.                 'dashboardDataForUser' => $dashboardDataForUser
  2017.             )
  2018.         );
  2019.     }
  2020.     public function indexProductionAction(Request $request)
  2021.     {
  2022.         $session $request->getSession();
  2023.         $dashboardDataForUser = [];
  2024.         $em $this->getDoctrine()->getManager();
  2025.         $companyId $this->getLoggedUserCompanyId($request);
  2026.         $userId $request->getSession()->get(UserConstants::USER_ID);
  2027.         $dbQuery $em->getRepository("ApplicationBundle:DashboardWidget")->findBy(
  2028.             array(
  2029.                 'CompanyId' => $companyId,
  2030.                 'userId' => $userId,
  2031.                 'status' => GeneralConstant::ACTIVE
  2032.             ),
  2033.             array(
  2034.                 'sequence' => 'ASC'
  2035.             )
  2036.         );
  2037.         if (empty($dbQuery))   ///now get the defaults
  2038.             $dbQuery $em->getRepository("ApplicationBundle:DashboardWidget")->findBy(
  2039.                 array(
  2040.                     'CompanyId' => $companyId,
  2041. //                    'userId'=>$userId,
  2042.                     'defaultBoxFlag' => 1,
  2043.                     'status' => GeneralConstant::ACTIVE
  2044.                 ),
  2045.                 array(
  2046.                     'sequence' => 'ASC'
  2047.                 )
  2048.             );
  2049.         foreach ($dbQuery as $entry) {
  2050.             $dashboardDataForUser[] = array(
  2051.                 'id' => $entry->getId(),
  2052.                 'widgetId' => $entry->getId(),
  2053.                 'widgetSequence' => $entry->getSequence(),
  2054.                 'widgetStatus' => $entry->getStatus(),
  2055.                 'widgetData' => json_decode($entry->getData(), true),
  2056.                 'defaultBoxFlag' => $entry->getDefaultBoxFlag(),
  2057.                 'widgetSizeTiny' => $entry->getSizeTiny(),
  2058.                 'widgetSizeSmall' => $entry->getSizeSmall(),
  2059.                 'widgetSizeMedium' => $entry->getSizeMedium(),
  2060.                 'widgetSizeLarge' => $entry->getSizeLarge(),
  2061.                 'refreshInterval' => $entry->getRefreshInterval(),
  2062.             );
  2063.         }
  2064.         return $this->render('ApplicationBundle:pages/dashboard:index_sales.html.twig',
  2065.             array(
  2066.                 'page_title' => 'Sales Dashboard',
  2067.                 'dashboardDataForUser' => $dashboardDataForUser
  2068.             )
  2069.         );
  2070.     }
  2071.     public function indexInventoryAction(Request $request)
  2072.     {
  2073.         $session $request->getSession();
  2074.         $dashboardDataForUser = [];
  2075.         $em $this->getDoctrine()->getManager();
  2076.         $companyId $this->getLoggedUserCompanyId($request);
  2077.         $userId $request->getSession()->get(UserConstants::USER_ID);
  2078.         $dbQuery $em->getRepository("ApplicationBundle:DashboardWidget")->findBy(
  2079.             array(
  2080.                 'CompanyId' => $companyId,
  2081.                 'userId' => $userId,
  2082.                 'status' => GeneralConstant::ACTIVE
  2083.             ),
  2084.             array(
  2085.                 'sequence' => 'ASC'
  2086.             )
  2087.         );
  2088.         if (empty($dbQuery))   ///now get the defaults
  2089.             $dbQuery $em->getRepository("ApplicationBundle:DashboardWidget")->findBy(
  2090.                 array(
  2091.                     'CompanyId' => $companyId,
  2092. //                    'userId'=>$userId,
  2093.                     'defaultBoxFlag' => 1,
  2094.                     'status' => GeneralConstant::ACTIVE
  2095.                 ),
  2096.                 array(
  2097.                     'sequence' => 'ASC'
  2098.                 )
  2099.             );
  2100.         foreach ($dbQuery as $entry) {
  2101.             $dashboardDataForUser[] = array(
  2102.                 'id' => $entry->getId(),
  2103.                 'widgetId' => $entry->getId(),
  2104.                 'widgetSequence' => $entry->getSequence(),
  2105.                 'widgetStatus' => $entry->getStatus(),
  2106.                 'widgetData' => json_decode($entry->getData(), true),
  2107.                 'defaultBoxFlag' => $entry->getDefaultBoxFlag(),
  2108.                 'widgetSizeTiny' => $entry->getSizeTiny(),
  2109.                 'widgetSizeSmall' => $entry->getSizeSmall(),
  2110.                 'widgetSizeMedium' => $entry->getSizeMedium(),
  2111.                 'widgetSizeLarge' => $entry->getSizeLarge(),
  2112.                 'refreshInterval' => $entry->getRefreshInterval(),
  2113.             );
  2114.         }
  2115.         return $this->render('ApplicationBundle:pages/dashboard:index_sales.html.twig',
  2116.             array(
  2117.                 'page_title' => 'Sales Dashboard',
  2118.                 'dashboardDataForUser' => $dashboardDataForUser
  2119.             )
  2120.         );
  2121.     }
  2122.     public function indexServiceAction(Request $request)
  2123.     {
  2124.         $session $request->getSession();
  2125.         $dashboardDataForUser = [];
  2126.         $em $this->getDoctrine()->getManager();
  2127.         $companyId $this->getLoggedUserCompanyId($request);
  2128.         $userId $request->getSession()->get(UserConstants::USER_ID);
  2129.         $dbQuery $em->getRepository("ApplicationBundle:DashboardWidget")->findBy(
  2130.             array(
  2131.                 'CompanyId' => $companyId,
  2132.                 'userId' => $userId,
  2133.                 'status' => GeneralConstant::ACTIVE
  2134.             ),
  2135.             array(
  2136.                 'sequence' => 'ASC'
  2137.             )
  2138.         );
  2139.         if (empty($dbQuery))   ///now get the defaults
  2140.             $dbQuery $em->getRepository("ApplicationBundle:DashboardWidget")->findBy(
  2141.                 array(
  2142.                     'CompanyId' => $companyId,
  2143. //                    'userId'=>$userId,
  2144.                     'defaultBoxFlag' => 1,
  2145.                     'status' => GeneralConstant::ACTIVE
  2146.                 ),
  2147.                 array(
  2148.                     'sequence' => 'ASC'
  2149.                 )
  2150.             );
  2151.         foreach ($dbQuery as $entry) {
  2152.             $dashboardDataForUser[] = array(
  2153.                 'id' => $entry->getId(),
  2154.                 'widgetId' => $entry->getId(),
  2155.                 'widgetSequence' => $entry->getSequence(),
  2156.                 'widgetStatus' => $entry->getStatus(),
  2157.                 'widgetData' => json_decode($entry->getData(), true),
  2158.                 'defaultBoxFlag' => $entry->getDefaultBoxFlag(),
  2159.                 'widgetSizeTiny' => $entry->getSizeTiny(),
  2160.                 'widgetSizeSmall' => $entry->getSizeSmall(),
  2161.                 'widgetSizeMedium' => $entry->getSizeMedium(),
  2162.                 'widgetSizeLarge' => $entry->getSizeLarge(),
  2163.                 'refreshInterval' => $entry->getRefreshInterval(),
  2164.             );
  2165.         }
  2166.         return $this->render('ApplicationBundle:pages/dashboard:index_sales.html.twig',
  2167.             array(
  2168.                 'page_title' => 'Sales Dashboard',
  2169.                 'dashboardDataForUser' => $dashboardDataForUser
  2170.             )
  2171.         );
  2172.     }
  2173.     public function modifyDashboardAction(Request $request)
  2174.     {
  2175.         $session $request->getSession();
  2176.         $em $this->getDoctrine()->getManager();
  2177.         $companyId $this->getLoggedUserCompanyId($request);
  2178.         $userId $request->getSession()->get(UserConstants::USER_ID);
  2179.         if ($request->isMethod('post')) {
  2180.             //update dashboard data
  2181.             if ($request->request->has('widgetId')) {
  2182.                 foreach ($request->request->get('widgetId') as $k => $v) {
  2183.                     if ($v != 0) {
  2184.                         //exists sso edit
  2185.                         $widget $em->getRepository("ApplicationBundle:DashboardWidget")->findOneBy(
  2186.                             array(
  2187.                                 'id' => $v,
  2188.                             )
  2189.                         );
  2190.                     } else
  2191.                         $widget = new DashboardWidget();
  2192.                     $widget->setData($request->request->get('widgetData')[$k]);
  2193.                     $widget->setSequence($request->request->get('widgetSequence')[$k]);
  2194.                     $widget->setStatus($request->request->has('widgetStatus') ? $request->request->get('widgetStatus')[$k] : GeneralConstant::ACTIVE);
  2195.                     $widget->setUserId($userId);
  2196.                     $widget->setCompanyId($companyId);
  2197.                     $widget->setDefaultBoxFlag($request->request->has('defaultBoxFlag') ? $request->request->get('defaultBoxFlag')[$k] : 0);
  2198.                     if ($v == 0)
  2199.                         $em->persist($widget);
  2200.                     $em->flush();
  2201.                 }
  2202.             }
  2203.         }
  2204.         $dashboardDataForUser = [];
  2205.         $dbQuery $em->getRepository("ApplicationBundle:DashboardWidget")->findBy(
  2206.             array(
  2207.                 'CompanyId' => $companyId,
  2208.                 'userId' => $userId,
  2209.                 'status' => GeneralConstant::ACTIVE
  2210.             )
  2211.         );
  2212.         if (empty($dbQuery))   ///now get the defaults
  2213.             $dbQuery $em->getRepository("ApplicationBundle:DashboardWidget")->findBy(
  2214.                 array(
  2215.                     'CompanyId' => $companyId,
  2216. //                    'userId'=>$userId,
  2217.                     'defaultBoxFlag' => 1,
  2218.                     'status' => GeneralConstant::ACTIVE
  2219.                 )
  2220.             );
  2221.         foreach ($dbQuery as $entry) {
  2222.             $dashboardDataForUser[] = array(
  2223.                 'id' => $entry->getId(),
  2224.                 'widgetId' => $entry->getId(),
  2225.                 'widgetSequence' => $entry->getSequence(),
  2226.                 'widgetStatus' => $entry->getStatus(),
  2227.                 'widgetData' => $entry->getData(),
  2228.                 'defaultBoxFlag' => $entry->getDefaultBoxFlag(),
  2229.                 'widgetSizeTiny' => $entry->getSizeTiny(),
  2230.                 'widgetSizeSmall' => $entry->getSizeSmall(),
  2231.                 'widgetSizeMedium' => $entry->getSizeMedium(),
  2232.                 'widgetSizeLarge' => $entry->getSizeLarge(),
  2233.                 'refreshInterval' => $entry->getRefreshInterval(),
  2234.             );
  2235.         }
  2236.         //1st try to see if any exists
  2237.         return $this->render('ApplicationBundle:pages/dashboard:index_sales.html.twig',
  2238.             array(
  2239.                 'page_title' => 'Modify Dashboard'
  2240.             )
  2241.         );
  2242.     }
  2243.     public function ChangeCompanyDashboardAction(Request $request$id 1)
  2244.     {
  2245.         $session $request->getSession();
  2246.         if ($request->query->has('sys_admin_panel'))
  2247.             return $this->redirectToRoute('system_admin_dashboard');
  2248.         else {
  2249.             $session->set(UserConstants::USER_COMPANY_ID$id);
  2250.             return $this->redirectToRoute('dashboard');
  2251.         }
  2252.     }
  2253.     public function ChangeLeftPanelDisplayStatusAction(Request $request)
  2254.     {
  2255.         $session $request->getSession();
  2256.         $curr_status 1;
  2257.         if ($session->has('HIDE_LEFT_PANEL'))
  2258.             $curr_status $session->get('HIDE_LEFT_PANEL');
  2259.         if ($curr_status == 1)
  2260.             $curr_status 0;
  2261.         else
  2262.             $curr_status 1;
  2263.         $session->set('HIDE_LEFT_PANEL'$curr_status);
  2264. //            return $this->redirectToRoute('dashboard');
  2265.         return new Response($curr_status);
  2266.     }
  2267.     public function PermissionDeniedAction(Request $request)
  2268.     {
  2269.         $session $request->getSession();
  2270.         // Generic::debugMessage($session);
  2271.         return $this->render('ApplicationBundle:pages/system/pages:permission_denied.html.twig',
  2272.             array(
  2273.                 'page_title' => 'Permission Denied'
  2274.             )
  2275.         );
  2276.     }
  2277.     public function MyDocumentsAction(Request $request)
  2278.     {
  2279.         $session $request->getSession();
  2280.         $em $this->getDoctrine()->getManager();
  2281.         $data MiscActions::getDocumentsByUserId($em$session->get(UserConstants::USER_ID));
  2282.         // Generic::debugMessage($session);
  2283.         return $this->render('ApplicationBundle:pages/dashboard:my_documents.html.twig',
  2284.             array(
  2285.                 'page_title' => 'My Documents',
  2286.                 'data' => $data
  2287.             )
  2288.         );
  2289.     }
  2290.     public function ShowExceptionAction(Request $requestFlattenException $exceptionDebugLoggerInterface $logger null)
  2291.     {
  2292.         $session $request->getSession();
  2293.         $em $this->getDoctrine()->getManager();
  2294.         // Generic::debugMessage($session);
  2295. //        $currentContent = $this->getAndCleanOutputBuffering($request->headers->get('X-Php-Ob-Level', -1));
  2296. //        $showException = $request->attributes->get('showException', $this->debug); // As opposed to an additional parameter, this maintains BC
  2297.         $code $exception->getStatusCode();
  2298. //        $data = MiscActions::getDocumentsByUserId($em, $session->get(UserConstants::USER_ID));
  2299.         return $this->render('ApplicationBundle:pages/error:error_' $code '.html.twig',
  2300.             array(
  2301.                 'page_title' => 'Sorry',
  2302. //                'data' => $data
  2303.             )
  2304.         );
  2305.     }
  2306.     public function NotificationAction(Request $request)
  2307.     {
  2308.         $session $request->getSession();
  2309.         //'error', 'success', 'alert', 'information', 'warning', 'confirm'
  2310.         $themes = array(
  2311.             'error' => 'bg-red',
  2312.             'success' => 'bg-green',
  2313.             'alert' => 'bg-purple',
  2314.             'information' => 'bg-grey',
  2315.             'warning' => 'bg-orange',
  2316.             'confirm' => 'bg-blue',
  2317.         );
  2318.         $fa = array(
  2319.             'error' => 'fa fa-ban',
  2320.             'success' => 'fa fa-check',
  2321.             'alert' => 'fa fa-envelope',
  2322.             'information' => 'fa fa-comments',
  2323.             'warning' => 'fa fa-warning',
  2324.             'confirm' => 'fa fa-crosshairs',
  2325.         );
  2326.         // Generic::debugMessage($session);
  2327.         return $this->render('ApplicationBundle:pages/dashboard:notification.html.twig',
  2328.             array(
  2329.                 'page_title' => 'Notifications',
  2330.                 'dt' => json_decode(System::GetAllNotification(
  2331.                     $this->container->getParameter('notification_enabled'),
  2332.                     $this->container->getParameter('notification_server'),
  2333.                     $request->getSession()->get(UserConstants::USER_ID),
  2334.                     $request->getSession()->get(UserConstants::USER_APP_ID),
  2335.                     $request->getSession()->get(UserConstants::USER_COMPANY_ID)
  2336.                 ), true),
  2337. //                'dt'=>System::GetAllNotification(
  2338. //                    $this->container->getParameter('notification_enabled'),
  2339. //                    $request->getSession()->get(UserConstants::USER_ID),
  2340. //                    $request->getSession()->get(UserConstants::USER_APP_ID),
  2341. //                    $request->getSession()->get(UserConstants::USER_COMPANY_ID)
  2342. //                ),
  2343.                 'themes' => $themes,
  2344.                 'fa' => $fa,
  2345.                 't' => curl_init()
  2346.             )
  2347.         );
  2348.     }
  2349.     public function EditAccountAction(Request $request)
  2350.     {
  2351.         $session $request->getSession();
  2352.         //'error', 'success', 'alert', 'information', 'warning', 'confirm'
  2353.         $themes = array(
  2354.             'error' => 'bg-red',
  2355.             'success' => 'bg-green',
  2356.             'alert' => 'bg-purple',
  2357.             'information' => 'bg-aqua',
  2358.             'warning' => 'bg-orange',
  2359.             'confirm' => 'bg-blue',
  2360.         );
  2361.         $fa = array(
  2362.             'error' => 'fa fa-ban',
  2363.             'success' => 'fa fa-check',
  2364.             'alert' => 'fa fa-envelope',
  2365.             'information' => 'fa fa-comments',
  2366.             'warning' => 'fa fa-warning',
  2367.             'confirm' => 'fa fa-crosshairs',
  2368.         );
  2369.         $em $this->getDoctrine()->getManager();
  2370.         $g_path '';
  2371.         if ($request->isMethod('POST')) {
  2372.             $post $request->request;
  2373.             $path "";
  2374.             foreach ($request->files as $uploadedFile) {
  2375.                 if ($uploadedFile != null) {
  2376.                     $fileName md5(uniqid()) . '.' $uploadedFile->guessExtension();
  2377.                     $path $fileName;
  2378.                     $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/FileUploads/' $request->request->get('userId') . '/';
  2379.                     if (!file_exists($upl_dir)) {
  2380.                         mkdir($upl_dir0777true);
  2381.                     }
  2382.                     $file $uploadedFile->move($upl_dir$path);
  2383.                 }
  2384.             }
  2385.             if ($path != "")
  2386.                 $file_path 'uploads/FileUploads/' $request->request->get('userId') . '/' $path;
  2387.             $g_path $this->container->getParameter('kernel.root_dir') . '/../web/uploads/FileUploads/' $request->request->get('userId') . '/' $path;
  2388. //            $img_file = file_get_contents($g_path);
  2389. //            $image_data=base64_encode($img_file);
  2390. //            $encoded_data=System::encryptSignature($image_data,$request->request->get('approvalHash'));
  2391.             $query_here $this->getDoctrine()
  2392.                 ->getRepository('ApplicationBundle:SysUser')
  2393.                 ->findOneBy(
  2394.                     array('userId' => $request->request->get('userId'))
  2395.                 );
  2396.             if ($query_here) {
  2397.                 $new $query_here;
  2398.                 if ($path != "") {
  2399.                     if ($request->request->has('check_pp')) {
  2400.                         $new->setImage($file_path);
  2401.                         $session->set(UserConstants::USER_IMAGE$new->getImage());
  2402.                     } else
  2403.                         $new->setImage('');
  2404.                 }
  2405.                 $new->setName($request->request->get('name'));
  2406.                 $session->set(UserConstants::USER_NAME$request->request->get('name'));
  2407.                 //now password
  2408.                 if ($request->request->get('oldPass') != '') {
  2409.                     //1st check if old pass valid
  2410.                     if (!$this->container->get('sha256salted_encoder')->isPasswordValid($new->getPassword(), $request->request->get('oldPass'), $new->getSalt())) {
  2411.                         $this->addFlash(
  2412.                             'error',
  2413.                             'Your Old Password Was Wrong'
  2414.                         );
  2415.                     } else {
  2416.                         //old pass valid so now check if neww passes matches
  2417.                         if ($request->request->get('newPass') == $request->request->get('newPassAgain')) {
  2418.                             $new->setSalt(uniqid(mt_rand()));
  2419.                             $password $this->container->get('sha256salted_encoder')->encodePassword($request->request->get('newPass'), $new->getSalt());
  2420.                             $new->setPassword($password);
  2421.                             $em->flush();
  2422.                         } else {
  2423.                             $this->addFlash(
  2424.                                 'error',
  2425.                                 'Passwords Did not Match'
  2426.                             );
  2427.                         }
  2428.                     }
  2429.                 }
  2430.             } else {
  2431. //                    $new=new EncryptedSignature();
  2432. //                    $new->setData($encoded_data);
  2433. //                    $new->setUserId($request->request->get('userId'));
  2434. //                    $em->persist($new);
  2435.             }
  2436.             $em->flush();
  2437. //            now deleting the file
  2438.         }
  2439.         $user_data Users::getUserInfoByLoginId($em$this->getLoggedUserLoginId($request));
  2440.         // Generic::debugMessage($session);
  2441.         return $this->render('ApplicationBundle:pages/system/settings:edit_account.html.twig',
  2442.             array(
  2443.                 'page_title' => 'Edit Account',
  2444.                 'user_data' => $user_data,
  2445. //                'dt'=>json_decode(System::GetAllNotification($request->getSession()->get(UserConstants::USER_ID)),true),
  2446.                 'themes' => $themes,
  2447.                 'fa' => $fa,
  2448.             )
  2449.         );
  2450.     }
  2451.     public function indexApplicantAction(Request $request)
  2452.     {
  2453.         $systemType $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
  2454.         $twig_file 'ApplicationBundle:pages/login:applicant_login.html.twig';
  2455.         $session $request->getSession();
  2456.         if ($systemType == '_BUDDYBEE_') {
  2457.             if ($session->get('buddybeeAdminLevel'0) > 1)
  2458.                 return $this->redirectToRoute("buddybee_admin_dashboard", [
  2459.                 ]);
  2460.             elseif ($session->get('isConsultant') == 1)
  2461.                 return $this->redirectToRoute("consultant_dashboard", [
  2462.                 ]);
  2463.             else
  2464.                 return $this->redirectToRoute("student_dashboard", [
  2465.                 ]);
  2466.         }
  2467.         elseif ($systemType == '_CENTRAL_') {
  2468.             return $this->render(
  2469.                 'ApplicationBundle:pages/dashboard:index_applicant.html.twig',
  2470.                 array(
  2471.                     'page_title' => 'Applicant Dashboard'
  2472.                 )
  2473.             );
  2474.         }
  2475.         else
  2476.             return $this->render(
  2477.                 'ApplicationBundle:pages/dashboard:consultant_dashboard.html.twig',
  2478.                 array(
  2479.                     'page_title' => 'Applicant Dashboard'
  2480.                 )
  2481.             );
  2482.     }
  2483.     public function indexCentralLandingAction(Request $request)
  2484.     {
  2485.         $systemType $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
  2486.         $twig_file 'ApplicationBundle:pages/login:applicant_login.html.twig';
  2487.         $session $request->getSession();
  2488.         return $this->render(
  2489.             'ApplicationBundle:pages/dashboard:index_central_landing.html.twig',
  2490.             array(
  2491.                 'page_title' => 'Central Landing'
  2492.             )
  2493.         );
  2494.     }
  2495.     public function HummanResourceAction()
  2496.     {
  2497.         return $this->render(
  2498.             'ApplicationBundle:pages/dashboard:humanResource.html.twig',
  2499.             array(
  2500.                 'page_title' => 'Human Resource Dashboard'
  2501.             )
  2502.         );
  2503.     }
  2504.     public function PerformanceReviewDashboardAction()
  2505.     {
  2506.         return $this->render(
  2507.             'ApplicationBundle:pages/dashboard:performance_review_dashboard.html.twig',
  2508.             array(
  2509.                 'page_title' => 'Performance Review Dashboard'
  2510.             )
  2511.         );
  2512.     }
  2513.     public function RecruitmentDashboardAction()
  2514.     {
  2515.         return $this->render(
  2516.             'ApplicationBundle:pages/dashboard:recruitment_dashboard.html.twig',
  2517.             array(
  2518.                 'page_title' => 'Recruitment Dashboard'
  2519.             )
  2520.         );
  2521.     }
  2522.     public function TalentManagementDashboardAction()
  2523.     {
  2524.         return $this->render(
  2525.             'ApplicationBundle:pages/dashboard:talent_management_dashboard.html.twig',
  2526.             array(
  2527.                 'page_title' => 'Talent Management Dashboard'
  2528.             )
  2529.         );
  2530.     }
  2531. }