src/CompanyGroupBundle/Controller/SuperAdminDashboardController.php line 37

Open in your IDE?
  1. <?php
  2. namespace CompanyGroupBundle\Controller;
  3. use ApplicationBundle\Constants\ModuleConstant;
  4. use ApplicationBundle\Modules\System\MiscActions;
  5. use ApplicationBundle\Modules\Authentication\Constants\UserConstants;
  6. use Symfony\Bundle\FrameworkBundle\Controller\Controller;
  7. use Symfony\Component\HttpFoundation\Request;
  8. class SuperAdminDashboardController extends Controller
  9. {
  10.     public function indexAction(Request $request)
  11.     {
  12.         if (!$this->canAccessSuperAdminDashboard($request)) {
  13.             return $this->redirectToRoute('dashboard');
  14.         }
  15.         $service $this->get('app.admin_dashboard_service');
  16.         $metrics $service->getMetrics();
  17.         $companies $service->listCompanies(120, []);
  18.         $usageSummary $service->getUsageSummary(30);
  19.         $alerts $service->getAlerts();
  20.         $chartData $this->buildChartData($usageSummary);
  21.         return $this->render('@CompanyGroup/pages/super_admin_command_center.html.twig', [
  22.             'page_title' => 'Super Admin Command Center',
  23.             'metrics' => $metrics,
  24.             'companies' => $companies,
  25.             'usage_summary' => $usageSummary,
  26.             'alerts' => $alerts,
  27.             'chart_data' => $chartData,
  28.         ]);
  29.     }
  30.     public function companyListAction(Request $request)
  31.     {
  32.         $systemType $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
  33.         if ($systemType !== '_CENTRAL_') {
  34.             return $this->redirectToRoute('dashboard');
  35.         }
  36.         if (!$this->canAccessSuperAdminDashboard($request)) {
  37.             return $this->redirectToRoute('dashboard');
  38.         }
  39.         $page max(1, (int)$request->query->get('page'1));
  40.         $limit 25;
  41.         $offset = ($page 1) * $limit;
  42.         $filters = array(
  43.             'search' => trim((string)$request->query->get('q''')),
  44.             'status' => trim((string)$request->query->get('status''')),
  45.         );
  46.         $service $this->get('app.admin_dashboard_service');
  47.         $companies $service->listCompanies($limit$offset$filters);
  48.         $total $this->countCompaniesForAdminList($filters);
  49.         $totalPages max(1, (int)ceil($total $limit));
  50.         $summary $this->getCompanyListSummary();
  51.         return $this->render('@CompanyGroup/pages/admin/companies/list_companies.html.twig', array(
  52.             'page_title' => 'Companies',
  53.             'companies' => $companies,
  54.             'filters' => $filters,
  55.             'summary' => $summary,
  56.             'total' => $total,
  57.             'currentPage' => $page,
  58.             'totalPages' => $totalPages,
  59.         ));
  60.     }
  61.     public function companyViewAction(Request $request$appId)
  62.     {
  63.         $systemType $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
  64.         if ($systemType !== '_CENTRAL_') {
  65.             return $this->redirectToRoute('dashboard');
  66.         }
  67.         if (!$this->canAccessSuperAdminDashboard($request)) {
  68.             return $this->redirectToRoute('dashboard');
  69.         }
  70.         $service $this->get('app.admin_dashboard_service');
  71.         $company $service->getCompanyByAppId((int)$appId);
  72.         if (!$company) {
  73.             throw $this->createNotFoundException('Company appId #' . (int)$appId ' not found.');
  74.         }
  75.         $em $this->getDoctrine()->getManager('company_group');
  76.         $companyEntity $em->getRepository('CompanyGroupBundle\\Entity\\CompanyGroup')->findOneBy(array(
  77.             'appId' => (int)$appId,
  78.         ));
  79.         $enabledModuleIds $companyEntity $this->parseCompanyModuleIdList($companyEntity->getEnabledModuleIdList()) : array();
  80.         if (empty($enabledModuleIds)) {
  81.             $enabledModuleIds $this->getDefaultEnabledCompanyModuleIds();
  82.         }
  83.         return $this->render('@CompanyGroup/pages/admin/companies/view_company.html.twig', array(
  84.             'page_title' => 'Company Details',
  85.             'company' => $company,
  86.             'company_entity' => $companyEntity,
  87.             'enabled_count' => count($enabledModuleIds),
  88.             'module_count' => count(ModuleConstant::$moduleList),
  89.         ));
  90.     }
  91.     private function canAccessSuperAdminDashboard(Request $request)
  92.     {
  93.         $session $request->getSession();
  94.         $userId = (int) $session->get(UserConstants::USER_ID0);
  95.         if ($userId <= 0) {
  96.             return false;
  97.         }
  98.         $userType = (int) $session->get(UserConstants::USER_TYPE0);
  99.         $isBuddybeeAdmin = (int) $session->get(UserConstants::IS_BUDDYBEE_ADMIN0);
  100.         $allModuleAccess = (int) $session->get(UserConstants::ALL_MODULE_ACCESS_FLAG0);
  101.         $allowedTypes = [
  102.             UserConstants::USER_TYPE_SYSTEM,
  103.             UserConstants::USER_TYPE_MANAGEMENT_USER,
  104.             UserConstants::USER_TYPE_GENERAL,
  105.         ];
  106.         return $isBuddybeeAdmin === || $allModuleAccess === || in_array($userType$allowedTypestrue);
  107.     }
  108.     private function countCompaniesForAdminList(array $filters)
  109.     {
  110.         $conn $this->getDoctrine()->getManager('company_group')->getConnection();
  111.         $where = array();
  112.         $params = array();
  113.         if (!empty($filters['search'])) {
  114.             $where[] = '(name LIKE :search OR CAST(app_id AS CHAR) LIKE :search OR email LIKE :search)';
  115.             $params['search'] = '%' $filters['search'] . '%';
  116.         }
  117.         if (!empty($filters['status'])) {
  118.             $where[] = 'company_status = :companyStatus';
  119.             $params['companyStatus'] = $filters['status'];
  120.         }
  121.         $sql 'SELECT COUNT(*) FROM company_group';
  122.         if (!empty($where)) {
  123.             $sql .= ' WHERE ' implode(' AND '$where);
  124.         }
  125.         return (int)$conn->fetchOne($sql$params);
  126.     }
  127.     private function getCompanyListSummary()
  128.     {
  129.         $conn $this->getDoctrine()->getManager('company_group')->getConnection();
  130.         return array(
  131.             'all' => (int)$conn->fetchOne('SELECT COUNT(*) FROM company_group'),
  132.             'active' => (int)$conn->fetchOne("SELECT COUNT(*) FROM company_group WHERE company_status = 'active'"),
  133.             'trial' => (int)$conn->fetchOne("SELECT COUNT(*) FROM company_group WHERE company_status = 'trial'"),
  134.             'suspended' => (int)$conn->fetchOne("SELECT COUNT(*) FROM company_group WHERE company_status = 'suspended'"),
  135.             'expired' => (int)$conn->fetchOne("SELECT COUNT(*) FROM company_group WHERE company_status = 'expired'"),
  136.             'enabled' => (int)$conn->fetchOne('SELECT COUNT(*) FROM company_group WHERE active = 1'),
  137.             'disabled' => (int)$conn->fetchOne('SELECT COUNT(*) FROM company_group WHERE active = 0'),
  138.         );
  139.     }
  140.     public function companySettingsAction(Request $request$appId)
  141.     {
  142.         $systemType $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
  143.         if ($systemType !== '_CENTRAL_') {
  144.             return $this->redirectToRoute('dashboard');
  145.         }
  146.         if (!$this->canAccessSuperAdminDashboard($request)) {
  147.             return $this->redirectToRoute('dashboard');
  148.         }
  149.         $appId = (int)$appId;
  150.         $em $this->getDoctrine()->getManager('company_group');
  151.         $company $em->getRepository('CompanyGroupBundle\\Entity\\CompanyGroup')->findOneBy(array(
  152.             'appId' => $appId,
  153.         ));
  154.         if (!$company) {
  155.             throw $this->createNotFoundException('Company appId #' $appId ' not found.');
  156.         }
  157.         if ($request->isMethod('POST')) {
  158.             $company->setName($request->request->get('name'$company->getName()));
  159.             $company->setAddress($request->request->get('address'$company->getAddress()));
  160.             $company->setShippingAddress($request->request->get('shippingAddress'$company->getShippingAddress()));
  161.             $company->setBillingAddress($request->request->get('billingAddress'$company->getBillingAddress()));
  162.             $company->setMotto($request->request->get('motto'$company->getMotto()));
  163.             $company->setInvoiceFooter($request->request->get('invoiceFooter'$company->getInvoiceFooter()));
  164.             $company->setGeneralFooter($request->request->get('generalFooter'$company->getGeneralFooter()));
  165.             $company->setCompanyDescription($request->request->get('companyDescription'$company->getCompanyDescription()));
  166.             $company->setCompanyStatus($request->request->get('companyStatus'$company->getCompanyStatus()));
  167.             $company->setPackageType($request->request->get('packageType'$company->getPackageType()));
  168.             $company->setActive((int)$request->request->get('active'0));
  169.             $company->setReadOnlyMode((int)$request->request->get('readOnlyMode'0));
  170.             $company->setAdminUserAllowed((int)$request->request->get('adminUserAllowed'0));
  171.             $company->setUserAllowed((int)$request->request->get('userAllowed'0));
  172.             $company->setSubscriptionMonth((int)$request->request->get('subscriptionMonth'0));
  173.             $company->setCurrentSubscriptionPackageId((int)$request->request->get('currentSubscriptionPackageId'0));
  174.             $company->setBillingAmount((int)$request->request->get('billingAmount'0));
  175.             $usageValidUptoDate $this->dateFromForm($request->request->get('usageValidUptoDate'''));
  176.             $company->setUsageValidUptoDate($usageValidUptoDate);
  177.             $company->setUsageValidUptoDateTs($usageValidUptoDate $usageValidUptoDate->format('U') : 0);
  178.             $subscriptionExpiry $this->dateFromForm($request->request->get('subscriptionExpiry'''));
  179.             $company->setSubscriptionExpiry($subscriptionExpiry);
  180.             $moduleIds $request->request->get('moduleIds', array());
  181.             if (!is_array($moduleIds)) {
  182.                 $moduleIds = array();
  183.             }
  184.             $validModuleIds = array();
  185.             foreach (ModuleConstant::$moduleList as $module) {
  186.                 $validModuleIds[(int)$module['id']] = true;
  187.             }
  188.             $enabledModuleIds = array();
  189.             foreach ($moduleIds as $moduleId) {
  190.                 $moduleId = (int)$moduleId;
  191.                 if ($moduleId && isset($validModuleIds[$moduleId])) {
  192.                     $enabledModuleIds[$moduleId] = $moduleId;
  193.                 }
  194.             }
  195.             ksort($enabledModuleIds);
  196.             $company->setEnabledModuleIdList(implode(','array_values($enabledModuleIds)));
  197.             $em->flush();
  198.             $companySyncResult $this->syncCompanySettingsToErp($em$company);
  199.             $syncResult $this->forceCompanyRouteSync($company);
  200.             if ($companySyncResult['success'] && $syncResult['success']) {
  201.                 $this->addFlash('success''Company settings were saved and synced to ERP.');
  202.             } else {
  203.                 $this->addFlash('warning''Company settings were saved, but ERP sync needs attention. Company sync: ' $companySyncResult['message'] . ' Route sync: ' $syncResult['message']);
  204.             }
  205.             return $this->redirectToRoute('admin_company_settings', array(
  206.                 'appId' => $appId,
  207.             ));
  208.         }
  209.         $enabledModuleIds $this->parseCompanyModuleIdList($company->getEnabledModuleIdList());
  210.         if (empty($enabledModuleIds)) {
  211.             $enabledModuleIds $this->getDefaultEnabledCompanyModuleIds();
  212.         }
  213.         $enabledLookup array_fill_keys($enabledModuleIdstrue);
  214.         $groupedModules $this->buildGroupedModuleList();
  215.         return $this->render('@CompanyGroup/pages/admin/companies/module_settings.html.twig', array(
  216.             'page_title' => 'Company Settings',
  217.             'company' => $company,
  218.             'grouped_modules' => $groupedModules,
  219.             'enabled_lookup' => $enabledLookup,
  220.             'enabled_count' => count($enabledLookup),
  221.             'module_count' => count(ModuleConstant::$moduleList),
  222.         ));
  223.     }
  224.     public function companyModuleSettingsAction(Request $request$appId)
  225.     {
  226.         return $this->companySettingsAction($request$appId);
  227.     }
  228.     private function dateFromForm($value)
  229.     {
  230.         $value trim((string)$value);
  231.         if ($value === '') {
  232.             return null;
  233.         }
  234.         try {
  235.             return new \DateTime($value);
  236.         } catch (\Exception $e) {
  237.             return null;
  238.         }
  239.     }
  240.     private function syncCompanySettingsToErp($em$company)
  241.     {
  242.         $response MiscActions::updateCompanyToErpServer($em, (int)$company->getAppId(), $this->container->getParameter('kernel.root_dir'));
  243.         if (isset($response['success']) && $response['success'] === true) {
  244.             return array(
  245.                 'success' => true,
  246.                 'message' => isset($response['message']) ? $response['message'] : 'Synced.',
  247.             );
  248.         }
  249.         return array(
  250.             'success' => false,
  251.             'message' => isset($response['message']) ? $response['message'] : 'Company metadata sync was not confirmed.',
  252.         );
  253.     }
  254.     private function parseCompanyModuleIdList($moduleIdList)
  255.     {
  256.         $moduleIdList trim((string)$moduleIdList);
  257.         if ($moduleIdList === '') {
  258.             return array();
  259.         }
  260.         $decoded json_decode($moduleIdListtrue);
  261.         $rawList is_array($decoded) ? $decoded explode(','$moduleIdList);
  262.         $cleanList = array();
  263.         foreach ($rawList as $moduleId) {
  264.             $moduleId = (int)$moduleId;
  265.             if ($moduleId 0) {
  266.                 $cleanList[$moduleId] = $moduleId;
  267.             }
  268.         }
  269.         return array_values($cleanList);
  270.     }
  271.     private function getDefaultEnabledCompanyModuleIds()
  272.     {
  273.         $moduleIds = array();
  274.         foreach (ModuleConstant::$moduleList as $module) {
  275.             if ((int)(isset($module['defaultEnabledForCompany']) ? $module['defaultEnabledForCompany'] : 0) === 1) {
  276.                 $moduleIds[] = (int)$module['id'];
  277.             }
  278.         }
  279.         return $moduleIds;
  280.     }
  281.     private function buildGroupedModuleList()
  282.     {
  283.         $groups = array();
  284.         foreach (ModuleConstant::$parentModuleList as $parentModule) {
  285.             $groups[(int)$parentModule['id']] = array(
  286.                 'parent' => $parentModule,
  287.                 'modules' => array(),
  288.             );
  289.         }
  290.         foreach (ModuleConstant::$moduleList as $module) {
  291.             $parentId = (int)$module['parentId'];
  292.             if (!isset($groups[$parentId])) {
  293.                 $groups[$parentId] = array(
  294.                     'parent' => array(
  295.                         'id' => $parentId,
  296.                         'name' => 'Other',
  297.                     ),
  298.                     'modules' => array(),
  299.                 );
  300.             }
  301.             $groups[$parentId]['modules'][] = $module;
  302.         }
  303.         foreach ($groups as $parentId => $group) {
  304.             if (empty($group['modules'])) {
  305.                 unset($groups[$parentId]);
  306.             }
  307.         }
  308.         return $groups;
  309.     }
  310.     private function forceCompanyRouteSync($company)
  311.     {
  312.         $serverAddress rtrim((string)$company->getCompanyGroupServerAddress(), '/');
  313.         if ($serverAddress === '') {
  314.             return array(
  315.                 'success' => false,
  316.                 'message' => 'ERP server address is not configured.',
  317.             );
  318.         }
  319.         $curl curl_init();
  320.         curl_setopt_array($curl, array(
  321.             CURLOPT_RETURNTRANSFER => 1,
  322.             CURLOPT_POST => 1,
  323.             CURLOPT_URL => $serverAddress '/update_route_company_wise',
  324.             CURLOPT_CONNECTTIMEOUT => 10,
  325.             CURLOPT_SSL_VERIFYPEER => false,
  326.             CURLOPT_SSL_VERIFYHOST => false,
  327.             CURLOPT_POSTFIELDS => http_build_query(array(
  328.                 'appId' => (int)$company->getAppId(),
  329.             )),
  330.         ));
  331.         $response curl_exec($curl);
  332.         $error curl_error($curl);
  333.         curl_close($curl);
  334.         if ($error) {
  335.             return array(
  336.                 'success' => false,
  337.                 'message' => $error,
  338.             );
  339.         }
  340.         return array(
  341.             'success' => true,
  342.             'message' => (string)$response,
  343.         );
  344.     }
  345.     private function buildChartData(array $usageSummary)
  346.     {
  347.         $activityTrend $usageSummary['activity_trend'] ?? [];
  348.         $usageTrend $usageSummary['usage_trend'] ?? [];
  349.         $revenueTrend $usageSummary['revenue_trend'] ?? [];
  350.         $activityByDay = [];
  351.         foreach ($activityTrend as $row) {
  352.             $day = (string) ($row['day'] ?? '');
  353.             if ($day === '') {
  354.                 continue;
  355.             }
  356.             if (!isset($activityByDay[$day])) {
  357.                 $activityByDay[$day] = 0;
  358.             }
  359.             $activityByDay[$day] += (int) ($row['total'] ?? 0);
  360.         }
  361.         $usageByDay = [];
  362.         foreach ($usageTrend as $row) {
  363.             $day = (string) ($row['day'] ?? '');
  364.             if ($day === '') {
  365.                 continue;
  366.             }
  367.             if (!isset($usageByDay[$day])) {
  368.                 $usageByDay[$day] = 0;
  369.             }
  370.             $usageByDay[$day] += (int) ($row['total'] ?? 0);
  371.         }
  372.         $revenueByDay = [];
  373.         foreach ($revenueTrend as $row) {
  374.             $day = (string) ($row['day'] ?? '');
  375.             if ($day === '') {
  376.                 continue;
  377.             }
  378.             $revenueByDay[$day] = (float) ($row['total'] ?? 0);
  379.         }
  380.         $labels array_values(array_unique(array_merge(
  381.             array_keys($activityByDay),
  382.             array_keys($usageByDay),
  383.             array_keys($revenueByDay)
  384.         )));
  385.         sort($labels);
  386.         $activitySeries = [];
  387.         $usageSeries = [];
  388.         $revenueSeries = [];
  389.         foreach ($labels as $label) {
  390.             $activitySeries[] = (int) ($activityByDay[$label] ?? 0);
  391.             $usageSeries[] = (int) ($usageByDay[$label] ?? 0);
  392.             $revenueSeries[] = (float) ($revenueByDay[$label] ?? 0);
  393.         }
  394.         return [
  395.             'labels' => $labels,
  396.             'activity_series' => $activitySeries,
  397.             'usage_series' => $usageSeries,
  398.             'revenue_series' => $revenueSeries,
  399.         ];
  400.     }
  401. }