src/ApplicationBundle/Controller/DashboardController.php line 37

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.                         'ApplicationBundle:pages/dashboard:index_finance_mobile.html.twig',
  1836.                         array(
  1837.                             'page_title' => 'Finance Dashboard',
  1838.                             'dashboardDataForUser' => []
  1839.                         )
  1840.                     );
  1841.                 }
  1842.             return $this->render(
  1843.                 'ApplicationBundle: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.                         'ApplicationBundle: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.             'ApplicationBundle: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.             'ApplicationBundle: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.                     'ApplicationBundle: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.             'ApplicationBundle:pages/dashboard:index_finance.html.twig',
  2009.             array(
  2010.                 'page_title' => 'Finance Dashboard',
  2011.                 'dashboardDataForUser' => $dashboardDataForUser
  2012.             )
  2013.         );
  2014.     }
  2015.     public function indexSalesAction(Request $request)
  2016.     {
  2017.         $session $request->getSession();
  2018.         $dashboardDataForUser = [];
  2019.         $em $this->getDoctrine()->getManager();
  2020.         $companyId $this->getLoggedUserCompanyId($request);
  2021.         $userId $request->getSession()->get(UserConstants::USER_ID);
  2022.         $dbQuery $em->getRepository("ApplicationBundle\\Entity\\DashboardWidget")->findBy(
  2023.             array(
  2024.                 'CompanyId' => $companyId,
  2025.                 'userId' => $userId,
  2026.                 'status' => GeneralConstant::ACTIVE
  2027.             ),
  2028.             array(
  2029.                 'sequence' => 'ASC'
  2030.             )
  2031.         );
  2032.         if (empty($dbQuery))   ///now get the defaults
  2033.             $dbQuery $em->getRepository("ApplicationBundle\\Entity\\DashboardWidget")->findBy(
  2034.                 array(
  2035.                     'CompanyId' => $companyId,
  2036.                     //                    'userId'=>$userId,
  2037.                     'defaultBoxFlag' => 1,
  2038.                     'status' => GeneralConstant::ACTIVE
  2039.                 ),
  2040.                 array(
  2041.                     'sequence' => 'ASC'
  2042.                 )
  2043.             );
  2044.         foreach ($dbQuery as $entry) {
  2045.             $dashboardDataForUser[] = array(
  2046.                 'id' => $entry->getId(),
  2047.                 'widgetId' => $entry->getId(),
  2048.                 'widgetSequence' => $entry->getSequence(),
  2049.                 'widgetStatus' => $entry->getStatus(),
  2050.                 'widgetData' => json_decode($entry->getData(), true),
  2051.                 'defaultBoxFlag' => $entry->getDefaultBoxFlag(),
  2052.                 'widgetSizeTiny' => $entry->getSizeTiny(),
  2053.                 'widgetSizeSmall' => $entry->getSizeSmall(),
  2054.                 'widgetSizeMedium' => $entry->getSizeMedium(),
  2055.                 'widgetSizeLarge' => $entry->getSizeLarge(),
  2056.                 'refreshInterval' => $entry->getRefreshInterval(),
  2057.             );
  2058.         }
  2059.         if ($session->has('isMobile')) {
  2060.             if ($session->get('isMobile') == true) {
  2061.                 return $this->render(
  2062.                     'ApplicationBundle:pages/dashboard:index_finance_mobile.html.twig',
  2063.                     array(
  2064.                         'page_title' => 'Finance Dashboard',
  2065.                         'dashboardDataForUser' => $dashboardDataForUser
  2066.                     )
  2067.                 );
  2068.             } else {
  2069.             }
  2070.         }
  2071.         return $this->render(
  2072.             'ApplicationBundle:pages/dashboard:index_sales.html.twig',
  2073.             array(
  2074.                 'page_title' => 'Sales Dashboard',
  2075.                 'dashboardDataForUser' => $dashboardDataForUser
  2076.             )
  2077.         );
  2078.     }
  2079.     public function indexPurchaseAction(Request $request)
  2080.     {
  2081.         $em $this->getDoctrine()->getManager();
  2082.         $companyId $this->getLoggedUserCompanyId($request);
  2083.         $dashboardDataForUser $this->loadDashboardWidgetsForUser($request);
  2084.         $dashboardAnalytics $this->buildPurchaseDashboardAnalytics($em$companyId);
  2085.         return $this->render(
  2086.             'ApplicationBundle:pages/dashboard:index_purchase.html.twig',
  2087.             array(
  2088.                 'page_title' => 'Purchase Dashboard',
  2089.                 'dashboardMode' => 'purchase',
  2090.                 'dashboardDataForUser' => $dashboardDataForUser,
  2091.                 'dashboardAnalytics' => $dashboardAnalytics
  2092.             )
  2093.         );
  2094.     }
  2095.     public function indexDistributionAction(Request $request)
  2096.     {
  2097.         $session $request->getSession();
  2098.         $dashboardDataForUser = [];
  2099.         $em $this->getDoctrine()->getManager();
  2100.         $companyId $this->getLoggedUserCompanyId($request);
  2101.         $userId $request->getSession()->get(UserConstants::USER_ID);
  2102.         $dbQuery $em->getRepository("ApplicationBundle\\Entity\\DashboardWidget")->findBy(
  2103.             array(
  2104.                 'CompanyId' => $companyId,
  2105.                 'userId' => $userId,
  2106.                 'status' => GeneralConstant::ACTIVE
  2107.             ),
  2108.             array(
  2109.                 'sequence' => 'ASC'
  2110.             )
  2111.         );
  2112.         if (empty($dbQuery))   ///now get the defaults
  2113.             $dbQuery $em->getRepository("ApplicationBundle\\Entity\\DashboardWidget")->findBy(
  2114.                 array(
  2115.                     'CompanyId' => $companyId,
  2116.                     //                    'userId'=>$userId,
  2117.                     'defaultBoxFlag' => 1,
  2118.                     'status' => GeneralConstant::ACTIVE
  2119.                 ),
  2120.                 array(
  2121.                     'sequence' => 'ASC'
  2122.                 )
  2123.             );
  2124.         foreach ($dbQuery as $entry) {
  2125.             $dashboardDataForUser[] = array(
  2126.                 'id' => $entry->getId(),
  2127.                 'widgetId' => $entry->getId(),
  2128.                 'widgetSequence' => $entry->getSequence(),
  2129.                 'widgetStatus' => $entry->getStatus(),
  2130.                 'widgetData' => json_decode($entry->getData(), true),
  2131.                 'defaultBoxFlag' => $entry->getDefaultBoxFlag(),
  2132.                 'widgetSizeTiny' => $entry->getSizeTiny(),
  2133.                 'widgetSizeSmall' => $entry->getSizeSmall(),
  2134.                 'widgetSizeMedium' => $entry->getSizeMedium(),
  2135.                 'widgetSizeLarge' => $entry->getSizeLarge(),
  2136.                 'refreshInterval' => $entry->getRefreshInterval(),
  2137.             );
  2138.         }
  2139.         return $this->render(
  2140.             'ApplicationBundle:pages/dashboard:index_sales.html.twig',
  2141.             array(
  2142.                 'page_title' => 'Sales Dashboard',
  2143.                 'dashboardDataForUser' => $dashboardDataForUser
  2144.             )
  2145.         );
  2146.     }
  2147.     public function indexProductionAction(Request $request)
  2148.     {
  2149.         $session $request->getSession();
  2150.         $dashboardDataForUser = [];
  2151.         $em $this->getDoctrine()->getManager();
  2152.         $companyId $this->getLoggedUserCompanyId($request);
  2153.         $userId $request->getSession()->get(UserConstants::USER_ID);
  2154.         $dbQuery $em->getRepository("ApplicationBundle\\Entity\\DashboardWidget")->findBy(
  2155.             array(
  2156.                 'CompanyId' => $companyId,
  2157.                 'userId' => $userId,
  2158.                 'status' => GeneralConstant::ACTIVE
  2159.             ),
  2160.             array(
  2161.                 'sequence' => 'ASC'
  2162.             )
  2163.         );
  2164.         if (empty($dbQuery))   ///now get the defaults
  2165.             $dbQuery $em->getRepository("ApplicationBundle\\Entity\\DashboardWidget")->findBy(
  2166.                 array(
  2167.                     'CompanyId' => $companyId,
  2168.                     //                    'userId'=>$userId,
  2169.                     'defaultBoxFlag' => 1,
  2170.                     'status' => GeneralConstant::ACTIVE
  2171.                 ),
  2172.                 array(
  2173.                     'sequence' => 'ASC'
  2174.                 )
  2175.             );
  2176.         foreach ($dbQuery as $entry) {
  2177.             $dashboardDataForUser[] = array(
  2178.                 'id' => $entry->getId(),
  2179.                 'widgetId' => $entry->getId(),
  2180.                 'widgetSequence' => $entry->getSequence(),
  2181.                 'widgetStatus' => $entry->getStatus(),
  2182.                 'widgetData' => json_decode($entry->getData(), true),
  2183.                 'defaultBoxFlag' => $entry->getDefaultBoxFlag(),
  2184.                 'widgetSizeTiny' => $entry->getSizeTiny(),
  2185.                 'widgetSizeSmall' => $entry->getSizeSmall(),
  2186.                 'widgetSizeMedium' => $entry->getSizeMedium(),
  2187.                 'widgetSizeLarge' => $entry->getSizeLarge(),
  2188.                 'refreshInterval' => $entry->getRefreshInterval(),
  2189.             );
  2190.         }
  2191.         return $this->render(
  2192.             'ApplicationBundle:pages/dashboard:index_sales.html.twig',
  2193.             array(
  2194.                 'page_title' => 'Sales Dashboard',
  2195.                 'dashboardDataForUser' => $dashboardDataForUser
  2196.             )
  2197.         );
  2198.     }
  2199.     public function indexInventoryAction(Request $request)
  2200.     {
  2201.         $em $this->getDoctrine()->getManager();
  2202.         $companyId $this->getLoggedUserCompanyId($request);
  2203.         $dashboardDataForUser $this->loadDashboardWidgetsForUser($request);
  2204.         $dashboardAnalytics $this->buildInventoryDashboardAnalytics($em$companyId);
  2205.         return $this->render(
  2206.             'ApplicationBundle:pages/dashboard:index_inventory.html.twig',
  2207.             array(
  2208.                 'page_title' => 'Inventory Dashboard',
  2209.                 'dashboardMode' => 'inventory',
  2210.                 'dashboardDataForUser' => $dashboardDataForUser,
  2211.                 'dashboardAnalytics' => $dashboardAnalytics
  2212.             )
  2213.         );
  2214.     }
  2215.     private function loadDashboardWidgetsForUser(Request $request)
  2216.     {
  2217.         $dashboardDataForUser = [];
  2218.         $em $this->getDoctrine()->getManager();
  2219.         $companyId $this->getLoggedUserCompanyId($request);
  2220.         $userId $request->getSession()->get(UserConstants::USER_ID);
  2221.         $dbQuery $em->getRepository("ApplicationBundle\\Entity\\DashboardWidget")->findBy(
  2222.             array(
  2223.                 'CompanyId' => $companyId,
  2224.                 'userId' => $userId,
  2225.                 'status' => GeneralConstant::ACTIVE
  2226.             ),
  2227.             array(
  2228.                 'sequence' => 'ASC'
  2229.             )
  2230.         );
  2231.         if (empty($dbQuery)) {
  2232.             $dbQuery $em->getRepository("ApplicationBundle\\Entity\\DashboardWidget")->findBy(
  2233.                 array(
  2234.                     'CompanyId' => $companyId,
  2235.                     'defaultBoxFlag' => 1,
  2236.                     'status' => GeneralConstant::ACTIVE
  2237.                 ),
  2238.                 array(
  2239.                     'sequence' => 'ASC'
  2240.                 )
  2241.             );
  2242.         }
  2243.         foreach ($dbQuery as $entry) {
  2244.             $dashboardDataForUser[] = array(
  2245.                 'id' => $entry->getId(),
  2246.                 'widgetId' => $entry->getId(),
  2247.                 'widgetSequence' => $entry->getSequence(),
  2248.                 'widgetStatus' => $entry->getStatus(),
  2249.                 'widgetData' => json_decode($entry->getData(), true),
  2250.                 'defaultBoxFlag' => $entry->getDefaultBoxFlag(),
  2251.                 'widgetSizeTiny' => $entry->getSizeTiny(),
  2252.                 'widgetSizeSmall' => $entry->getSizeSmall(),
  2253.                 'widgetSizeMedium' => $entry->getSizeMedium(),
  2254.                 'widgetSizeLarge' => $entry->getSizeLarge(),
  2255.                 'refreshInterval' => $entry->getRefreshInterval(),
  2256.             );
  2257.         }
  2258.         return $dashboardDataForUser;
  2259.     }
  2260.     private function buildPurchaseDashboardAnalytics($em$companyId)
  2261.     {
  2262.         $conn $em->getConnection();
  2263.         $monthKeys = [];
  2264.         $monthLabels = [];
  2265.         for ($i 5$i >= 0$i--) {
  2266.             $month = new \DateTime('first day of this month');
  2267.             if ($i 0) {
  2268.                 $month->modify('-' $i ' month');
  2269.             }
  2270.             $monthKeys[] = $month->format('Y-m');
  2271.             $monthLabels[] = $month->format('M');
  2272.         }
  2273.         $poTrendRows $conn->fetchAllAssociative("
  2274.             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
  2275.             FROM purchase_order
  2276.             WHERE company_id = :companyId
  2277.               AND status = 1
  2278.               AND approved = 1
  2279.               AND purchase_order_date >= DATE_SUB(CURDATE(), INTERVAL 5 MONTH)
  2280.             GROUP BY DATE_FORMAT(purchase_order_date, '%Y-%m')
  2281.             ORDER BY month ASC
  2282.         ", ['companyId' => $companyId]);
  2283.         $invoiceTrendRows $conn->fetchAllAssociative("
  2284.             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
  2285.             FROM purchase_invoice
  2286.             WHERE company_id = :companyId
  2287.               AND status = 1
  2288.               AND approved = 1
  2289.               AND purchase_invoice_date >= DATE_SUB(CURDATE(), INTERVAL 5 MONTH)
  2290.             GROUP BY DATE_FORMAT(purchase_invoice_date, '%Y-%m')
  2291.             ORDER BY month ASC
  2292.         ", ['companyId' => $companyId]);
  2293.         $paidTrendRows $conn->fetchAllAssociative("
  2294.             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
  2295.             FROM purchase_invoice
  2296.             WHERE company_id = :companyId
  2297.               AND status = 1
  2298.               AND approved = 1
  2299.               AND purchase_invoice_date >= DATE_SUB(CURDATE(), INTERVAL 5 MONTH)
  2300.             GROUP BY DATE_FORMAT(purchase_invoice_date, '%Y-%m')
  2301.             ORDER BY month ASC
  2302.         ", ['companyId' => $companyId]);
  2303.         $requisitionTrendRows $conn->fetchAllAssociative("
  2304.             SELECT DATE_FORMAT(purchase_requisition_date, '%Y-%m') AS month, COUNT(*) AS total
  2305.             FROM purchase_requisition
  2306.             WHERE company_id = :companyId
  2307.               AND status = 1
  2308.               AND purchase_requisition_date >= DATE_SUB(CURDATE(), INTERVAL 5 MONTH)
  2309.             GROUP BY DATE_FORMAT(purchase_requisition_date, '%Y-%m')
  2310.             ORDER BY month ASC
  2311.         ", ['companyId' => $companyId]);
  2312.         $seriesFromRows = function (array $rows, array $monthKeys) {
  2313.             $series array_fill_keys($monthKeys0);
  2314.             foreach ($rows as $row) {
  2315.                 $month $row['month'] ?? null;
  2316.                 if ($month !== null && array_key_exists($month$series)) {
  2317.                     $series[$month] = (float) $row['total'];
  2318.                 }
  2319.             }
  2320.             return array_values($series);
  2321.         };
  2322.         $purchaseOrderTotal = (float) $conn->fetchOne("
  2323.             SELECT COALESCE(SUM(CAST(COALESCE(NULLIF(po_amount, ''), 0) AS DECIMAL(15,2))), 0)
  2324.             FROM purchase_order
  2325.             WHERE company_id = :companyId AND status = 1 AND approved = 1
  2326.         ", ['companyId' => $companyId]);
  2327.         $purchaseInvoiceTotal = (float) $conn->fetchOne("
  2328.             SELECT COALESCE(SUM(CAST(COALESCE(NULLIF(invoice_amount, ''), 0) AS DECIMAL(15,2))), 0)
  2329.             FROM purchase_invoice
  2330.             WHERE company_id = :companyId AND status = 1 AND approved = 1
  2331.         ", ['companyId' => $companyId]);
  2332.         $purchasePaidTotal = (float) $conn->fetchOne("
  2333.             SELECT COALESCE(SUM(CAST(COALESCE(NULLIF(paid_amount, ''), invoice_amount, 0) AS DECIMAL(15,2))), 0)
  2334.             FROM purchase_invoice
  2335.             WHERE company_id = :companyId AND status = 1 AND approved = 1
  2336.         ", ['companyId' => $companyId]);
  2337.         $purchaseRequisitionCount = (int) $conn->fetchOne("
  2338.             SELECT COUNT(*)
  2339.             FROM purchase_requisition
  2340.             WHERE company_id = :companyId AND status = 1
  2341.         ", ['companyId' => $companyId]);
  2342.         $purchaseOrderCount = (int) $conn->fetchOne("
  2343.             SELECT COUNT(*)
  2344.             FROM purchase_order
  2345.             WHERE company_id = :companyId AND status = 1 AND approved = 1
  2346.         ", ['companyId' => $companyId]);
  2347.         $purchaseInvoiceCount = (int) $conn->fetchOne("
  2348.             SELECT COUNT(*)
  2349.             FROM purchase_invoice
  2350.             WHERE company_id = :companyId AND status = 1 AND approved = 1
  2351.         ", ['companyId' => $companyId]);
  2352.         $pendingPurchaseRequisitionCount = (int) $conn->fetchOne("
  2353.             SELECT COUNT(*)
  2354.             FROM purchase_requisition
  2355.             WHERE company_id = :companyId AND status = 1 AND COALESCE(approved, 0) = 0
  2356.         ", ['companyId' => $companyId]);
  2357.         $pendingPurchaseOrderCount = (int) $conn->fetchOne("
  2358.             SELECT COUNT(*)
  2359.             FROM purchase_order
  2360.             WHERE company_id = :companyId AND status = 1 AND COALESCE(approved, 0) = 0
  2361.         ", ['companyId' => $companyId]);
  2362.         $pendingPurchaseInvoiceCount = (int) $conn->fetchOne("
  2363.             SELECT COUNT(*)
  2364.             FROM purchase_invoice
  2365.             WHERE company_id = :companyId AND status = 1 AND COALESCE(approved, 0) = 0
  2366.         ", ['companyId' => $companyId]);
  2367.         $supplierCount = (int) $conn->fetchOne("
  2368.             SELECT COUNT(DISTINCT supplier_id)
  2369.             FROM purchase_order
  2370.             WHERE company_id = :companyId AND status = 1 AND approved = 1
  2371.         ", ['companyId' => $companyId]);
  2372.         $topSuppliers $conn->fetchAllAssociative("
  2373.             SELECT po.supplier_id, s.supplier_name, COALESCE(SUM(CAST(COALESCE(NULLIF(po.po_amount, ''), 0) AS DECIMAL(15,2))), 0) AS total
  2374.             FROM purchase_order po
  2375.             LEFT JOIN acc_suppliers s ON s.supplier_id = po.supplier_id
  2376.             WHERE po.company_id = :companyId AND po.status = 1 AND po.approved = 1
  2377.             GROUP BY po.supplier_id, s.supplier_name
  2378.             ORDER BY total DESC
  2379.             LIMIT 5
  2380.         ", ['companyId' => $companyId]);
  2381.         $topSupplierTotal 0;
  2382.         foreach ($topSuppliers as $row) {
  2383.             $topSupplierTotal += (float) $row['total'];
  2384.         }
  2385.         $funnelBase max($purchaseRequisitionCount$purchaseOrderCount$purchaseInvoiceCount1);
  2386.         $paidCoverage $purchaseInvoiceTotal ? ($purchasePaidTotal $purchaseInvoiceTotal) * 100 0;
  2387.         return array(
  2388.             'kpis' => array(
  2389.                 array('label' => 'Purchase Orders''value' => $purchaseOrderCount'note' => 'Approved and active''icon' => 'shopping-cart''color' => 'blue'),
  2390.                 array('label' => 'Invoice Value''value' => $purchaseInvoiceTotal'note' => 'Billed through the period''icon' => 'file-text''color' => 'green'),
  2391.                 array('label' => 'Paid Value''value' => $purchasePaidTotal'note' => 'Settled to suppliers''icon' => 'check-circle''color' => 'teal'),
  2392.                 array('label' => 'Outstanding Due''value' => max($purchaseInvoiceTotal $purchasePaidTotal0), 'note' => 'Open supplier liability''icon' => 'hourglass-half''color' => 'red'),
  2393.                 array('label' => 'Suppliers''value' => $supplierCount'note' => 'Active vendor base''icon' => 'building''color' => 'amber'),
  2394.                 array('label' => 'Open Requisitions''value' => $pendingPurchaseRequisitionCount'note' => 'Waiting for movement''icon' => 'tasks''color' => 'slate'),
  2395.             ),
  2396.             'pending_total' => $pendingPurchaseRequisitionCount $pendingPurchaseOrderCount $pendingPurchaseInvoiceCount,
  2397.             'pending_items' => array(
  2398.                 array('label' => 'Requisitions''value' => $pendingPurchaseRequisitionCount'note' => 'Needs buy-side review'),
  2399.                 array('label' => 'Purchase Orders''value' => $pendingPurchaseOrderCount'note' => 'Waiting for approval'),
  2400.                 array('label' => 'Purchase Invoices''value' => $pendingPurchaseInvoiceCount'note' => 'Pending matching'),
  2401.             ),
  2402.             'hero' => array(
  2403.                 'labels' => $monthLabels,
  2404.                 'series' => array(
  2405.                     array('label' => 'PO Value''values' => $seriesFromRows($poTrendRows$monthKeys), 'color' => '#3D7DB8''fill' => 'rgba(61,125,184,0.14)'),
  2406.                     array('label' => 'Invoice Value''values' => $seriesFromRows($invoiceTrendRows$monthKeys), 'color' => '#4BAA6B''fill' => 'rgba(75,170,107,0.14)'),
  2407.                     array('label' => 'Paid Value''values' => $seriesFromRows($paidTrendRows$monthKeys), 'color' => '#2F9E91''fill' => 'rgba(47,158,145,0.14)'),
  2408.                 ),
  2409.             ),
  2410.             'hero_summary' => array(
  2411.                 'headline' => $purchaseInvoiceTotal round($paidCoverage1) . '%' '0%',
  2412.                 'headline_label' => 'Payment coverage',
  2413.                 'subhead' => 'Paid ' round($paidCoverage1) . '% of billed value',
  2414.             ),
  2415.             'snapshot' => array(
  2416.                 'label' => 'Procurement Health',
  2417.                 'ring_value' => round($paidCoverage1),
  2418.                 'ring_note' => 'Invoice coverage',
  2419.                 'metrics' => array(
  2420.                     array('label' => 'Requisition to PO''value' => $purchaseRequisitionCount round(($purchaseOrderCount $purchaseRequisitionCount) * 1001) . '%' '0%''note' => 'Flow conversion'),
  2421.                     array('label' => 'Average PO Size''value' => $purchaseOrderCount number_format($purchaseOrderTotal $purchaseOrderCount0'.'',') : '0''note' => 'Approved order value'),
  2422.                     array('label' => 'Due Ratio''value' => $purchaseInvoiceTotal round((max($purchaseInvoiceTotal $purchasePaidTotal0) / $purchaseInvoiceTotal) * 1001) . '%' '0%''note' => 'Open liability share'),
  2423.                     array('label' => 'Supplier Concentration''value' => $purchaseOrderTotal round(($topSupplierTotal $purchaseOrderTotal) * 1001) . '%' '0%''note' => 'Top-5 spend share'),
  2424.                 ),
  2425.             ),
  2426.             'lower_cards' => array(
  2427.                 array(
  2428.                     'title' => 'Pipeline Atlas',
  2429.                     'subtitle' => 'Requisition to payment flow',
  2430.                     'type' => 'pipeline',
  2431.                     'items' => array(
  2432.                         array('label' => 'Requisitions''value' => $purchaseRequisitionCount'note' => 'Planning demand'),
  2433.                         array('label' => 'Purchase Orders''value' => $purchaseOrderCount'note' => 'Committed spend'),
  2434.                         array('label' => 'Purchase Invoices''value' => $purchaseInvoiceCount'note' => 'Vendor billing'),
  2435.                         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'),
  2436.                     ),
  2437.                     'base' => $funnelBase,
  2438.                 ),
  2439.                 array(
  2440.                     'title' => 'Supplier Mix',
  2441.                     'subtitle' => 'Concentration by approved spend',
  2442.                     'type' => 'bars',
  2443.                     'items' => array_map(function ($row) use ($topSupplierTotal) {
  2444.                         $total = (float) $row['total'];
  2445.                         return array(
  2446.                             'label' => $row['supplier_name'] ?: ('Supplier #' $row['supplier_id']),
  2447.                             'value' => $total,
  2448.                             'bar' => $topSupplierTotal round(($total $topSupplierTotal) * 1001) : 0,
  2449.                             'note' => 'Approved spend share',
  2450.                         );
  2451.                     }, $topSuppliers),
  2452.                 ),
  2453.                 array(
  2454.                     'title' => 'Spend Lens',
  2455.                     'subtitle' => 'Analytical ratios that matter',
  2456.                     'type' => 'ratios',
  2457.                     'items' => array(
  2458.                         array('label' => 'Payment Coverage''value' => round($paidCoverage1) . '%''bar' => $paidCoverage'note' => 'Cash settled vs billed'),
  2459.                         array('label' => 'Requisition Coverage''value' => $purchaseRequisitionCount round(($purchaseOrderCount $purchaseRequisitionCount) * 1001) . '%' '0%''bar' => $purchaseRequisitionCount ? (($purchaseOrderCount $purchaseRequisitionCount) * 100) : 0'note' => 'POs created from requests'),
  2460.                         array('label' => 'Open Due''value' => number_format(max($purchaseInvoiceTotal $purchasePaidTotal0), 0'.'','), 'bar' => $purchaseInvoiceTotal ? ((max($purchaseInvoiceTotal $purchasePaidTotal0) / $purchaseInvoiceTotal) * 100) : 0'note' => 'Balance still outstanding'),
  2461.                     ),
  2462.                 ),
  2463.             ),
  2464.             'months' => $monthLabels
  2465.         );
  2466.     }
  2467.     private function buildInventoryDashboardAnalytics($em$companyId)
  2468.     {
  2469.         $conn $em->getConnection();
  2470.         $monthKeys = [];
  2471.         $monthLabels = [];
  2472.         for ($i 5$i >= 0$i--) {
  2473.             $month = new \DateTime('first day of this month');
  2474.             if ($i 0) {
  2475.                 $month->modify('-' $i ' month');
  2476.             }
  2477.             $monthKeys[] = $month->format('Y-m');
  2478.             $monthLabels[] = $month->format('M');
  2479.         }
  2480.         $receivedRows $conn->fetchAllAssociative("
  2481.             SELECT DATE_FORMAT(stock_received_note_date, '%Y-%m') AS month, COUNT(*) AS total
  2482.             FROM stock_received_note
  2483.             WHERE company_id = :companyId
  2484.               AND status = 1
  2485.               AND approved = 1
  2486.               AND stock_received_note_date >= DATE_SUB(CURDATE(), INTERVAL 5 MONTH)
  2487.             GROUP BY DATE_FORMAT(stock_received_note_date, '%Y-%m')
  2488.             ORDER BY month ASC
  2489.         ", ['companyId' => $companyId]);
  2490.         $transferRows $conn->fetchAllAssociative("
  2491.             SELECT DATE_FORMAT(stock_transfer_date, '%Y-%m') AS month, COUNT(*) AS total
  2492.             FROM stock_transfer
  2493.             WHERE company_id = :companyId
  2494.               AND status = 1
  2495.               AND approved = 1
  2496.               AND stock_transfer_date >= DATE_SUB(CURDATE(), INTERVAL 5 MONTH)
  2497.             GROUP BY DATE_FORMAT(stock_transfer_date, '%Y-%m')
  2498.             ORDER BY month ASC
  2499.         ", ['companyId' => $companyId]);
  2500.         $consumptionRows $conn->fetchAllAssociative("
  2501.             SELECT DATE_FORMAT(stock_consumption_note_date, '%Y-%m') AS month, COUNT(*) AS total
  2502.             FROM stock_consumption_note
  2503.             WHERE company_id = :companyId
  2504.               AND status = 1
  2505.               AND approved = 1
  2506.               AND stock_consumption_note_date >= DATE_SUB(CURDATE(), INTERVAL 5 MONTH)
  2507.             GROUP BY DATE_FORMAT(stock_consumption_note_date, '%Y-%m')
  2508.             ORDER BY month ASC
  2509.         ", ['companyId' => $companyId]);
  2510.         $seriesFromRows = function (array $rows, array $monthKeys) {
  2511.             $series array_fill_keys($monthKeys0);
  2512.             foreach ($rows as $row) {
  2513.                 $month $row['month'] ?? null;
  2514.                 if ($month !== null && array_key_exists($month$series)) {
  2515.                     $series[$month] = (float) $row['total'];
  2516.                 }
  2517.             }
  2518.             return array_values($series);
  2519.         };
  2520.         $skuCount = (int) $conn->fetchOne("
  2521.             SELECT COUNT(*)
  2522.             FROM inv_products
  2523.             WHERE company_id = :companyId AND status = 1
  2524.         ", ['companyId' => $companyId]);
  2525.         $totalUnits = (float) $conn->fetchOne("
  2526.             SELECT COALESCE(SUM(CAST(COALESCE(NULLIF(qty, ''), 0) AS DECIMAL(15,2))), 0)
  2527.             FROM inv_products
  2528.             WHERE company_id = :companyId AND status = 1
  2529.         ", ['companyId' => $companyId]);
  2530.         $stockValue = (float) $conn->fetchOne("
  2531.             SELECT COALESCE(SUM(CAST(COALESCE(NULLIF(qty, ''), 0) AS DECIMAL(15,2)) * CAST(COALESCE(NULLIF(curr_purchase_price, ''), 0) AS DECIMAL(15,2))), 0)
  2532.             FROM inv_products
  2533.             WHERE company_id = :companyId AND status = 1
  2534.         ", ['companyId' => $companyId]);
  2535.         $lowStockCount = (int) $conn->fetchOne("
  2536.             SELECT COUNT(*)
  2537.             FROM inv_products
  2538.             WHERE company_id = :companyId
  2539.               AND status = 1
  2540.               AND CAST(COALESCE(NULLIF(qty, ''), 0) AS DECIMAL(15,2)) <= CAST(COALESCE(NULLIF(reorder_level, ''), 0) AS DECIMAL(15,2))
  2541.               AND CAST(COALESCE(NULLIF(reorder_level, ''), 0) AS DECIMAL(15,2)) > 0
  2542.         ", ['companyId' => $companyId]);
  2543.         $zeroStockCount = (int) $conn->fetchOne("
  2544.             SELECT COUNT(*)
  2545.             FROM inv_products
  2546.             WHERE company_id = :companyId AND status = 1 AND CAST(COALESCE(NULLIF(qty, ''), 0) AS DECIMAL(15,2)) <= 0
  2547.         ", ['companyId' => $companyId]);
  2548.         $overstockCount = (int) $conn->fetchOne("
  2549.             SELECT COUNT(*)
  2550.             FROM inv_products
  2551.             WHERE company_id = :companyId
  2552.               AND status = 1
  2553.               AND CAST(COALESCE(NULLIF(reorder_level, ''), 0) AS DECIMAL(15,2)) > 0
  2554.               AND CAST(COALESCE(NULLIF(qty, ''), 0) AS DECIMAL(15,2)) > (CAST(COALESCE(NULLIF(reorder_level, ''), 0) AS DECIMAL(15,2)) * 3)
  2555.         ", ['companyId' => $companyId]);
  2556.         $warehouseCount = (int) $conn->fetchOne("
  2557.             SELECT COUNT(*)
  2558.             FROM warehouse
  2559.             WHERE company_id = :companyId AND status = 1
  2560.         ", ['companyId' => $companyId]);
  2561.         $receivedPending = (int) $conn->fetchOne("
  2562.             SELECT COUNT(*)
  2563.             FROM stock_received_note
  2564.             WHERE company_id = :companyId AND status = 1 AND COALESCE(approved, 0) = 0
  2565.         ", ['companyId' => $companyId]);
  2566.         $transferPending = (int) $conn->fetchOne("
  2567.             SELECT COUNT(*)
  2568.             FROM stock_transfer
  2569.             WHERE company_id = :companyId AND status = 1 AND COALESCE(approved, 0) = 0
  2570.         ", ['companyId' => $companyId]);
  2571.         $consumptionPending = (int) $conn->fetchOne("
  2572.             SELECT COUNT(*)
  2573.             FROM stock_consumption_note
  2574.             WHERE company_id = :companyId AND status = 1 AND COALESCE(approved, 0) = 0
  2575.         ", ['companyId' => $companyId]);
  2576.         $receivedCount = (int) $conn->fetchOne("
  2577.             SELECT COUNT(*)
  2578.             FROM stock_received_note
  2579.             WHERE company_id = :companyId AND status = 1 AND approved = 1
  2580.         ", ['companyId' => $companyId]);
  2581.         $transferCount = (int) $conn->fetchOne("
  2582.             SELECT COUNT(*)
  2583.             FROM stock_transfer
  2584.             WHERE company_id = :companyId AND status = 1 AND approved = 1
  2585.         ", ['companyId' => $companyId]);
  2586.         $consumptionCount = (int) $conn->fetchOne("
  2587.             SELECT COUNT(*)
  2588.             FROM stock_consumption_note
  2589.             WHERE company_id = :companyId AND status = 1 AND approved = 1
  2590.         ", ['companyId' => $companyId]);
  2591.         $warehouseMap = \ApplicationBundle\Modules\Inventory\Inventory::WarehouseList($em$companyId);
  2592.         $warehouseRows $conn->fetchAllAssociative("
  2593.             SELECT warehouse_id, COALESCE(SUM(CAST(COALESCE(NULLIF(qty, ''), 0) AS DECIMAL(15,2))), 0) AS total_qty,
  2594.                    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
  2595.             FROM inventory_storage
  2596.             WHERE company_id = :companyId
  2597.             GROUP BY warehouse_id
  2598.             ORDER BY total_value DESC
  2599.             LIMIT 5
  2600.         ", ['companyId' => $companyId]);
  2601.         $productRows $conn->fetchAllAssociative("
  2602.             SELECT s.product_id, p.name, p.reorder_level,
  2603.                    COALESCE(SUM(CAST(COALESCE(NULLIF(s.qty, ''), 0) AS DECIMAL(15,2))), 0) AS total_qty,
  2604.                    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
  2605.             FROM inventory_storage s
  2606.             LEFT JOIN inv_products p ON p.id = s.product_id
  2607.             WHERE s.company_id = :companyId
  2608.             GROUP BY s.product_id, p.name, p.reorder_level
  2609.             ORDER BY total_value DESC
  2610.             LIMIT 5
  2611.         ", ['companyId' => $companyId]);
  2612.         $movementBalance $receivedCount $consumptionCount;
  2613.         $healthIndex $skuCount max(0100 round(($lowStockCount $skuCount) * 100)) : 0;
  2614.         $reorderPressure $skuCount round(($lowStockCount $skuCount) * 1001) : 0;
  2615.         $stockCoverage $warehouseCount round($totalUnits $warehouseCount1) : 0;
  2616.         $topWarehouseTotal 0;
  2617.         foreach ($warehouseRows as $row) {
  2618.             $topWarehouseTotal += (float) $row['total_value'];
  2619.         }
  2620.         $topProductTotal 0;
  2621.         foreach ($productRows as $row) {
  2622.             $topProductTotal += (float) $row['total_value'];
  2623.         }
  2624.         return array(
  2625.             'kpis' => array(
  2626.                 array('label' => 'SKUs''value' => $skuCount'note' => 'Active item master''icon' => 'cube''color' => 'blue'),
  2627.                 array('label' => 'On-hand Units''value' => $totalUnits'note' => 'Current quantity snapshot''icon' => 'cubes''color' => 'green'),
  2628.                 array('label' => 'Stock Value''value' => $stockValue'note' => 'Book value at purchase cost''icon' => 'database''color' => 'teal'),
  2629.                 array('label' => 'Low Stock SKUs''value' => $lowStockCount'note' => 'At or below reorder point''icon' => 'exclamation-triangle''color' => 'red'),
  2630.                 array('label' => 'Warehouses''value' => $warehouseCount'note' => 'Active storage nodes''icon' => 'warehouse''color' => 'amber'),
  2631.                 array('label' => 'Pending Docs''value' => $receivedPending $transferPending $consumptionPending'note' => 'Awaiting approval''icon' => 'hourglass-half''color' => 'slate'),
  2632.             ),
  2633.             'pending_total' => $receivedPending $transferPending $consumptionPending,
  2634.             'pending_items' => array(
  2635.                 array('label' => 'Stock Received''value' => $receivedPending'note' => 'Incoming goods'),
  2636.                 array('label' => 'Stock Transfer''value' => $transferPending'note' => 'Warehouse movement'),
  2637.                 array('label' => 'Consumption Notes''value' => $consumptionPending'note' => 'Consumption posting'),
  2638.             ),
  2639.             'hero' => array(
  2640.                 'labels' => $monthLabels,
  2641.                 'series' => array(
  2642.                     array('label' => 'Received''values' => $seriesFromRows($receivedRows$monthKeys), 'color' => '#3D7DB8''fill' => 'rgba(61,125,184,0.14)'),
  2643.                     array('label' => 'Transfers''values' => $seriesFromRows($transferRows$monthKeys), 'color' => '#D4A843''fill' => 'rgba(212,168,67,0.14)'),
  2644.                     array('label' => 'Consumed''values' => $seriesFromRows($consumptionRows$monthKeys), 'color' => '#C05350''fill' => 'rgba(192,83,80,0.14)'),
  2645.                 ),
  2646.             ),
  2647.             'hero_summary' => array(
  2648.                 'headline' => $healthIndex '%',
  2649.                 'headline_label' => 'Health index',
  2650.                 'subhead' => 'Low stock pressure at ' $reorderPressure '%',
  2651.             ),
  2652.             'snapshot' => array(
  2653.                 'label' => 'Stock Health',
  2654.                 'ring_value' => $healthIndex,
  2655.                 'ring_note' => 'Health index',
  2656.                 'metrics' => array(
  2657.                     array('label' => 'Low Stock Pressure''value' => $reorderPressure '%''note' => 'At or under reorder'),
  2658.                     array('label' => 'Movement Balance''value' => $movementBalance'note' => 'Received minus consumed'),
  2659.                     array('label' => 'Avg Units / Warehouse''value' => $stockCoverage'note' => 'Distribution breadth'),
  2660.                     array('label' => 'Zero Stock SKUs''value' => $zeroStockCount'note' => 'Immediate attention'),
  2661.                 ),
  2662.             ),
  2663.             'lower_cards' => array(
  2664.                 array(
  2665.                     'title' => 'Reorder Radar',
  2666.                     'subtitle' => 'What needs intervention now',
  2667.                     'type' => 'radar',
  2668.                     'items' => array(
  2669.                         array('label' => 'Low Stock''value' => $lowStockCount'bar' => $skuCount ? (($lowStockCount $skuCount) * 100) : 0'note' => 'At reorder threshold'),
  2670.                         array('label' => 'Zero Stock''value' => $zeroStockCount'bar' => $skuCount ? (($zeroStockCount $skuCount) * 100) : 0'note' => 'Unavailable items'),
  2671.                         array('label' => 'Overstock''value' => $overstockCount'bar' => $skuCount ? (($overstockCount $skuCount) * 100) : 0'note' => 'Potential capital lock-up'),
  2672.                         array('label' => 'Movement Balance''value' => $movementBalance'bar' => max(0min(10050 + ($movementBalance 5))), 'note' => 'Inbound vs consumption'),
  2673.                     ),
  2674.                 ),
  2675.                 array(
  2676.                     'title' => 'Warehouse Atlas',
  2677.                     'subtitle' => 'Value concentration by store',
  2678.                     'type' => 'bars',
  2679.                     'items' => array_map(function ($row) use ($warehouseMap$topWarehouseTotal) {
  2680.                         $warehouseId = (int) $row['warehouse_id'];
  2681.                         $warehouseName = isset($warehouseMap[$warehouseId]['name']) ? $warehouseMap[$warehouseId]['name'] : ('Warehouse #' $warehouseId);
  2682.                         $total = (float) $row['total_value'];
  2683.                         return array(
  2684.                             'label' => $warehouseName,
  2685.                             'value' => $total,
  2686.                             'bar' => $topWarehouseTotal round(($total $topWarehouseTotal) * 1001) : 0,
  2687.                             'note' => 'Stock value share',
  2688.                         );
  2689.                     }, $warehouseRows),
  2690.                 ),
  2691.                 array(
  2692.                     'title' => 'Value Lens',
  2693.                     'subtitle' => 'Highest value stock pockets',
  2694.                     'type' => 'products',
  2695.                     'items' => array_map(function ($row) use ($topProductTotal) {
  2696.                         $total = (float) $row['total_value'];
  2697.                         $reorderLevel = isset($row['reorder_level']) ? (float) $row['reorder_level'] : 0;
  2698.                         return array(
  2699.                             'label' => $row['name'] ?: ('SKU #' $row['product_id']),
  2700.                             'value' => $total,
  2701.                             'bar' => $topProductTotal round(($total $topProductTotal) * 1001) : 0,
  2702.                             'note' => 'Reorder level ' number_format($reorderLevel0'.'','),
  2703.                         );
  2704.                     }, $productRows),
  2705.                 ),
  2706.             ),
  2707.             'months' => $monthLabels
  2708.         );
  2709.     }
  2710.     public function indexServiceAction(Request $request)
  2711.     {
  2712.         $session $request->getSession();
  2713.         $dashboardDataForUser = [];
  2714.         $em $this->getDoctrine()->getManager();
  2715.         $companyId $this->getLoggedUserCompanyId($request);
  2716.         $userId $request->getSession()->get(UserConstants::USER_ID);
  2717.         $dbQuery $em->getRepository("ApplicationBundle\\Entity\\DashboardWidget")->findBy(
  2718.             array(
  2719.                 'CompanyId' => $companyId,
  2720.                 'userId' => $userId,
  2721.                 'status' => GeneralConstant::ACTIVE
  2722.             ),
  2723.             array(
  2724.                 'sequence' => 'ASC'
  2725.             )
  2726.         );
  2727.         if (empty($dbQuery))   ///now get the defaults
  2728.             $dbQuery $em->getRepository("ApplicationBundle\\Entity\\DashboardWidget")->findBy(
  2729.                 array(
  2730.                     'CompanyId' => $companyId,
  2731.                     //                    'userId'=>$userId,
  2732.                     'defaultBoxFlag' => 1,
  2733.                     'status' => GeneralConstant::ACTIVE
  2734.                 ),
  2735.                 array(
  2736.                     'sequence' => 'ASC'
  2737.                 )
  2738.             );
  2739.         foreach ($dbQuery as $entry) {
  2740.             $dashboardDataForUser[] = array(
  2741.                 'id' => $entry->getId(),
  2742.                 'widgetId' => $entry->getId(),
  2743.                 'widgetSequence' => $entry->getSequence(),
  2744.                 'widgetStatus' => $entry->getStatus(),
  2745.                 'widgetData' => json_decode($entry->getData(), true),
  2746.                 'defaultBoxFlag' => $entry->getDefaultBoxFlag(),
  2747.                 'widgetSizeTiny' => $entry->getSizeTiny(),
  2748.                 'widgetSizeSmall' => $entry->getSizeSmall(),
  2749.                 'widgetSizeMedium' => $entry->getSizeMedium(),
  2750.                 'widgetSizeLarge' => $entry->getSizeLarge(),
  2751.                 'refreshInterval' => $entry->getRefreshInterval(),
  2752.             );
  2753.         }
  2754.         return $this->render(
  2755.             'ApplicationBundle:pages/dashboard:index_sales.html.twig',
  2756.             array(
  2757.                 'page_title' => 'Sales Dashboard',
  2758.                 'dashboardDataForUser' => $dashboardDataForUser
  2759.             )
  2760.         );
  2761.     }
  2762.     public function modifyDashboardAction(Request $request)
  2763.     {
  2764.         $session $request->getSession();
  2765.         $em $this->getDoctrine()->getManager();
  2766.         $companyId $this->getLoggedUserCompanyId($request);
  2767.         $userId $request->getSession()->get(UserConstants::USER_ID);
  2768.         if ($request->isMethod('post')) {
  2769.             //update dashboard data
  2770.             if ($request->request->has('widgetId')) {
  2771.                 foreach ($request->request->get('widgetId') as $k => $v) {
  2772.                     if ($v != 0) {
  2773.                         //exists sso edit
  2774.                         $widget $em->getRepository("ApplicationBundle\\Entity\\DashboardWidget")->findOneBy(
  2775.                             array(
  2776.                                 'id' => $v,
  2777.                             )
  2778.                         );
  2779.                     } else
  2780.                         $widget = new DashboardWidget();
  2781.                     $widget->setData($request->request->get('widgetData')[$k]);
  2782.                     $widget->setSequence($request->request->get('widgetSequence')[$k]);
  2783.                     $widget->setStatus($request->request->has('widgetStatus') ? $request->request->get('widgetStatus')[$k] : GeneralConstant::ACTIVE);
  2784.                     $widget->setUserId($userId);
  2785.                     $widget->setCompanyId($companyId);
  2786.                     $widget->setDefaultBoxFlag($request->request->has('defaultBoxFlag') ? $request->request->get('defaultBoxFlag')[$k] : 0);
  2787.                     if ($v == 0)
  2788.                         $em->persist($widget);
  2789.                     $em->flush();
  2790.                 }
  2791.             }
  2792.         }
  2793.         $dashboardDataForUser = [];
  2794.         $dbQuery $em->getRepository("ApplicationBundle\\Entity\\DashboardWidget")->findBy(
  2795.             array(
  2796.                 'CompanyId' => $companyId,
  2797.                 'userId' => $userId,
  2798.                 'status' => GeneralConstant::ACTIVE
  2799.             )
  2800.         );
  2801.         if (empty($dbQuery))   ///now get the defaults
  2802.             $dbQuery $em->getRepository("ApplicationBundle\\Entity\\DashboardWidget")->findBy(
  2803.                 array(
  2804.                     'CompanyId' => $companyId,
  2805.                     //                    'userId'=>$userId,
  2806.                     'defaultBoxFlag' => 1,
  2807.                     'status' => GeneralConstant::ACTIVE
  2808.                 )
  2809.             );
  2810.         foreach ($dbQuery as $entry) {
  2811.             $dashboardDataForUser[] = array(
  2812.                 'id' => $entry->getId(),
  2813.                 'widgetId' => $entry->getId(),
  2814.                 'widgetSequence' => $entry->getSequence(),
  2815.                 'widgetStatus' => $entry->getStatus(),
  2816.                 'widgetData' => $entry->getData(),
  2817.                 'defaultBoxFlag' => $entry->getDefaultBoxFlag(),
  2818.                 'widgetSizeTiny' => $entry->getSizeTiny(),
  2819.                 'widgetSizeSmall' => $entry->getSizeSmall(),
  2820.                 'widgetSizeMedium' => $entry->getSizeMedium(),
  2821.                 'widgetSizeLarge' => $entry->getSizeLarge(),
  2822.                 'refreshInterval' => $entry->getRefreshInterval(),
  2823.             );
  2824.         }
  2825.         //1st try to see if any exists
  2826.         return $this->render(
  2827.             'ApplicationBundle:pages/dashboard:index_sales.html.twig',
  2828.             array(
  2829.                 'page_title' => 'Modify Dashboard'
  2830.             )
  2831.         );
  2832.     }
  2833.     public function ChangeCompanyDashboardAction(Request $request$id 1)
  2834.     {
  2835.         $session $request->getSession();
  2836.         if ($request->query->has('sys_admin_panel'))
  2837.             return $this->redirectToRoute('system_admin_dashboard');
  2838.         else {
  2839.             $session->set(UserConstants::USER_COMPANY_ID$id);
  2840.             return $this->redirectToRoute('dashboard');
  2841.         }
  2842.     }
  2843.     public function ChangeLeftPanelDisplayStatusAction(Request $request)
  2844.     {
  2845.         $session $request->getSession();
  2846.         $curr_status 1;
  2847.         if ($session->has('HIDE_LEFT_PANEL'))
  2848.             $curr_status $session->get('HIDE_LEFT_PANEL');
  2849.         if ($curr_status == 1)
  2850.             $curr_status 0;
  2851.         else
  2852.             $curr_status 1;
  2853.         $session->set('HIDE_LEFT_PANEL'$curr_status);
  2854.         //            return $this->redirectToRoute('dashboard');
  2855.         return new Response($curr_status);
  2856.     }
  2857.     public function PermissionDeniedAction(Request $request)
  2858.     {
  2859.         $session $request->getSession();
  2860.         // Generic::debugMessage($session);
  2861.         return $this->render(
  2862.             '@System/pages/permission_denied.html.twig',
  2863.             array(
  2864.                 'page_title' => 'Permission Denied'
  2865.             )
  2866.         );
  2867.     }
  2868.     public function MyDocumentsAction(Request $request)
  2869.     {
  2870.         $session $request->getSession();
  2871.         $em $this->getDoctrine()->getManager();
  2872.         $data MiscActions::getDocumentsByUserId($em$session->get(UserConstants::USER_ID));
  2873.         // Generic::debugMessage($session);
  2874.         return $this->render(
  2875.             'ApplicationBundle:pages/dashboard:my_documents.html.twig',
  2876.             array(
  2877.                 'page_title' => 'My Documents',
  2878.                 'data' => $data
  2879.             )
  2880.         );
  2881.     }
  2882.     //     public function MyDocumentsListForAppAction(Request $request)
  2883.     //     {
  2884.     //         $session = $request->getSession();
  2885.     //         $em = $this->getDoctrine()->getManager();
  2886.     //         $absoluteUrlList = [];
  2887.     //         foreach (GeneralConstant::$Entity_list_details as $e => $d) {
  2888.     //             if (isset($d['entity_print_route_path_name']))
  2889.     //                 $absoluteUrlList[$e] = $this->generateUrl($d['entity_print_route_path_name'], [], UrlGenerator::ABSOLUTE_URL);
  2890.     //         }
  2891.     //         $data = MiscActions::getDocumentsByUserIdForApp($em, $session->get(UserConstants::USER_ID), 1, $absoluteUrlList);
  2892.     //         // Generic::debugMessage($session);
  2893.     //         return new JsonResponse(array(
  2894.     //             'data' => $data
  2895.     //         ));
  2896.     // //        return $this->render('ApplicationBundle:pages/dashboard:my_documents.html.twig',
  2897.     // //            array(
  2898.     // //                'page_title' => 'My Documents',
  2899.     // //                'data' => $data
  2900.     // //            )
  2901.     // //        );
  2902.     //     }
  2903.     public function MyDocumentsListForAppAction(Request $request)
  2904.     {
  2905.         $session $request->getSession();
  2906.         $em $this->getDoctrine()->getManager();
  2907.         // Build absolute URL list
  2908.         $absoluteUrlList = [];
  2909.         foreach (GeneralConstant::$Entity_list_details as $e => $d) {
  2910.             if (isset($d['entity_print_route_path_name'])) {
  2911.                 $absoluteUrlList[$e] = $this->generateUrl($d['entity_print_route_path_name'], [], UrlGenerator::ABSOLUTE_URL);
  2912.             }
  2913.         }
  2914.         // Extract pagination parameters from the request
  2915.         $page $request->query->get('page''_UNSET_');
  2916.         $offset $request->query->get('offset'0);
  2917.         $limit $request->query->get('limit'10); // default limit is 10
  2918.         // Call the document list method with pagination
  2919.         return new JsonResponse(
  2920.             MiscActions::getDocumentsByUserIdForApp(
  2921.                 $em,
  2922.                 $session->get(UserConstants::USER_ID),
  2923.                 1,
  2924.                 $absoluteUrlList,
  2925.                 $page,
  2926.                 $offset,
  2927.                 $limit
  2928.             )
  2929.         );
  2930.     }
  2931.     public function ShowExceptionAction(Request $requestFlattenException $exceptionDebugLoggerInterface $logger null)
  2932.     {
  2933.         $session $request->getSession();
  2934.         $em $this->getDoctrine()->getManager();
  2935.         // Generic::debugMessage($session);
  2936.         //        $currentContent = $this->getAndCleanOutputBuffering($request->headers->get('X-Php-Ob-Level', -1));
  2937.         //        $showException = $request->attributes->get('showException', $this->debug); // As opposed to an additional parameter, this maintains BC
  2938.         $code $exception->getStatusCode();
  2939.         //        $data = MiscActions::getDocumentsByUserId($em, $session->get(UserConstants::USER_ID));
  2940.         return $this->render(
  2941.             'ApplicationBundle:pages/error:error_' $code '.html.twig',
  2942.             array(
  2943.                 'page_title' => 'Sorry',
  2944.                 //                'data' => $data
  2945.             )
  2946.         );
  2947.     }
  2948.     public function NotificationAction(Request $request)
  2949.     {
  2950.         $session $request->getSession();
  2951.         //'error', 'success', 'alert', 'information', 'warning', 'confirm'
  2952.         $themes = array(
  2953.             'error' => 'bg-red',
  2954.             'success' => 'bg-green',
  2955.             'alert' => 'bg-purple',
  2956.             'information' => 'bg-grey',
  2957.             'warning' => 'bg-orange',
  2958.             'confirm' => 'bg-blue',
  2959.         );
  2960.         $fa = array(
  2961.             'error' => 'fa fa-ban',
  2962.             'success' => 'fa fa-check',
  2963.             'alert' => 'fa fa-envelope',
  2964.             'information' => 'fa fa-comments',
  2965.             'warning' => 'fa fa-warning',
  2966.             'confirm' => 'fa fa-crosshairs',
  2967.         );
  2968.         // Generic::debugMessage($session);
  2969.         return $this->render(
  2970.             'ApplicationBundle:pages/dashboard:notification.html.twig',
  2971.             array(
  2972.                 'page_title' => 'Notifications',
  2973.                 'dt' => json_decode(System::GetAllNotification(
  2974.                     $this->container->getParameter('notification_enabled'),
  2975.                     $this->container->getParameter('notification_server'),
  2976.                     $request->getSession()->get(UserConstants::USER_ID),
  2977.                     $request->getSession()->get(UserConstants::USER_APP_ID),
  2978.                     $request->getSession()->get(UserConstants::USER_COMPANY_ID)
  2979.                 ), true),
  2980.                 //                'dt'=>System::GetAllNotification(
  2981.                 //                    $this->container->getParameter('notification_enabled'),
  2982.                 //                    $request->getSession()->get(UserConstants::USER_ID),
  2983.                 //                    $request->getSession()->get(UserConstants::USER_APP_ID),
  2984.                 //                    $request->getSession()->get(UserConstants::USER_COMPANY_ID)
  2985.                 //                ),
  2986.                 'themes' => $themes,
  2987.                 'fa' => $fa,
  2988.                 't' => curl_init()
  2989.             )
  2990.         );
  2991.     }
  2992.     public function NotificationDetailAction(Request $request$id 0)
  2993.     {
  2994.         $em $this->getDoctrine()->getManager('company_group');
  2995.         $notification $em->getRepository('CompanyGroupBundle\\Entity\\EntityNotification')->find($id);
  2996.         if (!$notification) {
  2997.             return $this->render(
  2998.                 'ApplicationBundle:pages/dashboard/notification_detail.html.twig',
  2999.                 array(
  3000.                     'page_title' => 'Notification Detail',
  3001.                     'notification' => null,
  3002.                     'detailError' => 'Notification not found.',
  3003.                 )
  3004.             );
  3005.         }
  3006.         if ((int) $notification->getSeenFlag() !== 1) {
  3007.             $notification->setSeenFlag(1);
  3008.         }
  3009.         if ((int) $notification->getReadFlag() !== 1) {
  3010.             $notification->setReadFlag(1);
  3011.         }
  3012.         $em->flush();
  3013.         return $this->render(
  3014.             'ApplicationBundle:pages/dashboard/notification_detail.html.twig',
  3015.             array(
  3016.                 'page_title' => 'Notification Detail',
  3017.                 'notification' => $notification,
  3018.                 'detailError' => '',
  3019.             )
  3020.         );
  3021.     }
  3022.     public function EditAccountAction(Request $request)
  3023.     {
  3024.         $session $request->getSession();
  3025.         //'error', 'success', 'alert', 'information', 'warning', 'confirm'
  3026.         $themes = array(
  3027.             'error' => 'bg-red',
  3028.             'success' => 'bg-green',
  3029.             'alert' => 'bg-purple',
  3030.             'information' => 'bg-aqua',
  3031.             'warning' => 'bg-orange',
  3032.             'confirm' => 'bg-blue',
  3033.         );
  3034.         $fa = array(
  3035.             'error' => 'fa fa-ban',
  3036.             'success' => 'fa fa-check',
  3037.             'alert' => 'fa fa-envelope',
  3038.             'information' => 'fa fa-comments',
  3039.             'warning' => 'fa fa-warning',
  3040.             'confirm' => 'fa fa-crosshairs',
  3041.         );
  3042.         $em $this->getDoctrine()->getManager();
  3043.         $g_path '';
  3044.         if ($request->isMethod('POST')) {
  3045.             $post $request->request;
  3046.             $path "";
  3047.             foreach ($request->files as $uploadedFile) {
  3048.                 if ($uploadedFile != null) {
  3049.                     $fileName md5(uniqid()) . '.' $uploadedFile->guessExtension();
  3050.                     $path $fileName;
  3051.                     $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/FileUploads/' $request->request->get('userId') . '/';
  3052.                     if (!file_exists($upl_dir)) {
  3053.                         mkdir($upl_dir0777true);
  3054.                     }
  3055.                     $file $uploadedFile->move($upl_dir$path);
  3056.                 }
  3057.             }
  3058.             if ($path != "")
  3059.                 $file_path 'uploads/FileUploads/' $request->request->get('userId') . '/' $path;
  3060.             $g_path $this->container->getParameter('kernel.root_dir') . '/../web/uploads/FileUploads/' $request->request->get('userId') . '/' $path;
  3061.             //            $img_file = file_get_contents($g_path);
  3062.             //            $image_data=base64_encode($img_file);
  3063.             //            $encoded_data=System::encryptSignature($image_data,$request->request->get('approvalHash'));
  3064.             $query_here $this->getDoctrine()
  3065.                 ->getRepository('ApplicationBundle\\Entity\\SysUser')
  3066.                 ->findOneBy(
  3067.                     array('userId' => $request->request->get('userId'))
  3068.                 );
  3069.             if ($query_here) {
  3070.                 $new $query_here;
  3071.                 if ($path != "") {
  3072.                     if ($request->request->has('check_pp')) {
  3073.                         $new->setImage($file_path);
  3074.                         $session->set(UserConstants::USER_IMAGE$new->getImage());
  3075.                     } else
  3076.                         $new->setImage('');
  3077.                 }
  3078.                 $new->setName($request->request->get('name'));
  3079.                 $session->set(UserConstants::USER_NAME$request->request->get('name'));
  3080.                 //now password
  3081.                 if ($request->request->get('oldPass') != '') {
  3082.                     //1st check if old pass valid
  3083.                     if (!$this->container->get('sha256salted_encoder')->isPasswordValid($new->getPassword(), $request->request->get('oldPass'), $new->getSalt())) {
  3084.                         $this->addFlash(
  3085.                             'error',
  3086.                             'Your Old Password Was Wrong'
  3087.                         );
  3088.                     } else {
  3089.                         //old pass valid so now check if neww passes matches
  3090.                         if ($request->request->get('newPass') == $request->request->get('newPassAgain')) {
  3091.                             $new->setSalt(uniqid(mt_rand()));
  3092.                             $password $this->container->get('sha256salted_encoder')->encodePassword($request->request->get('newPass'), $new->getSalt());
  3093.                             $new->setPassword($password);
  3094.                             $em->flush();
  3095.                         } else {
  3096.                             $this->addFlash(
  3097.                                 'error',
  3098.                                 'Passwords Did not Match'
  3099.                             );
  3100.                         }
  3101.                     }
  3102.                 }
  3103.             } else {
  3104.                 //                    $new=new EncryptedSignature();
  3105.                 //                    $new->setData($encoded_data);
  3106.                 //                    $new->setUserId($request->request->get('userId'));
  3107.                 //                    $em->persist($new);
  3108.             }
  3109.             $em->flush();
  3110.             //            now deleting the file
  3111.         }
  3112.         $user_data Users::getUserInfoByLoginId($em$this->getLoggedUserLoginId($request));
  3113.         // Generic::debugMessage($session);
  3114.         return $this->render(
  3115.             '@System/pages/settings/edit_account.html.twig',
  3116.             array(
  3117.                 'page_title' => 'Edit Account',
  3118.                 'user_data' => $user_data,
  3119.                 //                'dt'=>json_decode(System::GetAllNotification($request->getSession()->get(UserConstants::USER_ID)),true),
  3120.                 'themes' => $themes,
  3121.                 'fa' => $fa,
  3122.             )
  3123.         );
  3124.     }
  3125.     public function indexApplicantAction(Request $request)
  3126.     {
  3127.         $systemType $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
  3128.         $twig_file 'ApplicationBundle:pages/login:applicant_login.html.twig';
  3129.         $session $request->getSession();
  3130.         if ($systemType == '_BUDDYBEE_') {
  3131.             if ($session->get('buddybeeAdminLevel'0) > 1)
  3132.                 return $this->redirectToRoute("buddybee_admin_dashboard", []);
  3133.             elseif ($session->get('isConsultant') == 1)
  3134.                 return $this->redirectToRoute("consultant_dashboard", []);
  3135.             else
  3136.                 return $this->redirectToRoute("student_dashboard", []);
  3137.         } elseif ($systemType == '_CENTRAL_') {
  3138.             return $this->render(
  3139.                 'ApplicationBundle:pages/dashboard:index_applicant.html.twig',
  3140.                 array(
  3141.                     'page_title' => 'Applicant Dashboard'
  3142.                 )
  3143.             );
  3144.         } else
  3145.             return $this->render(
  3146.                 'ApplicationBundle:pages/dashboard:consultant_dashboard.html.twig',
  3147.                 array(
  3148.                     'page_title' => 'Applicant Dashboard'
  3149.                 )
  3150.             );
  3151.     }
  3152.     public function indexCentralLandingAction(Request $request)
  3153.     {
  3154.         $session $request->getSession();
  3155.         $userAccessList $session->get('userAccessList', []);
  3156.         $companyNames array_map(function ($company) {
  3157.             return $company['companyName'];
  3158.         }, $userAccessList);
  3159.         if ($request->isMethod('POST')) {
  3160.             $employeeId $request->request->get('employee_id');
  3161.             $companyName $request->request->get('company_name');
  3162.             if ($employeeId && $companyName) {
  3163.                 return new JsonResponse([
  3164.                     'status' => 'success',
  3165.                     'message' => 'Data received successfully',
  3166.                     'employee_id' => $employeeId,
  3167.                     'company_name' => $companyName,
  3168.                 ]);
  3169.             } else {
  3170.                 return new JsonResponse([
  3171.                     'status' => 'error',
  3172.                     'message' => 'Employee ID or Company Name is missing',
  3173.                 ]);
  3174.             }
  3175.         }
  3176.         // If the request is not a POST request, render the normal page
  3177.         return $this->render(
  3178.             'ApplicationBundle:pages/dashboard:index_central_landing.html.twig',
  3179.             [
  3180.                 'page_title' => 'Central Landing',
  3181.                 'companyNames' => $companyNames
  3182.             ]
  3183.         );
  3184.     }
  3185.     public function HummanResourceAction()
  3186.     {
  3187.         $em $this->getDoctrine()->getManager();
  3188.         $currentTime = new \Datetime();
  3189.         $currDate $currentTime->format('Y-m-d');
  3190.         $queryBuilder $em->createQueryBuilder();
  3191.         $queryBuilder->select('A.employeeId''A.entry''A.lastIn''A.lastOut''A.currentLocation','A.createdAt''E.name','E.image','D.positionName')
  3192.             ->from('ApplicationBundle\\Entity\\EmployeeAttendance''A')
  3193.             ->where('A.createdAt >=  :date')
  3194.             ->andWhere('A.createdAt <=  :date_end')
  3195.             ->leftJoin('ApplicationBundle\\Entity\\Employee''E''WITH''A.employeeId = E.employeeId')
  3196.             ->leftJoin('ApplicationBundle\\Entity\\SysDepartmentPosition''D''WITH''E.positionId = D.positionId')
  3197.             ->setParameter('date'$currDate)
  3198.             ->setParameter('date_end'$currDate ' 23:59:59')
  3199.             ->orderBy('A.createdAt''DESC'// latest records first
  3200.             ->setMaxResults(5); // limit to 5 records
  3201.         $data $queryBuilder->getQuery()->getResult();
  3202.         $formattedData array_map(function($item) {
  3203.             return [
  3204.                 'employeeId' => $item['employeeId'],
  3205.                 'entry' => $item['entry'] ? $item['entry']->format('Y-m-d H:i:s') : null,
  3206.                 'lastIn' => $item['lastIn'] ? $item['lastIn']->format('Y-m-d H:i:s') : null,
  3207.                 'lastOut' => $item['lastOut'] ? $item['lastOut']->format('Y-m-d H:i:s') : null,
  3208.                 'currentLocation' => $item['currentLocation'],
  3209.                 'createdAt' => $item['createdAt'] ? $item['createdAt']->format('Y-m-d H:i:s') : null,
  3210.                 'name' => $item['name'],
  3211.                 'image' => $item['image'],
  3212.                 'positionName' => $item['positionName'],
  3213.             ];
  3214.         }, $data);
  3215.         $totalEmployees $em->getRepository('ApplicationBundle\\Entity\\EmployeeDetails')
  3216.             ->createQueryBuilder('E')
  3217.             ->select('COUNT(E.emp_status)')
  3218.             ->where('E.emp_status = 1')
  3219.             ->getQuery()
  3220.             ->getSingleScalarResult();
  3221.         $maleCount $em->getRepository('ApplicationBundle\\Entity\\EmployeeDetails')
  3222.             ->createQueryBuilder('E')
  3223.             ->select('COUNT(E.id)')
  3224.             ->where('E.sex = 1')
  3225.             ->getQuery()
  3226.             ->getSingleScalarResult();
  3227.         $femaleCount $em->getRepository('ApplicationBundle\\Entity\\EmployeeDetails')
  3228.             ->createQueryBuilder('E')
  3229.             ->select('COUNT(E.id)')
  3230.             ->where('E.sex = 2')
  3231.             ->getQuery()
  3232.             ->getSingleScalarResult();
  3233.         $fullTime $em->getRepository('ApplicationBundle\\Entity\\EmployeeDetails')
  3234.             ->createQueryBuilder('E')
  3235.             ->select('COUNT(E.id)')
  3236.             ->where('E.empType = 1')
  3237.             ->getQuery()
  3238.             ->getSingleScalarResult();
  3239.         $partTime $em->getRepository('ApplicationBundle\\Entity\\EmployeeDetails')
  3240.             ->createQueryBuilder('E')
  3241.             ->select('COUNT(E.id)')
  3242.             ->where('E.empType = 2')
  3243.             ->getQuery()
  3244.             ->getSingleScalarResult();
  3245.         $intern $em->getRepository('ApplicationBundle\\Entity\\EmployeeDetails')
  3246.             ->createQueryBuilder('E')
  3247.             ->select('COUNT(E.id)')
  3248.             ->where('E.empType = 3')
  3249.             ->getQuery()
  3250.             ->getSingleScalarResult();
  3251.         $temporary $em->getRepository('ApplicationBundle\\Entity\\EmployeeDetails')
  3252.             ->createQueryBuilder('E')
  3253.             ->select('COUNT(E.id)')
  3254.             ->where('E.empType = 4')
  3255.             ->getQuery()
  3256.             ->getSingleScalarResult();
  3257.         $contractual $em->getRepository('ApplicationBundle\\Entity\\EmployeeDetails')
  3258.             ->createQueryBuilder('E')
  3259.             ->select('COUNT(E.id)')
  3260.             ->where('E.empType = 5')
  3261.             ->getQuery()
  3262.             ->getSingleScalarResult();
  3263.         return $this->render(
  3264.             'ApplicationBundle:pages/dashboard:humanResource.html.twig',
  3265.             [
  3266.                 'page_title' => 'Human Resource Dashboard',
  3267.                 'attendanceDetails' => $formattedData,
  3268.                 'totalEmployee' => $totalEmployees,
  3269.                 'maleCount' => $maleCount,
  3270.                 'femaleCount' => $femaleCount,
  3271.                 'fullTime' => $fullTime,
  3272.                 'partTime' => $partTime,
  3273.                 'temporary' => $temporary,
  3274.                 'contractual' => $contractual,
  3275.                 'intern' => $intern,
  3276.             ]
  3277.         );
  3278.     }
  3279.     public function projectCashFlowReportAction()
  3280.     {
  3281.         return $this->render(
  3282.             'ApplicationBundle:pages/dashboard:cash_flow_report.html.twig',
  3283.             array(
  3284.                 'page_title' => 'Cash Flow Report'
  3285.             )
  3286.         );
  3287.     }
  3288.     public function PerformanceReviewDashboardAction()
  3289.     {
  3290.         return $this->render(
  3291.             'ApplicationBundle:pages/dashboard:performance_review_dashboard.html.twig',
  3292.             array(
  3293.                 'page_title' => 'Performance Review Dashboard'
  3294.             )
  3295.         );
  3296.     }
  3297.     public function RecruitmentDashboardAction(Request $request)
  3298.     {
  3299.         $em $this->getDoctrine()->getManager();
  3300.         $em_goc $this->getDoctrine()->getManager('company_group');
  3301.         $companyId $this->getLoggedUserCompanyId($request);
  3302.         $company_data Company::getCompanyData($em$companyId);
  3303.         // 1. Total Job Posts
  3304.         $totalJobPosts $em->getRepository('ApplicationBundle\\Entity\\JobRecruitment')
  3305.             ->createQueryBuilder('j')
  3306.             ->select('COUNT(j.jobRecruitmentId)')
  3307.             ->where('j.approved = 1')
  3308.             ->getQuery()
  3309.             ->getSingleScalarResult();
  3310.         // 2. Active Job Posts
  3311.         $activeJobPosts $em->getRepository('ApplicationBundle\\Entity\\JobRecruitment')
  3312.             ->createQueryBuilder('j')
  3313.             ->select('COUNT(j.jobRecruitmentId)')
  3314.             ->where('j.approved = 1')
  3315.             ->andWhere('j.jobOpeningStatus = 2'// Assuming 2 is Active
  3316.             ->getQuery()
  3317.             ->getSingleScalarResult();
  3318.         // 3. Total Applicants
  3319.         $totalApplicants $em_goc->getRepository("CompanyGroupBundle\\Entity\\EntityApplicantApplicationList")
  3320.             ->createQueryBuilder('a')
  3321.             ->select('COUNT(a.id)')
  3322.             ->where('a.CompanyId = :companyId')
  3323.             ->andWhere('a.appId = :appId')
  3324.             ->setParameter('companyId'$companyId)
  3325.             ->setParameter('appId'$company_data->getAppId())
  3326.             ->getQuery()
  3327.             ->getSingleScalarResult();
  3328.         // 4. Simple recent activity for dashboard
  3329.         $recentJobs $em->getRepository('ApplicationBundle\\Entity\\JobRecruitment')
  3330.             ->findBy(['approved' => 1], ['createdAt' => 'DESC'], 5);
  3331.         // 5. Jobs with applicant counts
  3332.         $jobsWithApplicantCount $em->getRepository('ApplicationBundle\\Entity\\JobRecruitment')
  3333.             ->createQueryBuilder('j')
  3334.             ->select('j.jobRecruitmentId''j.title''j.applicationClosingDate''j.jobOpeningStatus')
  3335.             ->where('j.approved = 1')
  3336.             ->orderBy('j.createdAt''DESC')
  3337.             ->setMaxResults(8)
  3338.             ->getQuery()
  3339.             ->getResult();
  3340.         foreach ($jobsWithApplicantCount as &$job) {
  3341.             $count $em_goc->getRepository("CompanyGroupBundle\\Entity\\EntityApplicantApplicationList")
  3342.                 ->createQueryBuilder('a')
  3343.                 ->select('COUNT(a.id)')
  3344.                 ->where('a.jobPostId = :jobId')
  3345.                 ->setParameter('jobId'$job['jobRecruitmentId'])
  3346.                 ->getQuery()
  3347.                 ->getSingleScalarResult();
  3348.             $job['applicantCount'] = $count;
  3349.         }
  3350.         return $this->render(
  3351.             'ApplicationBundle:pages/dashboard:recruitment_dashboard.html.twig',
  3352.             array(
  3353.                 'page_title' => 'Recruitment Dashboard',
  3354.                 'totalJobPosts' => $totalJobPosts,
  3355.                 'activeJobPosts' => $activeJobPosts,
  3356.                 'totalApplicants' => $totalApplicants,
  3357.                 'recentJobs' => $recentJobs,
  3358.                 'jobsWithApplicantCount' => $jobsWithApplicantCount,
  3359.                 'jobOpeningStatusArr' => HumanResourceConstant::$jobOpeningStatus
  3360.             )
  3361.         );
  3362.     }
  3363.     public function TalentManagementDashboardAction()
  3364.     {
  3365.         return $this->render(
  3366.             'ApplicationBundle:pages/dashboard:talent_management_dashboard.html.twig',
  3367.             array(
  3368.                 'page_title' => 'Talent Management Dashboard'
  3369.             )
  3370.         );
  3371.     }
  3372.     public function CreateCompanyAction(Request $request)
  3373.     {
  3374.         $systemType $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
  3375.         $appId $request->get('app_id'0);
  3376.         $post $request;
  3377.         $session $request->getSession();
  3378.         if ($request->isMethod('POST')) {
  3379.             if ($systemType == '_CENTRAL_') {
  3380.                 $em_goc $this->getDoctrine()->getManager('company_group');
  3381.                 $em_goc->getConnection()->connect();
  3382.                 $connected $em_goc->getConnection()->isConnected();
  3383.                 $gocDataList = [];
  3384.                 if ($connected) {
  3385.                     $goc null;
  3386.                     $serverList MiscActions::getServerListById(                     $this->container->getParameter('database_user'),                     $this->container->getParameter('database_password'),                     $this->container->hasParameter('server_access_list') ?$this->container->getParameter('server_access_list') :[]                 );
  3387.                     $companyGroupHash $post->get('company_short_code''');
  3388.                     $defaultUsageDate = new \DateTime();
  3389.                     $defaultUsageDate->modify('+1 year');
  3390.                     $usageValidUpto = new \DateTime($post->get('usage_valid_upto_dt_str'$defaultUsageDate->format('Y-m-d')));
  3391.                     $companyGroupServerId $post->get('server_id'1);
  3392.                     $companyGroupServerAddress $serverList[$companyGroupServerId]['absoluteUrl'];
  3393.                     $companyGroupServerPort $serverList[$companyGroupServerId]['port'];
  3394.                     $companyGroupServerHash $serverList[$companyGroupServerId]['serverMarker'];
  3395.                     //                $dbUser=
  3396.                     if ($appId != 0)
  3397.                         $goc $this->getDoctrine()->getManager('company_group')
  3398.                             ->getRepository("CompanyGroupBundle\\Entity\\CompanyGroup")
  3399.                             ->findOneBy(array(
  3400.                                 'appId' => $appId
  3401.                             ));
  3402.                     if (!$goc)
  3403.                         $goc = new CompanyGroup();
  3404.                     if ($appId == 0) {
  3405.                         $biggestAppIdCg $this->getDoctrine()->getManager('company_group')
  3406.                             ->getRepository("CompanyGroupBundle\\Entity\\CompanyGroup")
  3407.                             ->findOneBy(array( //                            'appId' => $appId
  3408.                             ), array(
  3409.                                 'appId' => 'desc'
  3410.                             ));
  3411.                         if ($biggestAppIdCg)
  3412.                             $appId $biggestAppIdCg->getAppId();
  3413.                     }
  3414.                     $goc->setName($post->get('company_name'));
  3415.                     $goc->setCompanyGroupHash($companyGroupHash);
  3416.                     $goc->setAppId($appId);
  3417.                     $goc->setActive(1);
  3418.                     $goc->setAddress($post->get('address'));
  3419.                     $goc->setShippingAddress($post->get('s_address'));
  3420.                     $goc->setBillingAddress($post->get('b_address'));
  3421.                     $goc->setMotto($post->get('motto'));
  3422.                     $goc->setInitiateFlag($post->get('initiate_flag'3));
  3423.                     $goc->setInvoiceFooter($post->get('i_footer'));
  3424.                     $goc->setGeneralFooter($post->get('g_footer'));
  3425.                     $goc->setCompanyReg($post->get('company_reg'''));
  3426.                     $goc->setCompanyTin($post->get('company_tin'''));
  3427.                     $goc->setCompanyBin($post->get('company_bin'''));
  3428.                     $goc->setCompanyTl($post->get('company_tl'''));
  3429.                     $goc->setCompanyType($post->get('company_type'''));
  3430.                     $goc->setCurrentSubscriptionPackageId($post->get('package'1));
  3431.                     $goc->setUsageValidUptoDate($usageValidUpto);
  3432.                     $goc->setUsageValidUptoDateTs($usageValidUpto->format('U'));
  3433.                     //                $goc->setCu($post->get('package', ''));
  3434.                     $goc->setAdminUserAllowed($post->get('number_of_admin_user'1));
  3435.                     $goc->setUserAllowed($post->get('number_of_user'2));
  3436.                     $goc->setSubscriptionMonth($post->get('subscription_month'1));
  3437.                     $goc->setCompanyDescription($post->get('company_description'''));
  3438.                     $goc->setDbUser($post->get('db_user'));
  3439.                     $goc->setDbPass($post->get('db_pass'));
  3440.                     $goc->setDbHost($post->get('db_host'));
  3441.                     $goc->setOwnerId($session->get(UserConstants::USER_ID));
  3442.                     $goc->setCompanyGroupServerId($companyGroupServerId);
  3443.                     $goc->setCompanyGroupServerAddress($companyGroupServerAddress);
  3444.                     $goc->setCompanyGroupServerPort($companyGroupServerPort);
  3445.                     $goc->setCompanyGroupServerHash($companyGroupServerHash);
  3446.                     foreach ($request->files as $uploadedFile) {
  3447.                         if ($uploadedFile != null) {
  3448.                             $fileName 'company_image' $appId '.' $uploadedFile->guessExtension();
  3449.                             $path $fileName;
  3450.                             $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/CompanyImage/';
  3451.                             if ($goc->getImage() != null && $goc->getImage() != '' && file_exists($this->container->getParameter('kernel.root_dir') . '/../web' $goc->getImage())) {
  3452.                                 unlink($this->container->getParameter('kernel.root_dir') . '/../web' $goc->getImage());
  3453.                             }
  3454.                             if (!file_exists($upl_dir)) {
  3455.                                 mkdir($upl_dir0777true);
  3456.                             }
  3457.                             $file $uploadedFile->move($upl_dir$path);
  3458.                             if ($path != "")
  3459.                                 $goc->setImage('/uploads/CompanyImage/' $path);
  3460.                         }
  3461.                     }
  3462.                     $em_goc->persist($goc);
  3463.                     $em_goc->flush();
  3464.                     $goc->setDbName('cg_' $appId '_' $companyGroupHash);
  3465.                     $goc->setDbUser($serverList[$companyGroupServerId]['dbUser']);
  3466.                     $goc->setDbPass($serverList[$companyGroupServerId]['dbPass']);
  3467.                     $goc->setDbHost('localhost');
  3468.                     $em_goc->flush();
  3469.                     $centralUser $this->getDoctrine()->getManager('company_group')
  3470.                         ->getRepository("CompanyGroupBundle\\Entity\\EntityApplicantDetails")
  3471.                         ->findOneBy(array(
  3472.                             'applicantId' => $session->get(UserConstants::USER_ID0)
  3473.                         ));
  3474.                     if ($centralUser) {
  3475.                         $userAppIds json_decode($centralUser->getUserAppIds(), true);
  3476.                         $userTypesByAppIds json_decode($centralUser->getUserTypesByAppIds(), true);
  3477.                         if ($userAppIds == null$userAppIds = [];
  3478.                         if ($userTypesByAppIds == null$userTypesByAppIds = [];
  3479.                         $userAppIds array_merge($userAppIdsarray_diff([$appId], $userAppIds));
  3480.                         if (!isset($userTypesByAppIds[$appId])) {
  3481.                             $userTypesByAppIds[$appId] = [];
  3482.                         }
  3483.                         $userTypesByAppIds[$appId] = array_merge($userTypesByAppIds[$appId], array_diff([UserConstants::USER_TYPE_SYSTEM], $userTypesByAppIds[$appId]));
  3484.                         $centralUser->setUserAppIds(json_encode($userAppIds));
  3485.                         $centralUser->setUserTypesByAppIds(json_encode($userTypesByAppIds));
  3486.                         $em_goc->flush();
  3487.                     }
  3488.                     $accessList $session->get('userAccessList', []);
  3489.                     $d = array(
  3490.                         'userType' => UserConstants::USER_TYPE_SYSTEM,
  3491.                         'globalId' => $session->get(UserConstants::USER_ID0),
  3492.                         'serverId' => $companyGroupServerId,
  3493.                         'serverUrl' => $companyGroupServerAddress,
  3494.                         'serverPort' => $companyGroupServerPort,
  3495.                         'systemType' => '_ERP_',
  3496.                         'companyId' => 1,
  3497.                         'appId' => $appId,
  3498.                         'companyLogoUrl' => $goc->getImage(),
  3499.                         'companyName' => $goc->getName(),
  3500.                         'authenticationStr' => $this->get('url_encryptor')->encrypt(
  3501.                             json_encode(
  3502.                                 array(
  3503.                                     'globalId' => $session->get(UserConstants::USER_ID0),
  3504.                                     'appId' => $appId,
  3505.                                     'authenticate' => 1,
  3506.                                     'userType' => UserConstants::USER_TYPE_SYSTEM
  3507.                                 )
  3508.                             )
  3509.                         ),
  3510.                         'userCompanyList' => []
  3511.                     );
  3512.                     $accessList[] = $d;
  3513. //                    MiscActions::UpdateCompanyListInSession($em_goc, $centralUser->getApplicantId(), 1, 1, 1, $d);
  3514.                     //temporary solution
  3515.                     MiscActions::UpdateCompanyListInSession($em_goc$session->get(UserConstants::USER_ID), 111$d);
  3516.                     $session->set('userAccessList'$accessList);
  3517.                 }
  3518.                 return new JsonResponse(array(
  3519.                     'success' => true,
  3520.                     "message" => "Company Created Successfully",
  3521.                     'user_access_data' => $d,
  3522.                     'app_id' => $appId
  3523.                 ));
  3524.             }
  3525.         }
  3526.         return $this->render('@HoneybeeWeb/pages/create_company.html.twig', array(
  3527.             'page_title' => 'Company',
  3528.             'serverList' => GeneralConstant::$serverListById
  3529.         ));
  3530.     }
  3531.     public function checkBinTinAction(Request $request)
  3532.     {
  3533.         $em_goc $this->getDoctrine()->getManager('company_group');
  3534.         $type  $request->request->get('type');
  3535.         $value trim($request->request->get('value'));
  3536.         $repo $em_goc->getRepository("CompanyGroupBundle\\Entity\\CompanyGroup");
  3537.         if ($type === 'tin') {
  3538.             $company $repo->findOneBy(array(
  3539.                 'company_tin' => $value
  3540.             ));
  3541.         } elseif ($type === 'bin') {
  3542.             $company $repo->findOneBy(array(
  3543.                 'company_bin' => $value
  3544.             ));
  3545.         } elseif ($type === 'reg') {
  3546.             $company $repo->findOneBy(array(
  3547.                 'company_reg' => $value
  3548.             ));
  3549.         } else {
  3550.             return new JsonResponse(['exists' => false]);
  3551.         }
  3552.         return new JsonResponse([
  3553.             'exists' => $company true false
  3554.         ]);
  3555.     }
  3556.     public function createTicketAction(Request $request)
  3557.     {
  3558.         $em_goc $this->getDoctrine()->getManager('company_group');
  3559.         if ($request->isMethod('POST')) {
  3560.             $ticket = new EntityTicket();
  3561.             $ticket->setTitle($request->request->get('title'0));
  3562.             $ticket->setEmail($request->request->get('email'));
  3563.             $ticket->setTicketBody($request->request->get('ticketBody'));
  3564.             $em_goc->persist($ticket);
  3565.             $em_goc->flush();
  3566.         }
  3567.         return new JsonResponse(array(
  3568.             "success" => 'true',
  3569.             "message" => "Ticket Created Successfully",
  3570.         ));
  3571.     }
  3572.     public function GetSessionDataForAppAction(
  3573.         Request $request,
  3574.                 $remoteVerify 0,
  3575.                 $version 'latest',
  3576.                 $identifier '_default_',
  3577.                 $refRoute '',
  3578.                 $apiKey '_ignore_'
  3579.     )
  3580.     {
  3581.         $message "";
  3582.         $gocList = [];
  3583.         $session $request->getSession();
  3584.         if ($request->request->has('token')) {
  3585.             $em_goc $this->getDoctrine()->getManager('company_group');
  3586.             $to_set_session_data MiscActions::GetSessionDataFromToken($em_goc$request->request->get('token'))['sessionData'];
  3587.             if ($to_set_session_data != null) {
  3588.                 foreach ($to_set_session_data as $k => $d) {
  3589.                     //check if mobile
  3590.                     $session->set($k$d);
  3591.                 }
  3592.             }
  3593.         }
  3594.         if ($request->request->has('sessionData')) {
  3595.             $to_set_session_data $request->request->get('sessionData');
  3596.             foreach ($to_set_session_data as $k => $d) {
  3597.                 //check if mobile
  3598.                 $session->set($k$d);
  3599.             }
  3600.         }
  3601.         if ($version !== 'latest') {
  3602.             $session_data = array(
  3603.                 'oAuthToken' => $session->get('oAuthToken'),
  3604.                 'locale' => $session->get('locale'),
  3605.                 'firebaseToken' => $session->get('firebaseToken'),
  3606.                 'token' => $session->get('token'),
  3607.                 UserConstants::USER_EMPLOYEE_ID => $session->get(UserConstants::USER_EMPLOYEE_ID),
  3608.                 UserConstants::USER_ID => $session->get(UserConstants::USER_ID),
  3609.                 UserConstants::LAST_SETTINGS_UPDATED_TS => $session->get(UserConstants::LAST_SETTINGS_UPDATED_TS),
  3610.                 UserConstants::USER_LOGIN_ID => $session->get(UserConstants::USER_LOGIN_ID),
  3611.                 UserConstants::USER_EMAIL => $session->get(UserConstants::USER_EMAIL),
  3612.                 UserConstants::USER_TYPE => $session->get(UserConstants::USER_TYPE),
  3613.                 UserConstants::USER_IMAGE => $session->get(UserConstants::USER_IMAGE),
  3614.                 UserConstants::USER_DEFAULT_ROUTE => $session->get(UserConstants::USER_DEFAULT_ROUTE),
  3615.                 UserConstants::USER_NAME => $session->get(UserConstants::USER_NAME),
  3616.                 UserConstants::USER_COMPANY_ID => $session->get(UserConstants::USER_COMPANY_ID),
  3617.                 UserConstants::USER_COMPANY_ID_LIST => $session->get(UserConstants::USER_COMPANY_ID_LIST),
  3618.                 UserConstants::USER_COMPANY_NAME_LIST => $session->get(UserConstants::USER_COMPANY_NAME_LIST),
  3619.                 UserConstants::USER_COMPANY_IMAGE_LIST => $session->get(UserConstants::USER_COMPANY_IMAGE_LIST),
  3620.                 UserConstants::USER_APP_ID => $session->get(UserConstants::USER_APP_ID),
  3621.                 UserConstants::USER_POSITION_LIST => $session->get(UserConstants::USER_POSITION_LIST),
  3622.                 UserConstants::USER_CURRENT_POSITION => $session->get(UserConstants::USER_CURRENT_POSITION),
  3623.                 UserConstants::ALL_MODULE_ACCESS_FLAG => $session->get(UserConstants::ALL_MODULE_ACCESS_FLAG),
  3624.                 UserConstants::USER_GOC_ID => $session->get(UserConstants::USER_GOC_ID),
  3625.                 UserConstants::USER_NOTIFICATION_ENABLED => GeneralConstant::NOTIFICATION_ENABLED == ? ($this->getParameter('notification_enabled') == 0) : 0,
  3626.                 UserConstants::USER_NOTIFICATION_SERVER => $this->getParameter('notification_server'),
  3627.                 UserConstants::PRODUCT_NAME_DISPLAY_TYPE => $session->get(UserConstants::PRODUCT_NAME_DISPLAY_TYPE),
  3628.                 UserConstants::APPLICATION_SECRET => $session->get(UserConstants::APPLICATION_SECRET),
  3629.                 //new addition
  3630.                 'appIdList' => $session->get('appIdList'),
  3631.                 'branchIdList' => $session->get('branchIdList'null),
  3632.                 'branchId' => $session->get('branchId'null),
  3633.                 'companyIdListByAppId' => $session->get('companyIdListByAppId'),
  3634.                 'companyNameListByAppId' => $session->get('companyNameListByAppId'),
  3635.                 'companyImageListByAppId' => $session->get('companyImageListByAppId'),
  3636.                 'userAccessList' => $session->get('userAccessList'),
  3637.                 'csToken' => $session->get('csToken'),
  3638.             );
  3639.         } else {
  3640.             $session_data = array(
  3641.                 'oAuthToken' => $session->get('oAuthToken'),
  3642.                 'locale' => $session->get('locale'),
  3643.                 'firebaseToken' => $session->get('firebaseToken'),
  3644.                 'token' => $session->get('token'),
  3645.                 UserConstants::USER_EMPLOYEE_ID => $session->get(UserConstants::USER_EMPLOYEE_ID),
  3646.                 UserConstants::USER_ID => $session->get(UserConstants::USER_ID),
  3647.                 UserConstants::LAST_SETTINGS_UPDATED_TS => $session->get(UserConstants::LAST_SETTINGS_UPDATED_TS),
  3648.                 UserConstants::USER_LOGIN_ID => $session->get(UserConstants::USER_LOGIN_ID),
  3649.                 UserConstants::USER_EMAIL => $session->get(UserConstants::USER_EMAIL),
  3650.                 UserConstants::USER_TYPE => $session->get(UserConstants::USER_TYPE),
  3651.                 UserConstants::USER_IMAGE => $session->get(UserConstants::USER_IMAGE),
  3652.                 UserConstants::USER_DEFAULT_ROUTE => $session->get(UserConstants::USER_DEFAULT_ROUTE),
  3653.                 UserConstants::USER_NAME => $session->get(UserConstants::USER_NAME),
  3654.                 UserConstants::USER_COMPANY_ID => $session->get(UserConstants::USER_COMPANY_ID),
  3655.                 UserConstants::USER_COMPANY_ID_LIST => $session->get(UserConstants::USER_COMPANY_ID_LIST),
  3656.                 UserConstants::USER_COMPANY_NAME_LIST => $session->get(UserConstants::USER_COMPANY_NAME_LIST),
  3657.                 UserConstants::USER_COMPANY_IMAGE_LIST => $session->get(UserConstants::USER_COMPANY_IMAGE_LIST),
  3658.                 UserConstants::USER_APP_ID => $session->get(UserConstants::USER_APP_ID),
  3659.                 UserConstants::USER_POSITION_LIST => $session->get(UserConstants::USER_POSITION_LIST),
  3660.                 UserConstants::USER_CURRENT_POSITION => $session->get(UserConstants::USER_CURRENT_POSITION),
  3661.                 UserConstants::ALL_MODULE_ACCESS_FLAG => $session->get(UserConstants::ALL_MODULE_ACCESS_FLAG),
  3662.                 UserConstants::USER_GOC_ID => $session->get(UserConstants::USER_GOC_ID),
  3663.                 UserConstants::USER_NOTIFICATION_ENABLED => GeneralConstant::NOTIFICATION_ENABLED == ? ($this->getParameter('notification_enabled') == 0) : 0,
  3664.                 UserConstants::USER_NOTIFICATION_SERVER => $this->getParameter('notification_server'),
  3665.                 UserConstants::PRODUCT_NAME_DISPLAY_TYPE => $session->get(UserConstants::PRODUCT_NAME_DISPLAY_TYPE),
  3666.                 UserConstants::APPLICATION_SECRET => $session->get(UserConstants::APPLICATION_SECRET),
  3667.                 //new addition
  3668.                 'appIdList' => $session->get('appIdList'),
  3669.                 'branchIdList' => $session->get('branchIdList'null),
  3670.                 'branchId' => $session->get('branchId'null),
  3671.                 'companyIdListByAppId' => $session->get('companyIdListByAppId'),
  3672.                 'companyNameListByAppId' => $session->get('companyNameListByAppId'),
  3673.                 'companyImageListByAppId' => $session->get('companyImageListByAppId'),
  3674.                 'userAccessList' => $session->get('userAccessList'),
  3675.                 'csToken' => $session->get('csToken'),
  3676.             );
  3677.         }
  3678.         $response = new JsonResponse(array(
  3679.             "success" => empty($session->get(UserConstants::USER_ID)) ? false true,
  3680.             //            'session'=>$request->getSession(),
  3681.             'session_data' => $session_data,
  3682.             //            'session2'=>$_SESSION,
  3683.         ));
  3684.         $response->headers->set('Access-Control-Allow-Origin''*, null');
  3685.         $response->headers->set('Access-Control-Allow-Methods''POST');
  3686.         //        $response->setCallback('FUNCTION_CALLBACK_NAME');
  3687.         return $response;
  3688.     }
  3689.     public function EmployeeAddUsingQrCodeCentralAction(Request $request)
  3690.     {
  3691.         $session $request->getSession();
  3692.         if ($request->isMethod('post')) {
  3693.             $em_goc $this->getDoctrine()->getManager('company_group');
  3694.             $entityApplicant $em_goc->getRepository("CompanyGroupBundle\\Entity\\EntityApplicantDetails")
  3695.                 ->findOneBy(
  3696.                     array(
  3697.                         'applicantId' => $request->request->get('userId'),
  3698.                     )
  3699.                 );
  3700.             $app $em_goc->getRepository("CompanyGroupBundle\\Entity\\CompanyGroup")
  3701.                 ->findOneBy(
  3702.                     array(
  3703.                         'appId' => $request->request->get('appId'),
  3704.                     )
  3705.                 );
  3706.             $userType $request->request->get('userType');
  3707.             $currAccessData json_decode($entityApplicant->getUserTypesByAppIds(), true);
  3708.             if ($currAccessData == null$currAccessData = [];
  3709.             if (!isset($currAccessData[$request->request->get('appId')]))
  3710.                 $currAccessData[$request->request->get('appId')] = [];
  3711.             $currAccessData[$request->request->get('appId')] = array_merge($currAccessData[$request->request->get('appId')], array_diff([$request->request->get('userType'$userType)], $currAccessData[$request->request->get('appId')]));
  3712.             $entityApplicant->setUserTypesByAppIds(json_encode($currAccessData));
  3713.             $em_goc->flush();
  3714.             $postData = [];
  3715.             $postData['globalId'] = $entityApplicant->getApplicantId();
  3716.             $postData['username'] = $entityApplicant->getUsername();
  3717.             $postData['email'] = $entityApplicant->getEmail();
  3718.             $postData['firstname'] = $entityApplicant->getFirstname();
  3719.             $postData['lastname'] = $entityApplicant->getLastname();
  3720.             $postData['appId'] = $request->request->get('appId');
  3721.             $postData['companyId'] = $request->request->get('companyId');
  3722.             $postData['userType'] = $userType;
  3723.             $urlToCall $app->getCompanyGroupServerAddress() . '/add_employee_by_qr_erp';
  3724.             $userFiles $postData;
  3725.             $curl curl_init();
  3726.             curl_setopt_array($curl, array(
  3727.                 CURLOPT_RETURNTRANSFER => 1,
  3728.                 CURLOPT_POST => 1,
  3729.                 CURLOPT_URL => $urlToCall,
  3730.                 CURLOPT_CONNECTTIMEOUT => 10,
  3731.                 CURLOPT_SSL_VERIFYPEER => false,
  3732.                 CURLOPT_SSL_VERIFYHOST => false,
  3733.                 CURLOPT_HTTPHEADER => array( //              "Accept: multipart/form-data",
  3734.                 ),
  3735.                 //                            ),
  3736.                 CURLOPT_POSTFIELDS => $userFiles
  3737.             ));
  3738.             $retData curl_exec($curl);
  3739.             $errData curl_error($curl);
  3740.             curl_close($curl);
  3741.             if ($errData) {
  3742. //                $returnData['message']='';
  3743.             } else {
  3744.                 $retDataObj json_decode($retDatatrue);
  3745.                 if ($retDataObj['status'] == 'success') {
  3746.                     $newAccess = [
  3747.                         'userType' => 1,
  3748.                         'userTypeName' => 'Admin',
  3749.                         'globalId' => $entityApplicant->getApplicantId(),
  3750.                         'serverId' => $app->getCompanyGroupServerId(),
  3751.                         'serverUrl' => $app->getCompanyGroupServerAddress(),
  3752.                         'serverPort' => $app->getCompanyGroupServerPort(),
  3753.                         'systemType' => '_ERP_',
  3754.                         'companyId' => 1,
  3755.                         'appId' => $app->getAppId(),
  3756.                         'companyLogoUrl' => '/uploads/CompanyImage/company_image' $request->request->get('appId') . '.png',
  3757.                         'companyName' => $app->getName(),
  3758.                         'authenticationStr' => $this->get('url_encryptor')->encrypt(json_encode(
  3759.                                 array(
  3760.                                     'globalId' => $entityApplicant->getApplicantId(),
  3761.                                     'appId' => $app->getAppId(),
  3762.                                     'authenticate' => 1,
  3763.                                     'userType' => $userType,
  3764.                                     'userTypeName' => UserConstants::$userTypeName[$userType]
  3765.                                 )
  3766.                             )
  3767.                         ),
  3768.                         'userCompanyList' => [],
  3769.                     ];
  3770. //            $token = $session->get('token');
  3771. //            $em_goc = $this->getDoctrine()->getManager('company_group');
  3772.                     $to_set_session_data MiscActions::GetSessionDataFromToken($em_goc$session->get(UserConstants::USER_TOKEN''))['sessionData'];
  3773.                     $currentUserAccessListInSession $to_set_session_data['userAccessList'];
  3774.                     $isAlreadyJoined false;
  3775.                     foreach ($currentUserAccessListInSession as $acc) {
  3776.                         if (isset($acc['appId']) && $acc['appId'] == $request->request->get('appId')) {
  3777.                             $isAlreadyJoined true;
  3778.                             break;
  3779.                         }
  3780.                     }
  3781. //                    if(isset($currentUserAccessListInSession[$request->request->get('appId')]))
  3782. //                        $isAlreadyJoined=true;
  3783.                     if ($isAlreadyJoined) {
  3784.                         return new JsonResponse([
  3785.                             'status' => 'false',
  3786.                             'message' => 'Already joined.',
  3787.                             'currentUserAccessListInSession'  => $currentUserAccessListInSession
  3788.                         ]);
  3789.                     }else{
  3790.                         $currentUserAccessListInSession[] = $newAccess;
  3791.                         $session->set('userAccessList'$currentUserAccessListInSession);
  3792.                         $to_set_session_data['userAccessList'] = $currentUserAccessListInSession;
  3793.                         $updatedToken MiscActions::CreateTokenFromSessionData($em_goc,
  3794.                             $to_set_session_data,
  3795.                             1,
  3796.                             1,
  3797.                             11
  3798.                         );
  3799.                         return new JsonResponse([
  3800.                             'status' => 'success',
  3801.                             'message' => 'User successfully added to company.',
  3802.                             'currentUserAccessListInSession'  => $currentUserAccessListInSession
  3803.                         ]);
  3804.                     }
  3805.                 }
  3806.             }
  3807. //            MiscActions::UpdateCompanyListInSession($em_goc, $entityApplicant->getApplicantId(), 1, 1, 1, $newAccess);
  3808.         } else {
  3809.             $company $request->get('company');
  3810.             return new JsonResponse(array(
  3811.                 'status' => 'error',
  3812.                 'message' => 'Something went wrong while onboarding.'
  3813.             ));
  3814.         }
  3815.         return new JsonResponse(array(
  3816.             'status' => 'error',
  3817.             'message' => 'Something went wrong while onboarding.'
  3818.         ));
  3819.     }
  3820.     public function EmployeeAddUsingQrCodeAction(Request $request)
  3821.     {
  3822.         $post $request;
  3823.         $em $this->getDoctrine()->getManager('company_group');
  3824.         $appid $request->query->get('appid'$request->request->get('appid'null));
  3825.         $session $request->getSession();
  3826.         $CurrentRoute $request->attributes->get('_route');
  3827.         $systemType $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
  3828.         if ($request->isMethod('POST')) {
  3829.             $userId $request->request->get('userId'null);
  3830.             if ($userId === null) {
  3831.                 $companyId $request->request->get('company',1);
  3832.                 $email $request->request->get('email');
  3833.                 $qrImage $request->files->get('qr_image');
  3834.                 if (!$email) {
  3835.                     return new JsonResponse(['status' => 'error''message' => 'Invalid request'], 400);
  3836.                 }
  3837.                 if ($qrImage) {
  3838.                     $uploadsDir $this->getParameter('kernel.project_dir') . '/public/uploads/';
  3839.                     $fileName 'qr_' $companyId '_' time() . '.png';
  3840.                     $qrImage->move($uploadsDir$fileName);
  3841.                     $qrImagePath $uploadsDir $fileName;
  3842.                     $bodyTemplate 'ApplicationBundle:email/user:applicant_confirm.html.twig';
  3843.                     $bodyData = [
  3844.                         'name' => $email,
  3845.                         'companyData' => $companyId,
  3846.                         'companyName' => $request->request->get('company'),
  3847.                         'userType' => 2,
  3848.                         'appId' => $appid,
  3849.                         //                        'qr_code_url' => '/uploads/' . $fileName
  3850.                     ];
  3851.                     $userAccessList $session->get('userAccessList', []);
  3852.                     $companyName array_map(function ($company) {
  3853.                         return $company['companyName'];
  3854.                     }, $userAccessList);
  3855.                     $new_mail $this->get('mail_module');
  3856.                     $new_mail->sendMyMail([
  3857.                         'senderHash' => '_CUSTOM_',
  3858.                         'forwardToMailAddress' => $email,
  3859.                         'fromAddress' => 'accounts@ourhoneybee.eu',
  3860.                         'userName' => 'accounts@ourhoneybee.eu',
  3861.                         'password' => 'Honeybee@0112',
  3862.                         'smtpServer' => 'smtp.hostinger.com',
  3863.                         'smtpPort' => 465,
  3864.                         'subject' => 'User Registration on HoneyBee Ecosystem under Entity ',
  3865.                         'toAddress' => $email,
  3866.                         'mailTemplate' => $bodyTemplate,
  3867.                         'templateData' => $bodyData,
  3868.                         'companyId' => $companyId,
  3869.                     ]);
  3870.                     return $this->render(
  3871.                         'ApplicationBundle:pages/dashboard:index_central_landing.html.twig',
  3872.                         [
  3873.                             'page_title' => 'Central Landing',
  3874.                             'companyNames' => $companyName
  3875.                         ]
  3876.                     );
  3877.                 } else {
  3878.                     $userAccessList $session->get('userAccessList', []);
  3879.                     $companyName array_map(function ($company) {
  3880.                         return $company['companyName'];
  3881.                     }, $userAccessList);
  3882.                     return $this->render(
  3883.                         'ApplicationBundle:pages/dashboard:index_central_landing.html.twig',
  3884.                         [
  3885.                             'page_title' => 'Central Landing',
  3886.                             'companyNames' => $companyName
  3887.                         ]
  3888.                     );
  3889.                 }
  3890.             } else {
  3891.                 if ($systemType == '_CENTRAL_') {
  3892.                     $userAccessList $session->get('userAccessList', []);
  3893.                     $companyName array_map(function ($company) {
  3894.                         return $company['companyName'];
  3895.                     }, $userAccessList);
  3896.                     $modifiedRequest $request->duplicate(
  3897.                         null,
  3898.                         array_merge($request->request->all(), ['appId' => $request->request->get('appid')])
  3899.                     );
  3900.                     $response $this->EmployeeAddUsingQrCodeCentralAction($modifiedRequest);
  3901. //                    if ($CurrentRoute == 'employee_add_by_qr_api')
  3902.                     {
  3903.                         return $response;
  3904.                     }
  3905. //                    return $this->render(
  3906. //                        'ApplicationBundle:pages/dashboard:index_central_landing.html.twig',
  3907. //                        [
  3908. //                            'page_title' => 'Central Landing',
  3909. //                            'companyNames' => $companyName
  3910. //                        ]
  3911. //                    );
  3912.                 }
  3913.             }
  3914.         } else {
  3915.             $company $request->get('company');
  3916.             $em_goc $this->getDoctrine()->getManager('company_group');
  3917.             $company $em_goc->getRepository("CompanyGroupBundle\\Entity\\CompanyGroup")->findOneBy(['appId' => $request->get('appid')]);
  3918.             return $this->render(
  3919.                 'ApplicationBundle:pages/dashboard:employee_add_by_qr.html.twig',
  3920.                 [
  3921.                     'page_title' => 'Company Invitation',
  3922.                     'company' => $company
  3923.                 ]
  3924.             );
  3925.         }
  3926.     }
  3927.     public function EmployeeOnboardUsingQrAction(Request $request): JsonResponse
  3928.     {
  3929.         $email $request->get('email');
  3930.         $isAjax $request->isXmlHttpRequest();
  3931.         $currentRoute $request->attributes->get('_route');
  3932.         if (!$email) {
  3933.             if ($isAjax) {
  3934.                 return new JsonResponse(['status' => 'error''message' => 'Email is required.']);
  3935.             } else {
  3936.                 throw $this->createNotFoundException("Email is missing.");
  3937.             }
  3938.         }
  3939.         $em_goc $this->getDoctrine()->getManager('company_group');
  3940.         $user $em_goc->getRepository("CompanyGroupBundle\\Entity\\EntityApplicantDetails")->findOneBy(['email' => $email]);
  3941.         if (!$user) {
  3942.             if ($isAjax) {
  3943.                 return new JsonResponse(['status' => 'error''message' => 'Applicant not found.']);
  3944.             } else {
  3945.                 throw $this->createNotFoundException("Applicant not found.");
  3946.             }
  3947.         }
  3948.         $payloadUrl $this->generateUrl('employee_onboard_by_qr_api', [
  3949.             'email' => $user->getEmail(),
  3950.             'applicantId' => $user->getApplicantId(),
  3951.             'employeeQr' => 1
  3952.         ], UrlGeneratorInterface::ABSOLUTE_URL);
  3953.         if ($currentRoute === 'employee_onboard') {
  3954.             return new JsonResponse([
  3955.                 'status' => 'success',
  3956.                 'data' => [
  3957.                     'applicantId' => $user->getApplicantId(),
  3958.                     'username' => $user->getUsername(),
  3959.                     'email' => $user->getEmail(),
  3960.                     'firstName' => $user->getFirstname(),
  3961.                     'lastName' => $user->getLastname(),
  3962.                     'link' => $payloadUrl
  3963.                 ]
  3964.             ]);
  3965.         }
  3966.         if ($isAjax) {
  3967.             return new JsonResponse([
  3968.                 'status' => 'success',
  3969.                 'data' => [
  3970.                     'id' => $user->getApplicantId(),
  3971.                     'email' => $user->getEmail(),
  3972.                     'name' => $user->getFirstname() . ' ' $user->getLastname(),
  3973.                     'dob' => $user->getDob() ? $user->getDob()->format('Y-m-d') : null,
  3974.                 ]
  3975.             ]);
  3976.         }
  3977.         $companies $request->getSession()->get('userAccessList', []);
  3978.         return $this->render('ApplicationBundle:pages/dashboard:qr_onboard_result.html.twig', [
  3979.             'page_title' => 'Onboarding',
  3980.             'applicant' => $user,
  3981.             'companies' => $companies
  3982.         ]);
  3983.     }
  3984.     public function OnboardUserToCompanyAction(Request $request)
  3985.     {
  3986.         $systemType $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
  3987.         $currentRoute $request->attributes->get('_route');
  3988.         if ($systemType !== '_CENTRAL_') {
  3989.             throw new \Exception("This action must be called from CENTRAL system.");
  3990.         }
  3991.         $email $request->request->get('email');
  3992.         $applicantId $request->request->get('applicant_id');
  3993.         $appId $request->request->get('company_id');
  3994.         $userType $request->request->get('user_type');
  3995.         if (!$email || !$appId || !$userType) {
  3996.             $this->addFlash('error''Missing required fields.');
  3997.             return new JsonResponse(['status' => 'error''message' => 'Missing required fields.']);
  3998.         }
  3999.         $em $this->getDoctrine()->getManager('company_group');
  4000.         $applicant $em->getRepository("CompanyGroupBundle\\Entity\\EntityApplicantDetails")->findOneBy(['email' => $email]);
  4001.         if (!$applicant) {
  4002.             $this->addFlash('error''Applicant not found.');
  4003.             return $this->redirectToRoute('central_landing');
  4004.         }
  4005.         $userAppIds json_decode($applicant->getUserAppIds(), true);
  4006.         if (!is_array($userAppIds)) {
  4007.             $userAppIds = [];
  4008.         }
  4009.         if (!in_array($appId$userAppIds)) {
  4010.             $userAppIds[] = $appId;
  4011.             $applicant->setUserAppIds(json_encode($userAppIds));
  4012.         }
  4013.         $userTypesByAppIds json_decode($applicant->getUserTypesByAppIds(), true) ?: [];
  4014.         $userTypesByAppIds[$appId] = array((int)$userType);
  4015.         $applicant->setUserTypesByAppIds(json_encode($userTypesByAppIds));
  4016.         $em->persist($applicant);
  4017.         $em->flush();
  4018.         $companyRepo $this->getDoctrine()->getManager('company_group')->getRepository("CompanyGroupBundle\\Entity\\CompanyGroup");
  4019.         $targetCompany $companyRepo->findOneBy(['appId' => $appId]);
  4020.         if (!$targetCompany) {
  4021.             $this->addFlash('error''Target company not found.');
  4022.             return $this->redirectToRoute('central_landing');
  4023.         }
  4024.         $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') :[]                 );
  4025.         $serverId $targetCompany->getCompanyGroupServerId();
  4026.         $appId $targetCompany->getAppId();
  4027.         if (!isset($serverList[$serverId])) {
  4028.             $this->addFlash('error''Server configuration not found.');
  4029.             return $this->redirectToRoute('central_landing');
  4030.         }
  4031.         // Find correct companyId from session userAccessList using appId
  4032.         $session $request->getSession();
  4033.         $userAccessList $session->get('userAccessList', []);
  4034.         $resolvedCompanyId null;
  4035.         foreach ($userAccessList as $access) {
  4036.             if (isset($access['appId']) && $access['appId'] == $appId) {
  4037.                 $resolvedCompanyId $access['companyId'];
  4038.                 break;
  4039.             }
  4040.         }
  4041.         if (!$resolvedCompanyId) {
  4042.             $this->addFlash('error''Could not resolve companyId from session for the given appId.');
  4043.             return $this->redirectToRoute('central_landing');
  4044.         }
  4045.         $imagePath $this->container->getParameter('kernel.root_dir') . '/../web/' $applicant->getImage();
  4046.         $imageFile null;
  4047.         if ($applicant->getImage() && file_exists($imagePath)) {
  4048.             $mime mime_content_type($imagePath);
  4049.             $name pathinfo($imagePathPATHINFO_BASENAME);
  4050.             $imageFile = new \CURLFile($imagePath$mime$name);
  4051.         }
  4052.         // Prepare userData
  4053.         $userData = [];
  4054.         $getters array_filter(get_class_methods($applicant), function ($method) {
  4055.             return strpos($method'get') === 0;
  4056.         });
  4057.         foreach ($getters as $getter) {
  4058.             if (in_array($getter, ['getCreatedAt''getUpdatedAt''getImage'])) continue;
  4059.             $value $applicant->$getter();
  4060.             $userData[$getter] = $value instanceof \DateTime $value->format('Y-m-d') : $value;
  4061.         }
  4062.         $userData['getUserAppIds'] = json_encode($userAppIds);
  4063.         $userData['getUserTypesByAppIds'] = json_encode($userTypesByAppIds);
  4064.         $postFields = [
  4065.             'userData' => json_encode([$userData]),
  4066.             'appIds' => $appId,
  4067.             'userIds' => $applicantId,
  4068.             'companyId' => $resolvedCompanyId,
  4069.             'userType' => $userType,
  4070.             'imageFile' => $imageFile
  4071.         ];
  4072.         if ($imageFile) {
  4073.             $postFields['file_' $applicant->getApplicantId()] = $imageFile;
  4074.         }
  4075.         $url $serverList[$serverId]['absoluteUrl'] . '/OnBoardCentralUserToErp';
  4076.         $curl curl_init();
  4077.         curl_setopt_array($curl, [
  4078.             CURLOPT_RETURNTRANSFER => 1,
  4079.             CURLOPT_POST => 1,
  4080.             CURLOPT_URL => $url,
  4081.             CURLOPT_POSTFIELDS => $postFields,
  4082.             CURLOPT_CONNECTTIMEOUT => 10,
  4083.             CURLOPT_SSL_VERIFYPEER => false,
  4084.             CURLOPT_SSL_VERIFYHOST => false,
  4085.         ]);
  4086.         $response curl_exec($curl);
  4087.         $curlError curl_error($curl);
  4088.         curl_close($curl);
  4089.         $responseObj json_decode($responsetrue);
  4090.         if ($currentRoute === 'employee_onboard_api') {
  4091.             return new JsonResponse(
  4092.                 $responseObj
  4093.             );
  4094.         }
  4095.         if (!empty($responseObj['success'])) {
  4096.             $this->addFlash('success''Applicant onboarded and synced to ERP.');
  4097.         } else {
  4098.             $this->addFlash('warning''Onboarded, but ERP sync may have failed. Check logs.');
  4099.         }
  4100.         return $this->redirectToRoute('central_landing');
  4101.     }
  4102.     public function OnBoardCentralUserToErpAction(Request $request)
  4103.     {
  4104.         $systemType $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
  4105.         if ($systemType === '_CENTRAL_') {
  4106.             return new JsonResponse(['success' => false'message' => 'Invalid system type.']);
  4107.         }
  4108.         $userDataJson $request->get('userData');
  4109.         $userDataList json_decode($userDataJsontrue);
  4110.         if (!$userDataList || !is_array($userDataList)) {
  4111.             return new JsonResponse(['success' => false'message' => 'Invalid or missing userData.']);
  4112.         }
  4113.         $userData $userDataList[0] ?? null;
  4114.         if (!$userData || empty($userData['getApplicantId'])) {
  4115.             return new JsonResponse(['success' => false'message' => 'Missing applicant ID.']);
  4116.         }
  4117.         $em_goc $this->getDoctrine()->getManager('company_group');
  4118.         $globalId $userData['getApplicantId'];
  4119.         $appIds $request->get('appIds');
  4120.         $userIds $request->get('userIds');
  4121.         $companyId $request->get('companyId');
  4122.         $company $em_goc->getRepository("CompanyGroupBundle\\Entity\\CompanyGroup")->findOneBy(['appId' => $appIds]);
  4123.         if (!$company) {
  4124.             return new JsonResponse(['success' => false'message' => 'Target company not found.']);
  4125.         }
  4126.         $connector $this->container->get('application_connector');
  4127.         $connector->resetConnection(
  4128.             'default',
  4129.             $company->getDbName(),
  4130.             $company->getDbUser(),
  4131.             $company->getDbPass(),
  4132.             $company->getDbHost(),
  4133.             true
  4134.         );
  4135.         $em $this->getDoctrine()->getManager();
  4136.         $user $em->getRepository('ApplicationBundle\\Entity\\SysUser')->findOneBy([
  4137.             'globalId' => $globalId
  4138.         ]);
  4139.         if (!$user) {
  4140.             $user = new \ApplicationBundle\Entity\SysUser();
  4141.             $user->setGlobalId($globalId);
  4142.         } else {
  4143.             return new JsonResponse([
  4144.                 'status' => 'info',
  4145.                 'message' => 'User is already onboarded',
  4146.                 'userId' => $user->getUserId(),
  4147.                 'redirectUrl' => 'dashboard'
  4148.             ]);
  4149.         }
  4150.         $setterMap = [
  4151.             'getUsername' => 'setUserName',
  4152.             'getEmail' => 'setEmail',
  4153.             'getPassword' => 'setPassword',
  4154.             'getDeviceId' => 'setDeviceId',
  4155.             'getDeviceIdLockedFlag' => 'setDeviceIdLockedFlag',
  4156.             'getLockDeviceIdOnNextLoginFlag' => 'setLockDeviceIdOnNextLoginFlag',
  4157.             'getOAuthUniqueId' => 'setOAuthUniqueId',
  4158.             'getOAuthEmail' => 'setOAuthEmail',
  4159.             'getSyncFlag' => 'setSyncFlag',
  4160.             'getFirstname' => 'setName',
  4161.         ];
  4162.         $user->setUserAppId($appIds);
  4163.         $user->setUserAppIdList(json_encode([$appIds]));
  4164.         $user->setStatus(1);
  4165.         foreach ($setterMap as $getter => $setter) {
  4166.             if (isset($userData[$getter]) && method_exists($user$setter)) {
  4167.                 $user->$setter($userData[$getter]);
  4168.             }
  4169.         }
  4170.         $fullName trim(($userData['getFirstname'] ?? '') . ' ' . ($userData['getLastname'] ?? ''));
  4171.         if (!empty($fullName)) {
  4172.             $user->setName($fullName);
  4173.         }
  4174.         $imagePathToSet '';
  4175.         $uploadedFile $request->files->get('file_' $globalId);
  4176.         if ($uploadedFile) {
  4177.             $uploadDir $this->getParameter('kernel.project_dir') . '/web/uploads/UserImage/';
  4178.             if (!file_exists($uploadDir)) {
  4179.                 mkdir($uploadDir0777true);
  4180.             }
  4181.             $filename 'user_' $globalId '.' $uploadedFile->guessExtension();
  4182.             $uploadedFile->move($uploadDir$filename);
  4183.             $imagePathToSet 'uploads/UserImage/' $filename;
  4184.             $user->setImage($imagePathToSet);
  4185.         }
  4186.         $user->setUserType(1);
  4187.         $em->persist($user);
  4188.         $em->flush();
  4189.         $employee $em->getRepository('ApplicationBundle\\Entity\\Employee')->findOneBy([
  4190.             'userId' => $user->getUserId()
  4191.         ]);
  4192.         if (!$employee) {
  4193.             $employee = new \ApplicationBundle\Entity\Employee();
  4194.             $employee->setUserId($user->getUserId());
  4195.             $employee->setDateOfAddition(new \DateTime());
  4196.         }
  4197.         $employee->setFirstName($userData['getFirstname'] ?? null);
  4198.         $employee->setLastName($userData['getLastname'] ?? null);
  4199.         $employee->setName(trim(($userData['getFirstname'] ?? '') . ' ' . ($userData['getLastname'] ?? '')));
  4200.         $employee->setEmail($userData['getEmail'] ?? null);
  4201.         $employee->setEmmContact($userData['getEmmContact'] ?? null);
  4202.         $employee->setCurrentAddress($userData['getCurrAddr'] ?? null);
  4203.         $employee->setPermanentAddress($userData['getPermAddr'] ?? null);
  4204.         $employee->setCompanyId((int)$companyId);
  4205.         $employee->setDepartmentId($userData['getDept'] ?? null);
  4206.         $employee->setBranchId($userData['getBranch'] ?? null);
  4207.         $employee->setPositionId($userData['getDesg'] ?? null);
  4208.         $employee->setSupervisorId($userData['getSupervisor'] ?? null);
  4209.         if (!empty($imagePathToSet)) {
  4210.             $employee->setImage($imagePathToSet);
  4211.         }
  4212.         $employee->setStatus("1");
  4213.         $employee->setLastModifiedDate(new \DateTime());
  4214.         $em->persist($employee);
  4215.         $em->flush();
  4216.         $employeeDetails $em->getRepository('ApplicationBundle\\Entity\\EmployeeDetails')
  4217.             ->findOneBy(['userId' => $user->getUserId()]);
  4218.         if (!$employeeDetails) {
  4219.             $employeeDetails = new \ApplicationBundle\Entity\EmployeeDetails();
  4220.             $employeeDetails->setUserId($user->getUserId());
  4221.         }
  4222.         $employeeDetails->setId($employee->getEmployeeId());
  4223.         $employeeDetails->setFirstname($userData['getFirstname'] ?? null);
  4224.         $employeeDetails->setLastname($userData['getLastname'] ?? null);
  4225.         $employeeDetails->setUsername($userData['getUsername'] ?? null);
  4226.         $employeeDetails->setEmail($userData['getEmail'] ?? null);
  4227.         $employeeDetails->setPassword($userData['getPassword'] ?? null);
  4228.         $employeeDetails->setNid($userData['getNid'] ?? null);
  4229.         $employeeDetails->setSex($userData['getSex'] ?? null);
  4230.         $employeeDetails->setFather($userData['getFather'] ?? null);
  4231.         $employeeDetails->setMother($userData['getMother'] ?? null);
  4232.         $employeeDetails->setSpouse($userData['getSpouse'] ?? null);
  4233.         $employeeDetails->setChild1($userData['getChild1'] ?? null);
  4234.         $employeeDetails->setChild2($userData['getChild2'] ?? null);
  4235.         $employeeDetails->setPhone($userData['getPhone'] ?? null);
  4236.         $employeeDetails->setOfficialPhone($userData['getOfficailPhone'] ?? null);
  4237.         $employeeDetails->setCurrAddr($userData['getCurrAddr'] ?? null);
  4238.         $employeeDetails->setPermAddr($userData['getPermAddr'] ?? null);
  4239.         $employeeDetails->setEmmContact($userData['getEmmContact'] ?? null);
  4240.         if (!empty($userData['getDob'])) {
  4241.             $employeeDetails->setDob(new \DateTime($userData['getDob']));
  4242.         }
  4243.         if (!empty($userData['getJoiningDate'])) {
  4244.             $employeeDetails->setJoiningDate(new \DateTime($userData['getJoiningDate']));
  4245.         }
  4246.         if (!empty($userData['getEmpValidTill'])) {
  4247.             $employeeDetails->setEmpValidTill(new \DateTime($userData['getEmpValidTill']));
  4248.         }
  4249.         if (!empty($userData['getTinValidTill'])) {
  4250.             $employeeDetails->setTinValidTill(new \DateTime($userData['getTinValidTill']));
  4251.         }
  4252.         if (!empty($userData['getMedInsValidTill'])) {
  4253.             $employeeDetails->setMedInsValidTill(new \DateTime($userData['getMedInsValidTill']));
  4254.         }
  4255.         $employeeDetails->setEmpType($userData['getEmpType'] ?? null);
  4256.         $employeeDetails->setEmpCode($userData['getEmpCode'] ?? null);
  4257.         $employeeDetails->setEmployeeLevel($userData['getEmployeeLevel'] ?? null);
  4258.         $employeeDetails->setTin($userData['getTin'] ?? null);
  4259.         $employeeDetails->setSkill($userData['getSkill'] ?? null);
  4260.         $employeeDetails->setEducationData($userData['getEducationData'] ?? null);
  4261.         $employeeDetails->setWorkExperienceData($userData['getWorkExperienceData'] ?? null);
  4262.         $employeeDetails->setApplicationText($userData['getApplicationText'] ?? null);
  4263.         $employeeDetails->setCurrentEmployment($userData['getCurrentEmployment'] ?? null);
  4264.         $employeeDetails->setEmergencyContactNumber($userData['getEmergencyContactNumber'] ?? null);
  4265.         $employeeDetails->setPostalCode($userData['getPostalCode'] ?? null);
  4266.         $employeeDetails->setCountry($userData['getCountry'] ?? null);
  4267.         if (!empty($imagePathToSet)) {
  4268.             $employeeDetails->setImage($imagePathToSet);
  4269.         }
  4270.         $em->persist($employeeDetails);
  4271.         $em->flush();
  4272.         $uploadedFile $request->files->get('file_' $globalId);
  4273.         return new JsonResponse([
  4274.             'success' => true,
  4275.             'globalId' => $globalId,
  4276.             'appIds' => $appIds,
  4277.             'userIds' => $userIds,
  4278.             'hasFile' => $uploadedFile !== null,
  4279.         ]);
  4280.     }
  4281.     public function getIndustryListForAppAction()
  4282.     {
  4283.         $industryList GeneralConstant::$industryList;
  4284.         return new JsonResponse($industryList);
  4285.     }
  4286.     public function getFeatureListAction()
  4287.     {
  4288.         $featureList GeneralConstant::$featureList;
  4289.         return new JsonResponse($featureList);
  4290.     }
  4291.     public function chooseYourPlanAction()
  4292.     {
  4293.         $plan GeneralConstant::$chooseYourPlan;
  4294.         return new JsonResponse($plan);
  4295.     }
  4296. //    public function getLogindataFromTokenAction(Request $request)
  4297. //    {
  4298. //        $em_goc = $this->getDoctrine()->getManager('company_group');
  4299. //        $sessionData = MiscActions::GetSessionDataFromToken($em_goc, $request->query->get('hbeeSessionToken'))['sessionData'];
  4300. //        return new JsonResponse($sessionData);
  4301. //        $sessionDataa = MiscActions::GetSessionDataFromToken($em_goc, $request->query->get('hbeeSessionToken'))['sessionData'];
  4302. //        return new JsonResponse($sessionDataa);
  4303. //    }
  4304.     public function getLogindataFromTokenAction(Request $request)
  4305.     {
  4306.         $em_goc $this->getDoctrine()->getManager('company_group');
  4307.         $token $request->query->get('hbeeSessionToken');
  4308.         if (!$token) {
  4309.             return new JsonResponse(['error' => 'Missing session token'], 400);
  4310.         }
  4311.         $sessionResult MiscActions::GetSessionDataFromToken($em_goc$token);
  4312.         if (!$sessionResult || !isset($sessionResult['sessionData'])) {
  4313.             return new JsonResponse(['error' => 'Invalid session token or session not found'], 401);
  4314.         }
  4315.         $sessionData $sessionResult['sessionData'];
  4316.         return new JsonResponse($sessionData);
  4317.     }
  4318.    public function packageDetailsAction()
  4319. {
  4320.     $packageDetails GeneralConstant::$packageDetails;
  4321.     return new JsonResponse([
  4322.         'success' => true,
  4323.         'message' => 'Data fetched successfully.',
  4324.         'data' => $packageDetails
  4325.     ]);
  4326. }
  4327.     public function employeeRangeAction()
  4328.     {
  4329.         $employeeRangeForApp GeneralConstant::$employeeRange;
  4330.         return new JsonResponse($employeeRangeForApp);
  4331.     }
  4332.     public function paymentMethodAction()
  4333.     {
  4334.         $paymentMethod GeneralConstant::$paymentMethod;
  4335.         return new JsonResponse($paymentMethod);
  4336.     }
  4337.     public function companyTypeAction()
  4338.     {
  4339.         $companyType GeneralConstant::$companyType;
  4340.         return new JsonResponse(
  4341.             [
  4342.                 'status' => 'success',
  4343.                 'message' => 'Company types retrieved successfully.',
  4344.                 'data' => $companyType,
  4345.             ]
  4346.          );
  4347.     }
  4348.     public function getCountryListAction()
  4349.     {
  4350.         $em_goc $this->getDoctrine()->getManager('company_group');
  4351.         $countryList $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityCountries')
  4352.             ->createQueryBuilder('C')
  4353.             ->select('C.CountryId''C.code''C.nameEn')
  4354.             ->getQuery()
  4355.             ->getArrayResult();
  4356.         // $formattedList = array_map(function ($country) {
  4357.         //     return [
  4358.         //         'countryId' => $country['countryId'],
  4359.         //         'countryName' => $country['nameEn'],
  4360.         //         'countryCode' => $country['code'],
  4361.         //     ];
  4362.         // }, $countryList);
  4363.         return new JsonResponse([
  4364.             'status' => true,
  4365.             'message' => 'Country list fetched successfully',
  4366.             'data' => $countryList,
  4367.         ]);
  4368.     }
  4369. public function spotLightSearchAction(Request $request,$queryStr ''){
  4370.     
  4371.     $em $this->getDoctrine()->getManager();
  4372.     $data = [];
  4373.     $data_by_id = [];
  4374.     $session $request->getSession();
  4375.     $entityDetails GeneralConstant::$Entity_list_details
  4376.     if ($queryStr == '_DEFAULT_')
  4377.         $queryStr '';
  4378.     if ($request->request->has('query') && $queryStr == '')
  4379.         $queryStr $request->request->get('query');
  4380.     if ($queryStr == '_DEFAULT_')
  4381.         $queryStr '';
  4382.     $queryStr str_ireplace('_FSLASH_''/'$queryStr);
  4383.     //module
  4384.     $filterQryForCriteria "select * from sys_module where 1=1 and module_name  like '%" $queryStr "%'  limit 10";
  4385.     $get_kids_sql $filterQryForCriteria;
  4386.     $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  4387.     
  4388.     $get_kids $stmt;
  4389.     $productId 0;
  4390.     $absoluteUrl $this->generateUrl('dashboard', [], UrlGenerator::ABSOLUTE_URL);
  4391.     if (!empty($get_kids)) {
  4392.         foreach ($get_kids as $product) {
  4393.             $router $this->container->get('router');
  4394.             $routeName $product['module_route'];
  4395.             if ($router->getRouteCollection()->get($routeName)) {
  4396.                 $pa            = array();
  4397.                 $pa['id']      = $product['module_id'];
  4398.                 $pa['name']    = $product['module_name'];
  4399.                 $pa['type']    = 'module';
  4400. //            $pa['url']     = $absoluteUrl . '/' . $product['module_route'];
  4401.                 $pa['url']     = $this->generateUrl($product['module_route'], [], UrlGenerator::ABSOLUTE_URL);
  4402.                 $data[] = $pa;
  4403.             } else {
  4404.                 // treat as non-route
  4405. //                $pa['url'] = $routeName; // or custom fallback
  4406.             }
  4407.         }
  4408.     }
  4409.     // supplier
  4410.     $get_kids $em->getConnection()->fetchAllAssociative(
  4411.         "select * from acc_suppliers where supplier_name like '%" $queryStr "%' limit 10"
  4412.     );
  4413.     $url $this->generateUrl('supplier_profile');
  4414.     if (!empty($get_kids)) {
  4415.         foreach ($get_kids as $product) {
  4416.             $pa           = array();
  4417.             $pa['id']     = $product['supplier_id'];
  4418.             $pa['name']   = $product['supplier_name'];
  4419.             $pa['type']   = 'supplier';
  4420.             $pa['url']    = rtrim($absoluteUrl'/') . '/' ltrim($url'/') . '?ex_s_id=' $product['supplier_id'];
  4421.             $data[] = $pa;
  4422.         }
  4423.     }
  4424.     // client
  4425.     $get_kids $em->getConnection()->fetchAllAssociative(
  4426.         "select * from acc_clients where client_name like '%" $queryStr "%' limit 10"
  4427.     );
  4428.     $url $this->generateUrl('client_profile');
  4429.     if (!empty($get_kids)) {
  4430.         foreach ($get_kids as $product) {
  4431.             $pa           = array();
  4432.             $pa['id']     = $product['client_id'];
  4433.             $pa['name']   = $product['client_name'];
  4434.             $pa['type']   = 'client';
  4435.             $pa['url']    = rtrim($absoluteUrl'/') . '/' trim($url'/') . '/' $product['client_id'];
  4436.             $data[] = $pa;
  4437.         }
  4438.     }
  4439.     // document (approval)
  4440.     $get_kids $em->getConnection()->fetchAllAssociative(
  4441.         "select * from approval where document_hash like '%" $queryStr "%' limit 10"
  4442.     );
  4443.     if (!empty($get_kids)) {
  4444.         foreach ($get_kids as $product) {
  4445.             try {
  4446.                 $viewUrl $this->generateUrl(
  4447.                     $entityDetails[$product['entity']]['entity_view_route_path_name']
  4448.                 );
  4449.                 $pa           = array();
  4450.                 $pa['id']     = $product['id'];
  4451.                 $pa['name']   = $product['document_hash'];
  4452.                 $pa['type']   = 'document';
  4453.                 $pa['url']    = rtrim($absoluteUrl'/') . '/' trim($viewUrl'/') . '/' $product['entity_id'];
  4454.                 $data[] = $pa;
  4455.             } catch (\Exception $e) { /* skip if route undefined */ }
  4456.         }
  4457.     }
  4458.     return new JsonResponse(array(
  4459.         'success' => true,
  4460.         'data'    => $data,
  4461.     ));
  4462. }
  4463.     public function getMlDataAction()
  4464.     {
  4465.         $data GeneralConstant::$dataFromMl;
  4466.         return new JsonResponse($data);
  4467.     }
  4468.     public function UploadDocumentsAction(Request $request)
  4469.     {
  4470.         $session $request->getSession();
  4471.         $em $this->getDoctrine()->getManager();
  4472.         return $this->render(
  4473.             'ApplicationBundle:pages/dashboard:upload_documents.html.twig',
  4474.             array(
  4475.                 'page_title' => 'Upload Documents',
  4476.             )
  4477.         );
  4478.     }
  4479. }