diff --git a/app/Config/Acl.php b/app/Config/Acl.php index 86760bb0..2960595f 100644 --- a/app/Config/Acl.php +++ b/app/Config/Acl.php @@ -30,6 +30,10 @@ class Acl '#^/util/download_log#' => ['roles' => [ADMIN_ROLE_ID]], '#^/metaDashboardDemo#' => ['roles' => [ADMIN_ROLE_ID, HEAD_ROLE_ID]], '#^/metaTpaDashboardDemo#' => ['roles' => [ADMIN_ROLE_ID, HEAD_ROLE_ID]], + '#^/sales/dashboard#' => ['roles' => [ADMIN_ROLE_ID, HEAD_ROLE_ID, STAFF_ROLE_ID]], + '#^/sales#' => ['roles' => [ADMIN_ROLE_ID, HEAD_ROLE_ID, STAFF_ROLE_ID]], + + // ===================== PUBLIC DOWNLOADS / FORMS ===================== '#^/download-#' => ['public' => true], diff --git a/app/Config/Routes.php b/app/Config/Routes.php index d7353cb7..d9a05733 100755 --- a/app/Config/Routes.php +++ b/app/Config/Routes.php @@ -11,10 +11,11 @@ $routes->options('(:any)', function() { }); $routes->group('sheet', function ($routes) { - $routes->get('(:any)', 'GoogleSheetController::editor/$1'); - $routes->get('(:any)/fetch', 'GoogleSheetController::fetch/$1'); - $routes->post('(:any)/save', 'GoogleSheetController::save/$1'); - $routes->get('(:any)/download', 'GoogleSheetController::download/$1'); + $routes->post('create', 'GoogleSheetController::create'); + $routes->get('(:segment)/fetch', 'GoogleSheetController::fetch/$1'); + $routes->post('(:segment)/save', 'GoogleSheetController::save/$1'); + $routes->get('(:segment)/download', 'GoogleSheetController::download/$1'); + $routes->get('(:segment)', 'GoogleSheetController::editor/$1'); }); @@ -912,7 +913,7 @@ $routes->group('sales', function($routes) { $routes->get('/', 'SalesController::index'); - $routes->get('activities', 'SalesController::activities'); + $routes->get('loadactivities', 'SalesController::loadactivities'); $routes->get('page/(:segment)', 'SalesController::noPage/$1'); @@ -996,6 +997,7 @@ $routes->group('sales', function($routes) { //Dashboard + $routes->get('dashboard', 'SalesController::dashboard'); $routes->get('branchLevelDashboard', 'SalesController::branchLevelDashboard'); $routes->get('salesManagerLevelDashboard', 'SalesController::salesManagerLevelDashboard'); }); diff --git a/app/Controllers/GoogleSheetController.php b/app/Controllers/GoogleSheetController.php index e51f81ab..cfdd98fc 100644 --- a/app/Controllers/GoogleSheetController.php +++ b/app/Controllers/GoogleSheetController.php @@ -6,6 +6,35 @@ use CodeIgniter\Controller; class GoogleSheetController extends Controller { protected GoogleSheetLib $sheetLib; + public $config = [ + + 'permissions' => [ + 'editors' => [ + 'vitvelz@gmail.com', 'velz1990@gmail.com','venkateshraman786@gmail.com' + // 'group:rfq-editors@company.com' + ], + 'viewers' => [], + ], + + 'protections' => [ + [ + 'range' => 'RFQ Page!B12:C12', + 'users' => [ //allowed users to edit this cell range + 'velz1990@gmail.com','vitvelz@gmail.com','firebase-adminsdk-mcdfe@nhance-ee8d1.iam.gserviceaccount.com' + ], + 'groups' => [] + ], + [ + 'range' => 'Claims Page!A1', + 'users' => [ + 'velz1990@gmail.com','venkateshraman786@gmail.com','firebase-adminsdk-mcdfe@nhance-ee8d1.iam.gserviceaccount.com' + ], + 'groups' => [] + ] + ], + + 'parentFolderId' => '19uySI-PSFQfFpZvMSnBtirXbwfCTXFBL', // RFQ folder +]; public function __construct() { @@ -23,10 +52,16 @@ class GoogleSheetController extends Controller /* ---------- FETCH ---------- */ public function fetch(string $sheetId) { - // $data = $this->sheetLib->read($sheetId); + $data = $this->sheetLib->read($sheetId); // print_rr($data);die; - // return $this->response->setJSON($data); - echo 'Hi'; + return $this->response->setJSON($data); + // echo 'Hi'; + } + + public function sample(string $sheetId) + { + echo $sheetId; + } /* ---------- SAVE ---------- */ @@ -63,4 +98,39 @@ class GoogleSheetController extends Controller ) ->setBody($content); } + + public function create() + { + try { + $config = config('RfqConfig'); + // #$lib = new RfqGoogleSheetLib(); + + // $templateId = $this->request->getPost('templateId'); + // if (!$templateId) { + // throw new \Exception('Template ID missing'); + // } + + // $newSheetId = $this->sheetLib->copyTemplate( + // $templateId, + // 'RFQ_' . date('Ymd_His'), + // $this->config['parentFolderId'] + // ); + $newSheetId = '1GXNDNXoWriClb5HCqPYd2GAY1T8aie_Hos0yAOoTaC0'; + // $this->sheetLib->applyPermissions($newSheetId, $this->config['permissions']); + $this->sheetLib->applyProtections($newSheetId, $this->config['protections']); + + return $this->response->setJSON([ + 'status' => 'success', + 'url' => $this->sheetLib->sheetUrl($newSheetId) + ]); + + } catch (\Throwable $e) { + return $this->response + ->setStatusCode(500) + ->setJSON([ + 'status' => 'error', + 'message' => $e->getMessage() + ]); + } + } } diff --git a/app/Controllers/SalesController.php b/app/Controllers/SalesController.php index 459b919b..3de595f8 100644 --- a/app/Controllers/SalesController.php +++ b/app/Controllers/SalesController.php @@ -35,12 +35,11 @@ class SalesController extends BaseController $data = $this->getSalesStaffData(); $data['tab_name'] = 'Leads'; - $data['page_name'] = 'Leads'; - + $data['page_name'] = 'Leads'; return $this->loadLayout('sales/tracker_view', $data); } - public function activities(){ + public function loadactivities(){ $data = $this->getSalesStaffData(); $data['tab_name'] = 'Activities'; @@ -49,6 +48,7 @@ class SalesController extends BaseController $data['leads'] = $this->leadModel->select('lead_id, company_name') ->orderBy('lead_id', 'DESC') ->findAll(); + return $this->loadLayout('sales/activity_view', $data); } @@ -59,42 +59,36 @@ class SalesController extends BaseController private function getSalesStaffData(): array { $db = \Config\Database::connect(); - $logged_user_id = get_session_userid(); + $logged_user_id = get_session_userid(); + $role = get_role_id(); + $team_id = user_team(); $data = [ 'users' => [], 'sales_manager_ids' => [] ]; - // Get the Branch ID, Role, Team, and Name of the logged-in user - $row = $db->table('user_profiles up') - ->select('up.id, up.first_name, up.last_name, up.nhance_branch_id, up.role, ut.team_id') - ->join('user_teams ut', 'ut.user_id = up.id', 'left') - ->where('up.is_active', 1) - ->where('up.id', $logged_user_id) - ->get() - ->getRow(); - + $row = $db->table('user_profiles')->select('*') + ->where('is_active', 1)->where('id', $logged_user_id) + ->get()->getRow(); + $nhance_branch_id = $row ? $row->nhance_branch_id : null; - $role = $row ? $row->role : null; - $team_id = $row ? $row->team_id : null; - + // Is the logged-in user a Sales Manager? (Role 4, Team 5) - if ($role == 4 && $team_id == 5) { - + if ($role == 4 && in_array(5, $team_id)) { $data['sales_manager_ids'] = [$logged_user_id]; $data['users'] = [ [ 'id' => $row->id, - 'sales_manager' => trim($row->first_name . ' ' . $row->last_name), + 'first_name' => $row->first_name, 'nhance_branch_id' => $nhance_branch_id ] ]; } // Otherwise fetch ALL sales managers in this branch - elseif ($nhance_branch_id) { + elseif (in_array($role,[1,2,3,4,5])) { $data['users'] = $db->table('user_profiles up') ->select('up.id, up.first_name, up.last_name, up.nhance_branch_id') @@ -779,11 +773,59 @@ class SalesController extends BaseController // ==================== Dashboard ==================== + public function dashboard(){ - public function branchLevelDashboard() + $logged_user_id = get_session_userid(); + $role = get_role_id(); + $team_id = user_team(); + $payload = $this->request->getGet(); + + $db = \Config\Database::connect(); + + $row = $db->table('user_profiles') + ->select('*') + ->where('is_active', 1) + ->where('id', $logged_user_id) + ->get() + ->getRowArray(); + + $nhance_branch_id = $row ? $row['nhance_branch_id'] : null; + + // dd($logged_user_id, $nhance_branch_id, $role, $team_id ); + + if (in_array($role,[5])) { + + $sales_manager_ids = array_column( + $db->table('user_profiles up') + ->select('up.id') + ->join('user_teams ut', 'ut.user_id = up.id') + ->where([ + 'up.is_active' => 1, + 'ut.is_active' => 1, + 'up.role' => 4, + 'ut.team_id' => 5, + 'up.nhance_branch_id' => $nhance_branch_id + ]) + ->get() + ->getResultArray(), + 'id' + ); + $this->branchLevelDashboard($nhance_branch_id,$sales_manager_ids); + + } + elseif ($role == 4 && in_array(5, $team_id)) { + $sales_manager_ids = [$logged_user_id]; + $this->salesManagerLevelDashboard($logged_user_id,$sales_manager_ids, $payload); + } + + } + + public function branchLevelDashboard($branchId,$sales_manager_ids) { + $data['tab_name'] = 'Dashboard'; + $data['page_name'] = 'Dashboard'; // Hardcoded branch ID as requested - $branchId = 1; + // $branchId = 1; try { // 1. Lead Statistics @@ -798,11 +840,24 @@ class SalesController extends BaseController // 3. Team Performance (Aggregating activity counts per user) $db = \Config\Database::connect(); + // Final safe check + if (empty($sales_manager_ids)) { + // No valid IDs — skip queries or return empty + $teamPerformance = []; + $recentActivities = []; + $leadsOverview = []; + } else { + + if (empty($sales_manager_ids) || !is_array($sales_manager_ids)) { + $sales_manager_ids = array_filter((array) $sales_manager_ids); // removes null, "", 0 + } + $teamPerformance = $db->table('user_profiles as u') ->select('u.first_name, u.last_name, u.profile as role, (SELECT COUNT(*) FROM sales_activities WHERE assigned_to = u.id) as total_acts, (SELECT COUNT(*) FROM sales_activities WHERE assigned_to = u.id AND status = "completed") as done_acts') ->where('u.nhance_branch_id', $branchId) + ->whereIn('u.id', $sales_manager_ids) ->where('u.is_active', 1) ->get()->getResultArray(); @@ -812,11 +867,48 @@ class SalesController extends BaseController ->orderBy('sales_activities.scheduled_date', 'DESC') ->limit(6) ->findAll(); + + $sales_manager_ids = array_values(array_map('intval', $sales_manager_ids)); + $recentActivities = $db->table('sales_activities sa') + ->select('sa.activity_id,sa.lead_id,sa.activity_type,sa.scheduled_date,sa.status,sa.assigned_to,sal.company_name,up.first_name AS assigned_to_name') + ->join('(SELECT lead_id, MAX(company_name) AS company_name FROM sales_actual_leads GROUP BY lead_id) sal','sal.lead_id = sa.lead_id','left') + ->join('user_profiles up', 'up.id = sa.assigned_to', 'left') + ->orderBy('sa.scheduled_date', 'DESC') + ->limit(6) + ->whereIn('sa.assigned_to', $sales_manager_ids) + ->get()->getResultArray(); + + // 5. All Leads Overview + $leadsOverview = $db->table('sales_actual_leads sal') + ->select('sal.lead_id,sal.company_name,sal.status,up.first_name AS assigned_to, + COUNT(DISTINCT sa.activity_id) AS activities, + COUNT(DISTINCT l.id) AS opportunities + ') + ->join('user_profiles up', 'up.id = sal.assigned_to', 'left') + ->join('sales_activities sa', 'sa.lead_id = sal.lead_id', 'left') + ->join('leads l', 'l.actual_lead_id = sal.lead_id', 'left') + ->groupBy('sal.lead_id, sal.company_name, sal.status, up.first_name') + ->having('COUNT(DISTINCT sa.activity_id) + COUNT(DISTINCT l.id) >', 0) // ← this line + ->orderBy('sal.created_at', 'DESC') + ->whereIn('sal.assigned_to', $sales_manager_ids) + ->get() + ->getResultArray(); + } + + // 6. activityBreakdown + $total = $db->table('sales_activities')->countAll(); + + $activityBreakdown = $db->table('sales_activities') + ->select("activity_type, COUNT(*) AS total, ROUND(COUNT(*) * 100.0 / {$total}, 0) AS percentage", false) + ->groupBy('activity_type') + ->orderBy('total', 'DESC') + ->get() + ->getResultArray(); + + $teamPerformance = array_filter($teamPerformance, function($row) { + return ($row['total_acts'] + $row['done_acts']) > 0; + }); - // 5. All Leads Overview - $leadsOverview = $this->leadModel->select('sales_actual_leads.*, user_profiles.first_name, user_profiles.last_name') - ->join('user_profiles', 'user_profiles.id = sales_actual_leads.assigned_to', 'left') - ->findAll(); $data = [ 'total_leads' => $stats['total'], @@ -825,7 +917,10 @@ class SalesController extends BaseController 'pipeline_value' => '15.0L', // Hardcoded placeholder from PDF [cite: 14] 'team' => $teamPerformance, 'recent_acts' => $recentActivities, - 'leads_overview' => $leadsOverview + 'leads_overview' => $leadsOverview, + 'activity_breakdown'=> $activityBreakdown, + 'tab_name' => "Sales Dashboard", + 'page_name' => "Sales Dashboard" ]; // dd($data); @@ -839,16 +934,15 @@ class SalesController extends BaseController } } - - public function salesManagerLevelDashboard() + public function salesManagerLevelDashboard($userId,$sales_manager_ids, $payload = []) { - $userId = get_session_userid(); + // $userId = get_session_userid(); // $userId = 1; $db = \Config\Database::connect(); try { - $payload = $this->request->getGet(); + // $payload = $this->request->getGet(); $current_fin_year = $payload['fy'] ?? getCurrentFinancialYear(); @@ -858,8 +952,12 @@ class SalesController extends BaseController ->orderBy('fy_year', 'desc') ->get() ->getResultArray(); + $fin_years = array_column($fin_years, 'fy_year'); - $fin_years[] = '2024-2025'; + + if(empty($fin_years)){ + $fin_years[] = $current_fin_year; + } $target = $db->table('sales_target') ->where('user_id', $userId) @@ -907,7 +1005,9 @@ class SalesController extends BaseController 'recent_leads' => $recentLeads, 'fin_years' => $fin_years, 'display_fin_years' => format_financial_year($current_fin_year), - 'user_name' => get_session_userdata()->first_namee ?? '' + 'user_name' => get_session_userdata()->first_namee ?? '', + 'tab_name' => "Sales Dashboard", + 'page_name' => "Sales Dashboard" ]; // dd($data); diff --git a/app/Controllers/TestingController.php b/app/Controllers/TestingController.php index aaf62878..daae4293 100644 --- a/app/Controllers/TestingController.php +++ b/app/Controllers/TestingController.php @@ -1002,7 +1002,7 @@ class TestingController extends BaseController // 'dashboard' => 1 'dashboard' => $database_id ], - 'exp' => time() + (10 * 60) // 10 minutes + 'exp' => time() + (10 * 60), // 10 minutes ]; if(!empty($policy_id)){ diff --git a/app/Libraries/GoogleSheetLib.php b/app/Libraries/GoogleSheetLib.php index 5bdb9464..a04ab1e9 100644 --- a/app/Libraries/GoogleSheetLib.php +++ b/app/Libraries/GoogleSheetLib.php @@ -4,6 +4,7 @@ use Google_Client; use Google_Service_Sheets; use Google_Service_Drive; use Google_Service_Sheets_ValueRange; +use Google_Service_Sheets_BatchUpdateSpreadsheetRequest; class GoogleSheetLib { @@ -11,13 +12,14 @@ class GoogleSheetLib protected Google_Service_Sheets $sheets; protected Google_Service_Drive $drive; + public function __construct() { $this->client = new Google_Client(); // Service account JSON $this->client->setAuthConfig( - ROOTPATH . 'gdrive-demo-394007-5b1d856b0c5b.json' + ROOTPATH . 'nhance-ee8d1-e3c5269b1ec7.json' ); // IMPORTANT for service account @@ -32,11 +34,12 @@ class GoogleSheetLib // Init services $this->sheets = new Google_Service_Sheets($this->client); $this->drive = new Google_Service_Drive($this->client); + } /* ===================== READ ===================== */ - public function read(string $spreadsheetId, string $range = 'Sheet1') + public function read(string $spreadsheetId, string $range = 'RFQ Page') { $response = $this->sheets ->spreadsheets_values @@ -77,4 +80,205 @@ class GoogleSheetLib return $response->getBody()->getContents(); } + + + /* ================= COPY TEMPLATE ================= */ + + public function copyTemplate(string $templateId, string $name, string $folderId): string + { + $file = $this->drive->files->copy( + $templateId, + new \Google_Service_Drive_DriveFile([ + 'name' => $name, + 'parents' => [$folderId], + + ]),[ + 'supportsAllDrives' => true, + 'fields' => 'id, name, parents' + ] + ); + + return $file->id; + } + + /* ================= PERMISSIONS ================= */ + + public function applyPermissions(string $fileId, array $permissions) + { + foreach ($permissions['editors'] as $email) { + $this->createPermission($fileId, $email, 'writer'); + } + + foreach ($permissions['viewers'] as $email) { + $this->createPermission($fileId, $email, 'reader'); + } + } + + private function createPermission(string $fileId, string $email, string $role) + { + $type = str_starts_with($email, 'group:') ? 'group' : 'user'; + $email = str_replace('group:', '', $email); + + $this->drive->permissions->create( + $fileId, + new \Google_Service_Drive_Permission([ + 'type' => $type, + 'role' => $role, + 'emailAddress' => $email + ]), + ['sendNotificationEmail' => false,'supportsAllDrives' => true] + ); + } + + /* ================= PROTECTIONS ================= */ + + public function applyProtectionsold(string $spreadsheetId, array $ranges) + { + $spreadsheet = $this->sheets->spreadsheets->get($spreadsheetId); + $sheetId = $spreadsheet->getSheets()[0]->getProperties()->getSheetId(); + + $requests = []; + + foreach ($ranges as $range) { + [$sheetName, $a1] = explode('!', $range); + + $requests[] = [ + 'addProtectedRange' => [ + 'protectedRange' => [ + 'range' => [ + 'sheetId' => $sheetId + ], + 'warningOnly' => false + ] + ] + ]; + } + + $this->sheets->spreadsheets->batchUpdate( + $spreadsheetId, + new Google_Service_Sheets_BatchUpdateSpreadsheetRequest([ + 'requests' => $requests + ]) + ); + } + + + public function applyProtections(string $spreadsheetId, array $protections) +{ + // Fetch spreadsheet metadata + $spreadsheet = $this->sheets->spreadsheets->get( + $spreadsheetId, + ['fields' => 'sheets(properties(sheetId,title,gridProperties))'] + ); + + // Map sheet names + $sheetMap = []; + foreach ($spreadsheet->getSheets() as $sheet) { + $props = $sheet->getProperties(); + $sheetMap[$props->getTitle()] = [ + 'sheetId' => $props->getSheetId(), + 'rowCount' => $props->getGridProperties()->getRowCount(), + 'colCount' => $props->getGridProperties()->getColumnCount(), + ]; + } + + $requests = []; + + foreach ($protections as $protection) { + + $rangeStr = $protection['range']; + + if (!str_contains($rangeStr, '!')) { + throw new \Exception("Invalid range format: {$rangeStr}"); + } + + [$sheetName, $a1] = explode('!', $rangeStr, 2); + + if (!isset($sheetMap[$sheetName])) { + throw new \Exception("Sheet not found: {$sheetName}"); + } + + $sheetMeta = $sheetMap[$sheetName]; + + $gridRange = $this->convertA1ToGridRange( + $a1, + $sheetMeta['sheetId'], + $sheetMeta['rowCount'], + $sheetMeta['colCount'] + ); + + $protectedRange = [ + 'range' => $gridRange, + 'description' => 'RFQ Protected Area', + 'warningOnly' => false, + 'editors' => [ + 'users' => $protection['users'] ?? [], + 'groups' => $protection['groups'] ?? [] + ] + ]; + + $requests[] = [ + 'addProtectedRange' => [ + 'protectedRange' => $protectedRange + ] + ]; + } + + if (!empty($requests)) { + $batch = new \Google_Service_Sheets_BatchUpdateSpreadsheetRequest([ + 'requests' => $requests + ]); + + $this->sheets->spreadsheets->batchUpdate($spreadsheetId, $batch); + } + + return true; +} + + /* ================= URL ================= */ + + public function sheetUrl(string $sheetId): string + { + return "https://docs.google.com/spreadsheets/d/{$sheetId}/edit"; + } + + + private function convertA1ToGridRange($a1, $sheetId, $maxRows, $maxCols) +{ + if (preg_match('/^([A-Z]+)(\d+)(?::([A-Z]+)(\d+))?$/i', $a1, $m)) { + + $startCol = $this->colToIndex($m[1]); + $startRow = intval($m[2]) - 1; + + if (!empty($m[3])) { + $endCol = $this->colToIndex($m[3]) + 1; + $endRow = intval($m[4]); + } else { + $endCol = $startCol + 1; + $endRow = $startRow + 1; + } + + return [ + 'sheetId' => $sheetId, + 'startRowIndex' => $startRow, + 'endRowIndex' => $endRow, + 'startColumnIndex' => $startCol, + 'endColumnIndex' => $endCol + ]; + } + + throw new \Exception("Unsupported A1 format: {$a1}"); +} + +private function colToIndex($letters) +{ + $letters = strtoupper($letters); + $index = 0; + for ($i = 0; $i < strlen($letters); $i++) { + $index = $index * 26 + (ord($letters[$i]) - 64); + } + return $index - 1; +} + + } diff --git a/app/Views/gsheet_editor.php b/app/Views/gsheet_editor.php index 93f40957..e3c9f316 100644 --- a/app/Views/gsheet_editor.php +++ b/app/Views/gsheet_editor.php @@ -16,6 +16,28 @@ + + +
+ +