src/ApplicationBundle/Controller/DashboardController.php line 3834

Open in your IDE?
  1. <?php
  2. namespace ApplicationBundle\Controller;
  3. use ApplicationBundle\Constants\GeneralConstant;
  4. use ApplicationBundle\Constants\HumanResourceConstant;
  5. use ApplicationBundle\Entity\DashboardWidget;
  6. use ApplicationBundle\Entity\Employee;
  7. use ApplicationBundle\Entity\EmployeeDetails;
  8. use ApplicationBundle\Entity\SysUser;
  9. use ApplicationBundle\Interfaces\SessionCheckInterface;
  10. use ApplicationBundle\Modules\Accounts\Accounts;
  11. use ApplicationBundle\Modules\Authentication\Constants\UserConstants; use ApplicationBundle\Modules\Api\Constants\ApiConstants;
  12. use ApplicationBundle\Modules\HumanResource\HumanResource;
  13. use ApplicationBundle\Modules\Inventory\Inventory;
  14. use ApplicationBundle\Modules\Purchase\Supplier;
  15. use ApplicationBundle\Modules\Sales\Client;
  16. use ApplicationBundle\Modules\System\MiscActions;
  17. use ApplicationBundle\Modules\System\System;
  18. use ApplicationBundle\Modules\User\Company;
  19. use ApplicationBundle\Modules\User\Position;
  20. use ApplicationBundle\Modules\User\Users;
  21. use CompanyGroupBundle\Entity\CompanyGroup;
  22. use CompanyGroupBundle\Entity\EntityApplicantApplicationList;
  23. use CompanyGroupBundle\Entity\EntityApplicantDetails;
  24. use CompanyGroupBundle\Entity\EntityTicket;
  25. use Symfony\Component\BrowserKit\Client as BrowserClientKit;
  26. use Symfony\Component\Debug\Exception\FlattenException;
  27. use Symfony\Component\HttpFoundation\JsonResponse;
  28. use Symfony\Component\HttpFoundation\Request;
  29. use Symfony\Component\HttpFoundation\Response;
  30. use Symfony\Component\HttpKernel\Log\DebugLoggerInterface;
  31. use Symfony\Component\Routing\Generator\UrlGenerator;
  32. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  33. class DashboardController extends GenericController implements SessionCheckInterface
  34. {
  35.     private function getPublicDocumentEntityManager($appId)
  36.     {
  37.         $emGoc $this->getDoctrine()->getManager('company_group');
  38.         $emGoc->getConnection()->connect();
  39.         $goc $emGoc
  40.             ->getRepository("CompanyGroupBundle\\Entity\\CompanyGroup")
  41.             ->findOneBy(
  42.                 array(
  43.                     'appId' => $appId
  44.                 )
  45.             );
  46.         if (!$goc) {
  47.             return array(nullnull);
  48.         }
  49.         $connector $this->container->get('application_connector');
  50.         $connector->resetConnection(
  51.             'default',
  52.             $goc->getDbName(),
  53.             $goc->getDbUser(),
  54.             $goc->getDbPass(),
  55.             $goc->getDbHost(),
  56.             $reset true
  57.         );
  58.         return array($this->getDoctrine()->getManager(), $goc);
  59.     }
  60.     private function buildAllocationAwareTransactionSourceSql(array $filters = [])
  61.     {
  62.         $conn $this->getDoctrine()->getManager()->getConnection();
  63.         $conditions = [];
  64.         if (!empty($filters['document_type'])) {
  65.             $conditions[] = 't.document_type = ' . (int) $filters['document_type'];
  66.         }
  67.         if (!empty($filters['company_id'])) {
  68.             $conditions[] = 't.company_id = ' . (int) $filters['company_id'];
  69.         }
  70.         if (!empty($filters['start_date'])) {
  71.             $conditions[] = "t.ledger_hit_date >= " $conn->quote(date('Y-m-d'strtotime((string) $filters['start_date'])) . ' 00:00:00');
  72.         }
  73.         if (!empty($filters['end_date'])) {
  74.             $conditions[] = "t.ledger_hit_date <= " $conn->quote(date('Y-m-d'strtotime((string) $filters['end_date'])) . ' 23:59:59.999');
  75.         }
  76.         if (!empty($filters['client_head_ids'])) {
  77.             $conditions[] = 'td.accounts_head_id IN (' implode(','array_map('intval', (array) $filters['client_head_ids'])) . ')';
  78.         }
  79.         if (isset($filters['approved'])) {
  80.             $conditions[] = 't.approved = ' . (int) $filters['approved'];
  81.         } else {
  82.             $conditions[] = 't.approved = 1';
  83.         }
  84.         if (isset($filters['ledger_hit'])) {
  85.             $conditions[] = 't.ledger_hit = ' . (int) $filters['ledger_hit'];
  86.         } else {
  87.             $conditions[] = 't.ledger_hit = 1';
  88.         }
  89.         $whereSql = empty($conditions) ? '1=1' implode(' AND '$conditions);
  90.         return "(
  91.             SELECT td.transaction_details_id AS transaction_details_id,
  92.                    td.transaction_id,
  93.                    td.accounts_head_id,
  94.                    td.position,
  95.                    td.amount AS allocation_amount,
  96.                    td.ledger_hit_date,
  97.                    t.document_hash,
  98.                    t.company_id,
  99.                    t.document_type,
  100.                    1 AS has_allocation
  101.             FROM acc_transaction_details td
  102.             JOIN acc_transactions t ON t.transaction_id = td.transaction_id
  103.             JOIN transaction_detail_allocations tda ON tda.transaction_detail_id = td.transaction_details_id
  104.             WHERE " $whereSql "
  105.             UNION ALL
  106.             SELECT td.transaction_details_id AS transaction_details_id,
  107.                    td.transaction_id,
  108.                    td.accounts_head_id,
  109.                    td.position,
  110.                    td.amount AS allocation_amount,
  111.                    td.ledger_hit_date,
  112.                    t.document_hash,
  113.                    t.company_id,
  114.                    t.document_type,
  115.                    0 AS has_allocation
  116.             FROM acc_transaction_details td
  117.             JOIN acc_transactions t ON t.transaction_id = td.transaction_id
  118.             WHERE " $whereSql "
  119.               AND NOT EXISTS (
  120.                   SELECT 1
  121.                   FROM transaction_detail_allocations tda
  122.                   WHERE tda.transaction_detail_id = td.transaction_details_id
  123.               )
  124.         )";
  125.     }
  126.     public function doLoginAsAction(Request $request)
  127.     {
  128.         $session $request->getSession();
  129.         if ($request->isMethod('POST')) {
  130.             $session->set(UserConstants::USER_CURRENT_POSITION$request->request->get('position'));
  131.             $curr_position_id $request->request->get('position');
  132.             if ($session->get(UserConstants::USER_LOGIN_ID) != 0) {
  133.                 $loginID $this->get('user_module')->addUserLoginLog(
  134.                     $session->get(UserConstants::USER_ID),
  135.                     $request->server->get("REMOTE_ADDR"),
  136.                     $request->request->get('position'),
  137.                     '',
  138.                     '',
  139.                     '',
  140.                     $session->get(UserConstants::USER_LOGIN_ID)
  141.                 );
  142.             } else $loginID $this->get('user_module')->addUserLoginLog(
  143.                 $session->get(UserConstants::USER_ID),
  144.                 $request->server->get("REMOTE_ADDR"),
  145.                 $request->request->get('position'),
  146.                 '',
  147.                 '',
  148.                 '',
  149.                 0
  150.             );
  151.             if ($session->get(UserConstants::ALL_MODULE_ACCESS_FLAG) == 1)
  152.                 $prohibit_list_array = [];
  153.             else if ($curr_position_id != 0)
  154.                 $prohibit_list_array Position::getUserProhibitRouteArray($this->getDoctrine()->getManager(), $curr_position_id$session->get(UserConstants::USER_ID));
  155.             $session->set(UserConstants::USER_LOGIN_ID$loginID);
  156.             $session->set(UserConstants::USER_PROHIBIT_LISTjson_encode($prohibit_list_array));
  157.             $session->set(UserConstants::USER_ROUTE_LISTjson_encode(Position::getUserRouteArray($this->getDoctrine()->getManager(), $request->request->get('position'), $session->get(UserConstants::USER_ID))));
  158.             return $this->redirectToRoute("dashboard");
  159.         }
  160.         $message "";
  161.         $PositionList = array();
  162.         $PL json_decode($session->get(UserConstants::USER_POSITION_LIST), true);
  163.         foreach ($PL as &$positionID) {
  164.             $PositionList[$positionID] = Position::getPositionName($this->getDoctrine()->getManager(), $positionID);
  165.         }
  166.         return $this->render(
  167.             '@Authentication/pages/views/login_position.html.twig',
  168.             array(
  169.                 "message" => $message,
  170.                 'page_title' => 'Users',
  171.                 'position_list' => $PositionList
  172.             )
  173.         );
  174.     }
  175.     //    protected $twig;
  176.     //    protected $debug;
  177.     //
  178.     //    /**
  179.     //     * @param bool $debug Show error (false) or exception (true) pages by default
  180.     //     */
  181.     //    public function __construct(Environment $twig, $debug)
  182.     //    {
  183.     //        $this->twig = $twig;
  184.     //        $this->debug = $debug;
  185.     //    }
  186.     public function TestSmsAction(Request $request)
  187.     {
  188.         $em $this->getDoctrine()->getManager();
  189.         $session $request->getSession();
  190.         $em $this->getDoctrine()->getManager();
  191.         $userAppId $session->get('userAppId');
  192.         $companyId $session->get('userCompanyId');
  193.         if (GeneralConstant::SMS_ENABLED == 1) {
  194.             $company $em->getRepository('ApplicationBundle\\Entity\\Company')->findOneBy(
  195.                 array(
  196.                     'id' => $companyId///material
  197.                 )
  198.             );
  199.             if ($company->getSmsNotificationEnabled() == 1) {
  200.                 $smsData = [];
  201.                 $smsSettings json_decode($company->getSmsSettings(), true);
  202.                 if ($smsSettings != null && !empty($smsSettings)) {
  203.                     $method = isset($smsSettings['method']) ? $smsSettings['method'] : 'GET';
  204.                     $destination_url = isset($smsSettings['destination_url']) ? $smsSettings['destination_url'] : 'http://172.105.70.96:1234';
  205.                     $user_name = isset($smsSettings['user_name']) ? $smsSettings['user_name'] : 'test';
  206.                     $user_name_var = isset($smsSettings['user_name_var']) ? $smsSettings['user_name_var'] : 'Username';
  207.                     $password_var = isset($smsSettings['password_var']) ? $smsSettings['password_var'] : 'Password';
  208.                     $password = isset($smsSettings['password']) ? $smsSettings['password'] : '';
  209.                     $from_number_var = isset($smsSettings['from_number_var']) ? $smsSettings['from_number_var'] : 'From';
  210.                     $from_number = isset($smsSettings['from_number']) ? $smsSettings['from_number'] : '';
  211.                     $to_number_var = isset($smsSettings['to_number_var']) ? $smsSettings['to_number_var'] : 'To';
  212.                     $to_number $request->query->has('To') ? $request->query->get('To') : '01911706483';
  213.                     $text_var = isset($smsSettings['text_var']) ? $smsSettings['text_var'] : 'Message';
  214.                     $text $request->query->has('Message') ? $request->query->get('Message') : 'Test message';
  215.                     return new JsonResponse(System::sendSms(
  216.                         1,
  217.                         $method,
  218.                         $destination_url,
  219.                         $user_name_var,
  220.                         $user_name,
  221.                         $password_var,
  222.                         $password,
  223.                         $from_number_var,
  224.                         $from_number,
  225.                         $to_number_var,
  226.                         $to_number,
  227.                         $text_var,
  228.                         $text,
  229.                         $viewlink ""
  230.                     ));
  231.                 }
  232.             }
  233.             return new JsonResponse(
  234.                 [
  235.                     'companyId' => $companyId,
  236.                     'companyName' => $company->getName(),
  237.                     'enabled' => $company->getSmsNotificationEnabled(),
  238.                     //                    'smsSettings'=>$smsSettings
  239.                 ]
  240.             );
  241.         }
  242.         return new JsonResponse(
  243.             [
  244.                 'success' => false
  245.             ]
  246.         );
  247.     }
  248.     public function SyncCompanyProductToEntityProductAction(Request $request)
  249.     {
  250.         $gocId $request->query->has('gocId') ? $request->query->get('gocId') : 0;
  251.         $companyId $request->query->has('companyId') ? $request->query->get('companyId') : 1;
  252.         $genQueryArray = [];
  253.         $em_goc $this->getDoctrine()->getManager('company_group');
  254.         $em_goc->getConnection()->connect();
  255.         $em $this->getDoctrine()->getManager();
  256.         if ($request->query->has('forceRefresh')) {
  257.             $genQueryArray = [];
  258.             $query "
  259.             TRUNCATE `entity_brand_company`;
  260.             TRUNCATE `entity_item_group`;
  261.             TRUNCATE `entity_products`;
  262.             TRUNCATE `entity_product_categories`;
  263.             TRUNCATE `entity_product_specifications`;
  264.             TRUNCATE `entity_product_sub_categories`;
  265.             TRUNCATE `entity_specification_types`;
  266.             TRUNCATE `entity_unit_type`;
  267.             SELECT * from `entity_unit_type`;";
  268.             $stmt $em_goc->getConnection()->executeStatement($query);
  269.             
  270.             //            $Transactions = $stmt;
  271.             $get_kids_sql 'select * from acc_accounts_head where accounts_head_id not in (select distinct parent_id from acc_accounts_head) ;';
  272.             //UPDATE company SET sales=0, expense=0, payable=0 ,net_worth=0, monthly_growth=0 WHERE 1;';
  273.             $stmt $em->getConnection()->executeStatement($get_kids_sql);
  274.             
  275.             $query $stmt;
  276.         } else
  277.             $genQueryArray = ['globalId' => [0null]];
  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.             'SpecType',
  284.             'BrandCompany',
  285.             'InvItemGroup',
  286.             'InvProductCategories',
  287.             'InvProductSubCategories',
  288.             'InvProductSpecifications',
  289.             'InvSpecificationTypes',
  290.             'InvProducts'
  291.         ];
  292.         $entity_wise_entities = [
  293.             'EntityCurrencies',
  294.             'EntityUnitType',
  295.             'EntitySpecType',
  296.             'EntityBrandCompany',
  297.             'EntityItemGroup',
  298.             'EntityProductCategories',
  299.             'EntityProductSubCategories',
  300.             'EntityProductSpecifications',
  301.             'EntitySpecificationTypes',
  302.             'EntityProducts'
  303.         ];
  304.         ////ITEMGROUPS
  305.         foreach ($company_wise_entities as $k => $cwa) {
  306.             $dataOnCompany $em
  307.                 ->getRepository("ApplicationBundle\\Entity\\" $cwa)
  308.                 ->findBy(
  309.                     $genQueryArray
  310.                 );
  311.             $match_cid_gid_itemgroup = [];  //[cid=>gid]
  312.             $match_cid_gid_itemgroup = [];  //[cid=>gid]
  313.             foreach ($dataOnCompany as $data) {
  314.                 $newClass "\\CompanyGroupBundle\\Entity\\" $entity_wise_entities[$k];
  315.                 $new = new $newClass();
  316.                 //                $new = new \CompanyGroupBundle\Entity\EntityItemGroup();
  317.                 $getters array_filter(get_class_methods($data), function ($method) {
  318.                     return 'get' === substr($method03);
  319.                 });
  320.                 foreach ($getters as $getter) {
  321.                     if ($getter == 'getGlobalId')
  322.                         continue;
  323.                     //                    if ($getter == 'getId')
  324.                     //                        continue;
  325.                     $setMethod str_replace('get''set'$getter);
  326.                     if (method_exists($new$setMethod))
  327.                         $new->{$setMethod}($data->{$getter}()); // `foo!`
  328.                 }
  329.                 $em_goc->persist($new);
  330.                 $em_goc->flush();
  331.                 if ($cwa == 'Currencies') {
  332.                     $data->setGlobalId($new->getCurrencyId());
  333.                     $new->setGlobalId($new->getCurrencyId());
  334.                 } else {
  335.                     $data->setGlobalId($new->getId());
  336.                     $new->setGlobalId($new->getId());
  337.                 }
  338.                 $em->flush();
  339.                 $em_goc->flush();
  340.                 //                $match_cid_gid_itemgroup[$data->getId()] = $new->getId();
  341.             }
  342.         }
  343.         return new JsonResponse(
  344.             array(
  345.                 'data' => $entity_wise_entities
  346.             )
  347.         );
  348.     }
  349.     public function SyncEntityProductToCompanyProductAction(Request $request)
  350.     {
  351.         $gocId $request->query->has('gocId') ? $request->query->get('gocId') : 0;
  352.         $companyId $request->query->has('companyId') ? $request->query->get('companyId') : 1;
  353.         $genQueryArray = [];
  354.         $em_goc $this->getDoctrine()->getManager('company_group');
  355.         $em_goc->getConnection()->connect();
  356.         $em $this->getDoctrine()->getManager();
  357.         if ($request->query->has('forceRefresh')) {
  358.             $genQueryArray = [];
  359.             $query "
  360.             TRUNCATE `brand_company`;
  361.             TRUNCATE `inv_item_group`;
  362.             TRUNCATE `inv_products`;
  363.             TRUNCATE `inv_product_categories`;
  364.             TRUNCATE `inv_product_specifications`;
  365.             TRUNCATE `inv_product_sub_categories`;
  366.             TRUNCATE `inv_specification_types`;
  367.             TRUNCATE `unit_type`;
  368.             SELECT * from `unit_type`;";
  369.             $stmt $em->getConnection()->executeStatement($query);
  370.             
  371.             //            $Transactions = $stmt;
  372.             $get_kids_sql 'select * from acc_accounts_head where accounts_head_id not in (select distinct parent_id from acc_accounts_head) ;';
  373.             //UPDATE company SET sales=0, expense=0, payable=0 ,net_worth=0, monthly_growth=0 WHERE 1;';
  374.             $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  375.             
  376.             $query $stmt;
  377.         } else {
  378.             //            $genQueryArray = ['globalId' => [0, null]];
  379.         }
  380.         //1st step get all company item ids and then check for global id null if its null then the
  381.         // item group is not present in entity so add it
  382.         $company_wise_entities = [
  383.             'Currencies',
  384.             'UnitType',
  385.             'SpecType',
  386.             'BrandCompany',
  387.             'InvItemGroup',
  388.             'InvProductCategories',
  389.             'InvProductSubCategories',
  390.             'InvProductSpecifications',
  391.             'InvSpecificationTypes',
  392.             'InvProducts'
  393.         ];
  394.         $entity_wise_entities = [
  395.             'EntityCurrencies',
  396.             'EntityUnitType',
  397.             'EntitySpecType',
  398.             'EntityBrandCompany',
  399.             'EntityItemGroup',
  400.             'EntityProductCategories',
  401.             'EntityProductSubCategories',
  402.             'EntityProductSpecifications',
  403.             'EntitySpecificationTypes',
  404.             'EntityProducts'
  405.         ];
  406.         foreach ($entity_wise_entities as $k => $ewa) {
  407.             $dataOnEntity $em_goc
  408.                 ->getRepository("CompanyGroupBundle\\Entity\\" $ewa)
  409.                 ->findBy(
  410.                     $genQueryArray
  411.                 );
  412.             $match_cid_gid_itemgroup = [];  //[cid=>gid]
  413.             $match_cid_gid_itemgroup = [];  //[cid=>gid]
  414.             foreach ($dataOnEntity as $data) {
  415.                 $newClass "\\ApplicationBundle\\Entity\\" $company_wise_entities[$k];
  416.                 $rec_exists 0;
  417.                 $new $em
  418.                     ->getRepository("ApplicationBundle\\Entity\\" $company_wise_entities[$k])
  419.                     ->findOneBy(
  420.                         array(
  421.                             'globalId' => $data->getGlobalId()
  422.                         )
  423.                     );
  424.                 if ($new) {
  425.                     $rec_exists 1;
  426.                 } else
  427.                     $new = new $newClass();
  428.                 //                $new = new \CompanyGroupBundle\Entity\EntityItemGroup();
  429.                 $getters array_filter(get_class_methods($data), function ($method) {
  430.                     return 'get' === substr($method03);
  431.                 });
  432.                 foreach ($getters as $getter) {
  433.                     if ($getter == 'getId')
  434.                         continue;
  435.                     $setMethod str_replace('get''set'$getter);
  436.                     if (method_exists($new$setMethod)) {
  437.                         if ($ewa == 'EntityProducts') {
  438.                             if ($rec_exists == 1) {
  439.                                 if (in_array($setMethod, [
  440.                                     'setPurchasePrice',
  441.                                     'setPurchasePriceWoExpense',
  442.                                     'setQty',
  443.                                     'setReorderLevel',
  444.                                     'setBookingQty',
  445.                                     'setNonSalesInvoicedQty',
  446.                                     'setNonSalesReturnReceivedQty',
  447.                                     'setBookingQty',
  448.                                     'setPhysicalQty',
  449.                                 ])) {
  450.                                     continue;
  451.                                 }
  452.                             }
  453.                         }
  454.                         $new->{$setMethod}($data->{$getter}()); // `foo!`
  455.                     }
  456.                 }
  457.                 if ($rec_exists == 0)
  458.                     $em->persist($new);
  459.                 $em->flush();
  460.                 if ($ewa == 'EntityCurrencies') {
  461.                     $new->setGlobalId($data->getCurrencyId());
  462.                 } else {
  463.                     $new->setGlobalId($data->getId());
  464.                 }
  465.                 $em->flush();
  466.                 //                $match_cid_gid_itemgroup[$data->getId()] = $new->getId();
  467.             }
  468.         }
  469.         return new JsonResponse(
  470.             array(
  471.                 'data' => $company_wise_entities
  472.             )
  473.         );
  474.     }
  475.     public function getAppGeneralDashboardDataAction(Request $request)
  476.     {
  477.         $dataFor 'client';
  478.         $personId 0;
  479.         if ($request->query->has('dataFor'))
  480.             $dataFor $request->query->get('dataFor');
  481.         if ($request->request->has('dataFor'))
  482.             $dataFor $request->request->get('dataFor');
  483.         if ($request->query->has('personId'))
  484.             $personId $request->query->get('personId');
  485.         if ($request->request->has('personId'))
  486.             $personId $request->request->get('personId');
  487.         if ($personId == 0)
  488.             return new JsonResponse(
  489.                 array(
  490.                     'success' => false,
  491.                     'data' => [],
  492.                 )
  493.             );
  494.         $session $request->getSession();
  495.         $em $this->getDoctrine()->getManager();
  496.         $userAppId $session->get('userAppId');
  497.         $companyId $session->get('userCompanyId');
  498.         $dataToConnectList = [];
  499.         $appIdList $session->get('appIdList');
  500.         $companyIdListByAppId $session->get('companyIdListByAppId');
  501.         $companyNameListByAppId $session->get('companyNameListByAppId');
  502.         $companyImageListByAppId $session->get('companyImageListByAppId');
  503.         $gocEnabled 0;
  504.         if ($this->container->hasParameter('entity_group_enabled'))
  505.             $gocEnabled $this->container->getParameter('entity_group_enabled');
  506.         $connector $this->container->get('application_connector');
  507.         $connector->resetConnection(
  508.             'default',
  509.             $session->get('gocDbName'),
  510.             $session->get('gocDbUser'),
  511.             $session->get('gocDbPass'),
  512.             $session->get('gocDbHost'),
  513.             $reset true
  514.         );
  515.         $em $this->getDoctrine()->getManager();
  516.         $data = [];
  517.         if ($dataFor == 'client') {
  518.             //get order_count, order_amount,bill_count, bill_amount, collection_amount, due_amount
  519.             $data = [
  520.                 'order_count' => 0,
  521.                 'order_amount' => 0,
  522.                 'invoice_count' => 0,
  523.                 'invoice_amount' => 0,
  524.                 'collection_amount' => 0,
  525.                 'due_amount' => 0,
  526.                 'client_count' => 1,
  527.             ];
  528.             $clientIds = [$personId];
  529.             //order count and amount
  530.             $get_sql "SELECT count(sales_order_id) order_count, sum(so_amount) order_amount
  531. FROM sales_order WHERE approved=1 and sales_order.company_id=" $companyId "  and sales_order.client_id in (" implode(','$clientIds) . ");";
  532.             $stmt $em->getConnection()->fetchAllAssociative($get_sql);
  533.             
  534.             $entries $stmt;
  535.             if (!empty($entries)) {
  536.                 $data['order_count'] = $entries[0]['order_count'];
  537.                 $data['order_amount'] = $entries[0]['order_amount'];
  538.             }
  539.             //invoice
  540.             $get_sql "SELECT count(sales_invoice_id) invoice_count, sum(invoice_amount) invoice_amount
  541. FROM sales_invoice WHERE approved=1 and sales_invoice.company_id=" $companyId "  and sales_invoice.client_id in (" implode(','$clientIds) . ");";
  542.             $stmt $em->getConnection()->fetchAllAssociative($get_sql);
  543.             
  544.             $entries $stmt;
  545.             if (!empty($entries)) {
  546.                 $data['invoice_count'] = $entries[0]['invoice_count'];
  547.                 $data['invoice_amount'] = $entries[0]['invoice_amount'];
  548.             }
  549.             //now collection
  550.             $allocationSourceSql $this->buildAllocationAwareTransactionSourceSql(array(
  551.                 'document_type' => 6,
  552.                 'company_id' => $companyId,
  553.                 'start_date' => null,
  554.                 'end_date' => null,
  555.                 'approved' => 1,
  556.                 'ledger_hit' => 1,
  557.             ));
  558.             $get_sql "SELECT SUM(CASE WHEN alloc_rows.position = 'cr' THEN alloc_rows.allocation_amount ELSE 0 END) positive_amount,
  559. SUM(CASE WHEN alloc_rows.position = 'dr' THEN alloc_rows.allocation_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
  560.  FROM " $allocationSourceSql " alloc_rows
  561.    join acc_clients on acc_clients.accounts_head_id=alloc_rows.accounts_head_id or acc_clients.advance_head_id=alloc_rows.accounts_head_id
  562.   join client_type on acc_clients.type=client_type.client_type_id
  563.   WHERE acc_clients.company_id=" $companyId " and acc_clients.client_id in (" implode(','$clientIds) . ") ";
  564.             $stmt $em->getConnection()->fetchAllAssociative($get_sql);
  565.             
  566.             $entries $stmt;
  567.             $clientTypes = [];
  568.             $clientTypeNames = [];
  569.             $alreadyCids = [];
  570.             foreach ($entries as $entry) {
  571.                 $data['collection_amount'] += (* ($entry['positive_amount'] - $entry['negative_amount']));
  572.                 if (!in_array($entry['client_id'], $alreadyCids)) {
  573.                     $data['due_amount'] += ($entry['client_due']);
  574.                     $alreadyCids[] = $entry['client_id'];
  575.                 }
  576.             }
  577.         }
  578.         if ($dataFor == 'sales_user') {
  579.             //get order_count, order_amount,bill_count, bill_amount, collection_amount, due_amount
  580.             $data = [
  581.                 'order_count' => 0,
  582.                 'order_amount' => 0,
  583.                 'invoice_count' => 0,
  584.                 'invoice_amount' => 0,
  585.                 'collection_amount' => 0,
  586.                 'due_amount' => 0,
  587.                 'client_count' => 0,
  588.             ];
  589.             $clientIds = [];
  590.             $salesPersonIds = [];
  591.             $allSalespersonFlag 1//temp
  592.             if ($allSalespersonFlag != 1) {
  593.                 $query $em->getRepository('ApplicationBundle\\Entity\\Employee')->findOneBy(
  594.                     array(
  595.                         'userId' => $personId
  596.                     )
  597.                 );
  598.                 if ($query)
  599.                     $salesPersonIds[] = $query->getEmployeeId();
  600.             }
  601.             //Client count
  602.             $get_sql "SELECT  client_id
  603. FROM acc_clients WHERE  acc_clients.company_id=" $companyId " ";
  604.             if ($allSalespersonFlag != 1)
  605.                 $get_sql .= " and acc_clients.sales_person_id in (" implode(','$salesPersonIds) . ");";
  606.             else
  607.                 $get_sql .= " ;";
  608.             $stmt $em->getConnection()->fetchAllAssociative($get_sql);
  609.             
  610.             $entries $stmt;
  611.             if (!empty($entries)) {
  612.                 foreach ($entries as $entry) {
  613.                     $data['client_count'] += 1;
  614.                     $clientIds[] = $entry['client_id'];
  615.                 }
  616.             }
  617.             //order count and amount
  618.             if (!empty($clientIds)) {
  619.                 $get_sql "SELECT count(sales_order_id) order_count, sum(so_amount) order_amount
  620. FROM sales_order WHERE approved=1 and sales_order.company_id=" $companyId "  and sales_order.client_id in (" implode(','$clientIds) . ");";
  621.                 $stmt $em->getConnection()->fetchAllAssociative($get_sql);
  622.                 
  623.                 $entries $stmt;
  624.                 if (!empty($entries)) {
  625.                     $data['order_count'] = $entries[0]['order_count'];
  626.                     $data['order_amount'] = $entries[0]['order_amount'];
  627.                 }
  628.                 //invoice
  629.                 $get_sql "SELECT count(sales_invoice_id) invoice_count, sum(invoice_amount) invoice_amount
  630. FROM sales_invoice WHERE approved=1 and sales_invoice.company_id=" $companyId "  and sales_invoice.client_id in (" implode(','$clientIds) . ");";
  631.                 $stmt $em->getConnection()->fetchAllAssociative($get_sql);
  632.                 
  633.                 $entries $stmt;
  634.                 if (!empty($entries)) {
  635.                     $data['invoice_count'] = $entries[0]['invoice_count'];
  636.                     $data['invoice_amount'] = $entries[0]['invoice_amount'];
  637.                 }
  638.                 //now collection
  639.                 $allocationSourceSql $this->buildAllocationAwareTransactionSourceSql(array(
  640.                     'document_type' => 6,
  641.                     'approved' => 1,
  642.                     'ledger_hit' => 1,
  643.                 ));
  644.                 $get_sql "SELECT SUM(CASE WHEN alloc_rows.position = 'cr' THEN alloc_rows.allocation_amount ELSE 0 END) positive_amount,
  645. SUM(CASE WHEN alloc_rows.position = 'dr' THEN alloc_rows.allocation_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
  646.  FROM " $allocationSourceSql " alloc_rows
  647.    join acc_clients on acc_clients.accounts_head_id=alloc_rows.accounts_head_id or acc_clients.advance_head_id=alloc_rows.accounts_head_id
  648.   join client_type on acc_clients.type=client_type.client_type_id
  649.   WHERE acc_clients.company_id=" $companyId " and acc_clients.client_id in (" implode(','$clientIds) . ") ";
  650.                 $stmt $em->getConnection()->fetchAllAssociative($get_sql);
  651.                 
  652.                 $entries $stmt;
  653.                 $clientTypes = [];
  654.                 $clientTypeNames = [];
  655.                 $alreadyCids = [];
  656.                 foreach ($entries as $entry) {
  657.                     $data['collection_amount'] += (* ($entry['positive_amount'] - $entry['negative_amount']));
  658.                     if (!in_array($entry['client_id'], $alreadyCids)) {
  659.                         $data['due_amount'] += ($entry['client_due']);
  660.                         $alreadyCids[] = $entry['client_id'];
  661.                     }
  662.                 }
  663.             }
  664.         }
  665.         if ($dataFor == 'user') {
  666.             //get order_count, payment_amount,
  667.         }
  668.         return new JsonResponse(
  669.             array(
  670.                 'success' => true,
  671.                 'data' => $data,
  672.                 'dataFor' => $dataFor,
  673.                 'personId' => $personId,
  674.             )
  675.         );
  676.     }
  677.     public function getManagementDashboardDataAction(Request $request)
  678.     {
  679.         $session $request->getSession();
  680.         $data = array(
  681.             'cash_and_bank_position' => [],
  682.             'order_and_client_count' => [],
  683.             'expense_vs_revenue' => [],
  684.             'receivable_position' => [],
  685.             'payable_position' => [],
  686.             'expense_position' => [],
  687.             'inventory_position' => [],
  688.             'production_position' => [],
  689.             'sales_position' => [],
  690.             'collection_position' => [],
  691.             'market_return_position' => [],
  692.             'top_selling_item_position' => [],
  693.             'top_selling_client_position' => [],
  694.         );
  695.         $em $this->getDoctrine()->getManager();
  696.         $reportsToGet = [
  697.             'cash_and_bank_position',
  698.             'order_and_client_count',
  699.             'expense_vs_revenue',
  700.             'receivable_position',
  701.             'payable_position',
  702.             'expense_position',
  703.             'inventory_position',
  704.             'production_position',
  705.             'sales_position',
  706.             'collection_position',
  707.             'market_return_position',
  708.             'top_selling_item_position',
  709.             'top_selling_client_position',
  710.         ];
  711.         //        $periodType='day'; //day,month,week,year,quarter etc
  712.         $periodType 'month'//day,month,week,year,quarter etc
  713.         if ($request->request->has('reportsToGet')) {
  714.             if ($request->request->get('reportsToGet') != 'all' && !in_array('all'$request->request->get('reportsToGet'))) {
  715.                 $reportsToGet $request->request->get('reportsToGet');
  716.             }
  717.         }
  718.         if ($request->request->has('periodType')) {
  719.             $periodType $request->request->get('periodType');
  720.         }
  721.         $userAppId $session->get('userAppId');
  722.         $dataToConnectList = [];
  723.         $appIdList $session->get('appIdList');
  724.         $companyIdListByAppId $session->get('companyIdListByAppId');
  725.         $companyNameListByAppId $session->get('companyNameListByAppId');
  726.         $companyImageListByAppId $session->get('companyImageListByAppId');
  727.         $gocEnabled 0;
  728.         if ($this->container->hasParameter('entity_group_enabled'))
  729.             $gocEnabled $this->container->getParameter('entity_group_enabled');
  730.         $thisPeriodStartDate '';
  731.         $lastPeriodStartDate '';
  732.         $thisPeriodEndDate '';
  733.         $lastPeriodEndDate '';
  734.         $today = new \DateTime();
  735.         if ($periodType == 'month') {
  736.             $thisPeriodEndDate $today->format('Y-m-d');
  737.             $thisPeriodStartDate $today->format('Y-m-') . '01';
  738.             $currDate = new \DateTime($thisPeriodStartDate);
  739.             $currDate->modify('-1 day');
  740.             $lastPeriodEndDate $currDate->format('Y-m-d');
  741.             $lastPeriodStartDate $currDate->format('Y-m-') . '01';
  742.         } else if ($periodType == 'week') {
  743.             $thisPeriodEndDate $today->format('Y-m-d');
  744.             $thisWeekStartDate date("Y-m-d"strtotime("previous saturday"));
  745.             $thisPeriodStartDate date("Y-m-d"strtotime("previous saturday"));
  746.             $currDate = new \DateTime($thisPeriodStartDate);
  747.             $currDate->modify('-1 day');
  748.             $lastPeriodEndDate $currDate->format('Y-m-d');
  749.             $currDate->modify('-6 day');
  750.             $lastPeriodStartDate $currDate->format('Y-m-d');
  751.         } else if ($periodType == 'quarter') {
  752.             $thisPeriodEndDate $today->format('Y-m-d');
  753.             $thisWeekStartDate date("Y-m-d"strtotime("previous saturday"));
  754.             $thisPeriodStartDate date("Y-m-d"strtotime("previous saturday"));
  755.             $currDate = new \DateTime($thisPeriodStartDate);
  756.             $currDate->modify('-1 day');
  757.             $lastPeriodEndDate $currDate->format('Y-m-d');
  758.             $currDate->modify('-6 day');
  759.             $lastPeriodStartDate $currDate->format('Y-m-d');
  760.         } else if ($periodType == 'year') {
  761.             $thisPeriodEndDate $today->format('Y-m-d');
  762.             //            $thisWeekStartDate = date("Y-m-d", strtotime("previous saturday"));
  763.             $thisPeriodStartDate = ($today->format('Y')) . '-01-01';
  764.             $currDate = new \DateTime($thisPeriodStartDate);
  765.             $currDate->modify('-1 day');
  766.             $lastPeriodEndDate $currDate->format('Y-m-d');
  767.             $lastPeriodStartDate = ($currDate->format('Y')) . '-01-01';;
  768.         }
  769.         $companyListData = [];
  770.         foreach ($appIdList as $appId) {
  771.             //queryonly if mor ethan one app id
  772.             $skip 0;
  773.             if ($appId == $userAppId) {
  774.                 $connector $this->container->get('application_connector');
  775.                 $connector->resetConnection(
  776.                     'default',
  777.                     $session->get('gocDbName'),
  778.                     $session->get('gocDbUser'),
  779.                     $session->get('gocDbPass'),
  780.                     $session->get('gocDbHost'),
  781.                     $reset true
  782.                 );
  783.                 $em $this->getDoctrine()->getManager();
  784.             } else {
  785.                 $dataToConnect System::changeDoctrineManagerByAppId($this->getDoctrine()->getManager('company_group'), $gocEnabled$appId);
  786.                 $dataToConnectList[] = $dataToConnect;
  787.                 if (!empty($dataToConnect)) {
  788.                     $connector $this->container->get('application_connector');
  789.                     $connector->resetConnection(
  790.                         'default',
  791.                         $dataToConnect['dbName'],
  792.                         $dataToConnect['dbUser'],
  793.                         $dataToConnect['dbPass'],
  794.                         $dataToConnect['dbHost'],
  795.                         $reset true
  796.                     );
  797.                     $em $this->getDoctrine()->getManager();
  798.                 } else {
  799.                     $skip 1;
  800.                 }
  801.             }
  802.             if ($skip == 1)
  803.                 continue;
  804.             //                $companyListData[] = Company::getCompanyListWithImage($em);
  805.             //                $get_sql = "SELECT * FROM company ";
  806.             //                $stmt = $em->getConnection()->executeStatement($get_sql);
  807.             //                
  808.             //                $entries = $stmt;
  809.             //                $companyListData[] = $entries;
  810.             //                foreach ($companyIdListByAppId as $app_company_index)
  811.             if (isset($companyIdListByAppId[$appId])) {
  812.                 foreach ($companyIdListByAppId[$appId] as $app_company_index) {
  813.                     //exp vs rev
  814.                     if (in_array('expense_vs_revenue'$reportsToGet)) {
  815.                         $acHeadList = [];
  816.                         $companyId explode('_'$app_company_index)[1];
  817.                         $acHeadDataById = [];
  818.                         $thisBalanceDataByAcHead = [];
  819.                         $lastBalanceDataByAcHead = [];
  820.                         $mon_names = ["""January""February""March""April""May""June""July""August""September""October""November""December"];
  821.                         $limit 12;
  822.                         $get_kids_sql "SELECT expense, revenue, `date` summ_date
  823.                           FROM monthly_summary
  824.                             where monthly_summary.company_id=$companyId
  825.                             AND ( monthly_summary.branch_id=0 or monthly_summary.branch_id is null) ";
  826.                         //                               GROUP BY monthly_summary.`date`
  827.                         $get_kids_sql .= " ORDER BY monthly_summary.`date` DESC  limit " $limit;
  828.                         $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  829.                         
  830.                         $pl $stmt;
  831.                         $curr_date = new \DateTime();
  832.                         $curr_mon = ($curr_date->format('m'));
  833.                         $curr_year = ($curr_date->format('Y'));
  834.                         $object_list = [];
  835.                         $debug_list = [];
  836.                         $list = [];
  837.                         $timeStampList = [];
  838.                         //        $first
  839.                         foreach ($pl as $key => $entry) {
  840.                             $qryDate = new \DateTime($entry['summ_date']);
  841.                             $qrMon $qryDate->format('m');;
  842.                             $qrYr $qryDate->format('Y');;
  843.                             $object_list[$qrYr '_' $qrMon] = $entry;
  844.                         }
  845.                         for ($k 0$k 11$k++) {
  846.                             $debug_list[$k] = $curr_year '_' $curr_mon;
  847.                             $currTimeStamp strtotime($curr_year "-" $curr_mon '-1');
  848.                             $currTimeStampMili $currTimeStamp 1000;
  849.                             $cashAddition 0;
  850.                             $bankAddition 0;
  851.                             if (isset($object_list[$curr_year '_' $curr_mon])) {
  852.                                 $entry $object_list[$curr_year '_' $curr_mon];
  853.                                 $list['monthList'][] = $mon_names[$curr_mon];
  854.                                 $list['revenue'][] = round($entry['revenue']);
  855.                                 $list['tsCommaRevenue'][] = [$currTimeStampMiliround($entry['revenue'])];
  856.                                 $list['expense'][] = round($entry['expense']);
  857.                                 $list['tsCommaExpense'][] = [$currTimeStampMiliround($entry['expense'])];
  858.                             } else {
  859.                                 $list['monthList'][] = $mon_names[($curr_mon)];
  860.                                 $list['revenue'][] = 0;
  861.                                 $list['expense'][] = 0;
  862.                                 $list['tsCommaRevenue'][] = [$currTimeStampMili0];
  863.                                 $list['tsCommaExpense'][] = [$currTimeStampMili0];
  864.                             }
  865.                             $curr_mon--;
  866.                             if ($curr_mon <= 0) {
  867.                                 $curr_mon 12;
  868.                                 $curr_year--;
  869.                             }
  870.                             //new end
  871.                         }
  872.                         $data['expense_vs_revenue'][$app_company_index] = $list;
  873.                     }
  874.                     //cash and bank position
  875.                     if (in_array('cash_and_bank_position'$reportsToGet)) {
  876.                         $acHeadList = [];
  877.                         $companyId explode('_'$app_company_index)[1];
  878.                         $acHeadDataById = [];
  879.                         $thisBalanceDataByAcHead = [];
  880.                         $lastBalanceDataByAcHead = [];
  881.                         $bank_settings $em->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(array(
  882.                             'name' => 'bank_parents',
  883.                             //                        'CompanyId'=>$companyId
  884.                         ));
  885.                         $bank_id_list = [];
  886.                         if ($bank_settings)
  887.                             $bank_id_list json_decode($bank_settings->getData());
  888.                         $bank_child_id_list = [];
  889.                         $likeQuery '';
  890.                         foreach ($bank_id_list as $p) {
  891.                             $likeQuery .= "OR path_tree like '%/" $p "%/' ";
  892.                         }
  893.                         $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 ") ";
  894.                         $stmt $em->getConnection()->fetchAllAssociative($get_sql);
  895.                         
  896.                         $entries $stmt;
  897.                         foreach ($entries as $entry) {
  898.                             $has_payments 1;
  899.                             $bank_child_id_list[] = $entry['accounts_head_id'];
  900.                             $acHeadList[] = $entry['accounts_head_id'];
  901.                             $acHeadDataById[$entry['accounts_head_id']]['name'] = $entry['name'];
  902.                         }
  903.                         $cash_settings $em->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(array(
  904.                             'name' => 'cash_parents'
  905.                             //                        'CompanyId'=>$companyId
  906.                         ));
  907.                         $cash_id_list = [];
  908.                         if ($cash_settings)
  909.                             $cash_id_list json_decode($cash_settings->getData());
  910.                         $cash_child_id_list = [];
  911.                         $likeQuery '';
  912.                         foreach ($cash_id_list as $p) {
  913.                             $likeQuery .= "OR path_tree like '%/" $p "%/' ";
  914.                         }
  915.                         $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 ") ";
  916.                         $stmt $em->getConnection()->fetchAllAssociative($get_sql);
  917.                         
  918.                         $entries $stmt;
  919.                         foreach ($entries as $entry) {
  920.                             $has_payments 1;
  921.                             $cash_child_id_list[] = $entry['accounts_head_id'];
  922.                             $acHeadList[] = $entry['accounts_head_id'];
  923.                             $acHeadDataById[$entry['accounts_head_id']]['name'] = $entry['name'];
  924.                         }
  925.                         $thisBalance_data Accounts::GetBalanceOnDate($em$thisPeriodEndDate, []);
  926.                         $lastBalance_data Accounts::GetBalanceOnDate($em$lastPeriodEndDate, []);
  927.                         foreach ($acHeadList as $acHead) {
  928.                             $thisBalanceDataByAcHead[$acHead]['balance'] = $thisBalance_data[$acHead]['end_balance']['balance'];
  929.                             $lastBalanceDataByAcHead[$acHead]['balance'] = $lastBalance_data[$acHead]['end_balance']['balance'];
  930.                         }
  931.                         $thisReportData = array(
  932.                             'accountsHeadList' => $acHeadList,
  933.                             'acHeadDataById' => $acHeadDataById,
  934.                             'cash_child_id_list' => $cash_child_id_list,
  935.                             'bank_child_id_list' => $bank_child_id_list,
  936.                             'thisBalanceDataByAcHead' => $thisBalanceDataByAcHead,
  937.                             'lastBalanceDataByAcHead' => $lastBalanceDataByAcHead,
  938.                         );
  939.                         $data['cash_and_bank_position'][$app_company_index] = $thisReportData;
  940.                         //                    $companyListData[] = Company::getCompanyListWithImage($em);
  941.                     }
  942.                     //Expense Position
  943.                     if (in_array('expense_position'$reportsToGet)) {
  944.                         $acHeadList = [];
  945.                         $companyId explode('_'$app_company_index)[1];
  946.                         $acHeadDataById = [];
  947.                         $thisBalanceDataByAcHead = [];
  948.                         $lastBalanceDataByAcHead = [];
  949.                         $get_sql "SELECT * FROM acc_accounts_head WHERE acc_accounts_head.company_id=" $companyId "
  950.                         AND acc_accounts_head.head_level= 2 ";
  951.                         $stmt $em->getConnection()->fetchAllAssociative($get_sql);
  952.                         
  953.                         $entries $stmt;
  954.                         foreach ($entries as $entry) {
  955.                             $has_payments 1;
  956.                             $cash_child_id_list[] = $entry['accounts_head_id'];
  957.                             $acHeadList[] = $entry['accounts_head_id'];
  958.                             $acHeadDataById[$entry['accounts_head_id']]['name'] = $entry['name'];
  959.                         }
  960.                         $thisBalance_data Accounts::GetPeriodicDataByType($em$type 'exp'$level_to_group_by 1$parent_id_list = [], $expand_level 1$thisPeriodStartDate$thisPeriodEndDate'_during_', [], [], [], false);
  961.                         $lastBalance_data Accounts::GetPeriodicDataByType($em$type 'exp'$level_to_group_by 1$parent_id_list = [], $expand_level 1$lastPeriodStartDate$lastPeriodEndDate'_during_', [], [], [], false);
  962.                         $skipHeadIds = [];
  963.                         foreach ($thisBalance_data as $parentHead => $balanceData) {
  964.                             foreach ($balanceData['data'] as $acHead => $headData) {
  965.                                 if (!in_array($acHead$acHeadList))
  966.                                     continue;
  967.                                 $thisBalanceDataByAcHead[$acHead]['balance'] = $headData['head_balance'];
  968.                                 if (isset($lastBalance_data[$parentHead])) {
  969.                                     if (isset($lastBalance_data[$parentHead]['data'][$acHead]))
  970.                                         $lastBalanceDataByAcHead[$acHead]['balance'] = $lastBalance_data[$parentHead]['data'][$acHead]['head_balance'];
  971.                                     else
  972.                                         $lastBalanceDataByAcHead[$acHead]['balance'] = 0;
  973.                                 } else
  974.                                     $lastBalanceDataByAcHead[$acHead]['balance'] = 0;
  975.                                 $skipHeadIds[] = $acHead;
  976.                             }
  977.                         }
  978.                         foreach ($lastBalance_data as $parentHead => $balanceData) {
  979.                             foreach ($balanceData['data'] as $acHead => $headData) {
  980.                                 if (in_array($acHead$skipHeadIds))
  981.                                     continue;
  982.                                 if (!in_array($acHead$acHeadList))
  983.                                     continue;
  984.                                 $lastBalanceDataByAcHead[$acHead]['balance'] = $headData['head_balance'];
  985.                                 if (isset($thisBalance_data[$parentHead])) {
  986.                                     if (isset($thisBalance_data[$parentHead]['data'][$acHead]))
  987.                                         $thisBalanceDataByAcHead[$acHead]['balance'] = $thisBalance_data[$parentHead]['data'][$acHead]['head_balance'];
  988.                                     else
  989.                                         $thisBalanceDataByAcHead[$acHead]['balance'] = 0;
  990.                                 } else
  991.                                     $thisBalanceDataByAcHead[$acHead]['balance'] = 0;
  992.                                 $skipHeadIds[] = $acHead;
  993.                             }
  994.                         }
  995.                         $thisReportData = array(
  996.                             'accountsHeadList' => $acHeadList,
  997.                             //                            'thisBalance_data' => $thisBalance_data,
  998.                             'confirmedHeadList' => $skipHeadIds,
  999.                             'acHeadDataById' => $acHeadDataById,
  1000.                             'thisBalanceDataByAcHead' => $thisBalanceDataByAcHead,
  1001.                             'lastBalanceDataByAcHead' => $lastBalanceDataByAcHead,
  1002.                         );
  1003.                         $data['expense_position'][$app_company_index] = $thisReportData;
  1004.                         //                    $companyListData[] = Company::getCompanyListWithImage($em);
  1005.                     }
  1006.                     //Payable Position
  1007.                     if (in_array('payable_position'$reportsToGet)) {
  1008.                         $acHeadList = [];
  1009.                         $companyId explode('_'$app_company_index)[1];
  1010.                         $acHeadDataById = [];
  1011.                         $thisBalanceDataByAcHead = [];
  1012.                         $lastBalanceDataByAcHead = [];
  1013.                         $filter_settings $em->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(array(
  1014.                             'name' => 'payable_parents',
  1015.                             //                        'CompanyId'=>$companyId
  1016.                         ));
  1017.                         $filter_head_parents_id_list = [];
  1018.                         if ($filter_settings)
  1019.                             $filter_head_parents_id_list json_decode($filter_settings->getData());
  1020.                         $likeQuery '';
  1021.                         foreach ($filter_head_parents_id_list as $p) {
  1022.                             $likeQuery .= "OR path_tree like '%/" $p "%/' ";
  1023.                         }
  1024.                         $get_sql "SELECT * FROM acc_accounts_head WHERE acc_accounts_head.company_id=" $companyId "
  1025.                          and (1=0 " $likeQuery ") ";
  1026.                         $stmt $em->getConnection()->fetchAllAssociative($get_sql);
  1027.                         
  1028.                         $entries $stmt;
  1029.                         foreach ($entries as $entry) {
  1030.                             $has_payments 1;
  1031.                             $acHeadList[] = $entry['accounts_head_id'];
  1032.                             $acHeadDataById[$entry['accounts_head_id']]['name'] = $entry['name'];
  1033.                         }
  1034.                         //                        $get_sql = "SELECT * FROM acc_accounts_head WHERE acc_accounts_head.company_id=" . $companyId . "
  1035.                         //                        AND acc_accounts_head.head_level= 2 and acc_accounts_head.type='lib'";
  1036.                         //
  1037.                         //                        $stmt = $em->getConnection()->executeStatement($get_sql);
  1038.                         //                        
  1039.                         //                        $entries = $stmt;
  1040.                         //
  1041.                         //                        foreach ($entries as $entry) {
  1042.                         //                            $has_payments = 1;
  1043.                         //                            $cash_child_id_list[] = $entry['accounts_head_id'];
  1044.                         //                            $acHeadList[] = $entry['accounts_head_id'];
  1045.                         //                            $acHeadDataById[$entry['accounts_head_id']]['name'] = $entry['name'];
  1046.                         //                        }
  1047.                         $thisBalance_data Accounts::GetPeriodicDataByType($em$type 'lib'$level_to_group_by 2$parent_id_list = [], $expand_level 1$thisPeriodStartDate$thisPeriodEndDate'_during_', [], [], [], false);
  1048.                         $lastBalance_data Accounts::GetPeriodicDataByType($em$type 'lib'$level_to_group_by 2$parent_id_list = [], $expand_level 1$lastPeriodStartDate$lastPeriodEndDate'_during_', [], [], [], false);
  1049.                         $skipHeadIds = [];
  1050.                         foreach ($thisBalance_data as $parentHead => $balanceData) {
  1051.                             foreach ($balanceData['data'] as $acHead => $headData) {
  1052.                                 if (!(in_array($acHead$acHeadList)))
  1053.                                     continue;
  1054.                                 if ($headData['head_level'] > 4)
  1055.                                     continue;
  1056.                                 //                                $thisBalanceDataByAcHead[$acHead]['balance'] = $headData['head_balance'];
  1057.                                 $thisBalanceDataByAcHead[$acHead]['balance'] = $headData['end_balance']['balance'];
  1058.                                 if (isset($lastBalance_data[$parentHead])) {
  1059.                                     if (isset($lastBalance_data[$parentHead]['data'][$acHead]))
  1060.                                         //                                        $lastBalanceDataByAcHead[$acHead]['balance'] = $lastBalance_data[$parentHead]['data'][$acHead]['head_balance'];
  1061.                                         $lastBalanceDataByAcHead[$acHead]['balance'] = $lastBalance_data[$parentHead]['data'][$acHead]['end_balance']['balance'];
  1062.                                     else
  1063.                                         $lastBalanceDataByAcHead[$acHead]['balance'] = 0;
  1064.                                 } else
  1065.                                     $lastBalanceDataByAcHead[$acHead]['balance'] = 0;
  1066.                                 $skipHeadIds[] = $acHead;
  1067.                             }
  1068.                         }
  1069.                         foreach ($lastBalance_data as $parentHead => $balanceData) {
  1070.                             foreach ($balanceData['data'] as $acHead => $headData) {
  1071.                                 if (in_array($acHead$skipHeadIds))
  1072.                                     continue;
  1073.                                 if (!in_array($acHead$acHeadList))
  1074.                                     continue;
  1075.                                 if ($headData['head_level'] > 4)
  1076.                                     continue;
  1077.                                 $lastBalanceDataByAcHead[$acHead]['balance'] = $headData['end_balance']['balance'];
  1078.                                 if (isset($thisBalance_data[$parentHead])) {
  1079.                                     if (isset($thisBalance_data[$parentHead]['data'][$acHead]))
  1080.                                         $thisBalanceDataByAcHead[$acHead]['balance'] = $thisBalance_data[$parentHead]['data'][$acHead]['end_balance']['balance'];
  1081.                                     else
  1082.                                         $thisBalanceDataByAcHead[$acHead]['balance'] = 0;
  1083.                                 } else
  1084.                                     $thisBalanceDataByAcHead[$acHead]['balance'] = 0;
  1085.                                 $skipHeadIds[] = $acHead;
  1086.                             }
  1087.                         }
  1088.                         $thisReportData = array(
  1089.                             'accountsHeadList' => $acHeadList,
  1090.                             //                            'thisBalance_data' => $thisBalance_data,
  1091.                             'confirmedHeadList' => $skipHeadIds,
  1092.                             'acHeadDataById' => $acHeadDataById,
  1093.                             'thisBalanceDataByAcHead' => $thisBalanceDataByAcHead,
  1094.                             'lastBalanceDataByAcHead' => $lastBalanceDataByAcHead,
  1095.                         );
  1096.                         $data['payable_position'][$app_company_index] = $thisReportData;
  1097.                         //                    $companyListData[] = Company::getCompanyListWithImage($em);
  1098.                     }
  1099.                     //Receivable Position
  1100.                     if (in_array('receivable_position'$reportsToGet)) {
  1101.                         $acHeadList = [];
  1102.                         $companyId explode('_'$app_company_index)[1];
  1103.                         $acHeadDataById = [];
  1104.                         $thisBalanceDataByAcHead = [];
  1105.                         $lastBalanceDataByAcHead = [];
  1106.                         //                        $filter_settings = $em->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(array(
  1107.                         //                            'name' => 'receivable_parents',
  1108.                         ////                        'CompanyId'=>$companyId
  1109.                         //                        ));
  1110.                         //                        $filter_head_parents_id_list = [];
  1111.                         //                        if ($filter_settings)
  1112.                         //                            $filter_head_parents_id_list = json_decode($filter_settings->getData());
  1113.                         //                        $likeQuery = '';
  1114.                         //                        foreach ($filter_head_parents_id_list as $p) {
  1115.                         //                            $likeQuery .= "OR path_tree like '%/" . $p . "%/' ";
  1116.                         //                        }
  1117.                         //                        $get_sql = "SELECT * FROM acc_accounts_head WHERE acc_accounts_head.company_id=" . $companyId . "
  1118.                         //                         and (1=0 " . $likeQuery . ") ";
  1119.                         $get_sql "SELECT acc_accounts_head.*  FROM acc_accounts_head
  1120.  WHERE acc_accounts_head.company_id=" $companyId "
  1121.                          and  ( acc_accounts_head.accounts_head_id in (select distinct accounts_head_id from acc_clients)
  1122.                           OR acc_accounts_head.accounts_head_id in (select distinct advance_head_id from acc_clients)
  1123.                          ) ";
  1124.                         $stmt $em->getConnection()->fetchAllAssociative($get_sql);
  1125.                         
  1126.                         $entries $stmt;
  1127.                         $account_head_ids_by_client_type = [];
  1128.                         foreach ($entries as $entry) {
  1129.                             $has_payments 1;
  1130.                             $acHeadList[] = $entry['accounts_head_id'];
  1131.                             $acHeadDataById[$entry['accounts_head_id']]['name'] = $entry['name'];
  1132.                         }
  1133.                         $get_sql "SELECT acc_clients.*  FROM acc_clients
  1134.  WHERE acc_clients.company_id=" $companyId;
  1135.                         $stmt $em->getConnection()->fetchAllAssociative($get_sql);
  1136.                         
  1137.                         $entries $stmt;
  1138.                         $clientTypeListArray Client::ClientTypeList($em, [$companyId], true);
  1139.                         $clientTypesOfHeads = [];
  1140.                         foreach ($entries as $entry) {
  1141.                             if (!isset($account_head_ids_by_client_type[$entry['type']]))
  1142.                                 $account_head_ids_by_client_type[$entry['type']] = [];
  1143.                             $account_head_ids_by_client_type[$entry['type']][] = $entry['accounts_head_id'];
  1144.                             $clientTypesOfHeads[$entry['accounts_head_id']] = $entry['type'];
  1145.                             if ($entry['accounts_head_id'] != $entry['advance_head_id']) {
  1146.                                 $account_head_ids_by_client_type[$entry['type']][] = $entry['advance_head_id'];
  1147.                                 $clientTypesOfHeads[$entry['advance_head_id']] = $entry['type'];
  1148.                             }
  1149.                         }
  1150.                         //                        $get_sql = "SELECT * FROM acc_accounts_head WHERE acc_accounts_head.company_id=" . $companyId . "
  1151.                         //                        AND acc_accounts_head.head_level= 2 and acc_accounts_head.type='lib'";
  1152.                         //
  1153.                         //                        $stmt = $em->getConnection()->executeStatement($get_sql);
  1154.                         //                        
  1155.                         //                        $entries = $stmt;
  1156.                         //
  1157.                         //                        foreach ($entries as $entry) {
  1158.                         //                            $has_payments = 1;
  1159.                         //                            $cash_child_id_list[] = $entry['accounts_head_id'];
  1160.                         //                            $acHeadList[] = $entry['accounts_head_id'];
  1161.                         //                            $acHeadDataById[$entry['accounts_head_id']]['name'] = $entry['name'];
  1162.                         //                        }
  1163.                         $thisBalance_data Accounts::GetPeriodicDataByType($em$type 'ast'$level_to_group_by 2$parent_id_list = [], $expand_level 1$thisPeriodStartDate$thisPeriodEndDate'_during_', [], [], [], true);
  1164.                         $lastBalance_data Accounts::GetPeriodicDataByType($em$type 'ast'$level_to_group_by 2$parent_id_list = [], $expand_level 1$lastPeriodStartDate$lastPeriodEndDate'_during_', [], [], [], true);
  1165.                         $skipHeadIds = [];
  1166.                         $thisBalanceDataByClientType = [];
  1167.                         $lastBalanceDataByClientType = [];
  1168.                         foreach ($clientTypeListArray as $ct) {
  1169.                             $thisBalanceDataByClientType[$ct['id']] = 0;
  1170.                             $lastBalanceDataByClientType[$ct['id']] = 0;
  1171.                         }
  1172.                         foreach ($thisBalance_data as $parentHead => $balanceData) {
  1173.                             foreach ($balanceData['data'] as $acHead => $headData) {
  1174.                                 if (!(in_array($acHead$acHeadList)))
  1175.                                     continue;
  1176.                                 //                                if ($headData['head_level'] > 4)
  1177.                                 //                                    continue;
  1178.                                 $thisBalanceDataByAcHead[$acHead]['balance'] = $headData['end_balance']['balance'];
  1179.                                 if (isset($lastBalance_data[$parentHead])) {
  1180.                                     if (isset($lastBalance_data[$parentHead]['data'][$acHead]))
  1181.                                         $lastBalanceDataByAcHead[$acHead]['balance'] = $lastBalance_data[$parentHead]['data'][$acHead]['end_balance']['balance'];
  1182.                                     else
  1183.                                         $lastBalanceDataByAcHead[$acHead]['balance'] = 0;
  1184.                                 } else
  1185.                                     $lastBalanceDataByAcHead[$acHead]['balance'] = 0;
  1186.                                 if (!isset($thisBalanceDataByClientType[$clientTypesOfHeads[$acHead]]))
  1187.                                     $thisBalanceDataByClientType[$clientTypesOfHeads[$acHead]] = $headData['end_balance']['balance'];
  1188.                                 else
  1189.                                     $thisBalanceDataByClientType[$clientTypesOfHeads[$acHead]] += $headData['end_balance']['balance'];
  1190.                                 if (!isset($lastBalanceDataByClientType[$clientTypesOfHeads[$acHead]]))
  1191.                                     $lastBalanceDataByClientType[$clientTypesOfHeads[$acHead]] = 0;
  1192.                                 else
  1193.                                     $lastBalanceDataByClientType[$clientTypesOfHeads[$acHead]] += $lastBalance_data[$parentHead]['data'][$acHead]['end_balance']['balance'];
  1194.                                 $skipHeadIds[] = $acHead;
  1195.                             }
  1196.                         }
  1197.                         foreach ($lastBalance_data as $parentHead => $balanceData) {
  1198.                             foreach ($balanceData['data'] as $acHead => $headData) {
  1199.                                 if (in_array($acHead$skipHeadIds))
  1200.                                     continue;
  1201.                                 if (!in_array($acHead$acHeadList))
  1202.                                     continue;
  1203.                                 //                                if ($headData['head_level'] > 4)
  1204.                                 //                                    continue;
  1205.                                 $lastBalanceDataByAcHead[$acHead]['balance'] = $headData['end_balance']['balance'];
  1206.                                 if (isset($thisBalance_data[$parentHead])) {
  1207.                                     if (isset($thisBalance_data[$parentHead]['data'][$acHead]))
  1208.                                         $thisBalanceDataByAcHead[$acHead]['balance'] = $thisBalance_data[$parentHead]['data'][$acHead]['end_balance']['balance'];
  1209.                                     else
  1210.                                         $thisBalanceDataByAcHead[$acHead]['balance'] = 0;
  1211.                                 } else
  1212.                                     $thisBalanceDataByAcHead[$acHead]['balance'] = 0;
  1213.                                 if (!isset($lastBalanceDataByClientType[$clientTypesOfHeads[$acHead]]))
  1214.                                     $lastBalanceDataByClientType[$clientTypesOfHeads[$acHead]] = $headData['end_balance']['balance'];
  1215.                                 else
  1216.                                     $lastBalanceDataByClientType[$clientTypesOfHeads[$acHead]] += $headData['end_balance']['balance'];
  1217.                                 if (!isset($thisBalanceDataByClientType[$clientTypesOfHeads[$acHead]]))
  1218.                                     $thisBalanceDataByClientType[$clientTypesOfHeads[$acHead]] = 0;
  1219.                                 $skipHeadIds[] = $acHead;
  1220.                             }
  1221.                         }
  1222.                         $thisReportData = array(
  1223.                             //                            'accountsHeadList' => $acHeadList,
  1224.                             //                            'thisBalance_data' => $thisBalance_data,
  1225.                             //                            'confirmedHeadList' => $skipHeadIds,
  1226.                             //                            'acHeadDataById' => $acHeadDataById,
  1227.                             'thisBalance_data' => $thisBalance_data,
  1228.                             'lastBalance_data' => $lastBalance_data,
  1229.                             'thisBalanceDataByAcHead' => $thisBalanceDataByAcHead,
  1230.                             'lastBalanceDataByAcHead' => $lastBalanceDataByAcHead,
  1231.                             'clientTypeListArray' => $clientTypeListArray,
  1232.                             'thisBalanceDataByClientType' => $thisBalanceDataByClientType,
  1233.                             'lastBalanceDataByClientType' => $lastBalanceDataByClientType,
  1234.                         );
  1235.                         $data['receivable_position'][$app_company_index] = $thisReportData;
  1236.                         //                    $companyListData[] = Company::getCompanyListWithImage($em);
  1237.                     }
  1238.                     //Sales Position
  1239.                     if (in_array('sales_position'$reportsToGet)) {
  1240.                         $acHeadList = [];
  1241.                         $companyId explode('_'$app_company_index)[1];
  1242.                         $acHeadDataById = [];
  1243.                         $thisBalanceDataByClientType = [];
  1244.                         $lastBalanceDataByClientType = [];
  1245.                         $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
  1246.   FROM sales_invoice
  1247.   join acc_clients on acc_clients.client_id=sales_invoice.client_id
  1248.   join client_type on acc_clients.type=client_type.client_type_id
  1249.    WHERE sales_invoice.company_id=" $companyId " AND sales_invoice.approved=1
  1250.                           AND sales_invoice_date between '" $thisPeriodStartDate " 00:00:00' and '" $thisPeriodEndDate " 23:59:59.999'
  1251.                           GROUP BY client_type.client_type_id
  1252.                           ";
  1253.                         $stmt $em->getConnection()->fetchAllAssociative($get_sql);
  1254.                         
  1255.                         $entries $stmt;
  1256.                         $clientTypes = [];
  1257.                         $clientTypeNames = [];
  1258.                         $get_sql_1 $get_sql;
  1259.                         foreach ($entries as $entry) {
  1260.                             $has_payments 1;
  1261.                             $thisBalanceDataByClientType[$entry['client_type_id']] = $entry;
  1262.                             $lastBalanceDataByClientType[$entry['client_type_id']]['sales_amount'] = 0//just for the lulz
  1263.                             if (!in_array($entry['client_type_id'], $clientTypes)) {
  1264.                                 $clientTypes[] = $entry['client_type_id'];
  1265.                                 $clientTypeNames[$entry['client_type_id']] = $entry['name'];
  1266.                             }
  1267.                         }
  1268.                         $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
  1269.   FROM sales_invoice
  1270.   join acc_clients on acc_clients.client_id=sales_invoice.client_id
  1271.   join client_type on acc_clients.type=client_type.client_type_id
  1272.    WHERE sales_invoice.company_id=" $companyId " AND sales_invoice.approved=1
  1273.                           AND sales_invoice_date between '" $lastPeriodStartDate " 00:00:00' and '" $lastPeriodEndDate " 23:59:59.999'
  1274.                           GROUP BY client_type.client_type_id
  1275.                           ";
  1276.                         $stmt $em->getConnection()->fetchAllAssociative($get_sql);
  1277.                         
  1278.                         $entries $stmt;
  1279.                         foreach ($entries as $entry) {
  1280.                             $has_payments 1;
  1281.                             $lastBalanceDataByClientType[$entry['client_type_id']] = $entry;
  1282.                             if (!isset($thisBalanceDataByClientType[$entry['client_type_id']]))
  1283.                                 $thisBalanceDataByClientType[$entry['client_type_id']]['sales_amount'] = 0//just for the lulz
  1284.                             if (!in_array($entry['client_type_id'], $clientTypes)) {
  1285.                                 $clientTypes[] = $entry['client_type_id'];
  1286.                                 $clientTypeNames[$entry['client_type_id']] = $entry['name'];
  1287.                             }
  1288.                         }
  1289.                         $skipHeadIds = [];
  1290.                         $thisReportData = array(
  1291.                             'clientTypes' => $clientTypes,
  1292.                             //                            'get_sql_1' => $get_sql_1,
  1293.                             //                            'get_sql' => $get_sql,
  1294.                             'clientTypeNames' => $clientTypeNames,
  1295.                             'thisBalanceDataByClientType' => $thisBalanceDataByClientType,
  1296.                             'lastBalanceDataByClientType' => $lastBalanceDataByClientType,
  1297.                         );
  1298.                         $data['sales_position'][$app_company_index] = $thisReportData;
  1299.                         //                    $companyListData[] = Company::getCompanyListWithImage($em);
  1300.                     }
  1301.                     //Collection Position
  1302.                     if (in_array('collection_position'$reportsToGet)) {
  1303.                         $acHeadList = [];
  1304.                         $companyId explode('_'$app_company_index)[1];
  1305.                         $acHeadDataById = [];
  1306.                         $thisBalanceDataByClientType = [];
  1307.                         $lastBalanceDataByClientType = [];
  1308.                         $allocationSourceSql $this->buildAllocationAwareTransactionSourceSql(array(
  1309.                             'document_type' => 6,
  1310.                             'start_date' => $thisPeriodStartDate,
  1311.                             'end_date' => $thisPeriodEndDate,
  1312.                             'approved' => 1,
  1313.                             'ledger_hit' => 1,
  1314.                         ));
  1315.                         $get_sql "SELECT SUM(CASE WHEN alloc_rows.position = 'cr' THEN alloc_rows.allocation_amount ELSE 0 END) positive_amount,
  1316. SUM(CASE WHEN alloc_rows.position = 'dr' THEN alloc_rows.allocation_amount ELSE 0 END) negative_amount,client_type.client_type_id, client_type.name, acc_clients.client_id, acc_clients.type
  1317.  FROM " $allocationSourceSql " alloc_rows
  1318.    join acc_clients on acc_clients.accounts_head_id=alloc_rows.accounts_head_id or acc_clients.advance_head_id=alloc_rows.accounts_head_id
  1319.   join client_type on acc_clients.type=client_type.client_type_id
  1320.   WHERE acc_clients.company_id=" $companyId "
  1321.                               GROUP BY client_type.client_type_id";
  1322.                         $stmt $em->getConnection()->fetchAllAssociative($get_sql);
  1323.                         
  1324.                         $entries $stmt;
  1325.                         $clientTypes = [];
  1326.                         $clientTypeNames = [];
  1327.                         foreach ($entries as $entry) {
  1328.                             $has_payments 1;
  1329.                             $thisBalanceDataByClientType[$entry['client_type_id']] = $entry;
  1330.                             $lastBalanceDataByClientType[$entry['client_type_id']]['collection_amount'] = 0//just for the lulz
  1331.                             $thisBalanceDataByClientType[$entry['client_type_id']]['collection_amount'] = $entry['positive_amount'] - $entry['negative_amount'];
  1332.                             if (!in_array($entry['client_type_id'], $clientTypes)) {
  1333.                                 $clientTypes[] = $entry['client_type_id'];
  1334.                                 $clientTypeNames[$entry['client_type_id']] = $entry['name'];
  1335.                             }
  1336.                         }
  1337.                         $allocationSourceSql $this->buildAllocationAwareTransactionSourceSql(array(
  1338.                             'document_type' => 6,
  1339.                             'start_date' => $lastPeriodStartDate,
  1340.                             'end_date' => $lastPeriodEndDate,
  1341.                             'approved' => 1,
  1342.                             'ledger_hit' => 1,
  1343.                         ));
  1344.                         $get_sql "SELECT SUM(CASE WHEN alloc_rows.position = 'cr' THEN alloc_rows.allocation_amount ELSE 0 END) positive_amount,
  1345. SUM(CASE WHEN alloc_rows.position = 'dr' THEN alloc_rows.allocation_amount ELSE 0 END) negative_amount,client_type.client_type_id, client_type.name, acc_clients.client_id, acc_clients.type
  1346.  FROM " $allocationSourceSql " alloc_rows
  1347.    join acc_clients on acc_clients.accounts_head_id=alloc_rows.accounts_head_id or acc_clients.advance_head_id=alloc_rows.accounts_head_id
  1348.   join client_type on acc_clients.type=client_type.client_type_id
  1349.   WHERE acc_clients.company_id=" $companyId "
  1350.                               GROUP BY client_type.client_type_id";
  1351.                         $stmt $em->getConnection()->fetchAllAssociative($get_sql);
  1352.                         
  1353.                         $entries $stmt;
  1354.                         foreach ($entries as $entry) {
  1355.                             $has_payments 1;
  1356.                             $lastBalanceDataByClientType[$entry['client_type_id']] = $entry;
  1357.                             $lastBalanceDataByClientType[$entry['client_type_id']]['collection_amount'] = $entry['positive_amount'] - $entry['negative_amount'];
  1358.                             if (!isset($thisBalanceDataByClientType[$entry['client_type_id']]))
  1359.                                 $thisBalanceDataByClientType[$entry['client_type_id']]['collection_amount'] = 0//just for the lulz
  1360.                             if (!in_array($entry['client_type_id'], $clientTypes)) {
  1361.                                 $clientTypes[] = $entry['client_type_id'];
  1362.                                 $clientTypeNames[$entry['client_type_id']] = $entry['name'];
  1363.                             }
  1364.                         }
  1365.                         $skipHeadIds = [];
  1366.                         $thisReportData = array(
  1367.                             'clientTypes' => $clientTypes,
  1368.                             'clientTypeNames' => $clientTypeNames,
  1369.                             'thisBalanceDataByClientType' => $thisBalanceDataByClientType,
  1370.                             'lastBalanceDataByClientType' => $lastBalanceDataByClientType,
  1371.                         );
  1372.                         $data['collection_position'][$app_company_index] = $thisReportData;
  1373.                         //                    $companyListData[] = Company::getCompanyListWithImage($em);
  1374.                     }
  1375.                     //Return Position
  1376.                     if (in_array('market_return_position'$reportsToGet)) {
  1377.                         $acHeadList = [];
  1378.                         $companyId explode('_'$app_company_index)[1];
  1379.                         $acHeadDataById = [];
  1380.                         $thisBalanceDataByClientType = [];
  1381.                         $lastBalanceDataByClientType = [];
  1382.                         $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
  1383.   FROM irr_item
  1384.   join item_received_replacement on item_received_replacement.irr_id=irr_item.irr_id
  1385.   join acc_clients on acc_clients.client_id=item_received_replacement.client_id
  1386.   join client_type on acc_clients.type=client_type.client_type_id
  1387.    WHERE item_received_replacement.company_id=" $companyId " AND item_received_replacement.approved=1
  1388.                           AND item_received_replacement.irr_date between '" $thisPeriodStartDate " 00:00:00' and '" $thisPeriodEndDate " 23:59:59.999'
  1389.                           GROUP BY client_type.client_type_id
  1390.                           ";
  1391.                         $stmt $em->getConnection()->fetchAllAssociative($get_sql);
  1392.                         
  1393.                         $entries $stmt;
  1394.                         $clientTypes = [];
  1395.                         $clientTypeNames = [];
  1396.                         $get_sql_1 $get_sql;
  1397.                         foreach ($entries as $entry) {
  1398.                             $has_payments 1;
  1399.                             $thisBalanceDataByClientType[$entry['client_type_id']] = $entry;
  1400.                             $lastBalanceDataByClientType[$entry['client_type_id']]['return_amount'] = 0//just for the lulz
  1401.                             if (!in_array($entry['client_type_id'], $clientTypes)) {
  1402.                                 $clientTypes[] = $entry['client_type_id'];
  1403.                                 $clientTypeNames[$entry['client_type_id']] = $entry['name'];
  1404.                             }
  1405.                         }
  1406.                         $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
  1407.   FROM irr_item
  1408.   join item_received_replacement on item_received_replacement.irr_id=irr_item.irr_id
  1409.   join acc_clients on acc_clients.client_id=item_received_replacement.client_id
  1410.   join client_type on acc_clients.type=client_type.client_type_id
  1411.    WHERE item_received_replacement.company_id=" $companyId " AND item_received_replacement.approved=1
  1412.                           AND item_received_replacement.irr_date between '" $lastPeriodStartDate " 00:00:00' and '" $lastPeriodEndDate " 23:59:59.999'
  1413.                           GROUP BY client_type.client_type_id
  1414.                           ";
  1415.                         $stmt $em->getConnection()->fetchAllAssociative($get_sql);
  1416.                         
  1417.                         $entries $stmt;
  1418.                         foreach ($entries as $entry) {
  1419.                             $has_payments 1;
  1420.                             $lastBalanceDataByClientType[$entry['client_type_id']] = $entry;
  1421.                             if (!isset($thisBalanceDataByClientType[$entry['client_type_id']]))
  1422.                                 $thisBalanceDataByClientType[$entry['client_type_id']]['return_amount'] = 0//just for the lulz
  1423.                             if (!in_array($entry['client_type_id'], $clientTypes)) {
  1424.                                 $clientTypes[] = $entry['client_type_id'];
  1425.                                 $clientTypeNames[$entry['client_type_id']] = $entry['name'];
  1426.                             }
  1427.                         }
  1428.                         $skipHeadIds = [];
  1429.                         $thisReportData = array(
  1430.                             'clientTypes' => $clientTypes,
  1431.                             //                            'get_sql_1' => $get_sql_1,
  1432.                             //                            'get_sql' => $get_sql,
  1433.                             'clientTypeNames' => $clientTypeNames,
  1434.                             'thisBalanceDataByClientType' => $thisBalanceDataByClientType,
  1435.                             'lastBalanceDataByClientType' => $lastBalanceDataByClientType,
  1436.                         );
  1437.                         $data['market_return_position'][$app_company_index] = $thisReportData;
  1438.                         //                    $companyListData[] = Company::getCompanyListWithImage($em);
  1439.                     }
  1440.                     //order and client count
  1441.                     if (in_array('order_and_client_count'$reportsToGet)) {
  1442.                         $acHeadList = [];
  1443.                         $companyId explode('_'$app_company_index)[1];
  1444.                         $acHeadDataById = [];
  1445.                         $thisBalanceDataByAcHead = [];
  1446.                         $lastBalanceDataByAcHead = [];
  1447.                         $today = new \DateTime();
  1448.                         $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' ";
  1449.                         $stmt $em->getConnection()->fetchAllAssociative($get_sql);
  1450.                         
  1451.                         $entries1 $stmt;
  1452.                         $get_sql "SELECT count(client_id) total_clients FROM acc_clients WHERE acc_clients.company_id=" $companyId;
  1453.                         $stmt $em->getConnection()->fetchAllAssociative($get_sql);
  1454.                         
  1455.                         $entries2 $stmt;
  1456.                         $currCompanyData Company::getCompanyData($em$session->get(UserConstants::USER_COMPANY_ID$companyId));
  1457.                         $allocationSourceSql $this->buildAllocationAwareTransactionSourceSql(array(
  1458.                             'document_type' => 6,
  1459.                             'company_id' => $companyId,
  1460.                             'start_date' => $thisPeriodStartDate,
  1461.                             'end_date' => $thisPeriodEndDate,
  1462.                             'approved' => 1,
  1463.                             'ledger_hit' => 1,
  1464.                         ));
  1465.                         $get_sql "SELECT SUM(CASE WHEN alloc_rows.position = 'cr' THEN alloc_rows.allocation_amount ELSE ((-1)*alloc_rows.allocation_amount) END) total_collection_amount, alloc_rows.document_hash FROM " $allocationSourceSql " alloc_rows
  1466.                         join acc_clients on acc_clients.accounts_head_id=alloc_rows.accounts_head_id or acc_clients.advance_head_id=alloc_rows.accounts_head_id
  1467.                         WHERE acc_clients.company_id=" $companyId " ";
  1468.                         $stmt $em->getConnection()->fetchAllAssociative($get_sql);
  1469.                         
  1470.                         $entries3 $stmt;
  1471.                         //
  1472.                         //                        $get_sql = "SELECT (select  c.balance last_balance from inv_closing_balance c
  1473.                         //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
  1474.                         //from inv_closing_balance a
  1475.                         //                        where a.warehouse_id in (select distinct id from warehouse
  1476.                         //                        WHERE  warehouse.company_id=" . $companyId . ") and  a.date between '" . $thisPeriodStartDate . " 00:00:00' and '" . $thisPeriodEndDate . " 23:59:59.999' ";
  1477.                         $get_sql "SELECT a.* , (select  c.balance last_balance from inv_closing_balance c
  1478. 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
  1479. from inv_closing_balance a
  1480. where a.warehouse_id in (select distinct id from warehouse
  1481.                       WHERE  warehouse.company_id=" $companyId ") ";
  1482.                         $stmt $em->getConnection()->fetchAllAssociative($get_sql);
  1483.                         
  1484.                         $entries4 $stmt;
  1485.                         $currCompanyData Company::getCompanyData($em$session->get(UserConstants::USER_COMPANY_ID$companyId));
  1486.                         $total_stock_amount 0;
  1487.                         foreach ($entries4 as $ent) {
  1488.                             $total_stock_amount += $ent['last_balance'];
  1489.                         }
  1490.                         $thisReportData = array(
  1491.                             //                            'total_stock_amount' => empty($entries3) ? 0 : $entries4[0]['total_stock_amount'],
  1492.                             'total_stock_amount' => $total_stock_amount,
  1493.                             'total_collection_amount' => empty($entries3) ? $entries3[0]['total_collection_amount'],
  1494.                             'total_so_count' => empty($entries1) ? $entries1[0]['total_so_count'],
  1495.                             'total_so_amount' => empty($entries1) ? $entries1[0]['total_so_amount'],
  1496.                             'total_invoice_amount' => empty($entries1) ? $entries1[0]['total_invoice_amount'],
  1497.                             'total_receivable' => $currCompanyData->getReceivable(),
  1498.                             'total_payable' => $currCompanyData->getPayable(),
  1499.                             'total_clients' => empty($entries2) ? $entries2[0]['total_clients'],
  1500.                         );
  1501.                         $data['order_and_client_count'][$app_company_index] = $thisReportData;
  1502.                         //                    $companyListData[] = Company::getCompanyListWithImage($em);
  1503.                     }
  1504.                     //Inventory Position
  1505.                     if (in_array('inventory_position'$reportsToGet)) {
  1506.                         $acHeadList = [];
  1507.                         $companyId explode('_'$app_company_index)[1];
  1508.                         $acHeadDataById = [];
  1509.                         $thisBalanceDataByActionTag = [];
  1510.                         $lastBalanceDataByActionTag = [];
  1511.                         $warehouseList Inventory::warehouse_action_list($em$companyId$method 'object');
  1512.                         $get_sql "SELECT a.* , (select  c.balance last_balance from inv_closing_balance c
  1513. 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
  1514. from inv_closing_balance a
  1515. where a.warehouse_id in (select distinct id from warehouse
  1516.                        WHERE  warehouse.company_id=" $companyId ") ";
  1517.                         $stmt $em->getConnection()->fetchAllAssociative($get_sql);
  1518.                         
  1519.                         $entries $stmt;
  1520.                         $confirmed_action_ids = [];
  1521.                         $confirmed_action_names = [];
  1522.                         $get_sql_1 $get_sql;
  1523.                         foreach ($entries as $entry) {
  1524.                             $has_payments 1;
  1525.                             if (isset($thisBalanceDataByActionTag[$entry['action_tag_id']]))
  1526.                                 $thisBalanceDataByActionTag[$entry['action_tag_id']]['inventory_amount'] += $entry['last_balance'];
  1527.                             else
  1528.                                 $thisBalanceDataByActionTag[$entry['action_tag_id']]['inventory_amount'] = $entry['last_balance'];
  1529.                             if (!isset($lastBalanceDataByActionTag[$entry['action_tag_id']]))
  1530.                                 $lastBalanceDataByActionTag[$entry['action_tag_id']]['inventory_amount'] = 0;
  1531.                             if (!in_array($entry['action_tag_id'], $confirmed_action_ids)) {
  1532.                                 $confirmed_action_ids[] = $entry['action_tag_id'];
  1533.                                 $confirmed_action_names[$entry['action_tag_id']] = $warehouseList[$entry['action_tag_id']]['name'];
  1534.                             }
  1535.                         }
  1536.                         $get_sql "SELECT a.* , (select  c.balance last_balance from inv_closing_balance c
  1537. 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
  1538. from inv_closing_balance a
  1539. where a.warehouse_id in (select distinct id from warehouse
  1540.                        WHERE  warehouse.company_id=" $companyId ") ";
  1541.                         $stmt $em->getConnection()->fetchAllAssociative($get_sql);
  1542.                         
  1543.                         $entries $stmt;
  1544.                         foreach ($entries as $entry) {
  1545.                             $has_payments 1;
  1546.                             if (isset($lastBalanceDataByActionTag[$entry['action_tag_id']]))
  1547.                                 $lastBalanceDataByActionTag[$entry['action_tag_id']]['inventory_amount'] += $entry['last_balance'];
  1548.                             else
  1549.                                 $lastBalanceDataByActionTag[$entry['action_tag_id']]['inventory_amount'] = $entry['last_balance'];
  1550.                             if (!isset($thisBalanceDataByActionTag[$entry['action_tag_id']]))
  1551.                                 $thisBalanceDataByActionTag[$entry['action_tag_id']]['inventory_amount'] = 0;
  1552.                             if (!in_array($entry['action_tag_id'], $confirmed_action_ids)) {
  1553.                                 $confirmed_action_ids[] = $entry['action_tag_id'];
  1554.                                 $confirmed_action_names[$entry['action_tag_id']] = $warehouseList[$entry['action_tag_id']]['name'];
  1555.                             }
  1556.                         }
  1557.                         $skipHeadIds = [];
  1558.                         $thisReportData = array(
  1559.                             //                            'clientTypes' => $clientTypes,
  1560.                             //                            'get_sql_1' => $get_sql_1,
  1561.                             //                            'get_sql' => $get_sql,
  1562.                             'confirmed_action_ids' => $confirmed_action_ids,
  1563.                             'confirmed_action_names' => $confirmed_action_names,
  1564.                             'thisBalanceDataByActionTag' => $thisBalanceDataByActionTag,
  1565.                             'lastBalanceDataByActionTag' => $lastBalanceDataByActionTag,
  1566.                         );
  1567.                         $data['inventory_position'][$app_company_index] = $thisReportData;
  1568.                         //                    $companyListData[] = Company::getCompanyListWithImage($em);
  1569.                     }
  1570.                     //Production Position
  1571.                     if (in_array('production_position'$reportsToGet)) {
  1572.                         $acHeadList = [];
  1573.                         $companyId explode('_'$app_company_index)[1];
  1574.                         $acHeadDataById = [];
  1575.                         $thisBalanceDataByIgId = [];
  1576.                         $lastBalanceDataByIgId = [];
  1577.                         $itemGroups = [];
  1578.                         $itemGroupNames = [];
  1579.                         $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
  1580.   FROM production_entry_item
  1581.   join production on production_entry_item.production_id=production.production_id
  1582.   join inv_products on production_entry_item.product_id=inv_products.id
  1583.   join inv_item_group on inv_item_group.id=inv_products.ig_id
  1584.    WHERE production.company_id=" $companyId " AND production.approved=1
  1585.                           AND production.production_date between '" $thisPeriodStartDate " 00:00:00' and '" $thisPeriodEndDate " 23:59:59.999'
  1586.                           GROUP BY inv_item_group.id
  1587.                           ";
  1588.                         //                        $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
  1589.                         //  FROM production_entry_item
  1590.                         //  join production on production_entry_item.production_id=production.production_id
  1591.                         //  join inv_products on production_entry_item.product_id=inv_products.id
  1592.                         //  join product_mrp on production_entry_item.product_id=product_mrp.product_id
  1593.                         //  join inv_item_group on inv_item_group.id=inv_products.ig_id
  1594.                         //   WHERE production.company_id=" . $companyId . " AND production.approved=1
  1595.                         //                          AND production.production_date between '" . $thisPeriodStartDate . " 00:00:00' and '" . $thisPeriodEndDate . " 23:59:59.999'
  1596.                         //                          GROUP BY inv_item_group.id
  1597.                         //                          ";
  1598.                         $stmt $em->getConnection()->fetchAllAssociative($get_sql);
  1599.                         
  1600.                         $entries $stmt;
  1601.                         $get_sql_1 $get_sql;
  1602.                         foreach ($entries as $entry) {
  1603.                             $has_payments 1;
  1604.                             $thisBalanceDataByIgId[$entry['item_group_id']] = $entry;
  1605.                             $lastBalanceDataByIgId[$entry['item_group_id']]['production_amount'] = 0//just for the lulz
  1606.                             if (!in_array($entry['item_group_id'], $clientTypes)) {
  1607.                                 $itemGroups[] = $entry['item_group_id'];
  1608.                                 $itemGroupNames[$entry['item_group_id']] = $entry['item_group_name'];
  1609.                             }
  1610.                         }
  1611.                         $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
  1612.   FROM production_entry_item
  1613.   join production on production_entry_item.production_id=production.production_id
  1614.   join inv_products on production_entry_item.product_id=inv_products.id
  1615.   join inv_item_group on inv_item_group.id=inv_products.ig_id
  1616.    WHERE production.company_id=" $companyId " AND production.approved=1
  1617.                           AND production.production_date between '" $lastPeriodStartDate " 00:00:00' and '" $lastPeriodEndDate " 23:59:59.999'
  1618.                           GROUP BY inv_item_group.id
  1619.                           ";
  1620.                         $stmt $em->getConnection()->fetchAllAssociative($get_sql);
  1621.                         
  1622.                         $entries $stmt;
  1623.                         foreach ($entries as $entry) {
  1624.                             $has_payments 1;
  1625.                             $lastBalanceDataByIgId[$entry['item_group_id']] = $entry;
  1626.                             if (!isset($thisBalanceDataByIgId[$entry['item_group_id']]))
  1627.                                 $thisBalanceDataByIgId[$entry['item_group_id']]['production_amount'] = 0//just for the lulz
  1628.                             if (!in_array($entry['item_group_id'], $clientTypes)) {
  1629.                                 $itemGroups[] = $entry['item_group_id'];
  1630.                                 $itemGroupNames[$entry['item_group_id']] = $entry['item_group_name'];
  1631.                             }
  1632.                         }
  1633.                         $skipHeadIds = [];
  1634.                         $thisReportData = array(
  1635.                             'itemGroups' => $itemGroups,
  1636.                             //                            'get_sql_1' => $get_sql_1,
  1637.                             //                            'get_sql' => $get_sql,
  1638.                             'itemGroupNames' => $itemGroupNames,
  1639.                             'thisBalanceDataByIgId' => $thisBalanceDataByIgId,
  1640.                             'lastBalanceDataByIgId' => $lastBalanceDataByIgId,
  1641.                         );
  1642.                         $data['production_position'][$app_company_index] = $thisReportData;
  1643.                         //                    $companyListData[] = Company::getCompanyListWithImage($em);
  1644.                     }
  1645.                     //Top Products
  1646.                     if (in_array('top_selling_item_position'$reportsToGet)) {
  1647.                         $acHeadList = [];
  1648.                         $companyId explode('_'$app_company_index)[1];
  1649.                         $acHeadDataById = [];
  1650.                         $thisBalanceDataByRelId = [];
  1651.                         $lastBalanceDataByRelId = [];
  1652.                         $clientIds = [];
  1653.                         $clientNames = [];
  1654.                         $productIds = [];
  1655.                         $productNames = [];
  1656.                         $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
  1657.   FROM sales_invoice_item
  1658.   join sales_invoice on sales_invoice_item.sales_invoice_id=sales_invoice.sales_invoice_id
  1659.   join inv_products on sales_invoice_item.product_id=inv_products.id
  1660.   join acc_clients on acc_clients.client_id=sales_invoice.client_id
  1661.    WHERE sales_invoice.company_id=" $companyId " AND sales_invoice.approved=1
  1662.                           AND sales_invoice_date between '" $thisPeriodStartDate " 00:00:00' and '" $thisPeriodEndDate " 23:59:59.999'
  1663.                           GROUP BY sales_invoice_item.product_id
  1664.                           ORDER BY sales_amount DESC
  1665.                           LIMIT 10
  1666.                           ";
  1667.                         $stmt $em->getConnection()->fetchAllAssociative($get_sql);
  1668.                         
  1669.                         $entries $stmt;
  1670.                         $get_sql_1 $get_sql;
  1671.                         for ($k 0$k 10$k++) {
  1672.                             $has_payments 1;
  1673.                             if (!isset($entries[$k]))
  1674.                                 $entries[$k] = array(
  1675.                                     'sales_amount' => '',
  1676.                                     'product_name' => '',
  1677.                                     'client_name' => '',
  1678.                                 );
  1679.                             $has_payments 1;
  1680.                             $thisBalanceDataByRelId[$k] = $entries[$k];
  1681.                         }
  1682.                         $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
  1683.   FROM sales_invoice_item
  1684.   join sales_invoice on sales_invoice_item.sales_invoice_id=sales_invoice.sales_invoice_id
  1685.   join inv_products on sales_invoice_item.product_id=inv_products.id
  1686.   join acc_clients on acc_clients.client_id=sales_invoice.client_id
  1687.    WHERE sales_invoice.company_id=" $companyId " AND sales_invoice.approved=1
  1688.                           AND sales_invoice_date between '" $lastPeriodStartDate " 00:00:00' and '" $lastPeriodEndDate " 23:59:59.999'
  1689.                           GROUP BY sales_invoice_item.product_id
  1690.                           ORDER BY sales_amount DESC
  1691.                           LIMIT 10
  1692.                           ";
  1693.                         $stmt $em->getConnection()->fetchAllAssociative($get_sql);
  1694.                         
  1695.                         $entries $stmt;
  1696.                         for ($k 0$k 10$k++) {
  1697.                             $has_payments 1;
  1698.                             if (!isset($entries[$k]))
  1699.                                 $entries[$k] = array(
  1700.                                     'sales_amount' => '',
  1701.                                     'product_name' => '',
  1702.                                     'client_name' => '',
  1703.                                 );
  1704.                             $lastBalanceDataByRelId[$k] = $entries[$k];
  1705.                         }
  1706.                         $skipHeadIds = [];
  1707.                         $thisReportData = array(
  1708.                             //                            'clientTypes' => $clientTypes,
  1709.                             ////                            'get_sql_1' => $get_sql_1,
  1710.                             ////                            'get_sql' => $get_sql,
  1711.                             //                            'clientTypeNames' => $clientTypeNames,
  1712.                             'thisBalanceDataByRelId' => $thisBalanceDataByRelId,
  1713.                             'lastBalanceDataByRelId' => $lastBalanceDataByRelId,
  1714.                         );
  1715.                         $data['top_selling_item_position'][$app_company_index] = $thisReportData;
  1716.                         //                    $companyListData[] = Company::getCompanyListWithImage($em);
  1717.                     }
  1718.                     //Top Products
  1719.                     if (in_array('top_selling_client_position'$reportsToGet)) {
  1720.                         $acHeadList = [];
  1721.                         $companyId explode('_'$app_company_index)[1];
  1722.                         $acHeadDataById = [];
  1723.                         $thisBalanceDataByRelId = [];
  1724.                         $lastBalanceDataByRelId = [];
  1725.                         $clientIds = [];
  1726.                         $clientNames = [];
  1727.                         $productIds = [];
  1728.                         $productNames = [];
  1729.                         $get_sql "SELECT sum(sales_invoice.invoice_amount) sales_amount,  acc_clients.client_id, acc_clients.client_name client_name
  1730.   FROM sales_invoice
  1731.   join acc_clients on acc_clients.client_id=sales_invoice.client_id
  1732.    WHERE sales_invoice.company_id=" $companyId " AND sales_invoice.approved=1
  1733.                           AND sales_invoice_date between '" $thisPeriodStartDate " 00:00:00' and '" $thisPeriodEndDate " 23:59:59.999'
  1734.                           GROUP BY sales_invoice.client_id
  1735.                           ORDER BY sales_amount DESC
  1736.                           LIMIT 10
  1737.                           ";
  1738.                         $stmt $em->getConnection()->fetchAllAssociative($get_sql);
  1739.                         
  1740.                         $entries $stmt;
  1741.                         $get_sql_1 $get_sql;
  1742.                         for ($k 0$k 10$k++) {
  1743.                             $has_payments 1;
  1744.                             if (!isset($entries[$k]))
  1745.                                 $entries[$k] = array(
  1746.                                     'sales_amount' => '',
  1747.                                     'product_name' => '',
  1748.                                     'client_name' => '',
  1749.                                 );
  1750.                             $has_payments 1;
  1751.                             $thisBalanceDataByRelId[$k] = $entries[$k];
  1752.                         }
  1753.                         $get_sql "SELECT sum(sales_invoice.invoice_amount) sales_amount,  acc_clients.client_id, acc_clients.client_name client_name
  1754.   FROM sales_invoice
  1755.   join acc_clients on acc_clients.client_id=sales_invoice.client_id
  1756.    WHERE sales_invoice.company_id=" $companyId " AND sales_invoice.approved=1
  1757.                           AND sales_invoice_date between '" $lastPeriodStartDate " 00:00:00' and '" $lastPeriodEndDate " 23:59:59.999'
  1758.                           GROUP BY sales_invoice.client_id
  1759.                           ORDER BY sales_amount DESC
  1760.                           LIMIT 10
  1761.                           ";
  1762.                         $stmt $em->getConnection()->fetchAllAssociative($get_sql);
  1763.                         
  1764.                         $entries $stmt;
  1765.                         for ($k 0$k 10$k++) {
  1766.                             $has_payments 1;
  1767.                             if (!isset($entries[$k]))
  1768.                                 $entries[$k] = array(
  1769.                                     'sales_amount' => '',
  1770.                                     'product_name' => '',
  1771.                                     'client_name' => '',
  1772.                                 );
  1773.                             $lastBalanceDataByRelId[$k] = $entries[$k];
  1774.                         }
  1775.                         $skipHeadIds = [];
  1776.                         $thisReportData = array(
  1777.                             //                            'clientTypes' => $clientTypes,
  1778.                             ////                            'get_sql_1' => $get_sql_1,
  1779.                             ////                            'get_sql' => $get_sql,
  1780.                             //                            'clientTypeNames' => $clientTypeNames,
  1781.                             'thisBalanceDataByRelId' => $thisBalanceDataByRelId,
  1782.                             'lastBalanceDataByRelId' => $lastBalanceDataByRelId,
  1783.                         );
  1784.                         $data['top_selling_client_position'][$app_company_index] = $thisReportData;
  1785.                         //                    $companyListData[] = Company::getCompanyListWithImage($em);
  1786.                     }
  1787.                 }
  1788.             }
  1789.         }
  1790.         return new JsonResponse(
  1791.             array(
  1792.                 'success' => true,
  1793.                 'data' => $data,
  1794.                 'companyListData' => $companyListData,
  1795.                 'dataToConnectList' => $dataToConnectList,
  1796.                 'periodType' => $periodType,
  1797.                 'queriedReportsToGet' => $request->request->get('reportsToGet'),
  1798.                 'reportsToGet' => $reportsToGet,
  1799.                 'thisPeriodStartDate' => $thisPeriodStartDate,
  1800.                 'thisPeriodEndDate' => $thisPeriodEndDate,
  1801.                 'lastPeriodStartDate' => $lastPeriodStartDate,
  1802.                 'lastPeriodEndDate' => $lastPeriodEndDate,
  1803.                 'companyIdListByAppId' => $companyIdListByAppId,
  1804.                 'companyNameListByAppId' => $companyNameListByAppId,
  1805.                 'companyImageListByAppId' => $companyImageListByAppId,
  1806.                 'appIdList' => $appIdList,
  1807.             )
  1808.         );
  1809.     }
  1810.     public function indexAction(Request $request$cgHash '')
  1811.     {
  1812.         $session $request->getSession();
  1813.         $systemType $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
  1814.         if ($systemType == '_ERP_') {
  1815.             //do nothing its default to dashboard index
  1816.         } else if ($systemType == '_BUDDYBEE_') {
  1817.             if ($cgHash != '')
  1818.                 $session->set('codeHash'$cgHash);
  1819.         }
  1820.         // Generic::debugMessage($session);
  1821.         $ROUTE_LIST json_decode($session->get(UserConstants::USER_ROUTE_LIST), true);
  1822.         if ($ROUTE_LIST == null)
  1823.             $ROUTE_LIST = [];
  1824.         $CurrentRoute $request->attributes->get('_route');
  1825.         if ($session->get(UserConstants::USER_ROUTE_LIST) == || in_array('management_dashboard'$ROUTE_LIST)) {
  1826.             // User is not authorized. send him to dashboard
  1827.             //                    $controller->addFlash(
  1828.             //                        'error',
  1829.             //                        'Sorry Couldnot insert Data.'
  1830.             //                    );
  1831.             //                    return $this->render('ApplicationBundle:pages/dashboard:advanced_management_dashboard.html.twig',
  1832.             if ($session->has('isMobile'))
  1833.                 if ($session->get('isMobile') == true) {
  1834.                     return $this->render(
  1835.                         '@Application/pages/dashboard/index_finance_mobile.html.twig',
  1836.                         array(
  1837.                             'page_title' => 'Finance Dashboard',
  1838.                             'dashboardDataForUser' => []
  1839.                         )
  1840.                     );
  1841.                 }
  1842.             return $this->render(
  1843.                 '@Application/pages/dashboard/advanced_management_dashboard.html.twig',
  1844.                 array(
  1845.                     'page_title' => 'Dashboard'
  1846.                 )
  1847.             );
  1848.         }
  1849.         if ($session->has('isMobile'))
  1850.             if ($session->get('isMobile') == true) {
  1851.                 if ($systemType == '_CENTRAL_') {
  1852.                     $defaultRoute 'central_landing';
  1853.                     return $this->redirectToRoute($defaultRoute);
  1854.                 }
  1855.                 elseif ($systemType == '_SOPHIA_') {
  1856.                     $defaultRoute 'sofia_dashboard_admin';
  1857.                     return $this->redirectToRoute($defaultRoute);
  1858.                 }else
  1859.                     return $this->render(
  1860.                         '@Application/pages/dashboard/index_finance_mobile.html.twig',
  1861.                         array(
  1862.                             'page_title' => 'Finance Dashboard',
  1863.                             'dashboardDataForUser' => []
  1864.                         )
  1865.                     );
  1866.             }
  1867.         else {
  1868.                 //check if user has a default route if yes redirect to it
  1869.                 if ($session->get(UserConstants::USER_TYPE) == UserConstants::USER_TYPE_SUPPLIER)
  1870.                     $defaultRoute 'supplier_dashboard';
  1871.                 else if ($session->get(UserConstants::USER_TYPE) == UserConstants::USER_TYPE_CLIENT)
  1872.                     $defaultRoute 'client_dashboard';
  1873.                 else if ($session->get(UserConstants::USER_TYPE) == UserConstants::USER_TYPE_APPLICANT) {
  1874.                     if ($systemType == '_CENTRAL_') {
  1875.                         $defaultRoute 'central_landing';
  1876.                     }
  1877.                     elseif ($systemType == '_SOPHIA_') {
  1878.                         $defaultRoute 'sofia_dashboard_admin';
  1879.                     } else
  1880.                         $defaultRoute 'applicant_dashboard';
  1881.                 } else
  1882.                     $defaultRoute $session->get(UserConstants::USER_DEFAULT_ROUTE);
  1883.                 //            if(in_array($defaultRoute, $ROUTE_LIST))
  1884.                 if ($defaultRoute != '' && $defaultRoute != null)
  1885.                     return $this->redirectToRoute($defaultRoute);
  1886.                 else
  1887.                     return $this->redirectToRoute('sales_dashboard');
  1888. //                return $this->render(
  1889. //                    'ApplicationBundle:pages/dashboard:index.html.twig',
  1890. //                    array(
  1891. //                        'page_title' => 'Dashboard',
  1892. //                        'allocation_filters' => [],
  1893. //                        'allocationFilters' => [],
  1894. //                        'allocation_tag_types' => [],
  1895. //                        'allocation_tag_values_by_type' => [],
  1896. //                        'project_list' => [],
  1897. //                        'branch_list' => [],
  1898. //                        'cost_centers' => []
  1899. //                    )
  1900. //                );
  1901.             }
  1902.     }
  1903.     public function indexSupplierAction(Request $request)
  1904.     {
  1905.         $session $request->getSession();
  1906.         $supplierId 3;
  1907.         if ($request->query->has('supplierId')) //for debug now
  1908.         {
  1909.             $session->set('supplierId'$request->query->get('supplierId'));
  1910.         }
  1911.         $supplierId $session->get('supplierId');  //////////////////////LATER
  1912.         $em $this->getDoctrine()->getManager();
  1913.         $companyId $this->getLoggedUserCompanyId($request);
  1914.         $userId $request->getSession()->get(UserConstants::USER_ID);
  1915.         $SD Supplier::GetSupplierProfileDetails($em$supplierId'SI');
  1916.         $dashboardDataForUser = [];
  1917.         return $this->render(
  1918.             '@Application/pages/dashboard/index_supplier.html.twig',
  1919.             array(
  1920.                 'page_title' => 'Supplier Dashboard',
  1921.                 'dashboardDataForUser' => $dashboardDataForUser,
  1922.                 'data' => $SD,
  1923.                 'igList' => Inventory::ItemGroupList($em$companyId)
  1924.             )
  1925.         );
  1926.     }
  1927.     public function indexClientAction(Request $request)
  1928.     {
  1929.         $session $request->getSession();
  1930.         $clientId 3;
  1931.         if ($request->query->has('clientId')) //for debug now
  1932.         {
  1933.             $session->set('clientId'$request->query->get('clientId'));
  1934.         }
  1935.         $clientId $session->get('clientId');  //////////////////////LATER
  1936.         $em $this->getDoctrine()->getManager();
  1937.         $companyId $this->getLoggedUserCompanyId($request);
  1938.         $userId $request->getSession()->get(UserConstants::USER_ID);
  1939.         $SD Client::GetClientProfileDetails($em$clientId'CI');
  1940.         $dashboardDataForUser = [];
  1941.         return $this->render(
  1942.             '@Application/pages/dashboard/index_client.html.twig',
  1943.             array(
  1944.                 'page_title' => 'Client Dashboard',
  1945.                 'dashboardDataForUser' => $dashboardDataForUser,
  1946.                 'data' => $SD,
  1947.                 'igList' => Inventory::ItemGroupList($em$companyId)
  1948.             )
  1949.         );
  1950.     }
  1951.     public function indexFinanceAction(Request $request)
  1952.     {
  1953.         $session $request->getSession();
  1954.         $dashboardDataForUser = [];
  1955.         $em $this->getDoctrine()->getManager();
  1956.         $companyId $this->getLoggedUserCompanyId($request);
  1957.         $userId $request->getSession()->get(UserConstants::USER_ID);
  1958.         $dbQuery $em->getRepository("ApplicationBundle\\Entity\\DashboardWidget")->findBy(
  1959.             array(
  1960.                 'CompanyId' => $companyId,
  1961.                 'userId' => $userId,
  1962.                 'status' => GeneralConstant::ACTIVE
  1963.             ),
  1964.             array(
  1965.                 'sequence' => 'ASC'
  1966.             )
  1967.         );
  1968.         if (empty($dbQuery))   ///now get the defaults
  1969.             $dbQuery $em->getRepository("ApplicationBundle\\Entity\\DashboardWidget")->findBy(
  1970.                 array(
  1971.                     'CompanyId' => $companyId,
  1972.                     //                    'userId'=>$userId,
  1973.                     'defaultBoxFlag' => 1,
  1974.                     'status' => GeneralConstant::ACTIVE
  1975.                 ),
  1976.                 array(
  1977.                     'sequence' => 'ASC'
  1978.                 )
  1979.             );
  1980.         foreach ($dbQuery as $entry) {
  1981.             $dashboardDataForUser[] = array(
  1982.                 'id' => $entry->getId(),
  1983.                 'widgetId' => $entry->getId(),
  1984.                 'widgetSequence' => $entry->getSequence(),
  1985.                 'widgetStatus' => $entry->getStatus(),
  1986.                 'widgetData' => json_decode($entry->getData(), true),
  1987.                 'defaultBoxFlag' => $entry->getDefaultBoxFlag(),
  1988.                 'widgetSizeTiny' => $entry->getSizeTiny(),
  1989.                 'widgetSizeSmall' => $entry->getSizeSmall(),
  1990.                 'widgetSizeMedium' => $entry->getSizeMedium(),
  1991.                 'widgetSizeLarge' => $entry->getSizeLarge(),
  1992.                 'refreshInterval' => $entry->getRefreshInterval(),
  1993.             );
  1994.         }
  1995.         if ($session->has('isMobile')) {
  1996.             if ($session->get('isMobile') == true) {
  1997.                 return $this->render(
  1998.                     '@Application/pages/dashboard/index_finance_mobile.html.twig',
  1999.                     array(
  2000.                         'page_title' => 'Finance Dashboard',
  2001.                         'dashboardDataForUser' => $dashboardDataForUser
  2002.                     )
  2003.                 );
  2004.             } else {
  2005.             }
  2006.         }
  2007.         return $this->render(
  2008.             '@Accounts/pages/finance_dashboard.html.twig',
  2009.             array(
  2010.                 'page_title' => 'Finance Dashboard',
  2011.                 'dashboardDataForUser' => $dashboardDataForUser,
  2012.                 'dashboardAnalytics' => $this->buildFinanceDashboardAnalytics($em)
  2013.             )
  2014.         );
  2015.     }
  2016.     /**
  2017.      * Lean, fail-safe analytics for the Finance cp-shell dashboard. Guarded scalar DQL â€”
  2018.      * a schema/tenant quirk degrades to 0 rather than 500-ing the dashboard.
  2019.      */
  2020.     private function buildFinanceDashboardAnalytics($em)
  2021.     {
  2022.         $scalar = function ($dql$params = []) use ($em) {
  2023.             try {
  2024.                 $v $em->createQuery($dql)->setParameters($params)->getSingleScalarResult();
  2025.                 return $v === null $v;
  2026.             } catch (\Throwable $e) {
  2027.                 return 0;
  2028.             }
  2029.         };
  2030.         $salesInv     = (int) $scalar("SELECT COUNT(i) FROM ApplicationBundle:SalesInvoice i WHERE (i.deleteFlag = 0 OR i.deleteFlag IS NULL)");
  2031.         $expenseInv   = (int) $scalar("SELECT COUNT(e) FROM ApplicationBundle:ExpenseInvoice e WHERE (e.deleteFlag = 0 OR e.deleteFlag IS NULL)");
  2032.         $banks        = (int) $scalar("SELECT COUNT(b) FROM ApplicationBundle:BankAccounts b");
  2033.         $salesPending = (int) $scalar("SELECT COUNT(i) FROM ApplicationBundle:SalesInvoice i WHERE i.approved <> :a AND (i.deleteFlag = 0 OR i.deleteFlag IS NULL)", ['a' => GeneralConstant::APPROVED]);
  2034.         $expPending   = (int) $scalar("SELECT COUNT(e) FROM ApplicationBundle:ExpenseInvoice e WHERE e.approved <> :a AND (e.deleteFlag = 0 OR e.deleteFlag IS NULL)", ['a' => GeneralConstant::APPROVED]);
  2035.         return [
  2036.             'kpis' => [
  2037.                 ['label' => 'Sales Invoices',   'value' => $salesInv,   'note' => 'Receivables'],
  2038.                 ['label' => 'Expense Invoices''value' => $expenseInv'note' => 'Payables'],
  2039.                 ['label' => 'Bank Accounts',    'value' => $banks,      'note' => 'Cash & bank'],
  2040.                 ['label' => 'Pending AR',       'value' => $salesPending'note' => 'Sales invoices to approve'],
  2041.                 ['label' => 'Pending AP',       'value' => $expPending,   'note' => 'Expense invoices to approve'],
  2042.             ],
  2043.             'pending_items' => [
  2044.                 ['label' => 'Sales Invoices',   'value' => $salesPending'note' => 'Receivable approvals'],
  2045.                 ['label' => 'Expense Invoices''value' => $expPending,   'note' => 'Payable approvals'],
  2046.             ],
  2047.         ];
  2048.     }
  2049.     public function indexSalesAction(Request $request)
  2050.     {
  2051.         $session $request->getSession();
  2052.         $dashboardDataForUser = [];
  2053.         $em $this->getDoctrine()->getManager();
  2054.         $companyId $this->getLoggedUserCompanyId($request);
  2055.         $userId $request->getSession()->get(UserConstants::USER_ID);
  2056.         $dbQuery $em->getRepository("ApplicationBundle\\Entity\\DashboardWidget")->findBy(
  2057.             array(
  2058.                 'CompanyId' => $companyId,
  2059.                 'userId' => $userId,
  2060.                 'status' => GeneralConstant::ACTIVE
  2061.             ),
  2062.             array(
  2063.                 'sequence' => 'ASC'
  2064.             )
  2065.         );
  2066.         if (empty($dbQuery))   ///now get the defaults
  2067.             $dbQuery $em->getRepository("ApplicationBundle\\Entity\\DashboardWidget")->findBy(
  2068.                 array(
  2069.                     'CompanyId' => $companyId,
  2070.                     //                    'userId'=>$userId,
  2071.                     'defaultBoxFlag' => 1,
  2072.                     'status' => GeneralConstant::ACTIVE
  2073.                 ),
  2074.                 array(
  2075.                     'sequence' => 'ASC'
  2076.                 )
  2077.             );
  2078.         foreach ($dbQuery as $entry) {
  2079.             $dashboardDataForUser[] = array(
  2080.                 'id' => $entry->getId(),
  2081.                 'widgetId' => $entry->getId(),
  2082.                 'widgetSequence' => $entry->getSequence(),
  2083.                 'widgetStatus' => $entry->getStatus(),
  2084.                 'widgetData' => json_decode($entry->getData(), true),
  2085.                 'defaultBoxFlag' => $entry->getDefaultBoxFlag(),
  2086.                 'widgetSizeTiny' => $entry->getSizeTiny(),
  2087.                 'widgetSizeSmall' => $entry->getSizeSmall(),
  2088.                 'widgetSizeMedium' => $entry->getSizeMedium(),
  2089.                 'widgetSizeLarge' => $entry->getSizeLarge(),
  2090.                 'refreshInterval' => $entry->getRefreshInterval(),
  2091.             );
  2092.         }
  2093.         if ($session->has('isMobile')) {
  2094.             if ($session->get('isMobile') == true) {
  2095.                 return $this->render(
  2096.                     '@Application/pages/dashboard/index_finance_mobile.html.twig',
  2097.                     array(
  2098.                         'page_title' => 'Finance Dashboard',
  2099.                         'dashboardDataForUser' => $dashboardDataForUser
  2100.                     )
  2101.                 );
  2102.             } else {
  2103.             }
  2104.         }
  2105.         return $this->render(
  2106.             '@Sales/pages/sales_dashboard.html.twig',
  2107.             array(
  2108.                 'page_title' => 'Sales Dashboard',
  2109.                 'dashboardDataForUser' => $dashboardDataForUser,
  2110.                 'dashboardAnalytics' => $this->buildSalesDashboardAnalytics($em)
  2111.             )
  2112.         );
  2113.     }
  2114.     /**
  2115.      * Fail-safe analytics for the Sales cp-shell dashboard â€” KPIs + 6-month order-value trend +
  2116.      * a health snapshot. Every metric/query is guarded so a schema/tenant quirk degrades to
  2117.      * empty rather than 500-ing the dashboard.
  2118.      */
  2119.     private function buildSalesDashboardAnalytics($em)
  2120.     {
  2121.         $scalar = function ($dql$params = []) use ($em) {
  2122.             try {
  2123.                 $v $em->createQuery($dql)->setParameters($params)->getSingleScalarResult();
  2124.                 return $v === null $v;
  2125.             } catch (\Throwable $e) {
  2126.                 return 0;
  2127.             }
  2128.         };
  2129.         $soTotal    = (int) $scalar("SELECT COUNT(s) FROM ApplicationBundle:SalesOrder s WHERE (s.deleteFlag = 0 OR s.deleteFlag IS NULL)");
  2130.         $soApproved = (int) $scalar("SELECT COUNT(s) FROM ApplicationBundle:SalesOrder s WHERE s.approved = :a AND (s.deleteFlag = 0 OR s.deleteFlag IS NULL)", ['a' => GeneralConstant::APPROVED]);
  2131.         $soValue    = (float) $scalar("SELECT SUM(s.soAmount) FROM ApplicationBundle:SalesOrder s WHERE s.approved = :a AND (s.deleteFlag = 0 OR s.deleteFlag IS NULL)", ['a' => GeneralConstant::APPROVED]);
  2132.         $soPending  max($soTotal $soApproved0);
  2133.         $opps       = (int) $scalar("SELECT COUNT(o) FROM ApplicationBundle:Opportunity o WHERE (o.deleteFlag = 0 OR o.deleteFlag IS NULL)");
  2134.         $clients    = (int) $scalar("SELECT COUNT(c) FROM ApplicationBundle:AccClients c");
  2135.         // â”€â”€ 6-month order-value trend (guarded raw SQL â€” flat/empty on any quirk) â”€â”€
  2136.         $monthKeys = [];
  2137.         $monthLabels = [];
  2138.         for ($i 5$i >= 0$i--) {
  2139.             $m = new \DateTime('first day of this month');
  2140.             if ($i 0) {
  2141.                 $m->modify('-' $i ' month');
  2142.             }
  2143.             $monthKeys[] = $m->format('Y-m');
  2144.             $monthLabels[] = $m->format('M');
  2145.         }
  2146.         $trend = function ($sql) use ($em) {
  2147.             try {
  2148.                 return $em->getConnection()->fetchAllAssociative($sql);
  2149.             } catch (\Throwable $e) {
  2150.                 return [];
  2151.             }
  2152.         };
  2153.         $seriesFromRows = function (array $rows, array $keys) {
  2154.             $map = [];
  2155.             foreach ($rows as $r) {
  2156.                 $map[$r['month']] = (float) $r['total'];
  2157.             }
  2158.             $out = [];
  2159.             foreach ($keys as $k) {
  2160.                 $out[] = isset($map[$k]) ? round($map[$k], 2) : 0;
  2161.             }
  2162.             return $out;
  2163.         };
  2164.         $orderRows $trend("
  2165.             SELECT DATE_FORMAT(sales_order_date, '%Y-%m') AS month,
  2166.                    COALESCE(SUM(CAST(COALESCE(NULLIF(so_amount,''),0) AS DECIMAL(15,2))),0) AS total
  2167.             FROM sales_order
  2168.             WHERE status = 1 AND (delete_flag = 0 OR delete_flag IS NULL)
  2169.               AND sales_order_date >= DATE_SUB(CURDATE(), INTERVAL 5 MONTH)
  2170.             GROUP BY DATE_FORMAT(sales_order_date, '%Y-%m') ORDER BY month ASC");
  2171.         $approvedRows $trend("
  2172.             SELECT DATE_FORMAT(sales_order_date, '%Y-%m') AS month,
  2173.                    COALESCE(SUM(CAST(COALESCE(NULLIF(so_amount,''),0) AS DECIMAL(15,2))),0) AS total
  2174.             FROM sales_order
  2175.             WHERE status = 1 AND approved = 1 AND (delete_flag = 0 OR delete_flag IS NULL)
  2176.               AND sales_order_date >= DATE_SUB(CURDATE(), INTERVAL 5 MONTH)
  2177.             GROUP BY DATE_FORMAT(sales_order_date, '%Y-%m') ORDER BY month ASC");
  2178.         $coverage $soTotal round(($soApproved $soTotal) * 1001) : 0;
  2179.         return [
  2180.             'kpis' => [
  2181.                 ['label' => 'Sales Orders',     'value' => $soTotal,        'note' => 'Active orders'],
  2182.                 ['label' => 'Approved Value',   'value' => round($soValue), 'note' => 'Approved SO value'],
  2183.                 ['label' => 'Opportunities',    'value' => $opps,           'note' => 'In the pipeline'],
  2184.                 ['label' => 'Clients',          'value' => $clients,        'note' => 'Customer base'],
  2185.                 ['label' => 'Pending Approval''value' => $soPending,      'note' => 'Awaiting sign-off'],
  2186.             ],
  2187.             'pending_items' => [
  2188.                 ['label' => 'Sales Orders''value' => $soPending'note' => 'Waiting for approval'],
  2189.             ],
  2190.             'hero' => [
  2191.                 'labels' => $monthLabels,
  2192.                 'series' => [
  2193.                     ['label' => 'Order Value''values' => $seriesFromRows($orderRows$monthKeys),    'color' => '#2b5fb8''fill' => 'rgba(43,95,184,0.14)'],
  2194.                     ['label' => 'Approved',    'values' => $seriesFromRows($approvedRows$monthKeys), 'color' => '#4BAA6B''fill' => 'rgba(75,170,107,0.14)'],
  2195.                 ],
  2196.             ],
  2197.             'hero_summary' => [
  2198.                 'subhead' => 'Order value over the last 6 months',
  2199.             ],
  2200.             'snapshot' => [
  2201.                 'label' => 'Sales Health',
  2202.                 'ring_value' => $coverage,
  2203.                 'ring_note' => 'Approved of all orders',
  2204.                 'metrics' => [
  2205.                     ['label' => 'Approved Value''value' => number_format(round($soValue)), 'note' => 'Signed-off SO value'],
  2206.                     ['label' => 'Pending Orders''value' => $soPending'note' => 'Awaiting approval'],
  2207.                     ['label' => 'Opportunities',  'value' => $opps,      'note' => 'Open pipeline'],
  2208.                 ],
  2209.             ],
  2210.         ];
  2211.     }
  2212.     public function indexPurchaseAction(Request $request)
  2213.     {
  2214.         $em $this->getDoctrine()->getManager();
  2215.         $companyId $this->getLoggedUserCompanyId($request);
  2216.         $dashboardDataForUser $this->loadDashboardWidgetsForUser($request);
  2217.         $dashboardAnalytics $this->buildPurchaseDashboardAnalytics($em$companyId);
  2218.         return $this->render(
  2219.             '@Purchase/pages/supply_chain_dashboard.html.twig',
  2220.             array(
  2221.                 'page_title' => 'Purchasing Dashboard',
  2222.                 'dashboardMode' => 'purchase',
  2223.                 'dashboardDataForUser' => $dashboardDataForUser,
  2224.                 'dashboardAnalytics' => $dashboardAnalytics
  2225.             )
  2226.         );
  2227.     }
  2228.     public function indexDistributionAction(Request $request)
  2229.     {
  2230.         $session $request->getSession();
  2231.         $dashboardDataForUser = [];
  2232.         $em $this->getDoctrine()->getManager();
  2233.         $companyId $this->getLoggedUserCompanyId($request);
  2234.         $userId $request->getSession()->get(UserConstants::USER_ID);
  2235.         $dbQuery $em->getRepository("ApplicationBundle\\Entity\\DashboardWidget")->findBy(
  2236.             array(
  2237.                 'CompanyId' => $companyId,
  2238.                 'userId' => $userId,
  2239.                 'status' => GeneralConstant::ACTIVE
  2240.             ),
  2241.             array(
  2242.                 'sequence' => 'ASC'
  2243.             )
  2244.         );
  2245.         if (empty($dbQuery))   ///now get the defaults
  2246.             $dbQuery $em->getRepository("ApplicationBundle\\Entity\\DashboardWidget")->findBy(
  2247.                 array(
  2248.                     'CompanyId' => $companyId,
  2249.                     //                    'userId'=>$userId,
  2250.                     'defaultBoxFlag' => 1,
  2251.                     'status' => GeneralConstant::ACTIVE
  2252.                 ),
  2253.                 array(
  2254.                     'sequence' => 'ASC'
  2255.                 )
  2256.             );
  2257.         foreach ($dbQuery as $entry) {
  2258.             $dashboardDataForUser[] = array(
  2259.                 'id' => $entry->getId(),
  2260.                 'widgetId' => $entry->getId(),
  2261.                 'widgetSequence' => $entry->getSequence(),
  2262.                 'widgetStatus' => $entry->getStatus(),
  2263.                 'widgetData' => json_decode($entry->getData(), true),
  2264.                 'defaultBoxFlag' => $entry->getDefaultBoxFlag(),
  2265.                 'widgetSizeTiny' => $entry->getSizeTiny(),
  2266.                 'widgetSizeSmall' => $entry->getSizeSmall(),
  2267.                 'widgetSizeMedium' => $entry->getSizeMedium(),
  2268.                 'widgetSizeLarge' => $entry->getSizeLarge(),
  2269.                 'refreshInterval' => $entry->getRefreshInterval(),
  2270.             );
  2271.         }
  2272.         return $this->render(
  2273.             '@Distribution/pages/distribution_dashboard.html.twig',
  2274.             array(
  2275.                 'page_title' => 'Distribution Dashboard',
  2276.                 'dashboardDataForUser' => $dashboardDataForUser,
  2277.                 'dashboardAnalytics' => $this->buildDistributionDashboardAnalytics($em)
  2278.             )
  2279.         );
  2280.     }
  2281.     /**
  2282.      * Lean, fail-safe analytics for the Distribution cp-shell dashboard. Guarded scalar DQL â€”
  2283.      * a schema/tenant quirk degrades to 0 rather than 500-ing the dashboard.
  2284.      */
  2285.     private function buildDistributionDashboardAnalytics($em)
  2286.     {
  2287.         $scalar = function ($dql$params = []) use ($em) {
  2288.             try {
  2289.                 $v $em->createQuery($dql)->setParameters($params)->getSingleScalarResult();
  2290.                 return $v === null $v;
  2291.             } catch (\Throwable $e) {
  2292.                 return 0;
  2293.             }
  2294.         };
  2295.         $doTotal    = (int) $scalar("SELECT COUNT(d) FROM ApplicationBundle:DeliveryOrder d WHERE (d.deleteFlag = 0 OR d.deleteFlag IS NULL)");
  2296.         $doApproved = (int) $scalar("SELECT COUNT(d) FROM ApplicationBundle:DeliveryOrder d WHERE d.approved = :a AND (d.deleteFlag = 0 OR d.deleteFlag IS NULL)", ['a' => GeneralConstant::APPROVED]);
  2297.         $doPending  max($doTotal $doApproved0);
  2298.         $confirms   = (int) $scalar("SELECT COUNT(c) FROM ApplicationBundle:DeliveryConfirmation c");
  2299.         $receipts   = (int) $scalar("SELECT COUNT(r) FROM ApplicationBundle:DeliveryReceipt r");
  2300.         $challans   = (int) $scalar("SELECT COUNT(s) FROM ApplicationBundle:ServiceChallan s");
  2301.         return [
  2302.             'kpis' => [
  2303.                 ['label' => 'Delivery Orders',   'value' => $doTotal,   'note' => 'All dispatch orders'],
  2304.                 ['label' => 'Confirmations',     'value' => $confirms,  'note' => 'Delivery confirmed'],
  2305.                 ['label' => 'Delivery Receipts''value' => $receipts,  'note' => 'Received by customer'],
  2306.                 ['label' => 'Service Challans',  'value' => $challans,  'note' => 'Dispatch challans'],
  2307.                 ['label' => 'Pending Dispatch',  'value' => $doPending'note' => 'Awaiting sign-off'],
  2308.             ],
  2309.             'pending_items' => [
  2310.                 ['label' => 'Delivery Orders''value' => $doPending'note' => 'Waiting for approval'],
  2311.             ],
  2312.         ];
  2313.     }
  2314.     public function indexProductionAction(Request $request)
  2315.     {
  2316.         $session $request->getSession();
  2317.         $dashboardDataForUser = [];
  2318.         $em $this->getDoctrine()->getManager();
  2319.         $companyId $this->getLoggedUserCompanyId($request);
  2320.         $userId $request->getSession()->get(UserConstants::USER_ID);
  2321.         $dbQuery $em->getRepository("ApplicationBundle\\Entity\\DashboardWidget")->findBy(
  2322.             array(
  2323.                 'CompanyId' => $companyId,
  2324.                 'userId' => $userId,
  2325.                 'status' => GeneralConstant::ACTIVE
  2326.             ),
  2327.             array(
  2328.                 'sequence' => 'ASC'
  2329.             )
  2330.         );
  2331.         if (empty($dbQuery))   ///now get the defaults
  2332.             $dbQuery $em->getRepository("ApplicationBundle\\Entity\\DashboardWidget")->findBy(
  2333.                 array(
  2334.                     'CompanyId' => $companyId,
  2335.                     //                    'userId'=>$userId,
  2336.                     'defaultBoxFlag' => 1,
  2337.                     'status' => GeneralConstant::ACTIVE
  2338.                 ),
  2339.                 array(
  2340.                     'sequence' => 'ASC'
  2341.                 )
  2342.             );
  2343.         foreach ($dbQuery as $entry) {
  2344.             $dashboardDataForUser[] = array(
  2345.                 'id' => $entry->getId(),
  2346.                 'widgetId' => $entry->getId(),
  2347.                 'widgetSequence' => $entry->getSequence(),
  2348.                 'widgetStatus' => $entry->getStatus(),
  2349.                 'widgetData' => json_decode($entry->getData(), true),
  2350.                 'defaultBoxFlag' => $entry->getDefaultBoxFlag(),
  2351.                 'widgetSizeTiny' => $entry->getSizeTiny(),
  2352.                 'widgetSizeSmall' => $entry->getSizeSmall(),
  2353.                 'widgetSizeMedium' => $entry->getSizeMedium(),
  2354.                 'widgetSizeLarge' => $entry->getSizeLarge(),
  2355.                 'refreshInterval' => $entry->getRefreshInterval(),
  2356.             );
  2357.         }
  2358.         return $this->render(
  2359.             '@Application/pages/dashboard/index_sales.html.twig',
  2360.             array(
  2361.                 'page_title' => 'Sales Dashboard',
  2362.                 'dashboardDataForUser' => $dashboardDataForUser
  2363.             )
  2364.         );
  2365.     }
  2366.     public function indexInventoryAction(Request $request)
  2367.     {
  2368.         $em $this->getDoctrine()->getManager();
  2369.         $companyId $this->getLoggedUserCompanyId($request);
  2370.         $dashboardDataForUser $this->loadDashboardWidgetsForUser($request);
  2371.         $dashboardAnalytics $this->buildInventoryDashboardAnalytics($em$companyId);
  2372.         return $this->render(
  2373.             '@Inventory/pages/inventory_dashboard.html.twig',
  2374.             array(
  2375.                 'page_title' => 'Inventory Dashboard',
  2376.                 'dashboardMode' => 'inventory',
  2377.                 'dashboardDataForUser' => $dashboardDataForUser,
  2378.                 'dashboardAnalytics' => $dashboardAnalytics
  2379.             )
  2380.         );
  2381.     }
  2382.     private function loadDashboardWidgetsForUser(Request $request)
  2383.     {
  2384.         $dashboardDataForUser = [];
  2385.         $em $this->getDoctrine()->getManager();
  2386.         $companyId $this->getLoggedUserCompanyId($request);
  2387.         $userId $request->getSession()->get(UserConstants::USER_ID);
  2388.         $dbQuery $em->getRepository("ApplicationBundle\\Entity\\DashboardWidget")->findBy(
  2389.             array(
  2390.                 'CompanyId' => $companyId,
  2391.                 'userId' => $userId,
  2392.                 'status' => GeneralConstant::ACTIVE
  2393.             ),
  2394.             array(
  2395.                 'sequence' => 'ASC'
  2396.             )
  2397.         );
  2398.         if (empty($dbQuery)) {
  2399.             $dbQuery $em->getRepository("ApplicationBundle\\Entity\\DashboardWidget")->findBy(
  2400.                 array(
  2401.                     'CompanyId' => $companyId,
  2402.                     'defaultBoxFlag' => 1,
  2403.                     'status' => GeneralConstant::ACTIVE
  2404.                 ),
  2405.                 array(
  2406.                     'sequence' => 'ASC'
  2407.                 )
  2408.             );
  2409.         }
  2410.         foreach ($dbQuery as $entry) {
  2411.             $dashboardDataForUser[] = array(
  2412.                 'id' => $entry->getId(),
  2413.                 'widgetId' => $entry->getId(),
  2414.                 'widgetSequence' => $entry->getSequence(),
  2415.                 'widgetStatus' => $entry->getStatus(),
  2416.                 'widgetData' => json_decode($entry->getData(), true),
  2417.                 'defaultBoxFlag' => $entry->getDefaultBoxFlag(),
  2418.                 'widgetSizeTiny' => $entry->getSizeTiny(),
  2419.                 'widgetSizeSmall' => $entry->getSizeSmall(),
  2420.                 'widgetSizeMedium' => $entry->getSizeMedium(),
  2421.                 'widgetSizeLarge' => $entry->getSizeLarge(),
  2422.                 'refreshInterval' => $entry->getRefreshInterval(),
  2423.             );
  2424.         }
  2425.         return $dashboardDataForUser;
  2426.     }
  2427.     private function buildPurchaseDashboardAnalytics($em$companyId)
  2428.     {
  2429.         $conn $em->getConnection();
  2430.         $monthKeys = [];
  2431.         $monthLabels = [];
  2432.         for ($i 5$i >= 0$i--) {
  2433.             $month = new \DateTime('first day of this month');
  2434.             if ($i 0) {
  2435.                 $month->modify('-' $i ' month');
  2436.             }
  2437.             $monthKeys[] = $month->format('Y-m');
  2438.             $monthLabels[] = $month->format('M');
  2439.         }
  2440.         $poTrendRows $conn->fetchAllAssociative("
  2441.             SELECT DATE_FORMAT(purchase_order_date, '%Y-%m') AS month, COALESCE(SUM(CAST(COALESCE(NULLIF(po_amount, ''), 0) AS DECIMAL(15,2))), 0) AS total
  2442.             FROM purchase_order
  2443.             WHERE company_id = :companyId
  2444.               AND status = 1
  2445.               AND approved = 1
  2446.               AND purchase_order_date >= DATE_SUB(CURDATE(), INTERVAL 5 MONTH)
  2447.             GROUP BY DATE_FORMAT(purchase_order_date, '%Y-%m')
  2448.             ORDER BY month ASC
  2449.         ", ['companyId' => $companyId]);
  2450.         $invoiceTrendRows $conn->fetchAllAssociative("
  2451.             SELECT DATE_FORMAT(purchase_invoice_date, '%Y-%m') AS month, COALESCE(SUM(CAST(COALESCE(NULLIF(invoice_amount, ''), 0) AS DECIMAL(15,2))), 0) AS total
  2452.             FROM purchase_invoice
  2453.             WHERE company_id = :companyId
  2454.               AND status = 1
  2455.               AND approved = 1
  2456.               AND purchase_invoice_date >= DATE_SUB(CURDATE(), INTERVAL 5 MONTH)
  2457.             GROUP BY DATE_FORMAT(purchase_invoice_date, '%Y-%m')
  2458.             ORDER BY month ASC
  2459.         ", ['companyId' => $companyId]);
  2460.         $paidTrendRows $conn->fetchAllAssociative("
  2461.             SELECT DATE_FORMAT(purchase_invoice_date, '%Y-%m') AS month, COALESCE(SUM(CAST(COALESCE(NULLIF(paid_amount, ''), invoice_amount, 0) AS DECIMAL(15,2))), 0) AS total
  2462.             FROM purchase_invoice
  2463.             WHERE company_id = :companyId
  2464.               AND status = 1
  2465.               AND approved = 1
  2466.               AND purchase_invoice_date >= DATE_SUB(CURDATE(), INTERVAL 5 MONTH)
  2467.             GROUP BY DATE_FORMAT(purchase_invoice_date, '%Y-%m')
  2468.             ORDER BY month ASC
  2469.         ", ['companyId' => $companyId]);
  2470.         $requisitionTrendRows $conn->fetchAllAssociative("
  2471.             SELECT DATE_FORMAT(purchase_requisition_date, '%Y-%m') AS month, COUNT(*) AS total
  2472.             FROM purchase_requisition
  2473.             WHERE company_id = :companyId
  2474.               AND status = 1
  2475.               AND purchase_requisition_date >= DATE_SUB(CURDATE(), INTERVAL 5 MONTH)
  2476.             GROUP BY DATE_FORMAT(purchase_requisition_date, '%Y-%m')
  2477.             ORDER BY month ASC
  2478.         ", ['companyId' => $companyId]);
  2479.         $seriesFromRows = function (array $rows, array $monthKeys) {
  2480.             $series array_fill_keys($monthKeys0);
  2481.             foreach ($rows as $row) {
  2482.                 $month $row['month'] ?? null;
  2483.                 if ($month !== null && array_key_exists($month$series)) {
  2484.                     $series[$month] = (float) $row['total'];
  2485.                 }
  2486.             }
  2487.             return array_values($series);
  2488.         };
  2489.         $purchaseOrderTotal = (float) $conn->fetchOne("
  2490.             SELECT COALESCE(SUM(CAST(COALESCE(NULLIF(po_amount, ''), 0) AS DECIMAL(15,2))), 0)
  2491.             FROM purchase_order
  2492.             WHERE company_id = :companyId AND status = 1 AND approved = 1
  2493.         ", ['companyId' => $companyId]);
  2494.         $purchaseInvoiceTotal = (float) $conn->fetchOne("
  2495.             SELECT COALESCE(SUM(CAST(COALESCE(NULLIF(invoice_amount, ''), 0) AS DECIMAL(15,2))), 0)
  2496.             FROM purchase_invoice
  2497.             WHERE company_id = :companyId AND status = 1 AND approved = 1
  2498.         ", ['companyId' => $companyId]);
  2499.         $purchasePaidTotal = (float) $conn->fetchOne("
  2500.             SELECT COALESCE(SUM(CAST(COALESCE(NULLIF(paid_amount, ''), invoice_amount, 0) AS DECIMAL(15,2))), 0)
  2501.             FROM purchase_invoice
  2502.             WHERE company_id = :companyId AND status = 1 AND approved = 1
  2503.         ", ['companyId' => $companyId]);
  2504.         $purchaseRequisitionCount = (int) $conn->fetchOne("
  2505.             SELECT COUNT(*)
  2506.             FROM purchase_requisition
  2507.             WHERE company_id = :companyId AND status = 1
  2508.         ", ['companyId' => $companyId]);
  2509.         $purchaseOrderCount = (int) $conn->fetchOne("
  2510.             SELECT COUNT(*)
  2511.             FROM purchase_order
  2512.             WHERE company_id = :companyId AND status = 1 AND approved = 1
  2513.         ", ['companyId' => $companyId]);
  2514.         $purchaseInvoiceCount = (int) $conn->fetchOne("
  2515.             SELECT COUNT(*)
  2516.             FROM purchase_invoice
  2517.             WHERE company_id = :companyId AND status = 1 AND approved = 1
  2518.         ", ['companyId' => $companyId]);
  2519.         $pendingPurchaseRequisitionCount = (int) $conn->fetchOne("
  2520.             SELECT COUNT(*)
  2521.             FROM purchase_requisition
  2522.             WHERE company_id = :companyId AND status = 1 AND COALESCE(approved, 0) = 0
  2523.         ", ['companyId' => $companyId]);
  2524.         $pendingPurchaseOrderCount = (int) $conn->fetchOne("
  2525.             SELECT COUNT(*)
  2526.             FROM purchase_order
  2527.             WHERE company_id = :companyId AND status = 1 AND COALESCE(approved, 0) = 0
  2528.         ", ['companyId' => $companyId]);
  2529.         $pendingPurchaseInvoiceCount = (int) $conn->fetchOne("
  2530.             SELECT COUNT(*)
  2531.             FROM purchase_invoice
  2532.             WHERE company_id = :companyId AND status = 1 AND COALESCE(approved, 0) = 0
  2533.         ", ['companyId' => $companyId]);
  2534.         $supplierCount = (int) $conn->fetchOne("
  2535.             SELECT COUNT(DISTINCT supplier_id)
  2536.             FROM purchase_order
  2537.             WHERE company_id = :companyId AND status = 1 AND approved = 1
  2538.         ", ['companyId' => $companyId]);
  2539.         $topSuppliers $conn->fetchAllAssociative("
  2540.             SELECT po.supplier_id, s.supplier_name, COALESCE(SUM(CAST(COALESCE(NULLIF(po.po_amount, ''), 0) AS DECIMAL(15,2))), 0) AS total
  2541.             FROM purchase_order po
  2542.             LEFT JOIN acc_suppliers s ON s.supplier_id = po.supplier_id
  2543.             WHERE po.company_id = :companyId AND po.status = 1 AND po.approved = 1
  2544.             GROUP BY po.supplier_id, s.supplier_name
  2545.             ORDER BY total DESC
  2546.             LIMIT 5
  2547.         ", ['companyId' => $companyId]);
  2548.         $topSupplierTotal 0;
  2549.         foreach ($topSuppliers as $row) {
  2550.             $topSupplierTotal += (float) $row['total'];
  2551.         }
  2552.         $funnelBase max($purchaseRequisitionCount$purchaseOrderCount$purchaseInvoiceCount1);
  2553.         $paidCoverage $purchaseInvoiceTotal ? ($purchasePaidTotal $purchaseInvoiceTotal) * 100 0;
  2554.         return array(
  2555.             'kpis' => array(
  2556.                 array('label' => 'Purchase Orders''value' => $purchaseOrderCount'note' => 'Approved and active''icon' => 'shopping-cart''color' => 'blue'),
  2557.                 array('label' => 'Invoice Value''value' => $purchaseInvoiceTotal'note' => 'Billed through the period''icon' => 'file-text''color' => 'green'),
  2558.                 array('label' => 'Paid Value''value' => $purchasePaidTotal'note' => 'Settled to suppliers''icon' => 'check-circle''color' => 'teal'),
  2559.                 array('label' => 'Outstanding Due''value' => max($purchaseInvoiceTotal $purchasePaidTotal0), 'note' => 'Open supplier liability''icon' => 'hourglass-half''color' => 'red'),
  2560.                 array('label' => 'Suppliers''value' => $supplierCount'note' => 'Active vendor base''icon' => 'building''color' => 'amber'),
  2561.                 array('label' => 'Open Requisitions''value' => $pendingPurchaseRequisitionCount'note' => 'Waiting for movement''icon' => 'tasks''color' => 'slate'),
  2562.             ),
  2563.             'pending_total' => $pendingPurchaseRequisitionCount $pendingPurchaseOrderCount $pendingPurchaseInvoiceCount,
  2564.             'pending_items' => array(
  2565.                 array('label' => 'Requisitions''value' => $pendingPurchaseRequisitionCount'note' => 'Needs buy-side review'),
  2566.                 array('label' => 'Purchase Orders''value' => $pendingPurchaseOrderCount'note' => 'Waiting for approval'),
  2567.                 array('label' => 'Purchase Invoices''value' => $pendingPurchaseInvoiceCount'note' => 'Pending matching'),
  2568.             ),
  2569.             'hero' => array(
  2570.                 'labels' => $monthLabels,
  2571.                 'series' => array(
  2572.                     array('label' => 'PO Value''values' => $seriesFromRows($poTrendRows$monthKeys), 'color' => '#3D7DB8''fill' => 'rgba(61,125,184,0.14)'),
  2573.                     array('label' => 'Invoice Value''values' => $seriesFromRows($invoiceTrendRows$monthKeys), 'color' => '#4BAA6B''fill' => 'rgba(75,170,107,0.14)'),
  2574.                     array('label' => 'Paid Value''values' => $seriesFromRows($paidTrendRows$monthKeys), 'color' => '#2F9E91''fill' => 'rgba(47,158,145,0.14)'),
  2575.                 ),
  2576.             ),
  2577.             'hero_summary' => array(
  2578.                 'headline' => $purchaseInvoiceTotal round($paidCoverage1) . '%' '0%',
  2579.                 'headline_label' => 'Payment coverage',
  2580.                 'subhead' => 'Paid ' round($paidCoverage1) . '% of billed value',
  2581.             ),
  2582.             'snapshot' => array(
  2583.                 'label' => 'Procurement Health',
  2584.                 'ring_value' => round($paidCoverage1),
  2585.                 'ring_note' => 'Invoice coverage',
  2586.                 'metrics' => array(
  2587.                     array('label' => 'Requisition to PO''value' => $purchaseRequisitionCount round(($purchaseOrderCount $purchaseRequisitionCount) * 1001) . '%' '0%''note' => 'Flow conversion'),
  2588.                     array('label' => 'Average PO Size''value' => $purchaseOrderCount number_format($purchaseOrderTotal $purchaseOrderCount0'.'',') : '0''note' => 'Approved order value'),
  2589.                     array('label' => 'Due Ratio''value' => $purchaseInvoiceTotal round((max($purchaseInvoiceTotal $purchasePaidTotal0) / $purchaseInvoiceTotal) * 1001) . '%' '0%''note' => 'Open liability share'),
  2590.                     array('label' => 'Supplier Concentration''value' => $purchaseOrderTotal round(($topSupplierTotal $purchaseOrderTotal) * 1001) . '%' '0%''note' => 'Top-5 spend share'),
  2591.                 ),
  2592.             ),
  2593.             'lower_cards' => array(
  2594.                 array(
  2595.                     'title' => 'Pipeline Atlas',
  2596.                     'subtitle' => 'Requisition to payment flow',
  2597.                     'type' => 'pipeline',
  2598.                     'items' => array(
  2599.                         array('label' => 'Requisitions''value' => $purchaseRequisitionCount'note' => 'Planning demand'),
  2600.                         array('label' => 'Purchase Orders''value' => $purchaseOrderCount'note' => 'Committed spend'),
  2601.                         array('label' => 'Purchase Invoices''value' => $purchaseInvoiceCount'note' => 'Vendor billing'),
  2602.                         array('label' => 'Settled''value' => (int) $conn->fetchOne("SELECT COUNT(*) FROM purchase_invoice WHERE company_id = :companyId AND status = 1 AND approved = 1 AND CAST(COALESCE(NULLIF(paid_amount, ''), 0) AS DECIMAL(15,2)) > 0", ['companyId' => $companyId]), 'note' => 'Cash released'),
  2603.                     ),
  2604.                     'base' => $funnelBase,
  2605.                 ),
  2606.                 array(
  2607.                     'title' => 'Supplier Mix',
  2608.                     'subtitle' => 'Concentration by approved spend',
  2609.                     'type' => 'bars',
  2610.                     'items' => array_map(function ($row) use ($topSupplierTotal) {
  2611.                         $total = (float) $row['total'];
  2612.                         return array(
  2613.                             'label' => $row['supplier_name'] ?: ('Supplier #' $row['supplier_id']),
  2614.                             'value' => $total,
  2615.                             'bar' => $topSupplierTotal round(($total $topSupplierTotal) * 1001) : 0,
  2616.                             'note' => 'Approved spend share',
  2617.                         );
  2618.                     }, $topSuppliers),
  2619.                 ),
  2620.                 array(
  2621.                     'title' => 'Spend Lens',
  2622.                     'subtitle' => 'Analytical ratios that matter',
  2623.                     'type' => 'ratios',
  2624.                     'items' => array(
  2625.                         array('label' => 'Payment Coverage''value' => round($paidCoverage1) . '%''bar' => $paidCoverage'note' => 'Cash settled vs billed'),
  2626.                         array('label' => 'Requisition Coverage''value' => $purchaseRequisitionCount round(($purchaseOrderCount $purchaseRequisitionCount) * 1001) . '%' '0%''bar' => $purchaseRequisitionCount ? (($purchaseOrderCount $purchaseRequisitionCount) * 100) : 0'note' => 'POs created from requests'),
  2627.                         array('label' => 'Open Due''value' => number_format(max($purchaseInvoiceTotal $purchasePaidTotal0), 0'.'','), 'bar' => $purchaseInvoiceTotal ? ((max($purchaseInvoiceTotal $purchasePaidTotal0) / $purchaseInvoiceTotal) * 100) : 0'note' => 'Balance still outstanding'),
  2628.                     ),
  2629.                 ),
  2630.             ),
  2631.             'months' => $monthLabels
  2632.         );
  2633.     }
  2634.     private function buildInventoryDashboardAnalytics($em$companyId)
  2635.     {
  2636.         $conn $em->getConnection();
  2637.         $monthKeys = [];
  2638.         $monthLabels = [];
  2639.         for ($i 5$i >= 0$i--) {
  2640.             $month = new \DateTime('first day of this month');
  2641.             if ($i 0) {
  2642.                 $month->modify('-' $i ' month');
  2643.             }
  2644.             $monthKeys[] = $month->format('Y-m');
  2645.             $monthLabels[] = $month->format('M');
  2646.         }
  2647.         $receivedRows $conn->fetchAllAssociative("
  2648.             SELECT DATE_FORMAT(stock_received_note_date, '%Y-%m') AS month, COUNT(*) AS total
  2649.             FROM stock_received_note
  2650.             WHERE company_id = :companyId
  2651.               AND status = 1
  2652.               AND approved = 1
  2653.               AND stock_received_note_date >= DATE_SUB(CURDATE(), INTERVAL 5 MONTH)
  2654.             GROUP BY DATE_FORMAT(stock_received_note_date, '%Y-%m')
  2655.             ORDER BY month ASC
  2656.         ", ['companyId' => $companyId]);
  2657.         $transferRows $conn->fetchAllAssociative("
  2658.             SELECT DATE_FORMAT(stock_transfer_date, '%Y-%m') AS month, COUNT(*) AS total
  2659.             FROM stock_transfer
  2660.             WHERE company_id = :companyId
  2661.               AND status = 1
  2662.               AND approved = 1
  2663.               AND stock_transfer_date >= DATE_SUB(CURDATE(), INTERVAL 5 MONTH)
  2664.             GROUP BY DATE_FORMAT(stock_transfer_date, '%Y-%m')
  2665.             ORDER BY month ASC
  2666.         ", ['companyId' => $companyId]);
  2667.         $consumptionRows $conn->fetchAllAssociative("
  2668.             SELECT DATE_FORMAT(stock_consumption_note_date, '%Y-%m') AS month, COUNT(*) AS total
  2669.             FROM stock_consumption_note
  2670.             WHERE company_id = :companyId
  2671.               AND status = 1
  2672.               AND approved = 1
  2673.               AND stock_consumption_note_date >= DATE_SUB(CURDATE(), INTERVAL 5 MONTH)
  2674.             GROUP BY DATE_FORMAT(stock_consumption_note_date, '%Y-%m')
  2675.             ORDER BY month ASC
  2676.         ", ['companyId' => $companyId]);
  2677.         $seriesFromRows = function (array $rows, array $monthKeys) {
  2678.             $series array_fill_keys($monthKeys0);
  2679.             foreach ($rows as $row) {
  2680.                 $month $row['month'] ?? null;
  2681.                 if ($month !== null && array_key_exists($month$series)) {
  2682.                     $series[$month] = (float) $row['total'];
  2683.                 }
  2684.             }
  2685.             return array_values($series);
  2686.         };
  2687.         $skuCount = (int) $conn->fetchOne("
  2688.             SELECT COUNT(*)
  2689.             FROM inv_products
  2690.             WHERE company_id = :companyId AND status = 1
  2691.         ", ['companyId' => $companyId]);
  2692.         $totalUnits = (float) $conn->fetchOne("
  2693.             SELECT COALESCE(SUM(CAST(COALESCE(NULLIF(qty, ''), 0) AS DECIMAL(15,2))), 0)
  2694.             FROM inv_products
  2695.             WHERE company_id = :companyId AND status = 1
  2696.         ", ['companyId' => $companyId]);
  2697.         $stockValue = (float) $conn->fetchOne("
  2698.             SELECT COALESCE(SUM(CAST(COALESCE(NULLIF(qty, ''), 0) AS DECIMAL(15,2)) * CAST(COALESCE(NULLIF(curr_purchase_price, ''), 0) AS DECIMAL(15,2))), 0)
  2699.             FROM inv_products
  2700.             WHERE company_id = :companyId AND status = 1
  2701.         ", ['companyId' => $companyId]);
  2702.         $lowStockCount = (int) $conn->fetchOne("
  2703.             SELECT COUNT(*)
  2704.             FROM inv_products
  2705.             WHERE company_id = :companyId
  2706.               AND status = 1
  2707.               AND CAST(COALESCE(NULLIF(qty, ''), 0) AS DECIMAL(15,2)) <= CAST(COALESCE(NULLIF(reorder_level, ''), 0) AS DECIMAL(15,2))
  2708.               AND CAST(COALESCE(NULLIF(reorder_level, ''), 0) AS DECIMAL(15,2)) > 0
  2709.         ", ['companyId' => $companyId]);
  2710.         $zeroStockCount = (int) $conn->fetchOne("
  2711.             SELECT COUNT(*)
  2712.             FROM inv_products
  2713.             WHERE company_id = :companyId AND status = 1 AND CAST(COALESCE(NULLIF(qty, ''), 0) AS DECIMAL(15,2)) <= 0
  2714.         ", ['companyId' => $companyId]);
  2715.         $overstockCount = (int) $conn->fetchOne("
  2716.             SELECT COUNT(*)
  2717.             FROM inv_products
  2718.             WHERE company_id = :companyId
  2719.               AND status = 1
  2720.               AND CAST(COALESCE(NULLIF(reorder_level, ''), 0) AS DECIMAL(15,2)) > 0
  2721.               AND CAST(COALESCE(NULLIF(qty, ''), 0) AS DECIMAL(15,2)) > (CAST(COALESCE(NULLIF(reorder_level, ''), 0) AS DECIMAL(15,2)) * 3)
  2722.         ", ['companyId' => $companyId]);
  2723.         $warehouseCount = (int) $conn->fetchOne("
  2724.             SELECT COUNT(*)
  2725.             FROM warehouse
  2726.             WHERE company_id = :companyId AND status = 1
  2727.         ", ['companyId' => $companyId]);
  2728.         $receivedPending = (int) $conn->fetchOne("
  2729.             SELECT COUNT(*)
  2730.             FROM stock_received_note
  2731.             WHERE company_id = :companyId AND status = 1 AND COALESCE(approved, 0) = 0
  2732.         ", ['companyId' => $companyId]);
  2733.         $transferPending = (int) $conn->fetchOne("
  2734.             SELECT COUNT(*)
  2735.             FROM stock_transfer
  2736.             WHERE company_id = :companyId AND status = 1 AND COALESCE(approved, 0) = 0
  2737.         ", ['companyId' => $companyId]);
  2738.         $consumptionPending = (int) $conn->fetchOne("
  2739.             SELECT COUNT(*)
  2740.             FROM stock_consumption_note
  2741.             WHERE company_id = :companyId AND status = 1 AND COALESCE(approved, 0) = 0
  2742.         ", ['companyId' => $companyId]);
  2743.         $receivedCount = (int) $conn->fetchOne("
  2744.             SELECT COUNT(*)
  2745.             FROM stock_received_note
  2746.             WHERE company_id = :companyId AND status = 1 AND approved = 1
  2747.         ", ['companyId' => $companyId]);
  2748.         $transferCount = (int) $conn->fetchOne("
  2749.             SELECT COUNT(*)
  2750.             FROM stock_transfer
  2751.             WHERE company_id = :companyId AND status = 1 AND approved = 1
  2752.         ", ['companyId' => $companyId]);
  2753.         $consumptionCount = (int) $conn->fetchOne("
  2754.             SELECT COUNT(*)
  2755.             FROM stock_consumption_note
  2756.             WHERE company_id = :companyId AND status = 1 AND approved = 1
  2757.         ", ['companyId' => $companyId]);
  2758.         $warehouseMap = \ApplicationBundle\Modules\Inventory\Inventory::WarehouseList($em$companyId);
  2759.         $warehouseRows $conn->fetchAllAssociative("
  2760.             SELECT warehouse_id, COALESCE(SUM(CAST(COALESCE(NULLIF(qty, ''), 0) AS DECIMAL(15,2))), 0) AS total_qty,
  2761.                    COALESCE(SUM(CAST(COALESCE(NULLIF(qty, ''), 0) AS DECIMAL(15,2)) * CAST(COALESCE(NULLIF(curr_purchase_price, ''), 0) AS DECIMAL(15,2))), 0) AS total_value
  2762.             FROM inventory_storage
  2763.             WHERE company_id = :companyId
  2764.             GROUP BY warehouse_id
  2765.             ORDER BY total_value DESC
  2766.             LIMIT 5
  2767.         ", ['companyId' => $companyId]);
  2768.         $productRows $conn->fetchAllAssociative("
  2769.             SELECT s.product_id, p.name, p.reorder_level,
  2770.                    COALESCE(SUM(CAST(COALESCE(NULLIF(s.qty, ''), 0) AS DECIMAL(15,2))), 0) AS total_qty,
  2771.                    COALESCE(SUM(CAST(COALESCE(NULLIF(s.qty, ''), 0) AS DECIMAL(15,2)) * CAST(COALESCE(NULLIF(s.curr_purchase_price, ''), 0) AS DECIMAL(15,2))), 0) AS total_value
  2772.             FROM inventory_storage s
  2773.             LEFT JOIN inv_products p ON p.id = s.product_id
  2774.             WHERE s.company_id = :companyId
  2775.             GROUP BY s.product_id, p.name, p.reorder_level
  2776.             ORDER BY total_value DESC
  2777.             LIMIT 5
  2778.         ", ['companyId' => $companyId]);
  2779.         $movementBalance $receivedCount $consumptionCount;
  2780.         $healthIndex $skuCount max(0100 round(($lowStockCount $skuCount) * 100)) : 0;
  2781.         $reorderPressure $skuCount round(($lowStockCount $skuCount) * 1001) : 0;
  2782.         $stockCoverage $warehouseCount round($totalUnits $warehouseCount1) : 0;
  2783.         $topWarehouseTotal 0;
  2784.         foreach ($warehouseRows as $row) {
  2785.             $topWarehouseTotal += (float) $row['total_value'];
  2786.         }
  2787.         $topProductTotal 0;
  2788.         foreach ($productRows as $row) {
  2789.             $topProductTotal += (float) $row['total_value'];
  2790.         }
  2791.         return array(
  2792.             'kpis' => array(
  2793.                 array('label' => 'SKUs''value' => $skuCount'note' => 'Active item master''icon' => 'cube''color' => 'blue'),
  2794.                 array('label' => 'On-hand Units''value' => $totalUnits'note' => 'Current quantity snapshot''icon' => 'cubes''color' => 'green'),
  2795.                 array('label' => 'Stock Value''value' => $stockValue'note' => 'Book value at purchase cost''icon' => 'database''color' => 'teal'),
  2796.                 array('label' => 'Low Stock SKUs''value' => $lowStockCount'note' => 'At or below reorder point''icon' => 'exclamation-triangle''color' => 'red'),
  2797.                 array('label' => 'Warehouses''value' => $warehouseCount'note' => 'Active storage nodes''icon' => 'warehouse''color' => 'amber'),
  2798.                 array('label' => 'Pending Docs''value' => $receivedPending $transferPending $consumptionPending'note' => 'Awaiting approval''icon' => 'hourglass-half''color' => 'slate'),
  2799.             ),
  2800.             'pending_total' => $receivedPending $transferPending $consumptionPending,
  2801.             'pending_items' => array(
  2802.                 array('label' => 'Stock Received''value' => $receivedPending'note' => 'Incoming goods'),
  2803.                 array('label' => 'Stock Transfer''value' => $transferPending'note' => 'Warehouse movement'),
  2804.                 array('label' => 'Consumption Notes''value' => $consumptionPending'note' => 'Consumption posting'),
  2805.             ),
  2806.             'hero' => array(
  2807.                 'labels' => $monthLabels,
  2808.                 'series' => array(
  2809.                     array('label' => 'Received''values' => $seriesFromRows($receivedRows$monthKeys), 'color' => '#3D7DB8''fill' => 'rgba(61,125,184,0.14)'),
  2810.                     array('label' => 'Transfers''values' => $seriesFromRows($transferRows$monthKeys), 'color' => '#D4A843''fill' => 'rgba(212,168,67,0.14)'),
  2811.                     array('label' => 'Consumed''values' => $seriesFromRows($consumptionRows$monthKeys), 'color' => '#C05350''fill' => 'rgba(192,83,80,0.14)'),
  2812.                 ),
  2813.             ),
  2814.             'hero_summary' => array(
  2815.                 'headline' => $healthIndex '%',
  2816.                 'headline_label' => 'Health index',
  2817.                 'subhead' => 'Low stock pressure at ' $reorderPressure '%',
  2818.             ),
  2819.             'snapshot' => array(
  2820.                 'label' => 'Stock Health',
  2821.                 'ring_value' => $healthIndex,
  2822.                 'ring_note' => 'Health index',
  2823.                 'metrics' => array(
  2824.                     array('label' => 'Low Stock Pressure''value' => $reorderPressure '%''note' => 'At or under reorder'),
  2825.                     array('label' => 'Movement Balance''value' => $movementBalance'note' => 'Received minus consumed'),
  2826.                     array('label' => 'Avg Units / Warehouse''value' => $stockCoverage'note' => 'Distribution breadth'),
  2827.                     array('label' => 'Zero Stock SKUs''value' => $zeroStockCount'note' => 'Immediate attention'),
  2828.                 ),
  2829.             ),
  2830.             'lower_cards' => array(
  2831.                 array(
  2832.                     'title' => 'Reorder Radar',
  2833.                     'subtitle' => 'What needs intervention now',
  2834.                     'type' => 'radar',
  2835.                     'items' => array(
  2836.                         array('label' => 'Low Stock''value' => $lowStockCount'bar' => $skuCount ? (($lowStockCount $skuCount) * 100) : 0'note' => 'At reorder threshold'),
  2837.                         array('label' => 'Zero Stock''value' => $zeroStockCount'bar' => $skuCount ? (($zeroStockCount $skuCount) * 100) : 0'note' => 'Unavailable items'),
  2838.                         array('label' => 'Overstock''value' => $overstockCount'bar' => $skuCount ? (($overstockCount $skuCount) * 100) : 0'note' => 'Potential capital lock-up'),
  2839.                         array('label' => 'Movement Balance''value' => $movementBalance'bar' => max(0min(10050 + ($movementBalance 5))), 'note' => 'Inbound vs consumption'),
  2840.                     ),
  2841.                 ),
  2842.                 array(
  2843.                     'title' => 'Warehouse Atlas',
  2844.                     'subtitle' => 'Value concentration by store',
  2845.                     'type' => 'bars',
  2846.                     'items' => array_map(function ($row) use ($warehouseMap$topWarehouseTotal) {
  2847.                         $warehouseId = (int) $row['warehouse_id'];
  2848.                         $warehouseName = isset($warehouseMap[$warehouseId]['name']) ? $warehouseMap[$warehouseId]['name'] : ('Warehouse #' $warehouseId);
  2849.                         $total = (float) $row['total_value'];
  2850.                         return array(
  2851.                             'label' => $warehouseName,
  2852.                             'value' => $total,
  2853.                             'bar' => $topWarehouseTotal round(($total $topWarehouseTotal) * 1001) : 0,
  2854.                             'note' => 'Stock value share',
  2855.                         );
  2856.                     }, $warehouseRows),
  2857.                 ),
  2858.                 array(
  2859.                     'title' => 'Value Lens',
  2860.                     'subtitle' => 'Highest value stock pockets',
  2861.                     'type' => 'products',
  2862.                     'items' => array_map(function ($row) use ($topProductTotal) {
  2863.                         $total = (float) $row['total_value'];
  2864.                         $reorderLevel = isset($row['reorder_level']) ? (float) $row['reorder_level'] : 0;
  2865.                         return array(
  2866.                             'label' => $row['name'] ?: ('SKU #' $row['product_id']),
  2867.                             'value' => $total,
  2868.                             'bar' => $topProductTotal round(($total $topProductTotal) * 1001) : 0,
  2869.                             'note' => 'Reorder level ' number_format($reorderLevel0'.'','),
  2870.                         );
  2871.                     }, $productRows),
  2872.                 ),
  2873.             ),
  2874.             'months' => $monthLabels
  2875.         );
  2876.     }
  2877.     public function indexServiceAction(Request $request)
  2878.     {
  2879.         $session $request->getSession();
  2880.         $dashboardDataForUser = [];
  2881.         $em $this->getDoctrine()->getManager();
  2882.         $companyId $this->getLoggedUserCompanyId($request);
  2883.         $userId $request->getSession()->get(UserConstants::USER_ID);
  2884.         $dbQuery $em->getRepository("ApplicationBundle\\Entity\\DashboardWidget")->findBy(
  2885.             array(
  2886.                 'CompanyId' => $companyId,
  2887.                 'userId' => $userId,
  2888.                 'status' => GeneralConstant::ACTIVE
  2889.             ),
  2890.             array(
  2891.                 'sequence' => 'ASC'
  2892.             )
  2893.         );
  2894.         if (empty($dbQuery))   ///now get the defaults
  2895.             $dbQuery $em->getRepository("ApplicationBundle\\Entity\\DashboardWidget")->findBy(
  2896.                 array(
  2897.                     'CompanyId' => $companyId,
  2898.                     //                    'userId'=>$userId,
  2899.                     'defaultBoxFlag' => 1,
  2900.                     'status' => GeneralConstant::ACTIVE
  2901.                 ),
  2902.                 array(
  2903.                     'sequence' => 'ASC'
  2904.                 )
  2905.             );
  2906.         foreach ($dbQuery as $entry) {
  2907.             $dashboardDataForUser[] = array(
  2908.                 'id' => $entry->getId(),
  2909.                 'widgetId' => $entry->getId(),
  2910.                 'widgetSequence' => $entry->getSequence(),
  2911.                 'widgetStatus' => $entry->getStatus(),
  2912.                 'widgetData' => json_decode($entry->getData(), true),
  2913.                 'defaultBoxFlag' => $entry->getDefaultBoxFlag(),
  2914.                 'widgetSizeTiny' => $entry->getSizeTiny(),
  2915.                 'widgetSizeSmall' => $entry->getSizeSmall(),
  2916.                 'widgetSizeMedium' => $entry->getSizeMedium(),
  2917.                 'widgetSizeLarge' => $entry->getSizeLarge(),
  2918.                 'refreshInterval' => $entry->getRefreshInterval(),
  2919.             );
  2920.         }
  2921.         return $this->render(
  2922.             '@Application/pages/dashboard/index_sales.html.twig',
  2923.             array(
  2924.                 'page_title' => 'Sales Dashboard',
  2925.                 'dashboardDataForUser' => $dashboardDataForUser
  2926.             )
  2927.         );
  2928.     }
  2929.     public function modifyDashboardAction(Request $request)
  2930.     {
  2931.         $session $request->getSession();
  2932.         $em $this->getDoctrine()->getManager();
  2933.         $companyId $this->getLoggedUserCompanyId($request);
  2934.         $userId $request->getSession()->get(UserConstants::USER_ID);
  2935.         if ($request->isMethod('post')) {
  2936.             //update dashboard data
  2937.             if ($request->request->has('widgetId')) {
  2938.                 foreach ($request->request->get('widgetId') as $k => $v) {
  2939.                     if ($v != 0) {
  2940.                         //exists sso edit
  2941.                         $widget $em->getRepository("ApplicationBundle\\Entity\\DashboardWidget")->findOneBy(
  2942.                             array(
  2943.                                 'id' => $v,
  2944.                             )
  2945.                         );
  2946.                     } else
  2947.                         $widget = new DashboardWidget();
  2948.                     $widget->setData($request->request->get('widgetData')[$k]);
  2949.                     $widget->setSequence($request->request->get('widgetSequence')[$k]);
  2950.                     $widget->setStatus($request->request->has('widgetStatus') ? $request->request->get('widgetStatus')[$k] : GeneralConstant::ACTIVE);
  2951.                     $widget->setUserId($userId);
  2952.                     $widget->setCompanyId($companyId);
  2953.                     $widget->setDefaultBoxFlag($request->request->has('defaultBoxFlag') ? $request->request->get('defaultBoxFlag')[$k] : 0);
  2954.                     if ($v == 0)
  2955.                         $em->persist($widget);
  2956.                     $em->flush();
  2957.                 }
  2958.             }
  2959.         }
  2960.         $dashboardDataForUser = [];
  2961.         $dbQuery $em->getRepository("ApplicationBundle\\Entity\\DashboardWidget")->findBy(
  2962.             array(
  2963.                 'CompanyId' => $companyId,
  2964.                 'userId' => $userId,
  2965.                 'status' => GeneralConstant::ACTIVE
  2966.             )
  2967.         );
  2968.         if (empty($dbQuery))   ///now get the defaults
  2969.             $dbQuery $em->getRepository("ApplicationBundle\\Entity\\DashboardWidget")->findBy(
  2970.                 array(
  2971.                     'CompanyId' => $companyId,
  2972.                     //                    'userId'=>$userId,
  2973.                     'defaultBoxFlag' => 1,
  2974.                     'status' => GeneralConstant::ACTIVE
  2975.                 )
  2976.             );
  2977.         foreach ($dbQuery as $entry) {
  2978.             $dashboardDataForUser[] = array(
  2979.                 'id' => $entry->getId(),
  2980.                 'widgetId' => $entry->getId(),
  2981.                 'widgetSequence' => $entry->getSequence(),
  2982.                 'widgetStatus' => $entry->getStatus(),
  2983.                 'widgetData' => $entry->getData(),
  2984.                 'defaultBoxFlag' => $entry->getDefaultBoxFlag(),
  2985.                 'widgetSizeTiny' => $entry->getSizeTiny(),
  2986.                 'widgetSizeSmall' => $entry->getSizeSmall(),
  2987.                 'widgetSizeMedium' => $entry->getSizeMedium(),
  2988.                 'widgetSizeLarge' => $entry->getSizeLarge(),
  2989.                 'refreshInterval' => $entry->getRefreshInterval(),
  2990.             );
  2991.         }
  2992.         //1st try to see if any exists
  2993.         return $this->render(
  2994.             '@Application/pages/dashboard/index_sales.html.twig',
  2995.             array(
  2996.                 'page_title' => 'Modify Dashboard'
  2997.             )
  2998.         );
  2999.     }
  3000.     public function ChangeCompanyDashboardAction(Request $request$id 1)
  3001.     {
  3002.         $session $request->getSession();
  3003.         if ($request->query->has('sys_admin_panel'))
  3004.             return $this->redirectToRoute('system_admin_dashboard');
  3005.         else {
  3006.             $session->set(UserConstants::USER_COMPANY_ID$id);
  3007.             return $this->redirectToRoute('dashboard');
  3008.         }
  3009.     }
  3010.     public function ChangeLeftPanelDisplayStatusAction(Request $request)
  3011.     {
  3012.         $session $request->getSession();
  3013.         $curr_status 1;
  3014.         if ($session->has('HIDE_LEFT_PANEL'))
  3015.             $curr_status $session->get('HIDE_LEFT_PANEL');
  3016.         if ($curr_status == 1)
  3017.             $curr_status 0;
  3018.         else
  3019.             $curr_status 1;
  3020.         $session->set('HIDE_LEFT_PANEL'$curr_status);
  3021.         //            return $this->redirectToRoute('dashboard');
  3022.         return new Response($curr_status);
  3023.     }
  3024.     public function PermissionDeniedAction(Request $request)
  3025.     {
  3026.         $session $request->getSession();
  3027.         // Generic::debugMessage($session);
  3028.         return $this->render(
  3029.             '@System/pages/permission_denied.html.twig',
  3030.             array(
  3031.                 'page_title' => 'Permission Denied'
  3032.             )
  3033.         );
  3034.     }
  3035.     public function MyDocumentsAction(Request $request)
  3036.     {
  3037.         $session $request->getSession();
  3038.         $em $this->getDoctrine()->getManager();
  3039.         $data MiscActions::getDocumentsByUserId($em$session->get(UserConstants::USER_ID));
  3040.         // DOC-001: the view calls path(item.documentViewPathName); if an entity's
  3041.         // registered view-route name is stale/unregistered, path() throws and the
  3042.         // whole page 500s the moment a user owns a document of that type. Validate
  3043.         // each route against the router and fall back to a safe one.
  3044.         $routes $this->container->get('router')->getRouteCollection();
  3045.         if (is_array($data)) {
  3046.             foreach ($data as $k => $item) {
  3047.                 $rn = isset($item['documentViewPathName']) ? $item['documentViewPathName'] : '';
  3048.                 if ($rn === '' || $routes->get($rn) === null) {
  3049.                     $data[$k]['documentViewPathName'] = 'dashboard';
  3050.                 }
  3051.             }
  3052.         }
  3053.         return $this->render(
  3054.             '@Application/pages/dashboard/my_documents.html.twig',
  3055.             array(
  3056.                 'page_title' => 'My Documents',
  3057.                 'data' => $data
  3058.             )
  3059.         );
  3060.     }
  3061.     //     public function MyDocumentsListForAppAction(Request $request)
  3062.     //     {
  3063.     //         $session = $request->getSession();
  3064.     //         $em = $this->getDoctrine()->getManager();
  3065.     //         $absoluteUrlList = [];
  3066.     //         foreach (GeneralConstant::$Entity_list_details as $e => $d) {
  3067.     //             if (isset($d['entity_print_route_path_name']))
  3068.     //                 $absoluteUrlList[$e] = $this->generateUrl($d['entity_print_route_path_name'], [], UrlGenerator::ABSOLUTE_URL);
  3069.     //         }
  3070.     //         $data = MiscActions::getDocumentsByUserIdForApp($em, $session->get(UserConstants::USER_ID), 1, $absoluteUrlList);
  3071.     //         // Generic::debugMessage($session);
  3072.     //         return new JsonResponse(array(
  3073.     //             'data' => $data
  3074.     //         ));
  3075.     // //        return $this->render('ApplicationBundle:pages/dashboard:my_documents.html.twig',
  3076.     // //            array(
  3077.     // //                'page_title' => 'My Documents',
  3078.     // //                'data' => $data
  3079.     // //            )
  3080.     // //        );
  3081.     //     }
  3082.     public function MyDocumentsListForAppAction(Request $request)
  3083.     {
  3084.         $session $request->getSession();
  3085.         $em $this->getDoctrine()->getManager();
  3086.         // Build absolute URL list
  3087.         $absoluteUrlList = [];
  3088.         foreach (GeneralConstant::$Entity_list_details as $e => $d) {
  3089.             if (isset($d['entity_print_route_path_name'])) {
  3090.                 $absoluteUrlList[$e] = $this->generateUrl($d['entity_print_route_path_name'], [], UrlGenerator::ABSOLUTE_URL);
  3091.             }
  3092.         }
  3093.         // Extract pagination parameters from the request
  3094.         $page $request->query->get('page''_UNSET_');
  3095.         $offset $request->query->get('offset'0);
  3096.         $limit $request->query->get('limit'10); // default limit is 10
  3097.         // Call the document list method with pagination
  3098.         return new JsonResponse(
  3099.             MiscActions::getDocumentsByUserIdForApp(
  3100.                 $em,
  3101.                 $session->get(UserConstants::USER_ID),
  3102.                 1,
  3103.                 $absoluteUrlList,
  3104.                 $page,
  3105.                 $offset,
  3106.                 $limit
  3107.             )
  3108.         );
  3109.     }
  3110.     public function ShowExceptionAction(Request $requestFlattenException $exceptionDebugLoggerInterface $logger null)
  3111.     {
  3112.         $session $request->getSession();
  3113.         $em $this->getDoctrine()->getManager();
  3114.         // Generic::debugMessage($session);
  3115.         //        $currentContent = $this->getAndCleanOutputBuffering($request->headers->get('X-Php-Ob-Level', -1));
  3116.         //        $showException = $request->attributes->get('showException', $this->debug); // As opposed to an additional parameter, this maintains BC
  3117.         $code $exception->getStatusCode();
  3118.         //        $data = MiscActions::getDocumentsByUserId($em, $session->get(UserConstants::USER_ID));
  3119.         return $this->render(
  3120.             '@Application/pages/error/error_' $code '.html.twig',
  3121.             array(
  3122.                 'page_title' => 'Sorry',
  3123.                 //                'data' => $data
  3124.             )
  3125.         );
  3126.     }
  3127.     public function NotificationAction(Request $request)
  3128.     {
  3129.         $session $request->getSession();
  3130.         //'error', 'success', 'alert', 'information', 'warning', 'confirm'
  3131.         $themes = array(
  3132.             'error' => 'bg-red',
  3133.             'success' => 'bg-green',
  3134.             'alert' => 'bg-purple',
  3135.             'information' => 'bg-grey',
  3136.             'warning' => 'bg-orange',
  3137.             'confirm' => 'bg-blue',
  3138.         );
  3139.         $fa = array(
  3140.             'error' => 'fa fa-ban',
  3141.             'success' => 'fa fa-check',
  3142.             'alert' => 'fa fa-envelope',
  3143.             'information' => 'fa fa-comments',
  3144.             'warning' => 'fa fa-warning',
  3145.             'confirm' => 'fa fa-crosshairs',
  3146.         );
  3147.         // Generic::debugMessage($session);
  3148.         // â”€â”€ DB-first notification list â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€
  3149.         // History is sourced from entity_notification (persistent DB), not the
  3150.         // socket server's in-memory cache which is lost on restart / missing the
  3151.         // /get_all_notification endpoint entirely.
  3152.         $cgEm   $this->getDoctrine()->getManager('company_group');
  3153.         $userId = (int) $request->getSession()->get(UserConstants::USER_ID0);
  3154.         $companyId = (int) $request->getSession()->get(UserConstants::USER_COMPANY_ID0);
  3155.         $filterUnread $request->query->get('filter') === 'unread';
  3156.         $qb $cgEm->getRepository('CompanyGroupBundle\\Entity\\EntityNotification')
  3157.             ->createQueryBuilder('n')
  3158.             ->where('n.userId = :uid')
  3159.             ->setParameter('uid'$userId);
  3160.         if ($filterUnread) {
  3161.             $qb->andWhere('n.seenFlag = 0');
  3162.         }
  3163.         $notifications $qb
  3164.             ->orderBy('n.notificationTs''DESC')
  3165.             ->setMaxResults(100)
  3166.             ->getQuery()
  3167.             ->getResult();
  3168.         $unreadCount = (int) $cgEm->getConnection()->fetchOne(
  3169.             'SELECT COUNT(*) FROM entity_notification WHERE user_id = :uid AND seen_flag = 0',
  3170.             ['uid' => $userId]
  3171.         );
  3172.         return $this->render(
  3173.             '@Application/pages/dashboard/notification.html.twig',
  3174.             array(
  3175.                 'page_title'    => 'Notifications',
  3176.                 'dt'            => $notifications,
  3177.                 'unreadCount'   => $unreadCount,
  3178.                 'filterUnread'  => $filterUnread,
  3179.                 'themes'        => $themes,
  3180.                 'fa'            => $fa,
  3181.             )
  3182.         );
  3183.     }
  3184.     public function NotificationDetailAction(Request $request$id 0)
  3185.     {
  3186.         $em $this->getDoctrine()->getManager('company_group');
  3187.         $notification $em->getRepository('CompanyGroupBundle\\Entity\\EntityNotification')->find($id);
  3188.         if (!$notification) {
  3189.             return $this->render(
  3190.                 '@Application/pages/dashboard/notification_detail.html.twig',
  3191.                 array(
  3192.                     'page_title' => 'Notification Detail',
  3193.                     'notification' => null,
  3194.                     'detailError' => 'Notification not found.',
  3195.                 )
  3196.             );
  3197.         }
  3198.         if ((int) $notification->getSeenFlag() !== 1) {
  3199.             $notification->setSeenFlag(1);
  3200.         }
  3201.         if ((int) $notification->getReadFlag() !== 1) {
  3202.             $notification->setReadFlag(1);
  3203.         }
  3204.         $em->flush();
  3205.         return $this->render(
  3206.             '@Application/pages/dashboard/notification_detail.html.twig',
  3207.             array(
  3208.                 'page_title' => 'Notification Detail',
  3209.                 'notification' => $notification,
  3210.                 'detailError' => '',
  3211.             )
  3212.         );
  3213.     }
  3214.     public function EditAccountAction(Request $request)
  3215.     {
  3216.         $session $request->getSession();
  3217.         //'error', 'success', 'alert', 'information', 'warning', 'confirm'
  3218.         $themes = array(
  3219.             'error' => 'bg-red',
  3220.             'success' => 'bg-green',
  3221.             'alert' => 'bg-purple',
  3222.             'information' => 'bg-aqua',
  3223.             'warning' => 'bg-orange',
  3224.             'confirm' => 'bg-blue',
  3225.         );
  3226.         $fa = array(
  3227.             'error' => 'fa fa-ban',
  3228.             'success' => 'fa fa-check',
  3229.             'alert' => 'fa fa-envelope',
  3230.             'information' => 'fa fa-comments',
  3231.             'warning' => 'fa fa-warning',
  3232.             'confirm' => 'fa fa-crosshairs',
  3233.         );
  3234.         $em $this->getDoctrine()->getManager();
  3235.         $g_path '';
  3236.         if ($request->isMethod('POST')) {
  3237.             $post $request->request;
  3238.             $path "";
  3239.             foreach ($request->files as $uploadedFile) {
  3240.                 if ($uploadedFile != null) {
  3241.                     $fileName md5(uniqid()) . '.' $uploadedFile->guessExtension();
  3242.                     $path $fileName;
  3243.                     $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/FileUploads/' $request->request->get('userId') . '/';
  3244.                     if (!file_exists($upl_dir)) {
  3245.                         mkdir($upl_dir0777true);
  3246.                     }
  3247.                     $file $uploadedFile->move($upl_dir$path);
  3248.                 }
  3249.             }
  3250.             if ($path != "")
  3251.                 $file_path 'uploads/FileUploads/' $request->request->get('userId') . '/' $path;
  3252.             $g_path $this->container->getParameter('kernel.root_dir') . '/../web/uploads/FileUploads/' $request->request->get('userId') . '/' $path;
  3253.             //            $img_file = file_get_contents($g_path);
  3254.             //            $image_data=base64_encode($img_file);
  3255.             //            $encoded_data=System::encryptSignature($image_data,$request->request->get('approvalHash'));
  3256.             $query_here $this->getDoctrine()
  3257.                 ->getRepository('ApplicationBundle\\Entity\\SysUser')
  3258.                 ->findOneBy(
  3259.                     array('userId' => $request->request->get('userId'))
  3260.                 );
  3261.             if ($query_here) {
  3262.                 $new $query_here;
  3263.                 if ($path != "") {
  3264.                     if ($request->request->has('check_pp')) {
  3265.                         $new->setImage($file_path);
  3266.                         $session->set(UserConstants::USER_IMAGE$new->getImage());
  3267.                     } else
  3268.                         $new->setImage('');
  3269.                 }
  3270.                 $new->setName($request->request->get('name'));
  3271.                 $session->set(UserConstants::USER_NAME$request->request->get('name'));
  3272.                 //now password
  3273.                 if ($request->request->get('oldPass') != '') {
  3274.                     //1st check if old pass valid
  3275.                     if (!$this->container->get('app.legacy_password_service')->verifyWithSalt($new->getPassword(), $request->request->get('oldPass'), $new->getSalt())) {
  3276.                         $this->addFlash(
  3277.                             'error',
  3278.                             'Your Old Password Was Wrong'
  3279.                         );
  3280.                     } else {
  3281.                         //old pass valid so now check if neww passes matches
  3282.                         if ($request->request->get('newPass') == $request->request->get('newPassAgain')) {
  3283.                             $new->setSalt(uniqid(mt_rand()));
  3284.                             $password $this->container->get('app.legacy_password_service')->hashWithSalt($request->request->get('newPass'), $new->getSalt());
  3285.                             $new->setPassword($password);
  3286.                             $em->flush();
  3287.                         } else {
  3288.                             $this->addFlash(
  3289.                                 'error',
  3290.                                 'Passwords Did not Match'
  3291.                             );
  3292.                         }
  3293.                     }
  3294.                 }
  3295.             } else {
  3296.                 //                    $new=new EncryptedSignature();
  3297.                 //                    $new->setData($encoded_data);
  3298.                 //                    $new->setUserId($request->request->get('userId'));
  3299.                 //                    $em->persist($new);
  3300.             }
  3301.             $em->flush();
  3302.             //            now deleting the file
  3303.         }
  3304.         $user_data Users::getUserInfoByLoginId($em$this->getLoggedUserLoginId($request));
  3305.         // Generic::debugMessage($session);
  3306.         return $this->render(
  3307.             '@System/pages/settings/edit_account.html.twig',
  3308.             array(
  3309.                 'page_title' => 'Edit Account',
  3310.                 'user_data' => $user_data,
  3311.                 //                'dt'=>json_decode(System::GetAllNotification($request->getSession()->get(UserConstants::USER_ID)),true),
  3312.                 'themes' => $themes,
  3313.                 'fa' => $fa,
  3314.             )
  3315.         );
  3316.     }
  3317.     public function indexApplicantAction(Request $request)
  3318.     {
  3319.         $systemType $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
  3320.         $twig_file '@Application/pages/login/applicant_login.html.twig';
  3321.         $session $request->getSession();
  3322.         if ($systemType == '_BUDDYBEE_') {
  3323.             if ($session->get('buddybeeAdminLevel'0) > 1)
  3324.                 return $this->redirectToRoute("buddybee_admin_dashboard", []);
  3325.             elseif ($session->get('isConsultant') == 1)
  3326.                 return $this->redirectToRoute("consultant_dashboard", []);
  3327.             else
  3328.                 return $this->redirectToRoute("student_dashboard", []);
  3329.         } elseif ($systemType == '_CENTRAL_') {
  3330.             return $this->render(
  3331.                 '@Application/pages/dashboard/index_applicant.html.twig',
  3332.                 array(
  3333.                     'page_title' => 'Applicant Dashboard'
  3334.                 )
  3335.             );
  3336.         } else
  3337.             return $this->render(
  3338.                 '@Application/pages/dashboard/consultant_dashboard.html.twig',
  3339.                 array(
  3340.                     'page_title' => 'Applicant Dashboard'
  3341.                 )
  3342.             );
  3343.     }
  3344.     public function indexCentralLandingAction(Request $request)
  3345.     {
  3346.         $session $request->getSession();
  3347.         $userAccessList $session->get('userAccessList', []);
  3348.         $companyNames array_map(function ($company) {
  3349.             return $company['companyName'];
  3350.         }, $userAccessList);
  3351.         if ($request->isMethod('POST')) {
  3352.             $employeeId $request->request->get('employee_id');
  3353.             $companyName $request->request->get('company_name');
  3354.             if ($employeeId && $companyName) {
  3355.                 return new JsonResponse([
  3356.                     'status' => 'success',
  3357.                     'message' => 'Data received successfully',
  3358.                     'employee_id' => $employeeId,
  3359.                     'company_name' => $companyName,
  3360.                 ]);
  3361.             } else {
  3362.                 return new JsonResponse([
  3363.                     'status' => 'error',
  3364.                     'message' => 'Employee ID or Company Name is missing',
  3365.                 ]);
  3366.             }
  3367.         }
  3368.         // If the request is not a POST request, render the normal page
  3369.         return $this->render(
  3370.             '@Application/pages/dashboard/index_central_landing.html.twig',
  3371.             [
  3372.                 'page_title' => 'Central Landing',
  3373.                 'companyNames' => $companyNames
  3374.             ]
  3375.         );
  3376.     }
  3377.     public function HummanResourceAction()
  3378.     {
  3379.         $em $this->getDoctrine()->getManager();
  3380.         $currentTime = new \Datetime();
  3381.         $currDate $currentTime->format('Y-m-d');
  3382.         $queryBuilder $em->createQueryBuilder();
  3383.         $queryBuilder->select('A.employeeId''A.entry''A.lastIn''A.lastOut''A.currentLocation','A.createdAt''E.name','E.image','D.positionName')
  3384.             ->from('ApplicationBundle\\Entity\\EmployeeAttendance''A')
  3385.             ->where('A.createdAt >=  :date')
  3386.             ->andWhere('A.createdAt <=  :date_end')
  3387.             ->leftJoin('ApplicationBundle\\Entity\\Employee''E''WITH''A.employeeId = E.employeeId')
  3388.             ->leftJoin('ApplicationBundle\\Entity\\SysDepartmentPosition''D''WITH''E.positionId = D.positionId')
  3389.             ->setParameter('date'$currDate)
  3390.             ->setParameter('date_end'$currDate ' 23:59:59')
  3391.             ->orderBy('A.createdAt''DESC'// latest records first
  3392.             ->setMaxResults(5); // limit to 5 records
  3393.         $data $queryBuilder->getQuery()->getResult();
  3394.         $formattedData array_map(function($item) {
  3395.             return [
  3396.                 'employeeId' => $item['employeeId'],
  3397.                 'entry' => $item['entry'] ? $item['entry']->format('Y-m-d H:i:s') : null,
  3398.                 'lastIn' => $item['lastIn'] ? $item['lastIn']->format('Y-m-d H:i:s') : null,
  3399.                 'lastOut' => $item['lastOut'] ? $item['lastOut']->format('Y-m-d H:i:s') : null,
  3400.                 'currentLocation' => $item['currentLocation'],
  3401.                 'createdAt' => $item['createdAt'] ? $item['createdAt']->format('Y-m-d H:i:s') : null,
  3402.                 'name' => $item['name'],
  3403.                 'image' => $item['image'],
  3404.                 'positionName' => $item['positionName'],
  3405.             ];
  3406.         }, $data);
  3407.         $totalEmployees $em->getRepository('ApplicationBundle\\Entity\\EmployeeDetails')
  3408.             ->createQueryBuilder('E')
  3409.             ->select('COUNT(E.emp_status)')
  3410.             ->where('E.emp_status = 1')
  3411.             ->getQuery()
  3412.             ->getSingleScalarResult();
  3413.         $maleCount $em->getRepository('ApplicationBundle\\Entity\\EmployeeDetails')
  3414.             ->createQueryBuilder('E')
  3415.             ->select('COUNT(E.id)')
  3416.             ->where('E.sex = 1')
  3417.             ->getQuery()
  3418.             ->getSingleScalarResult();
  3419.         $femaleCount $em->getRepository('ApplicationBundle\\Entity\\EmployeeDetails')
  3420.             ->createQueryBuilder('E')
  3421.             ->select('COUNT(E.id)')
  3422.             ->where('E.sex = 2')
  3423.             ->getQuery()
  3424.             ->getSingleScalarResult();
  3425.         $fullTime $em->getRepository('ApplicationBundle\\Entity\\EmployeeDetails')
  3426.             ->createQueryBuilder('E')
  3427.             ->select('COUNT(E.id)')
  3428.             ->where('E.empType = 1')
  3429.             ->getQuery()
  3430.             ->getSingleScalarResult();
  3431.         $partTime $em->getRepository('ApplicationBundle\\Entity\\EmployeeDetails')
  3432.             ->createQueryBuilder('E')
  3433.             ->select('COUNT(E.id)')
  3434.             ->where('E.empType = 2')
  3435.             ->getQuery()
  3436.             ->getSingleScalarResult();
  3437.         $intern $em->getRepository('ApplicationBundle\\Entity\\EmployeeDetails')
  3438.             ->createQueryBuilder('E')
  3439.             ->select('COUNT(E.id)')
  3440.             ->where('E.empType = 3')
  3441.             ->getQuery()
  3442.             ->getSingleScalarResult();
  3443.         $temporary $em->getRepository('ApplicationBundle\\Entity\\EmployeeDetails')
  3444.             ->createQueryBuilder('E')
  3445.             ->select('COUNT(E.id)')
  3446.             ->where('E.empType = 4')
  3447.             ->getQuery()
  3448.             ->getSingleScalarResult();
  3449.         $contractual $em->getRepository('ApplicationBundle\\Entity\\EmployeeDetails')
  3450.             ->createQueryBuilder('E')
  3451.             ->select('COUNT(E.id)')
  3452.             ->where('E.empType = 5')
  3453.             ->getQuery()
  3454.             ->getSingleScalarResult();
  3455.         return $this->render(
  3456.             '@Application/pages/dashboard/humanResource.html.twig',
  3457.             [
  3458.                 'page_title' => 'Human Resource Dashboard',
  3459.                 'attendanceDetails' => $formattedData,
  3460.                 'totalEmployee' => $totalEmployees,
  3461.                 'maleCount' => $maleCount,
  3462.                 'femaleCount' => $femaleCount,
  3463.                 'fullTime' => $fullTime,
  3464.                 'partTime' => $partTime,
  3465.                 'temporary' => $temporary,
  3466.                 'contractual' => $contractual,
  3467.                 'intern' => $intern,
  3468.             ]
  3469.         );
  3470.     }
  3471.     public function projectCashFlowReportAction()
  3472.     {
  3473.         return $this->render(
  3474.             '@Application/pages/dashboard/cash_flow_report.html.twig',
  3475.             array(
  3476.                 'page_title' => 'Cash Flow Report'
  3477.             )
  3478.         );
  3479.     }
  3480.     public function PerformanceReviewDashboardAction()
  3481.     {
  3482.         return $this->render(
  3483.             '@Application/pages/dashboard/performance_review_dashboard.html.twig',
  3484.             array(
  3485.                 'page_title' => 'Performance Review Dashboard'
  3486.             )
  3487.         );
  3488.     }
  3489.     public function RecruitmentDashboardAction(Request $request)
  3490.     {
  3491.         $em $this->getDoctrine()->getManager();
  3492.         $em_goc $this->getDoctrine()->getManager('company_group');
  3493.         $companyId $this->getLoggedUserCompanyId($request);
  3494.         $company_data Company::getCompanyData($em$companyId);
  3495.         // 1. Total Job Posts
  3496.         $totalJobPosts $em->getRepository('ApplicationBundle\\Entity\\JobRecruitment')
  3497.             ->createQueryBuilder('j')
  3498.             ->select('COUNT(j.jobRecruitmentId)')
  3499.             ->where('j.approved = 1')
  3500.             ->getQuery()
  3501.             ->getSingleScalarResult();
  3502.         // 2. Active Job Posts
  3503.         $activeJobPosts $em->getRepository('ApplicationBundle\\Entity\\JobRecruitment')
  3504.             ->createQueryBuilder('j')
  3505.             ->select('COUNT(j.jobRecruitmentId)')
  3506.             ->where('j.approved = 1')
  3507.             ->andWhere('j.jobOpeningStatus = 2'// Assuming 2 is Active
  3508.             ->getQuery()
  3509.             ->getSingleScalarResult();
  3510.         // 3. Total Applicants
  3511.         $totalApplicants $em_goc->getRepository("CompanyGroupBundle\\Entity\\EntityApplicantApplicationList")
  3512.             ->createQueryBuilder('a')
  3513.             ->select('COUNT(a.id)')
  3514.             ->where('a.CompanyId = :companyId')
  3515.             ->andWhere('a.appId = :appId')
  3516.             ->setParameter('companyId'$companyId)
  3517.             ->setParameter('appId'$company_data->getAppId())
  3518.             ->getQuery()
  3519.             ->getSingleScalarResult();
  3520.         // 4. Simple recent activity for dashboard
  3521.         $recentJobs $em->getRepository('ApplicationBundle\\Entity\\JobRecruitment')
  3522.             ->findBy(['approved' => 1], ['createdAt' => 'DESC'], 5);
  3523.         // 5. Jobs with applicant counts
  3524.         $jobsWithApplicantCount $em->getRepository('ApplicationBundle\\Entity\\JobRecruitment')
  3525.             ->createQueryBuilder('j')
  3526.             ->select('j.jobRecruitmentId''j.title''j.applicationClosingDate''j.jobOpeningStatus')
  3527.             ->where('j.approved = 1')
  3528.             ->orderBy('j.createdAt''DESC')
  3529.             ->setMaxResults(8)
  3530.             ->getQuery()
  3531.             ->getResult();
  3532.         foreach ($jobsWithApplicantCount as &$job) {
  3533.             $count $em_goc->getRepository("CompanyGroupBundle\\Entity\\EntityApplicantApplicationList")
  3534.                 ->createQueryBuilder('a')
  3535.                 ->select('COUNT(a.id)')
  3536.                 ->where('a.jobPostId = :jobId')
  3537.                 ->setParameter('jobId'$job['jobRecruitmentId'])
  3538.                 ->getQuery()
  3539.                 ->getSingleScalarResult();
  3540.             $job['applicantCount'] = $count;
  3541.         }
  3542.         return $this->render(
  3543.             '@Application/pages/dashboard/recruitment_dashboard.html.twig',
  3544.             array(
  3545.                 'page_title' => 'Recruitment Dashboard',
  3546.                 'totalJobPosts' => $totalJobPosts,
  3547.                 'activeJobPosts' => $activeJobPosts,
  3548.                 'totalApplicants' => $totalApplicants,
  3549.                 'recentJobs' => $recentJobs,
  3550.                 'jobsWithApplicantCount' => $jobsWithApplicantCount,
  3551.                 'jobOpeningStatusArr' => HumanResourceConstant::$jobOpeningStatus
  3552.             )
  3553.         );
  3554.     }
  3555.     public function TalentManagementDashboardAction()
  3556.     {
  3557.         return $this->render(
  3558.             '@Application/pages/dashboard/talent_management_dashboard.html.twig',
  3559.             array(
  3560.                 'page_title' => 'Talent Management Dashboard'
  3561.             )
  3562.         );
  3563.     }
  3564.     public function CreateCompanyAction(Request $request)
  3565.     {
  3566.         $systemType $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
  3567.         $appId $request->get('app_id'0);
  3568.         $post $request;
  3569.         $session $request->getSession();
  3570.         if ($request->isMethod('POST')) {
  3571.             if ($systemType == '_CENTRAL_') {
  3572.                 $em_goc $this->getDoctrine()->getManager('company_group');
  3573.                 $em_goc->getConnection()->connect();
  3574.                 $connected $em_goc->getConnection()->isConnected();
  3575.                 $gocDataList = [];
  3576.                 if ($connected) {
  3577.                     $goc null;
  3578.                     $serverList MiscActions::getServerListById(                     $this->container->getParameter('database_user'),                     $this->container->getParameter('database_password'),                     $this->container->hasParameter('server_access_list') ?$this->container->getParameter('server_access_list') :[]                 );
  3579.                     $companyGroupHash $post->get('company_short_code''');
  3580.                     $defaultUsageDate = new \DateTime();
  3581.                     $defaultUsageDate->modify('+1 year');
  3582.                     $usageValidUpto = new \DateTime($post->get('usage_valid_upto_dt_str'$defaultUsageDate->format('Y-m-d')));
  3583.                     $companyGroupServerId $post->get('server_id'1);
  3584.                     $companyGroupServerAddress $serverList[$companyGroupServerId]['absoluteUrl'];
  3585.                     $companyGroupServerPort $serverList[$companyGroupServerId]['port'];
  3586.                     $companyGroupServerHash $serverList[$companyGroupServerId]['serverMarker'];
  3587.                     //                $dbUser=
  3588.                     if ($appId != 0)
  3589.                         $goc $this->getDoctrine()->getManager('company_group')
  3590.                             ->getRepository("CompanyGroupBundle\\Entity\\CompanyGroup")
  3591.                             ->findOneBy(array(
  3592.                                 'appId' => $appId
  3593.                             ));
  3594.                     if (!$goc)
  3595.                         $goc = new CompanyGroup();
  3596.                     if ($appId == 0) {
  3597.                         $biggestAppIdCg $this->getDoctrine()->getManager('company_group')
  3598.                             ->getRepository("CompanyGroupBundle\\Entity\\CompanyGroup")
  3599.                             ->findOneBy(array( //                            'appId' => $appId
  3600.                             ), array(
  3601.                                 'appId' => 'desc'
  3602.                             ));
  3603.                         if ($biggestAppIdCg)
  3604.                             $appId $biggestAppIdCg->getAppId();
  3605.                     }
  3606.                     $goc->setName($post->get('company_name'));
  3607.                     $goc->setCompanyGroupHash($companyGroupHash);
  3608.                     $goc->setAppId($appId);
  3609.                     $goc->setActive(1);
  3610.                     $goc->setAddress($post->get('address'));
  3611.                     $goc->setShippingAddress($post->get('s_address'));
  3612.                     $goc->setBillingAddress($post->get('b_address'));
  3613.                     $goc->setMotto($post->get('motto'));
  3614.                     $goc->setInitiateFlag($post->get('initiate_flag'3));
  3615.                     $goc->setInvoiceFooter($post->get('i_footer'));
  3616.                     $goc->setGeneralFooter($post->get('g_footer'));
  3617.                     $goc->setCompanyReg($post->get('company_reg'''));
  3618.                     $goc->setCompanyTin($post->get('company_tin'''));
  3619.                     $goc->setCompanyBin($post->get('company_bin'''));
  3620.                     $goc->setCompanyTl($post->get('company_tl'''));
  3621.                     $goc->setCompanyType($post->get('company_type'''));
  3622.                     $goc->setCurrentSubscriptionPackageId($post->get('package'1));
  3623.                     $goc->setUsageValidUptoDate($usageValidUpto);
  3624.                     $goc->setUsageValidUptoDateTs($usageValidUpto->format('U'));
  3625.                     //                $goc->setCu($post->get('package', ''));
  3626.                     $goc->setAdminUserAllowed($post->get('number_of_admin_user'1));
  3627.                     $goc->setUserAllowed($post->get('number_of_user'2));
  3628.                     $goc->setSubscriptionMonth($post->get('subscription_month'1));
  3629.                     $goc->setCompanyDescription($post->get('company_description'''));
  3630.                     $goc->setDbUser($post->get('db_user'));
  3631.                     $goc->setDbPass($post->get('db_pass'));
  3632.                     $goc->setDbHost($post->get('db_host'));
  3633.                     $goc->setOwnerId($session->get(UserConstants::USER_ID));
  3634.                     $goc->setCompanyGroupServerId($companyGroupServerId);
  3635.                     $goc->setCompanyGroupServerAddress($companyGroupServerAddress);
  3636.                     $goc->setCompanyGroupServerPort($companyGroupServerPort);
  3637.                     $goc->setCompanyGroupServerHash($companyGroupServerHash);
  3638.                     foreach ($request->files as $uploadedFile) {
  3639.                         if ($uploadedFile != null) {
  3640.                             $fileName 'company_image' $appId '.' $uploadedFile->guessExtension();
  3641.                             $path $fileName;
  3642.                             $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/CompanyImage/';
  3643.                             if ($goc->getImage() != null && $goc->getImage() != '' && file_exists($this->container->getParameter('kernel.root_dir') . '/../web' $goc->getImage())) {
  3644.                                 unlink($this->container->getParameter('kernel.root_dir') . '/../web' $goc->getImage());
  3645.                             }
  3646.                             if (!file_exists($upl_dir)) {
  3647.                                 mkdir($upl_dir0777true);
  3648.                             }
  3649.                             $file $uploadedFile->move($upl_dir$path);
  3650.                             if ($path != "")
  3651.                                 $goc->setImage('/uploads/CompanyImage/' $path);
  3652.                         }
  3653.                     }
  3654.                     $em_goc->persist($goc);
  3655.                     $em_goc->flush();
  3656.                     $goc->setDbName('cg_' $appId '_' $companyGroupHash);
  3657.                     $goc->setDbUser($serverList[$companyGroupServerId]['dbUser']);
  3658.                     $goc->setDbPass($serverList[$companyGroupServerId]['dbPass']);
  3659.                     $goc->setDbHost('localhost');
  3660.                     $em_goc->flush();
  3661.                     $centralUser $this->getDoctrine()->getManager('company_group')
  3662.                         ->getRepository("CompanyGroupBundle\\Entity\\EntityApplicantDetails")
  3663.                         ->findOneBy(array(
  3664.                             'applicantId' => $session->get(UserConstants::USER_ID0)
  3665.                         ));
  3666.                     if ($centralUser) {
  3667.                         $userAppIds json_decode($centralUser->getUserAppIds(), true);
  3668.                         $userTypesByAppIds json_decode($centralUser->getUserTypesByAppIds(), true);
  3669.                         if ($userAppIds == null$userAppIds = [];
  3670.                         if ($userTypesByAppIds == null$userTypesByAppIds = [];
  3671.                         $userAppIds array_merge($userAppIdsarray_diff([$appId], $userAppIds));
  3672.                         if (!isset($userTypesByAppIds[$appId])) {
  3673.                             $userTypesByAppIds[$appId] = [];
  3674.                         }
  3675.                         $userTypesByAppIds[$appId] = array_merge($userTypesByAppIds[$appId], array_diff([UserConstants::USER_TYPE_SYSTEM], $userTypesByAppIds[$appId]));
  3676.                         $centralUser->setUserAppIds(json_encode($userAppIds));
  3677.                         $centralUser->setUserTypesByAppIds(json_encode($userTypesByAppIds));
  3678.                         $em_goc->flush();
  3679.                     }
  3680.                     $accessList $session->get('userAccessList', []);
  3681.                     $d = array(
  3682.                         'userType' => UserConstants::USER_TYPE_SYSTEM,
  3683.                         'globalId' => $session->get(UserConstants::USER_ID0),
  3684.                         'serverId' => $companyGroupServerId,
  3685.                         'serverUrl' => $companyGroupServerAddress,
  3686.                         'serverPort' => $companyGroupServerPort,
  3687.                         'systemType' => '_ERP_',
  3688.                         'companyId' => 1,
  3689.                         'appId' => $appId,
  3690.                         'companyLogoUrl' => $goc->getImage(),
  3691.                         'companyName' => $goc->getName(),
  3692.                         'authenticationStr' => $this->get('url_encryptor')->encrypt(
  3693.                             json_encode(
  3694.                                 array(
  3695.                                     'globalId' => $session->get(UserConstants::USER_ID0),
  3696.                                     'appId' => $appId,
  3697.                                     'authenticate' => 1,
  3698.                                     'userType' => UserConstants::USER_TYPE_SYSTEM
  3699.                                 )
  3700.                             )
  3701.                         ),
  3702.                         'userCompanyList' => []
  3703.                     );
  3704.                     $accessList[] = $d;
  3705. //                    MiscActions::UpdateCompanyListInSession($em_goc, $centralUser->getApplicantId(), 1, 1, 1, $d);
  3706.                     //temporary solution
  3707.                     MiscActions::UpdateCompanyListInSession($em_goc$session->get(UserConstants::USER_ID), 111$d);
  3708.                     $session->set('userAccessList'$accessList);
  3709.                 }
  3710.                 return new JsonResponse(array(
  3711.                     'success' => true,
  3712.                     "message" => "Company Created Successfully",
  3713.                     'user_access_data' => $d,
  3714.                     'app_id' => $appId
  3715.                 ));
  3716.             }
  3717.         }
  3718.         return $this->render('@HoneybeeWeb/pages/create_company.html.twig', array(
  3719.             'page_title' => 'Company',
  3720.             'serverList' => GeneralConstant::$serverListById
  3721.         ));
  3722.     }
  3723.     public function checkBinTinAction(Request $request)
  3724.     {
  3725.         $em_goc $this->getDoctrine()->getManager('company_group');
  3726.         $type  $request->request->get('type');
  3727.         $value trim($request->request->get('value'));
  3728.         $repo $em_goc->getRepository("CompanyGroupBundle\\Entity\\CompanyGroup");
  3729.         if ($type === 'tin') {
  3730.             $company $repo->findOneBy(array(
  3731.                 'company_tin' => $value
  3732.             ));
  3733.         } elseif ($type === 'bin') {
  3734.             $company $repo->findOneBy(array(
  3735.                 'company_bin' => $value
  3736.             ));
  3737.         } elseif ($type === 'reg') {
  3738.             $company $repo->findOneBy(array(
  3739.                 'company_reg' => $value
  3740.             ));
  3741.         } else {
  3742.             return new JsonResponse(['exists' => false]);
  3743.         }
  3744.         return new JsonResponse([
  3745.             'exists' => $company true false
  3746.         ]);
  3747.     }
  3748.     public function createTicketAction(Request $request)
  3749.     {
  3750.         $em_goc $this->getDoctrine()->getManager('company_group');
  3751.         if ($request->isMethod('POST')) {
  3752.             $ticket = new EntityTicket();
  3753.             $ticket->setTitle($request->request->get('title'0));
  3754.             $ticket->setEmail($request->request->get('email'));
  3755.             $ticket->setTicketBody($request->request->get('ticketBody'));
  3756.             $em_goc->persist($ticket);
  3757.             $em_goc->flush();
  3758.         }
  3759.         return new JsonResponse(array(
  3760.             "success" => 'true',
  3761.             "message" => "Ticket Created Successfully",
  3762.         ));
  3763.     }
  3764.     public function GetSessionDataForAppAction(
  3765.         Request $request,
  3766.                 $remoteVerify 0,
  3767.                 $version 'latest',
  3768.                 $identifier '_default_',
  3769.                 $refRoute '',
  3770.                 $apiKey '_ignore_'
  3771.     )
  3772.     {
  3773.         $message "";
  3774.         $gocList = [];
  3775.         $session $request->getSession();
  3776.         if ($request->request->has('token')) {
  3777.             $em_goc $this->getDoctrine()->getManager('company_group');
  3778.             $to_set_session_data MiscActions::GetSessionDataFromToken($em_goc$request->request->get('token'))['sessionData'];
  3779.             if ($to_set_session_data != null) {
  3780.                 foreach ($to_set_session_data as $k => $d) {
  3781.                     //check if mobile
  3782.                     $session->set($k$d);
  3783.                 }
  3784.             }
  3785.         }
  3786.         if ($request->request->has('sessionData')) {
  3787.             $to_set_session_data $request->request->get('sessionData');
  3788.             foreach ($to_set_session_data as $k => $d) {
  3789.                 //check if mobile
  3790.                 $session->set($k$d);
  3791.             }
  3792.         }
  3793.         if ($version !== 'latest') {
  3794.             $session_data = array(
  3795.                 'oAuthToken' => $session->get('oAuthToken'),
  3796.                 'locale' => $session->get('locale'),
  3797.                 'firebaseToken' => $session->get('firebaseToken'),
  3798.                 'token' => $session->get('token'),
  3799.                 UserConstants::USER_EMPLOYEE_ID => $session->get(UserConstants::USER_EMPLOYEE_ID),
  3800.                 UserConstants::USER_ID => $session->get(UserConstants::USER_ID),
  3801.                 UserConstants::LAST_SETTINGS_UPDATED_TS => $session->get(UserConstants::LAST_SETTINGS_UPDATED_TS),
  3802.                 UserConstants::USER_LOGIN_ID => $session->get(UserConstants::USER_LOGIN_ID),
  3803.                 UserConstants::USER_EMAIL => $session->get(UserConstants::USER_EMAIL),
  3804.                 UserConstants::USER_TYPE => $session->get(UserConstants::USER_TYPE),
  3805.                 UserConstants::USER_IMAGE => $session->get(UserConstants::USER_IMAGE),
  3806.                 UserConstants::USER_DEFAULT_ROUTE => $session->get(UserConstants::USER_DEFAULT_ROUTE),
  3807.                 UserConstants::USER_NAME => $session->get(UserConstants::USER_NAME),
  3808.                 UserConstants::USER_COMPANY_ID => $session->get(UserConstants::USER_COMPANY_ID),
  3809.                 UserConstants::USER_COMPANY_ID_LIST => $session->get(UserConstants::USER_COMPANY_ID_LIST),
  3810.                 UserConstants::USER_COMPANY_NAME_LIST => $session->get(UserConstants::USER_COMPANY_NAME_LIST),
  3811.                 UserConstants::USER_COMPANY_IMAGE_LIST => $session->get(UserConstants::USER_COMPANY_IMAGE_LIST),
  3812.                 UserConstants::USER_APP_ID => $session->get(UserConstants::USER_APP_ID),
  3813.                 UserConstants::USER_POSITION_LIST => $session->get(UserConstants::USER_POSITION_LIST),
  3814.                 UserConstants::USER_CURRENT_POSITION => $session->get(UserConstants::USER_CURRENT_POSITION),
  3815.                 UserConstants::ALL_MODULE_ACCESS_FLAG => $session->get(UserConstants::ALL_MODULE_ACCESS_FLAG),
  3816.                 UserConstants::USER_GOC_ID => $session->get(UserConstants::USER_GOC_ID),
  3817.                 UserConstants::USER_NOTIFICATION_ENABLED => GeneralConstant::NOTIFICATION_ENABLED == ? ($this->getParameter('notification_enabled') == 0) : 0,
  3818.                 UserConstants::USER_NOTIFICATION_SERVER => $this->getParameter('notification_server'),
  3819.                 UserConstants::PRODUCT_NAME_DISPLAY_TYPE => $session->get(UserConstants::PRODUCT_NAME_DISPLAY_TYPE),
  3820.                 UserConstants::APPLICATION_SECRET => $session->get(UserConstants::APPLICATION_SECRET),
  3821.                 //new addition
  3822.                 'appIdList' => $session->get('appIdList'),
  3823.                 'branchIdList' => $session->get('branchIdList'null),
  3824.                 'branchId' => $session->get('branchId'null),
  3825.                 'companyIdListByAppId' => $session->get('companyIdListByAppId'),
  3826.                 'companyNameListByAppId' => $session->get('companyNameListByAppId'),
  3827.                 'companyImageListByAppId' => $session->get('companyImageListByAppId'),
  3828.                 'userAccessList' => $session->get('userAccessList'),
  3829.                 'csToken' => $session->get('csToken'),
  3830.             );
  3831.         } else {
  3832.             $session_data = array(
  3833.                 'oAuthToken' => $session->get('oAuthToken'),
  3834.                 'locale' => $session->get('locale'),
  3835.                 'firebaseToken' => $session->get('firebaseToken'),
  3836.                 'token' => $session->get('token'),
  3837.                 UserConstants::USER_EMPLOYEE_ID => $session->get(UserConstants::USER_EMPLOYEE_ID),
  3838.                 UserConstants::USER_ID => $session->get(UserConstants::USER_ID),
  3839.                 UserConstants::LAST_SETTINGS_UPDATED_TS => $session->get(UserConstants::LAST_SETTINGS_UPDATED_TS),
  3840.                 UserConstants::USER_LOGIN_ID => $session->get(UserConstants::USER_LOGIN_ID),
  3841.                 UserConstants::USER_EMAIL => $session->get(UserConstants::USER_EMAIL),
  3842.                 UserConstants::USER_TYPE => $session->get(UserConstants::USER_TYPE),
  3843.                 UserConstants::USER_IMAGE => $session->get(UserConstants::USER_IMAGE),
  3844.                 UserConstants::USER_DEFAULT_ROUTE => $session->get(UserConstants::USER_DEFAULT_ROUTE),
  3845.                 UserConstants::USER_NAME => $session->get(UserConstants::USER_NAME),
  3846.                 UserConstants::USER_COMPANY_ID => $session->get(UserConstants::USER_COMPANY_ID),
  3847.                 UserConstants::USER_COMPANY_ID_LIST => $session->get(UserConstants::USER_COMPANY_ID_LIST),
  3848.                 UserConstants::USER_COMPANY_NAME_LIST => $session->get(UserConstants::USER_COMPANY_NAME_LIST),
  3849.                 UserConstants::USER_COMPANY_IMAGE_LIST => $session->get(UserConstants::USER_COMPANY_IMAGE_LIST),
  3850.                 UserConstants::USER_APP_ID => $session->get(UserConstants::USER_APP_ID),
  3851.                 UserConstants::USER_POSITION_LIST => $session->get(UserConstants::USER_POSITION_LIST),
  3852.                 UserConstants::USER_CURRENT_POSITION => $session->get(UserConstants::USER_CURRENT_POSITION),
  3853.                 UserConstants::ALL_MODULE_ACCESS_FLAG => $session->get(UserConstants::ALL_MODULE_ACCESS_FLAG),
  3854.                 UserConstants::USER_GOC_ID => $session->get(UserConstants::USER_GOC_ID),
  3855.                 UserConstants::USER_NOTIFICATION_ENABLED => GeneralConstant::NOTIFICATION_ENABLED == ? ($this->getParameter('notification_enabled') == 0) : 0,
  3856.                 UserConstants::USER_NOTIFICATION_SERVER => $this->getParameter('notification_server'),
  3857.                 UserConstants::PRODUCT_NAME_DISPLAY_TYPE => $session->get(UserConstants::PRODUCT_NAME_DISPLAY_TYPE),
  3858.                 UserConstants::APPLICATION_SECRET => $session->get(UserConstants::APPLICATION_SECRET),
  3859.                 //new addition
  3860.                 'appIdList' => $session->get('appIdList'),
  3861.                 'branchIdList' => $session->get('branchIdList'null),
  3862.                 'branchId' => $session->get('branchId'null),
  3863.                 'companyIdListByAppId' => $session->get('companyIdListByAppId'),
  3864.                 'companyNameListByAppId' => $session->get('companyNameListByAppId'),
  3865.                 'companyImageListByAppId' => $session->get('companyImageListByAppId'),
  3866.                 'userAccessList' => $session->get('userAccessList'),
  3867.                 'csToken' => $session->get('csToken'),
  3868.             );
  3869.         }
  3870.         $response = new JsonResponse(array(
  3871.             "success" => empty($session->get(UserConstants::USER_ID)) ? false true,
  3872.             //            'session'=>$request->getSession(),
  3873.             'session_data' => $session_data,
  3874.             //            'session2'=>$_SESSION,
  3875.         ));
  3876.         $response->headers->set('Access-Control-Allow-Origin''*, null');
  3877.         $response->headers->set('Access-Control-Allow-Methods''POST');
  3878.         //        $response->setCallback('FUNCTION_CALLBACK_NAME');
  3879.         return $response;
  3880.     }
  3881.     public function EmployeeAddUsingQrCodeCentralAction(Request $request)
  3882.     {
  3883.         $session $request->getSession();
  3884.         if ($request->isMethod('post')) {
  3885.             $em_goc $this->getDoctrine()->getManager('company_group');
  3886.             $entityApplicant $em_goc->getRepository("CompanyGroupBundle\\Entity\\EntityApplicantDetails")
  3887.                 ->findOneBy(
  3888.                     array(
  3889.                         'applicantId' => $request->request->get('userId'),
  3890.                     )
  3891.                 );
  3892.             $app $em_goc->getRepository("CompanyGroupBundle\\Entity\\CompanyGroup")
  3893.                 ->findOneBy(
  3894.                     array(
  3895.                         'appId' => $request->request->get('appId'),
  3896.                     )
  3897.                 );
  3898.             $userType $request->request->get('userType');
  3899.             $currAccessData json_decode($entityApplicant->getUserTypesByAppIds(), true);
  3900.             if ($currAccessData == null$currAccessData = [];
  3901.             if (!isset($currAccessData[$request->request->get('appId')]))
  3902.                 $currAccessData[$request->request->get('appId')] = [];
  3903.             $currAccessData[$request->request->get('appId')] = array_merge($currAccessData[$request->request->get('appId')], array_diff([$request->request->get('userType'$userType)], $currAccessData[$request->request->get('appId')]));
  3904.             $entityApplicant->setUserTypesByAppIds(json_encode($currAccessData));
  3905.             $em_goc->flush();
  3906.             $postData = [];
  3907.             $postData['globalId'] = $entityApplicant->getApplicantId();
  3908.             $postData['username'] = $entityApplicant->getUsername();
  3909.             $postData['email'] = $entityApplicant->getEmail();
  3910.             $postData['firstname'] = $entityApplicant->getFirstname();
  3911.             $postData['lastname'] = $entityApplicant->getLastname();
  3912.             $postData['appId'] = $request->request->get('appId');
  3913.             $postData['companyId'] = $request->request->get('companyId');
  3914.             $postData['userType'] = $userType;
  3915.             $urlToCall $app->getCompanyGroupServerAddress() . '/add_employee_by_qr_erp';
  3916.             $userFiles $postData;
  3917.             $curl curl_init();
  3918.             curl_setopt_array($curl, array(
  3919.                 CURLOPT_RETURNTRANSFER => 1,
  3920.                 CURLOPT_POST => 1,
  3921.                 CURLOPT_URL => $urlToCall,
  3922.                 CURLOPT_CONNECTTIMEOUT => 10,
  3923.                 CURLOPT_SSL_VERIFYPEER => false,
  3924.                 CURLOPT_SSL_VERIFYHOST => false,
  3925.                 CURLOPT_HTTPHEADER => array( //              "Accept: multipart/form-data",
  3926.                 ),
  3927.                 //                            ),
  3928.                 CURLOPT_POSTFIELDS => $userFiles
  3929.             ));
  3930.             $retData curl_exec($curl);
  3931.             $errData curl_error($curl);
  3932.             curl_close($curl);
  3933.             if ($errData) {
  3934. //                $returnData['message']='';
  3935.             } else {
  3936.                 $retDataObj json_decode($retDatatrue);
  3937.                 if ($retDataObj['status'] == 'success') {
  3938.                     $newAccess = [
  3939.                         'userType' => 1,
  3940.                         'userTypeName' => 'Admin',
  3941.                         'globalId' => $entityApplicant->getApplicantId(),
  3942.                         'serverId' => $app->getCompanyGroupServerId(),
  3943.                         'serverUrl' => $app->getCompanyGroupServerAddress(),
  3944.                         'serverPort' => $app->getCompanyGroupServerPort(),
  3945.                         'systemType' => '_ERP_',
  3946.                         'companyId' => 1,
  3947.                         'appId' => $app->getAppId(),
  3948.                         'companyLogoUrl' => '/uploads/CompanyImage/company_image' $request->request->get('appId') . '.png',
  3949.                         'companyName' => $app->getName(),
  3950.                         'authenticationStr' => $this->get('url_encryptor')->encrypt(json_encode(
  3951.                                 array(
  3952.                                     'globalId' => $entityApplicant->getApplicantId(),
  3953.                                     'appId' => $app->getAppId(),
  3954.                                     'authenticate' => 1,
  3955.                                     'userType' => $userType,
  3956.                                     'userTypeName' => UserConstants::$userTypeName[$userType]
  3957.                                 )
  3958.                             )
  3959.                         ),
  3960.                         'userCompanyList' => [],
  3961.                     ];
  3962. //            $token = $session->get('token');
  3963. //            $em_goc = $this->getDoctrine()->getManager('company_group');
  3964.                     $to_set_session_data MiscActions::GetSessionDataFromToken($em_goc$session->get(UserConstants::USER_TOKEN''))['sessionData'];
  3965.                     $currentUserAccessListInSession $to_set_session_data['userAccessList'];
  3966.                     $isAlreadyJoined false;
  3967.                     foreach ($currentUserAccessListInSession as $acc) {
  3968.                         if (isset($acc['appId']) && $acc['appId'] == $request->request->get('appId')) {
  3969.                             $isAlreadyJoined true;
  3970.                             break;
  3971.                         }
  3972.                     }
  3973. //                    if(isset($currentUserAccessListInSession[$request->request->get('appId')]))
  3974. //                        $isAlreadyJoined=true;
  3975.                     if ($isAlreadyJoined) {
  3976.                         return new JsonResponse([
  3977.                             'status' => 'false',
  3978.                             'message' => 'Already joined.',
  3979.                             'currentUserAccessListInSession'  => $currentUserAccessListInSession
  3980.                         ]);
  3981.                     }else{
  3982.                         $currentUserAccessListInSession[] = $newAccess;
  3983.                         $session->set('userAccessList'$currentUserAccessListInSession);
  3984.                         $to_set_session_data['userAccessList'] = $currentUserAccessListInSession;
  3985.                         $updatedToken MiscActions::CreateTokenFromSessionData($em_goc,
  3986.                             $to_set_session_data,
  3987.                             1,
  3988.                             1,
  3989.                             11
  3990.                         );
  3991.                         return new JsonResponse([
  3992.                             'status' => 'success',
  3993.                             'message' => 'User successfully added to company.',
  3994.                             'currentUserAccessListInSession'  => $currentUserAccessListInSession
  3995.                         ]);
  3996.                     }
  3997.                 }
  3998.             }
  3999. //            MiscActions::UpdateCompanyListInSession($em_goc, $entityApplicant->getApplicantId(), 1, 1, 1, $newAccess);
  4000.         } else {
  4001.             $company $request->get('company');
  4002.             return new JsonResponse(array(
  4003.                 'status' => 'error',
  4004.                 'message' => 'Something went wrong while onboarding.'
  4005.             ));
  4006.         }
  4007.         return new JsonResponse(array(
  4008.             'status' => 'error',
  4009.             'message' => 'Something went wrong while onboarding.'
  4010.         ));
  4011.     }
  4012.     public function EmployeeAddUsingQrCodeAction(Request $request)
  4013.     {
  4014.         $post $request;
  4015.         $em $this->getDoctrine()->getManager('company_group');
  4016.         $appid $request->query->get('appid'$request->request->get('appid'null));
  4017.         $session $request->getSession();
  4018.         $CurrentRoute $request->attributes->get('_route');
  4019.         $systemType $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
  4020.         if ($request->isMethod('POST')) {
  4021.             $userId $request->request->get('userId'null);
  4022.             if ($userId === null) {
  4023.                 $companyId $request->request->get('company',1);
  4024.                 $email $request->request->get('email');
  4025.                 $qrImage $request->files->get('qr_image');
  4026.                 if (!$email) {
  4027.                     return new JsonResponse(['status' => 'error''message' => 'Invalid request'], 400);
  4028.                 }
  4029.                 if ($qrImage) {
  4030.                     $uploadsDir $this->getParameter('kernel.project_dir') . '/public/uploads/';
  4031.                     $fileName 'qr_' $companyId '_' time() . '.png';
  4032.                     $qrImage->move($uploadsDir$fileName);
  4033.                     $qrImagePath $uploadsDir $fileName;
  4034.                     $bodyTemplate '@Application/email/user/applicant_confirm.html.twig';
  4035.                     $bodyData = [
  4036.                         'name' => $email,
  4037.                         'companyData' => $companyId,
  4038.                         'companyName' => $request->request->get('company'),
  4039.                         'userType' => 2,
  4040.                         'appId' => $appid,
  4041.                         //                        'qr_code_url' => '/uploads/' . $fileName
  4042.                     ];
  4043.                     $userAccessList $session->get('userAccessList', []);
  4044.                     $companyName array_map(function ($company) {
  4045.                         return $company['companyName'];
  4046.                     }, $userAccessList);
  4047.                     $new_mail $this->get('mail_module');
  4048.                     $new_mail->sendMyMail([
  4049.                         'senderHash' => '_CUSTOM_',
  4050.                         'forwardToMailAddress' => $email,
  4051.                         'fromAddress' => 'accounts@ourhoneybee.eu',
  4052.                         'userName' => 'accounts@ourhoneybee.eu',
  4053.                         'password' => \ApplicationBundle\Helper\MailerConfig::buddybeePassword(),
  4054.                         'smtpServer' => \ApplicationBundle\Helper\MailerConfig::host(),
  4055.                         'smtpPort' => \ApplicationBundle\Helper\MailerConfig::port(),
  4056.                         'subject' => 'User Registration on HoneyBee Ecosystem under Entity ',
  4057.                         'toAddress' => $email,
  4058.                         'mailTemplate' => $bodyTemplate,
  4059.                         'templateData' => $bodyData,
  4060.                         'companyId' => $companyId,
  4061.                     ]);
  4062.                     return $this->render(
  4063.                         '@Application/pages/dashboard/index_central_landing.html.twig',
  4064.                         [
  4065.                             'page_title' => 'Central Landing',
  4066.                             'companyNames' => $companyName
  4067.                         ]
  4068.                     );
  4069.                 } else {
  4070.                     $userAccessList $session->get('userAccessList', []);
  4071.                     $companyName array_map(function ($company) {
  4072.                         return $company['companyName'];
  4073.                     }, $userAccessList);
  4074.                     return $this->render(
  4075.                         '@Application/pages/dashboard/index_central_landing.html.twig',
  4076.                         [
  4077.                             'page_title' => 'Central Landing',
  4078.                             'companyNames' => $companyName
  4079.                         ]
  4080.                     );
  4081.                 }
  4082.             } else {
  4083.                 if ($systemType == '_CENTRAL_') {
  4084.                     $userAccessList $session->get('userAccessList', []);
  4085.                     $companyName array_map(function ($company) {
  4086.                         return $company['companyName'];
  4087.                     }, $userAccessList);
  4088.                     $modifiedRequest $request->duplicate(
  4089.                         null,
  4090.                         array_merge($request->request->all(), ['appId' => $request->request->get('appid')])
  4091.                     );
  4092.                     $response $this->EmployeeAddUsingQrCodeCentralAction($modifiedRequest);
  4093. //                    if ($CurrentRoute == 'employee_add_by_qr_api')
  4094.                     {
  4095.                         return $response;
  4096.                     }
  4097. //                    return $this->render(
  4098. //                        'ApplicationBundle:pages/dashboard:index_central_landing.html.twig',
  4099. //                        [
  4100. //                            'page_title' => 'Central Landing',
  4101. //                            'companyNames' => $companyName
  4102. //                        ]
  4103. //                    );
  4104.                 }
  4105.             }
  4106.         } else {
  4107.             $company $request->get('company');
  4108.             $em_goc $this->getDoctrine()->getManager('company_group');
  4109.             $company $em_goc->getRepository("CompanyGroupBundle\\Entity\\CompanyGroup")->findOneBy(['appId' => $request->get('appid')]);
  4110.             return $this->render(
  4111.                 '@Application/pages/dashboard/employee_add_by_qr.html.twig',
  4112.                 [
  4113.                     'page_title' => 'Company Invitation',
  4114.                     'company' => $company
  4115.                 ]
  4116.             );
  4117.         }
  4118.     }
  4119.     public function EmployeeOnboardUsingQrAction(Request $request): JsonResponse
  4120.     {
  4121.         $email $request->get('email');
  4122.         $isAjax $request->isXmlHttpRequest();
  4123.         $currentRoute $request->attributes->get('_route');
  4124.         if (!$email) {
  4125.             if ($isAjax) {
  4126.                 return new JsonResponse(['status' => 'error''message' => 'Email is required.']);
  4127.             } else {
  4128.                 throw $this->createNotFoundException("Email is missing.");
  4129.             }
  4130.         }
  4131.         $em_goc $this->getDoctrine()->getManager('company_group');
  4132.         $user $em_goc->getRepository("CompanyGroupBundle\\Entity\\EntityApplicantDetails")->findOneBy(['email' => $email]);
  4133.         if (!$user) {
  4134.             if ($isAjax) {
  4135.                 return new JsonResponse(['status' => 'error''message' => 'Applicant not found.']);
  4136.             } else {
  4137.                 throw $this->createNotFoundException("Applicant not found.");
  4138.             }
  4139.         }
  4140.         $payloadUrl $this->generateUrl('employee_onboard_by_qr_api', [
  4141.             'email' => $user->getEmail(),
  4142.             'applicantId' => $user->getApplicantId(),
  4143.             'employeeQr' => 1
  4144.         ], UrlGeneratorInterface::ABSOLUTE_URL);
  4145.         if ($currentRoute === 'employee_onboard') {
  4146.             return new JsonResponse([
  4147.                 'status' => 'success',
  4148.                 'data' => [
  4149.                     'applicantId' => $user->getApplicantId(),
  4150.                     'username' => $user->getUsername(),
  4151.                     'email' => $user->getEmail(),
  4152.                     'firstName' => $user->getFirstname(),
  4153.                     'lastName' => $user->getLastname(),
  4154.                     'link' => $payloadUrl
  4155.                 ]
  4156.             ]);
  4157.         }
  4158.         if ($isAjax) {
  4159.             return new JsonResponse([
  4160.                 'status' => 'success',
  4161.                 'data' => [
  4162.                     'id' => $user->getApplicantId(),
  4163.                     'email' => $user->getEmail(),
  4164.                     'name' => $user->getFirstname() . ' ' $user->getLastname(),
  4165.                     'dob' => $user->getDob() ? $user->getDob()->format('Y-m-d') : null,
  4166.                 ]
  4167.             ]);
  4168.         }
  4169.         $companies $request->getSession()->get('userAccessList', []);
  4170.         return $this->render('@Application/pages/dashboard/qr_onboard_result.html.twig', [
  4171.             'page_title' => 'Onboarding',
  4172.             'applicant' => $user,
  4173.             'companies' => $companies
  4174.         ]);
  4175.     }
  4176.     public function OnboardUserToCompanyAction(Request $request)
  4177.     {
  4178.         $systemType $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
  4179.         $currentRoute $request->attributes->get('_route');
  4180.         if ($systemType !== '_CENTRAL_') {
  4181.             throw new \Exception("This action must be called from CENTRAL system.");
  4182.         }
  4183.         $email $request->request->get('email');
  4184.         $applicantId $request->request->get('applicant_id');
  4185.         $appId $request->request->get('company_id');
  4186.         $userType $request->request->get('user_type');
  4187.         if (!$email || !$appId || !$userType) {
  4188.             $this->addFlash('error''Missing required fields.');
  4189.             return new JsonResponse(['status' => 'error''message' => 'Missing required fields.']);
  4190.         }
  4191.         $em $this->getDoctrine()->getManager('company_group');
  4192.         $applicant $em->getRepository("CompanyGroupBundle\\Entity\\EntityApplicantDetails")->findOneBy(['email' => $email]);
  4193.         if (!$applicant) {
  4194.             $this->addFlash('error''Applicant not found.');
  4195.             return $this->redirectToRoute('central_landing');
  4196.         }
  4197.         $userAppIds json_decode($applicant->getUserAppIds(), true);
  4198.         if (!is_array($userAppIds)) {
  4199.             $userAppIds = [];
  4200.         }
  4201.         if (!in_array($appId$userAppIds)) {
  4202.             $userAppIds[] = $appId;
  4203.             $applicant->setUserAppIds(json_encode($userAppIds));
  4204.         }
  4205.         $userTypesByAppIds json_decode($applicant->getUserTypesByAppIds(), true) ?: [];
  4206.         $userTypesByAppIds[$appId] = array((int)$userType);
  4207.         $applicant->setUserTypesByAppIds(json_encode($userTypesByAppIds));
  4208.         $em->persist($applicant);
  4209.         $em->flush();
  4210.         $companyRepo $this->getDoctrine()->getManager('company_group')->getRepository("CompanyGroupBundle\\Entity\\CompanyGroup");
  4211.         $targetCompany $companyRepo->findOneBy(['appId' => $appId]);
  4212.         if (!$targetCompany) {
  4213.             $this->addFlash('error''Target company not found.');
  4214.             return $this->redirectToRoute('central_landing');
  4215.         }
  4216.         $serverList MiscActions::getServerListById(                     $this->container->getParameter('database_user'),                     $this->container->getParameter('database_password'),                     $this->container->hasParameter('server_access_list') ?$this->container->getParameter('server_access_list') :[]                 );
  4217.         $serverId $targetCompany->getCompanyGroupServerId();
  4218.         $appId $targetCompany->getAppId();
  4219.         if (!isset($serverList[$serverId])) {
  4220.             $this->addFlash('error''Server configuration not found.');
  4221.             return $this->redirectToRoute('central_landing');
  4222.         }
  4223.         // Find correct companyId from session userAccessList using appId
  4224.         $session $request->getSession();
  4225.         $userAccessList $session->get('userAccessList', []);
  4226.         $resolvedCompanyId null;
  4227.         foreach ($userAccessList as $access) {
  4228.             if (isset($access['appId']) && $access['appId'] == $appId) {
  4229.                 $resolvedCompanyId $access['companyId'];
  4230.                 break;
  4231.             }
  4232.         }
  4233.         if (!$resolvedCompanyId) {
  4234.             $this->addFlash('error''Could not resolve companyId from session for the given appId.');
  4235.             return $this->redirectToRoute('central_landing');
  4236.         }
  4237.         $imagePath $this->container->getParameter('kernel.root_dir') . '/../web/' $applicant->getImage();
  4238.         $imageFile null;
  4239.         if ($applicant->getImage() && file_exists($imagePath)) {
  4240.             $mime mime_content_type($imagePath);
  4241.             $name pathinfo($imagePathPATHINFO_BASENAME);
  4242.             $imageFile = new \CURLFile($imagePath$mime$name);
  4243.         }
  4244.         // Prepare userData
  4245.         $userData = [];
  4246.         $getters array_filter(get_class_methods($applicant), function ($method) {
  4247.             return strpos($method'get') === 0;
  4248.         });
  4249.         foreach ($getters as $getter) {
  4250.             if (in_array($getter, ['getCreatedAt''getUpdatedAt''getImage'])) continue;
  4251.             $value $applicant->$getter();
  4252.             $userData[$getter] = $value instanceof \DateTime $value->format('Y-m-d') : $value;
  4253.         }
  4254.         $userData['getUserAppIds'] = json_encode($userAppIds);
  4255.         $userData['getUserTypesByAppIds'] = json_encode($userTypesByAppIds);
  4256.         $postFields = [
  4257.             'userData' => json_encode([$userData]),
  4258.             'appIds' => $appId,
  4259.             'userIds' => $applicantId,
  4260.             'companyId' => $resolvedCompanyId,
  4261.             'userType' => $userType,
  4262.             'imageFile' => $imageFile
  4263.         ];
  4264.         if ($imageFile) {
  4265.             $postFields['file_' $applicant->getApplicantId()] = $imageFile;
  4266.         }
  4267.         $url $serverList[$serverId]['absoluteUrl'] . '/OnBoardCentralUserToErp';
  4268.         $curl curl_init();
  4269.         curl_setopt_array($curl, [
  4270.             CURLOPT_RETURNTRANSFER => 1,
  4271.             CURLOPT_POST => 1,
  4272.             CURLOPT_URL => $url,
  4273.             CURLOPT_POSTFIELDS => $postFields,
  4274.             CURLOPT_CONNECTTIMEOUT => 10,
  4275.             CURLOPT_SSL_VERIFYPEER => false,
  4276.             CURLOPT_SSL_VERIFYHOST => false,
  4277.         ]);
  4278.         $response curl_exec($curl);
  4279.         $curlError curl_error($curl);
  4280.         curl_close($curl);
  4281.         $responseObj json_decode($responsetrue);
  4282.         if ($currentRoute === 'employee_onboard_api') {
  4283.             return new JsonResponse(
  4284.                 $responseObj
  4285.             );
  4286.         }
  4287.         if (!empty($responseObj['success'])) {
  4288.             $this->addFlash('success''Applicant onboarded and synced to ERP.');
  4289.         } else {
  4290.             $this->addFlash('warning''Onboarded, but ERP sync may have failed. Check logs.');
  4291.         }
  4292.         return $this->redirectToRoute('central_landing');
  4293.     }
  4294.     public function OnBoardCentralUserToErpAction(Request $request)
  4295.     {
  4296.         $systemType $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
  4297.         if ($systemType === '_CENTRAL_') {
  4298.             return new JsonResponse(['success' => false'message' => 'Invalid system type.']);
  4299.         }
  4300.         $userDataJson $request->get('userData');
  4301.         $userDataList json_decode($userDataJsontrue);
  4302.         if (!$userDataList || !is_array($userDataList)) {
  4303.             return new JsonResponse(['success' => false'message' => 'Invalid or missing userData.']);
  4304.         }
  4305.         $userData $userDataList[0] ?? null;
  4306.         if (!$userData || empty($userData['getApplicantId'])) {
  4307.             return new JsonResponse(['success' => false'message' => 'Missing applicant ID.']);
  4308.         }
  4309.         $em_goc $this->getDoctrine()->getManager('company_group');
  4310.         $globalId $userData['getApplicantId'];
  4311.         $appIds $request->get('appIds');
  4312.         $userIds $request->get('userIds');
  4313.         $companyId $request->get('companyId');
  4314.         $company $em_goc->getRepository("CompanyGroupBundle\\Entity\\CompanyGroup")->findOneBy(['appId' => $appIds]);
  4315.         if (!$company) {
  4316.             return new JsonResponse(['success' => false'message' => 'Target company not found.']);
  4317.         }
  4318.         $connector $this->container->get('application_connector');
  4319.         $connector->resetConnection(
  4320.             'default',
  4321.             $company->getDbName(),
  4322.             $company->getDbUser(),
  4323.             $company->getDbPass(),
  4324.             $company->getDbHost(),
  4325.             true
  4326.         );
  4327.         $em $this->getDoctrine()->getManager();
  4328.         $user $em->getRepository('ApplicationBundle\\Entity\\SysUser')->findOneBy([
  4329.             'globalId' => $globalId
  4330.         ]);
  4331.         if (!$user) {
  4332.             $user = new \ApplicationBundle\Entity\SysUser();
  4333.             $user->setGlobalId($globalId);
  4334.         } else {
  4335.             return new JsonResponse([
  4336.                 'status' => 'info',
  4337.                 'message' => 'User is already onboarded',
  4338.                 'userId' => $user->getUserId(),
  4339.                 'redirectUrl' => 'dashboard'
  4340.             ]);
  4341.         }
  4342.         $setterMap = [
  4343.             'getUsername' => 'setUserName',
  4344.             'getEmail' => 'setEmail',
  4345.             'getPassword' => 'setPassword',
  4346.             'getDeviceId' => 'setDeviceId',
  4347.             'getDeviceIdLockedFlag' => 'setDeviceIdLockedFlag',
  4348.             'getLockDeviceIdOnNextLoginFlag' => 'setLockDeviceIdOnNextLoginFlag',
  4349.             'getOAuthUniqueId' => 'setOAuthUniqueId',
  4350.             'getOAuthEmail' => 'setOAuthEmail',
  4351.             'getSyncFlag' => 'setSyncFlag',
  4352.             'getFirstname' => 'setName',
  4353.         ];
  4354.         $user->setUserAppId($appIds);
  4355.         $user->setUserAppIdList(json_encode([$appIds]));
  4356.         $user->setStatus(1);
  4357.         foreach ($setterMap as $getter => $setter) {
  4358.             if (isset($userData[$getter]) && method_exists($user$setter)) {
  4359.                 $user->$setter($userData[$getter]);
  4360.             }
  4361.         }
  4362.         $fullName trim(($userData['getFirstname'] ?? '') . ' ' . ($userData['getLastname'] ?? ''));
  4363.         if (!empty($fullName)) {
  4364.             $user->setName($fullName);
  4365.         }
  4366.         $imagePathToSet '';
  4367.         $uploadedFile $request->files->get('file_' $globalId);
  4368.         if ($uploadedFile) {
  4369.             $uploadDir $this->getParameter('kernel.project_dir') . '/web/uploads/UserImage/';
  4370.             if (!file_exists($uploadDir)) {
  4371.                 mkdir($uploadDir0777true);
  4372.             }
  4373.             $filename 'user_' $globalId '.' $uploadedFile->guessExtension();
  4374.             $uploadedFile->move($uploadDir$filename);
  4375.             $imagePathToSet 'uploads/UserImage/' $filename;
  4376.             $user->setImage($imagePathToSet);
  4377.         }
  4378.         $user->setUserType(1);
  4379.         $em->persist($user);
  4380.         $em->flush();
  4381.         $employee $em->getRepository('ApplicationBundle\\Entity\\Employee')->findOneBy([
  4382.             'userId' => $user->getUserId()
  4383.         ]);
  4384.         if (!$employee) {
  4385.             $employee = new \ApplicationBundle\Entity\Employee();
  4386.             $employee->setUserId($user->getUserId());
  4387.             $employee->setDateOfAddition(new \DateTime());
  4388.         }
  4389.         $employee->setFirstName($userData['getFirstname'] ?? null);
  4390.         $employee->setLastName($userData['getLastname'] ?? null);
  4391.         $employee->setName(trim(($userData['getFirstname'] ?? '') . ' ' . ($userData['getLastname'] ?? '')));
  4392.         $employee->setEmail($userData['getEmail'] ?? null);
  4393.         $employee->setEmmContact($userData['getEmmContact'] ?? null);
  4394.         $employee->setCurrentAddress($userData['getCurrAddr'] ?? null);
  4395.         $employee->setPermanentAddress($userData['getPermAddr'] ?? null);
  4396.         $employee->setCompanyId((int)$companyId);
  4397.         $employee->setDepartmentId($userData['getDept'] ?? null);
  4398.         $employee->setBranchId($userData['getBranch'] ?? null);
  4399.         $employee->setPositionId($userData['getDesg'] ?? null);
  4400.         $employee->setSupervisorId($userData['getSupervisor'] ?? null);
  4401.         if (!empty($imagePathToSet)) {
  4402.             $employee->setImage($imagePathToSet);
  4403.         }
  4404.         $employee->setStatus("1");
  4405.         $employee->setLastModifiedDate(new \DateTime());
  4406.         $em->persist($employee);
  4407.         $em->flush();
  4408.         $employeeDetails $em->getRepository('ApplicationBundle\\Entity\\EmployeeDetails')
  4409.             ->findOneBy(['userId' => $user->getUserId()]);
  4410.         if (!$employeeDetails) {
  4411.             $employeeDetails = new \ApplicationBundle\Entity\EmployeeDetails();
  4412.             $employeeDetails->setUserId($user->getUserId());
  4413.         }
  4414.         $employeeDetails->setId($employee->getEmployeeId());
  4415.         $employeeDetails->setFirstname($userData['getFirstname'] ?? null);
  4416.         $employeeDetails->setLastname($userData['getLastname'] ?? null);
  4417.         $employeeDetails->setUsername($userData['getUsername'] ?? null);
  4418.         $employeeDetails->setEmail($userData['getEmail'] ?? null);
  4419.         $employeeDetails->setPassword($userData['getPassword'] ?? null);
  4420.         $employeeDetails->setNid($userData['getNid'] ?? null);
  4421.         $employeeDetails->setSex($userData['getSex'] ?? null);
  4422.         $employeeDetails->setFather($userData['getFather'] ?? null);
  4423.         $employeeDetails->setMother($userData['getMother'] ?? null);
  4424.         $employeeDetails->setSpouse($userData['getSpouse'] ?? null);
  4425.         $employeeDetails->setChild1($userData['getChild1'] ?? null);
  4426.         $employeeDetails->setChild2($userData['getChild2'] ?? null);
  4427.         $employeeDetails->setPhone($userData['getPhone'] ?? null);
  4428.         $employeeDetails->setOfficialPhone($userData['getOfficailPhone'] ?? null);
  4429.         $employeeDetails->setCurrAddr($userData['getCurrAddr'] ?? null);
  4430.         $employeeDetails->setPermAddr($userData['getPermAddr'] ?? null);
  4431.         $employeeDetails->setEmmContact($userData['getEmmContact'] ?? null);
  4432.         if (!empty($userData['getDob'])) {
  4433.             $employeeDetails->setDob(new \DateTime($userData['getDob']));
  4434.         }
  4435.         if (!empty($userData['getJoiningDate'])) {
  4436.             $employeeDetails->setJoiningDate(new \DateTime($userData['getJoiningDate']));
  4437.         }
  4438.         if (!empty($userData['getEmpValidTill'])) {
  4439.             $employeeDetails->setEmpValidTill(new \DateTime($userData['getEmpValidTill']));
  4440.         }
  4441.         if (!empty($userData['getTinValidTill'])) {
  4442.             $employeeDetails->setTinValidTill(new \DateTime($userData['getTinValidTill']));
  4443.         }
  4444.         if (!empty($userData['getMedInsValidTill'])) {
  4445.             $employeeDetails->setMedInsValidTill(new \DateTime($userData['getMedInsValidTill']));
  4446.         }
  4447.         $employeeDetails->setEmpType($userData['getEmpType'] ?? null);
  4448.         $employeeDetails->setEmpCode($userData['getEmpCode'] ?? null);
  4449.         $employeeDetails->setEmployeeLevel($userData['getEmployeeLevel'] ?? null);
  4450.         $employeeDetails->setTin($userData['getTin'] ?? null);
  4451.         $employeeDetails->setSkill($userData['getSkill'] ?? null);
  4452.         $employeeDetails->setEducationData($userData['getEducationData'] ?? null);
  4453.         $employeeDetails->setWorkExperienceData($userData['getWorkExperienceData'] ?? null);
  4454.         $employeeDetails->setApplicationText($userData['getApplicationText'] ?? null);
  4455.         $employeeDetails->setCurrentEmployment($userData['getCurrentEmployment'] ?? null);
  4456.         $employeeDetails->setEmergencyContactNumber($userData['getEmergencyContactNumber'] ?? null);
  4457.         $employeeDetails->setPostalCode($userData['getPostalCode'] ?? null);
  4458.         $employeeDetails->setCountry($userData['getCountry'] ?? null);
  4459.         if (!empty($imagePathToSet)) {
  4460.             $employeeDetails->setImage($imagePathToSet);
  4461.         }
  4462.         $em->persist($employeeDetails);
  4463.         $em->flush();
  4464.         $uploadedFile $request->files->get('file_' $globalId);
  4465.         return new JsonResponse([
  4466.             'success' => true,
  4467.             'globalId' => $globalId,
  4468.             'appIds' => $appIds,
  4469.             'userIds' => $userIds,
  4470.             'hasFile' => $uploadedFile !== null,
  4471.         ]);
  4472.     }
  4473.     public function getIndustryListForAppAction()
  4474.     {
  4475.         $industryList GeneralConstant::$industryList;
  4476.         return new JsonResponse($industryList);
  4477.     }
  4478.     public function getFeatureListAction()
  4479.     {
  4480.         $featureList GeneralConstant::$featureList;
  4481.         return new JsonResponse($featureList);
  4482.     }
  4483.     public function chooseYourPlanAction()
  4484.     {
  4485.         $plan GeneralConstant::$chooseYourPlan;
  4486.         return new JsonResponse($plan);
  4487.     }
  4488. //    public function getLogindataFromTokenAction(Request $request)
  4489. //    {
  4490. //        $em_goc = $this->getDoctrine()->getManager('company_group');
  4491. //        $sessionData = MiscActions::GetSessionDataFromToken($em_goc, $request->query->get('hbeeSessionToken'))['sessionData'];
  4492. //        return new JsonResponse($sessionData);
  4493. //        $sessionDataa = MiscActions::GetSessionDataFromToken($em_goc, $request->query->get('hbeeSessionToken'))['sessionData'];
  4494. //        return new JsonResponse($sessionDataa);
  4495. //    }
  4496.     public function getLogindataFromTokenAction(Request $request)
  4497.     {
  4498.         $em_goc $this->getDoctrine()->getManager('company_group');
  4499.         $token $request->query->get('hbeeSessionToken');
  4500.         if (!$token) {
  4501.             return new JsonResponse(['error' => 'Missing session token'], 400);
  4502.         }
  4503.         $sessionResult MiscActions::GetSessionDataFromToken($em_goc$token);
  4504.         if (!$sessionResult || !isset($sessionResult['sessionData'])) {
  4505.             return new JsonResponse(['error' => 'Invalid session token or session not found'], 401);
  4506.         }
  4507.         $sessionData $sessionResult['sessionData'];
  4508.         return new JsonResponse($sessionData);
  4509.     }
  4510.    public function packageDetailsAction()
  4511. {
  4512.     $packageDetails GeneralConstant::$packageDetails;
  4513.     return new JsonResponse([
  4514.         'success' => true,
  4515.         'message' => 'Data fetched successfully.',
  4516.         'data' => $packageDetails
  4517.     ]);
  4518. }
  4519.     public function employeeRangeAction()
  4520.     {
  4521.         $employeeRangeForApp GeneralConstant::$employeeRange;
  4522.         return new JsonResponse($employeeRangeForApp);
  4523.     }
  4524.     public function paymentMethodAction()
  4525.     {
  4526.         $paymentMethod GeneralConstant::$paymentMethod;
  4527.         return new JsonResponse($paymentMethod);
  4528.     }
  4529.     public function companyTypeAction()
  4530.     {
  4531.         $companyType GeneralConstant::$companyType;
  4532.         return new JsonResponse(
  4533.             [
  4534.                 'status' => 'success',
  4535.                 'message' => 'Company types retrieved successfully.',
  4536.                 'data' => $companyType,
  4537.             ]
  4538.          );
  4539.     }
  4540.     public function getCountryListAction()
  4541.     {
  4542.         $em_goc $this->getDoctrine()->getManager('company_group');
  4543.         $countryList $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityCountries')
  4544.             ->createQueryBuilder('C')
  4545.             ->select('C.CountryId''C.code''C.nameEn')
  4546.             ->getQuery()
  4547.             ->getArrayResult();
  4548.         // $formattedList = array_map(function ($country) {
  4549.         //     return [
  4550.         //         'countryId' => $country['countryId'],
  4551.         //         'countryName' => $country['nameEn'],
  4552.         //         'countryCode' => $country['code'],
  4553.         //     ];
  4554.         // }, $countryList);
  4555.         return new JsonResponse([
  4556.             'status' => true,
  4557.             'message' => 'Country list fetched successfully',
  4558.             'data' => $countryList,
  4559.         ]);
  4560.     }
  4561. public function spotLightSearchAction(Request $request,$queryStr ''){
  4562.     
  4563.     $em $this->getDoctrine()->getManager();
  4564.     $data = [];
  4565.     $data_by_id = [];
  4566.     $session $request->getSession();
  4567.     $entityDetails GeneralConstant::$Entity_list_details
  4568.     if ($queryStr == '_DEFAULT_')
  4569.         $queryStr '';
  4570.     if ($request->request->has('query') && $queryStr == '')
  4571.         $queryStr $request->request->get('query');
  4572.     if ($queryStr == '_DEFAULT_')
  4573.         $queryStr '';
  4574.     $queryStr str_ireplace('_FSLASH_''/'$queryStr);
  4575.     //module
  4576.     $filterQryForCriteria "select * from sys_module where 1=1 and module_name  like '%" $queryStr "%'  limit 10";
  4577.     $get_kids_sql $filterQryForCriteria;
  4578.     $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  4579.     
  4580.     $get_kids $stmt;
  4581.     $productId 0;
  4582.     $absoluteUrl $this->generateUrl('dashboard', [], UrlGenerator::ABSOLUTE_URL);
  4583.     if (!empty($get_kids)) {
  4584.         foreach ($get_kids as $product) {
  4585.             $router $this->container->get('router');
  4586.             $routeName $product['module_route'];
  4587.             if ($router->getRouteCollection()->get($routeName)) {
  4588.                 $pa            = array();
  4589.                 $pa['id']      = $product['module_id'];
  4590.                 $pa['name']    = $product['module_name'];
  4591.                 $pa['type']    = 'module';
  4592. //            $pa['url']     = $absoluteUrl . '/' . $product['module_route'];
  4593.                 $pa['url']     = $this->generateUrl($product['module_route'], [], UrlGenerator::ABSOLUTE_URL);
  4594.                 $data[] = $pa;
  4595.             } else {
  4596.                 // treat as non-route
  4597. //                $pa['url'] = $routeName; // or custom fallback
  4598.             }
  4599.         }
  4600.     }
  4601.     // supplier
  4602.     $get_kids $em->getConnection()->fetchAllAssociative(
  4603.         "select * from acc_suppliers where supplier_name like '%" $queryStr "%' limit 10"
  4604.     );
  4605.     $url $this->generateUrl('supplier_profile');
  4606.     if (!empty($get_kids)) {
  4607.         foreach ($get_kids as $product) {
  4608.             $pa           = array();
  4609.             $pa['id']     = $product['supplier_id'];
  4610.             $pa['name']   = $product['supplier_name'];
  4611.             $pa['type']   = 'supplier';
  4612.             $pa['url']    = rtrim($absoluteUrl'/') . '/' ltrim($url'/') . '?ex_s_id=' $product['supplier_id'];
  4613.             $data[] = $pa;
  4614.         }
  4615.     }
  4616.     // client
  4617.     $get_kids $em->getConnection()->fetchAllAssociative(
  4618.         "select * from acc_clients where client_name like '%" $queryStr "%' limit 10"
  4619.     );
  4620.     $url $this->generateUrl('client_profile');
  4621.     if (!empty($get_kids)) {
  4622.         foreach ($get_kids as $product) {
  4623.             $pa           = array();
  4624.             $pa['id']     = $product['client_id'];
  4625.             $pa['name']   = $product['client_name'];
  4626.             $pa['type']   = 'client';
  4627.             $pa['url']    = rtrim($absoluteUrl'/') . '/' trim($url'/') . '/' $product['client_id'];
  4628.             $data[] = $pa;
  4629.         }
  4630.     }
  4631.     // document (approval)
  4632.     $get_kids $em->getConnection()->fetchAllAssociative(
  4633.         "select * from approval where document_hash like '%" $queryStr "%' limit 10"
  4634.     );
  4635.     if (!empty($get_kids)) {
  4636.         foreach ($get_kids as $product) {
  4637.             try {
  4638.                 $viewUrl $this->generateUrl(
  4639.                     $entityDetails[$product['entity']]['entity_view_route_path_name']
  4640.                 );
  4641.                 $pa           = array();
  4642.                 $pa['id']     = $product['id'];
  4643.                 $pa['name']   = $product['document_hash'];
  4644.                 $pa['type']   = 'document';
  4645.                 $pa['url']    = rtrim($absoluteUrl'/') . '/' trim($viewUrl'/') . '/' $product['entity_id'];
  4646.                 $data[] = $pa;
  4647.             } catch (\Exception $e) { /* skip if route undefined */ }
  4648.         }
  4649.     }
  4650.     return new JsonResponse(array(
  4651.         'success' => true,
  4652.         'data'    => $data,
  4653.     ));
  4654. }
  4655.     public function getMlDataAction()
  4656.     {
  4657.         $data GeneralConstant::$dataFromMl;
  4658.         return new JsonResponse($data);
  4659.     }
  4660.     public function UploadDocumentsAction(Request $request)
  4661.     {
  4662.         $session $request->getSession();
  4663.         $em $this->getDoctrine()->getManager();
  4664.         return $this->render(
  4665.             '@Application/pages/dashboard/upload_documents.html.twig',
  4666.             array(
  4667.                 'page_title' => 'Upload Documents',
  4668.             )
  4669.         );
  4670.     }
  4671. }