diff --git a/app/Config/Routes.php b/app/Config/Routes.php index 798f021..9043252 100755 --- a/app/Config/Routes.php +++ b/app/Config/Routes.php @@ -44,6 +44,7 @@ $routes->group('api', ['filter' => 'appSignature'], function ($routes) { $routes->get('agent/findAgent', 'AgentController::findAgent'); $routes->post('agent/createAgent', 'AgentController::createAgent'); $routes->post('agent/updateAgent', 'AgentController::updateAgent'); + $routes->post('agent/updateDeviceToken', 'AgentController::updateDeviceToken'); $routes->post('agent/changeAgentStatus', 'AgentController::changeAgentStatus'); $routes->get('agent/downloadAgentCertificateFile', 'AgentController::downloadAgentCertificateFile'); $routes->get('agent/agentIncentiveFileList', 'AgentController::agentIncentiveFileList'); @@ -84,6 +85,17 @@ $routes->group('api', ['filter' => 'appSignature'], function ($routes) { $routes->post('policy/updatePolicy', 'PolicyController::updatePolicy'); $routes->get('policy/downloadPolicyFile', 'PolicyController::downloadPolicyFile'); + //claims + $routes->get('claim/ClaimList', 'ClaimController::ClaimList'); + $routes->post('claim/createClaim', 'ClaimController::createPolicy'); + + //endorsement + $routes->get('endorsement/endorsementList', 'EndorsementController::endorsementList'); + $routes->post('endorsement/createEndorsement', 'EndorsementController::createEndorsement'); + + //dashboard + $routes->get('dashboard/agentDashboard', 'DashboardController::agentDashboard'); + }); diff --git a/app/Controllers/AgentController.php b/app/Controllers/AgentController.php index ff38635..acaeac3 100644 --- a/app/Controllers/AgentController.php +++ b/app/Controllers/AgentController.php @@ -144,6 +144,38 @@ class AgentController extends ResourceController } } + //update device token + public function updateDeviceToken() + { + try{ + + $data = $this->request->getPost(); + if (!isset($data['id'])) { + return $this->respond(['status' => 'failed', 'code' => 200, 'data' => 'ID Required'], 200); + } + + $id = $data['id']; + + // check if agent exists + $agent = $this->AgentModel->find($id); + if (!$agent) { + return $this->respond(['status' => 'failed', 'code' => 200, 'data' => 'Date Not Found'], 200); + } + + + $updateData = [ + 'firebase_device_token' => $data['firebase_device_token'] ?? null, + ]; + + $this->AgentModel->update($id, $updateData); + + return $this->respond(['status' => 'success', 'code' => 200, 'data' => []], 200); + + } catch (\Exception $e) { + return $this->respond(['status' => 'failed', 'code' => 500, 'data' => $e->getMessage()], 500); + } + } + // ACTIVATE / DEACTIVATE agent public function changeAgentStatus() { diff --git a/app/Controllers/ClaimController.php b/app/Controllers/ClaimController.php new file mode 100644 index 0000000..7c284e1 --- /dev/null +++ b/app/Controllers/ClaimController.php @@ -0,0 +1,144 @@ +db = db_connect(); + $this->ClaimModel = new ClaimModel(); + $this->PolicyModel = new PolicyModel(); + $this->QuotationModel = new QuotationModel(); + $this->EnquiryModel = new EnquiryModel(); + } + + // Get all tickets + public function ClaimList() + { + try { + + $id = $this->request->getGet('id'); // claim id + $manager_id = $this->request->getGet('manager_id'); + $agent_id = $this->request->getGet('agent_id'); + + + $builder = $this->db->table('ticket_master tm') + ->select('tm.*, + i.name as insurer_name, + c.client_name, c.phone as client_phone, c.email as client_email, + pct.claim_type, + pa.name as agent_name, + tcs.claim_status') + ->join('insurers i', 'i.id = tm.insurer_id', 'left') + ->join('clients c', 'c.id = tm.client_id', 'left') + ->join('partner_claim_type_master pct', 'pct.id = tm.ticket_type_id', 'left') + ->join('partner_agent pa', 'pa.id = tm.agent_id', 'left') + ->join('ticket_claim_status tcs', 'tcs.id = tm.claim_status_id AND tcs.ticket_type = 8', 'left') + ->where('tm.ticket_type_id', 8); + + // If ID is provided, fetch single record + if (!empty($id)) { + $builder->where('tm.id', $id); + $ticket = $builder->get()->getRowArray(); + + if (!$ticket) { + return $this->respond(['status' => 'failed', 'code' => 404, 'data' => 'Not Found'], 404); + } + + return $this->respond(['status' => 'success', 'code' => 200, 'data' => $ticket], 200); + } + + // Apply filters + if (!empty($manager_id)) { + $builder->where('tm.manager_id', $manager_id); + } + + if (!empty($agent_id)) { + $builder->where('tm.agent_id', $agent_id); + } + + $data = $builder->get()->getResultArray(); + + return $this->respond(['status' => 'success', 'code' => 200, 'data' => $data], 200); + } catch (\Exception $e) { + return $this->respond(['status' => 'failed', 'code' => 500, 'data' => $e->getMessage()], 500); + } + } + + + + // Create new ticket + public function createClaim() + { + try { + $reqData = $this->request->getJSON(true); + + // Validate required fields + if (empty($reqData['policy_number']) || empty($reqData['claim_description'] || empty($reqData['claim_type']))) { + return $this->respond(['status' => 'failed','code' => 400, 'data' => 'policy_number and claim_description and claim_type are required'], 200); + } + + // Fetch policy details from partner_policy + $policy = $this->PolicyModel->select('partner_policy.*,E.insurer_id,E.insurer_branch_id,E.name as client_name,E.mobile as client_mobile,E.email as client_email,E.reg_no') + ->join('partner_quotation Q', 'Q.id = partner_policy.quotation_id', 'left') + ->join('partner_enquiry E', 'E.id = partner_policy.enquiry_id', 'left') + ->where('partner_policy.policy_number',$reqData['policy_number']) + ->first(); + + if (empty($policy)) { + return $this->respond([ + 'status' => 'failed', + 'code' => 404, + 'data' => 'Policy not found' + ], 200); + } + + // Prepare claim data for ticket_master + $claimData = [ + 'ticket_type_id' => 8, + 'claim_status_id' => 1, + 'policy_no' => $policy['policy_number'], + 'client_policy_id' => $policy['client_policy_id'], + 'insurer_id' => $policy['insurer_id'], + 'client_id' => $policy['client_id'] ?? null, + 'agent_id' => $policy['agent_id'] ?? null, + 'manager_id' => $policy['manager_id'] ?? null, + 'vehicle_id' => $policy['vehicle_id'] ?? null, + 'insured_name' => $policy['insured_name'] ?? null, + 'emp_name' => $policy['client_name'] ?? null, + 'emp_mobile' => $policy['client_mobile'] ?? null, + 'emp_mail' => $policy['client_email'] ?? null, + 'emp_personal_mail'=> $policy['client_email'] ?? null, + 'claim_type' => $reqData['claim_type'], + 'claim_description'=> $reqData['claim_description'], + 'created_by' => $reqData['created_by'] ?? null, + ]; + + // Insert claim + if (!$this->ClaimModel->insert($claimData)) { + return $this->respond(['status' => 'failed','code' => 422,'data' => $this->ClaimModel->errors()], 422); + } + + return $this->respond(['status' => 'success','code' => 200,'data' => ['claim_id' => $this->ClaimModel->getInsertID()]], 200); + + } catch (\Exception $e) { + return $this->respond(['status' => 'failed','code' => 500,'data' => $e->getMessage()], 500); + } + } + + + +} diff --git a/app/Controllers/DashboardController.php b/app/Controllers/DashboardController.php new file mode 100644 index 0000000..8ee4c34 --- /dev/null +++ b/app/Controllers/DashboardController.php @@ -0,0 +1,126 @@ +db = \Config\Database::connect(); + } + + public function agentDashboard() + { + $today = date('Y-m-d'); + $month = date('m'); + $year = date('Y'); + + // --- Policies Issued --- + $policiesToday = $this->db->table('partner_policy') + ->where('created_on >=', $today.' 00:00:00') + ->where('created_on <=', $today.' 23:59:59') + ->countAllResults(); + + $policiesMonth = $this->db->table('partner_policy') + ->where('MONTH(created_on)', $month) + ->where('YEAR(created_on)', $year) + ->countAllResults(); + + $policiesYear = $this->db->table('partner_policy') + ->where('YEAR(created_on)', $year) + ->countAllResults(); + + // --- Premium Value --- + $premiumToday = (float) ($this->db->table('partner_policy') + ->selectSum('premium_amount', 'total') + ->where('created_on >=', $today.' 00:00:00') + ->where('created_on <=', $today.' 23:59:59') + ->get()->getRow()->total ?? 0); + + $premiumMonth = (float) ($this->db->table('partner_policy') + ->selectSum('premium_amount', 'total') + ->where('MONTH(created_on)', $month) + ->where('YEAR(created_on)', $year) + ->get()->getRow()->total ?? 0); + + $premiumYear = (float) ($this->db->table('partner_policy') + ->selectSum('premium_amount', 'total') + ->where('YEAR(created_on)', $year) + ->get()->getRow()->total ?? 0); + + // --- Earnings (same as premium for now) --- + $earningsToday = $premiumToday; + $earningsMonth = $premiumMonth; + $earningsYear = $premiumYear; + + $last30 = date('Y-m-d H:i:s', strtotime('-30 days')); + + // --- Performance Agents (top 5, last 30 days) --- + $performanceAgents = $this->db->table('partner_policy pp') + ->select('pa.id AS agent_id, pa.name AS agent_name, COUNT(pp.id) AS policies_issued, COALESCE(SUM(pp.premium_amount),0) AS premium_value') + ->join('partner_agent pa', 'pa.id = pp.agent_id', 'inner') + ->where('pp.created_on >=', $last30) + ->groupBy('pa.id') + ->orderBy('policies_issued', 'DESC') + ->limit(5) + ->get() + ->getResultArray(); + + // --- Non-Performing Agents (bottom 5, last 30 days) --- + $nonPerformingAgents = $this->db->table('partner_agent pa') + ->select('pa.id AS agent_id, pa.name AS agent_name, COUNT(pp.id) AS policies_issued, IF(pa.is_active=1,"Active","Inactive") AS status') + ->join('partner_policy pp', 'pp.agent_id = pa.id AND ', 'left') + ->groupBy('pa.id') + ->orderBy('policies_issued', 'ASC') + ->limit(5) + ->get() + ->getResultArray(); + + // --- Quotations Pending --- + $quotationsPending = $this->db->table('partner_quotation pq') + ->select('ps.name as staff_name, COUNT(pq.id) as quotation_issued, COALESCE(SUM(pq.premium_amount),0) as premium_value') + ->join('partner_enquiry pe', 'pe.id = pq.enquiry_id') + ->join('partner_staff ps', 'ps.id = pe.assigned_to') + ->where('pq.status', 'Pending') + ->groupBy('ps.id') + ->limit(10) + ->get()->getResultArray(); + + // --- Policies Pending --- + $policiesPending = $this->db->table('partner_enquiry pe') + ->select('ps.name as staff_name, COUNT(pp.id) as policies_issued, COALESCE(SUM(pp.premium_amount),0) as premium_value') + ->join('partner_staff ps', 'ps.id = pe.assigned_to') + ->join('partner_policy pp', 'pp.enquiry_id = pe.id', 'left') + // ->where('pp.id', null) // correct way in CI4 for IS NULL + ->groupBy('ps.id') + ->limit(15) + ->get()->getResultArray(); + + return $this->respond([ + 'policies_issued' => [ + 'today' => $policiesToday, + 'month' => $policiesMonth, + 'year' => $policiesYear, + ], + 'premium_value' => [ + 'today' => $premiumToday, + 'month' => $premiumMonth, + 'year' => $premiumYear, + ], + 'earnings' => [ + 'today' => $earningsToday, + 'month' => $earningsMonth, + 'year' => $earningsYear, + ], + 'performance_agents' => $performanceAgents, + 'non_performing_agents'=> $nonPerformingAgents, + 'quotations_pending' => $quotationsPending, + 'policies_pending' => $policiesPending, + ]); + } + +} diff --git a/app/Controllers/EndorsementController.php b/app/Controllers/EndorsementController.php new file mode 100644 index 0000000..0754be9 --- /dev/null +++ b/app/Controllers/EndorsementController.php @@ -0,0 +1,31 @@ +db = db_connect(); + $this->EndorsementModel = new EndorsementModel(); + $this->PolicyModel = new PolicyModel(); + $this->QuotationModel = new QuotationModel(); + $this->EnquiryModel = new EnquiryModel(); + } + + + + +} diff --git a/app/Helpers/status_helper.php b/app/Helpers/status_helper.php index 4b8005c..e69de29 100644 --- a/app/Helpers/status_helper.php +++ b/app/Helpers/status_helper.php @@ -1,908 +0,0 @@ -find($plan_id, 'internal'); - if (!$planData) { - log_message('error', "No plan data found for plan_id: {$plan_id}"); - return false; - } - - $planServices = []; - if (count($planData['flight'])) { array_push($planServices, 1); } - if (count($planData['train'])) { array_push($planServices, 2); } - if (count($planData['bus'])) { array_push($planServices, 3); } - if (count($planData['taxi'])) { array_push($planServices, 4); } - if (count($planData['accomodation'])) { array_push($planServices, 5); } - if (count($planData['forex'])) { array_push($planServices, 6); } - if (count($planData['insurance'])) { array_push($planServices, 7); } - if (count($planData['visa'])) { array_push($planServices, 8); } - if (count($planData['miscellaneous'])) { array_push($planServices, 9); } - - log_message('debug', "Plan services found: " . json_encode($planServices)); - - $userId = $planData['user_id'] ?? $planData['traveller_id']; - $userData = $userModel->where('user_id', $userId)->first(); - if (!$userData) { - log_message('error', "User data not found for user_id: {$userId}"); - return false; - } - - $groupId = $userData['group_id']; - $a1Id = $userData['first_approver']; - $a2Id = $userData['second_approver']; - $a3Id = $userData['third_approver']; - $a4Id = $userData['fourth_approver']; - - $groupData = $groupModel->where('group_id', $groupId)->first(); - if (!$groupData) { - log_message('error', "Group data not found for group_id: {$groupId}"); - return false; - } - - $tripType = $planData['trip_type']; - $policyId = ($tripType == 1) ? $groupData['domestic_policy_id'] : $groupData['international_policy_id']; - - $policyData = $policyModel->where('policy_id', $policyId)->first(); - if (!$policyData) { - log_message('error', "Policy data not found for policy_id: {$policyId}"); - return false; - } - - $priorityOrderOfService = json_decode($policyData['services_ids'], true); - if (!is_array($priorityOrderOfService)) { - log_message('error', "Invalid service priority list in policy_id: {$policyId}"); - return false; - } - - foreach ($priorityOrderOfService as $key => &$value) { - $value['priority'] = $key + 1; - } - unset($value); - - log_message('debug', "Service priority list: " . json_encode($priorityOrderOfService)); - - // Step 1: Filter only services present in current plan - $filtered = array_filter($priorityOrderOfService, function ($item) use ($planServices) { - return in_array($item['service_id'], $planServices); - }); - - // Step 2: Sort by priority - usort($filtered, function ($a, $b) { - return $a['priority'] <=> $b['priority']; - }); - - $topPriorityService = reset($filtered); - if (!$topPriorityService) { - log_message('error', "No matching service found for plan_id: {$plan_id}"); - return false; - } - - log_message('info', "Top priority service identified: " . json_encode($topPriorityService)); - - $policyServiceDetails = $policyDetailsModel - ->where('policy_id', $policyId) - ->where('service_id', $topPriorityService['service_id']) - ->where('is_active', 1) - ->first(); - - if (!$policyServiceDetails) { - log_message('error', "Policy service details not found for service_id: {$topPriorityService['service_id']}, policy_id: {$policyId}"); - return false; - } - // dd($policyServiceDetails); - - - $isExceptional = $planData['exceptional_plan_reason'] !== null && $planData['exceptional_plan_reason'] !== ''; - // dd($isExceptional); - - if ($isExceptional) { - $policyA1Action = $policyServiceDetails['a1_exceptional_action']; - $policyA2Action = $policyServiceDetails['a2_exceptional_action']; - $policyA3Action = $policyServiceDetails['a3_exceptional_action']; - $policyA4Action = $policyServiceDetails['a4_exceptional_action']; - $policyParallelAction = $policyServiceDetails['exceptional_parallel_process_from']; - } else if ($is_data_edited) { - $policyA1Action = $policyServiceDetails['a1_amendment_action']; - $policyA2Action = $policyServiceDetails['a2_amendment_action']; - $policyA3Action = $policyServiceDetails['a3_amendment_action']; - $policyA4Action = $policyServiceDetails['a4_amendment_action']; - $policyParallelAction = $policyServiceDetails['amendment_parallel_process_from']; - } else { - $policyA1Action = $policyServiceDetails['a1_action']; - $policyA2Action = $policyServiceDetails['a2_action']; - $policyA3Action = $policyServiceDetails['a3_action']; - $policyA4Action = 'None'; - $policyParallelAction = $policyServiceDetails['parallel_process_from']; - } - - - $data = [ - 'plan_id' => $plan_id, - 'service_id' => $topPriorityService['service_id'], - 'a1_id' => $a1Id, - 'a1_action' => $policyA1Action, - 'is_a1_action_done' => ($policyA1Action == 'None') ? 1 : 0, - 'a2_id' => $a2Id, - 'a2_action' => $policyA2Action, - 'is_a2_action_done' => ($policyA2Action == 'None') ? 1 : 0, - 'a3_id' => $a3Id, - 'a3_action' => $policyA3Action, - 'is_a3_action_done' => ($policyA3Action == 'None') ? 1 : 0, - 'a4_id' => $a4Id, - 'a4_action' => $policyA4Action, - 'is_a4_action_done' => ($policyA4Action == 'None') ? 1 : 0, - 'parallel_process_from' => $policyParallelAction - ]; - - // dd($data); - - if ($is_data_edited == false) { - log_message('info', "Creating new plan status for plan_id: {$plan_id}"); - $planStatusModel->insert($data); - } else { - $oldStatusData = $planStatusModel->where('plan_id', $plan_id)->where('is_active', 1)->first(); - if ($oldStatusData) { - if ($oldStatusData['service_id'] == $topPriorityService['service_id']) { - log_message('info', "No status update needed; service_id unchanged for plan_id: {$plan_id}"); - } else { - log_message('info', "Updating plan status for edited plan_id: {$plan_id}. New service_id: {$topPriorityService['service_id']}, Old service_id: {$oldStatusData['service_id']}"); - $planStatusModel->insert($data); - $planStatusModel->set(['is_active' => 0]) - ->where('plan_id', $plan_id) - ->where('service_id', $oldStatusData['service_id']) - ->update(); - } - } else { - log_message('warning', "Old status data not found for edited plan_id: {$plan_id}"); - $planStatusModel->insert($data); - } - } - - log_message('info', "palnStatusHandler() completed for plan_id: {$plan_id}"); - } -} - - -// if (!function_exists('palnStatusHandler')) { -// function palnStatusHandler($plan_id , $is_data_edited) -// { - -// $planModel = new PlanModel(); -// $planStatusModel = new PlanStatusModel(); -// $userModel = new UserModel(); -// $groupModel = new GroupModel(); -// $policyModel = new PolicyModel(); -// $policyDetailsModel = new PolicyDetailsModel(); -// $planController = new PlanController(); - -// $planData = $planController->find($plan_id, 'internal'); - -// $planServices = []; -// if($planData) -// { -// if(count($planData['flight'])){ array_push($planServices,1); } -// if(count($planData['train'])){ array_push($planServices,2); } -// if(count($planData['bus'])){ array_push($planServices,3); } -// if(count($planData['taxi'])){ array_push($planServices,4); } -// if(count($planData['accomodation'])){ array_push($planServices,5); } -// if(count($planData['forex'])){ array_push($planServices,6); } -// if(count($planData['insurance'])){ array_push($planServices,7); } -// if(count($planData['visa'])){ array_push($planServices,8); } -// if(count($planData['miscellaneous'])){ array_push($planServices,9); } - -// } -// echo '
';
-// print_r($planServices);
-
-
-// // Fetch plan data
-// if (!$planData) { return false; }
-// $userId = $planData['user_id'] ?? $planData['traveller_id'];
-
-// // Fetch user data
-// $userData = $userModel->where('user_id', $userId)->first();
-// if (!$userData) { return false; }
-// $groupId = $userData['group_id'];
-// $a1Id = $userData['first_approver'];
-// $a2Id = $userData['second_approver'];
-// $a3Id = $userData['third_approver'];
-
-
-// // Fetch group data
-// $groupData = $groupModel->where('group_id', $groupId)->first();
-// if (!$groupData) { return false; }
-// $policyId = ($planData['trip_type'] == 1) ? $groupData['domestic_policy_id'] : $groupData['international_policy_id'];
-
-// // Fetch policy service data
-// $policyData = $policyModel->where('policy_id', $policyId)->first();
-// if (!$policyData) {return false; }
-
-// $priorityOrderOfService = json_decode($policyData['services_ids'],true);
-// if (is_array($priorityOrderOfService)) {
-// foreach ($priorityOrderOfService as $key => &$value) {
-// $value['priority'] = $key + 1;
-// }
-// unset($value); // always break reference after loop
-// }
-// echo '';
-// print_r($priorityOrderOfService);
-
-// // Step 1: Filter only services you currently have
-// $filtered = array_filter($priorityOrderOfService, function($item) use ($planServices) {
-// return in_array($item['service_id'], $planServices);
-// });
-
-// // Step 2: Sort by priority ascending
-// usort($filtered, function($a, $b) {
-// return $a['priority'] <=> $b['priority'];
-// });
-
-// // Step 3: Get the top priority service
-// $topPriorityService = reset($filtered);
-// echo '';
-// print_r($topPriorityService); die;
-
-// $policyServiceDetails = $policyDetailsModel->where('policy_id',$policyId)->where('service_id',$topPriorityService['service_id'])->where('is_active',1)->first();
-// if (!$policyServiceDetails) { return false; }
-// $policyA1Action = $policyServiceDetails['a1_action'];
-// $policyA2Action = $policyServiceDetails['a2_action'];
-// $policyA3Action = $policyServiceDetails['a3_action'];
-// $policyParallelAction = $policyServiceDetails['parallel_process_from'];
-
-
-
-
-// if($is_data_edited == false)//plan Creation
-// {
-// $data['plan_id'] = $plan_id;
-// $data['service_id'] = $topPriorityService['service_id'];
-// $data['a1_id'] = $a1Id;
-// $data['a1_action'] = $policyA1Action;
-// $data['a2_id'] = $a2Id;
-// $data['a2_action'] = $policyA2Action;
-// $data['a3_id'] = $a3Id;
-// $data['a3_action'] = $policyA3Action;
-// $data['parallel_process_from'] = $policyParallelAction;
-// // Insert Status
-// $planStatusModel->insert($data);
-
-// }else{
-
-// $oldStatusData = $planStatusModel->where('plan_id',$plan_id)->where('is_active', 1)->first();
-
-// if($oldStatusData['service_id'] == $topPriorityService['service_id']){ // skip the process
-
-// }else{ // insert new data
-
-// //insert new service data
-// $data['plan_id'] = $plan_id;
-// $data['service_id'] = $topPriorityService['service_id'];
-// $data['a1_id'] = $a1Id;
-// $data['a1_action'] = $policyA1Action;
-// $data['a2_id'] = $a2Id;
-// $data['a2_action'] = $policyA2Action;
-// $data['a3_id'] = $a3Id;
-// $data['a3_action'] = $policyA3Action;
-// $data['parallel_process_from'] = $policyParallelAction;
-// // Insert Status
-// $planStatusModel->insert($data);
-
-// //update old service data is_active = 0
-// $planStatusModel->set(['is_active'=>0])->where('plan_id',$plan_id)->where('service_id',$oldStatusData['service_id'])->update();
-
-// }
-
-// }
-
-
-// }
-// }
-
-if (!function_exists('updatePlanStatus')) {
- function updatePlanStatus($plan_id)
- {
-
- $planStatusModel = new PlanStatusModel();
- $planModel = new PlanModel();
-
- $a1 = $planStatusModel->where('plan_id',$plan_id)->where('a1_action','Approval')->where('is_active',1)->findAll();
- $a1ApproveSum = 0;
- $a1ApproveCount = 0;
- if(count($a1))
- {
- $a1ApproveSum = array_sum(array_column($a1, 'is_a1_action_done'));
- $a1ApproveCount = count($a1);
- }
-
- $a2 = $planStatusModel->where('plan_id',$plan_id)->where('a2_action','Approval')->where('is_active',1)->findAll();
- $a2ApproveSum = 0;
- $a2ApproveCount = 0;
- if(count($a2))
- {
- $a2ApproveSum = array_sum(array_column($a2, 'is_a2_action_done'));
- $a2ApproveCount = count($a2);
- }
-
-
- $a3 = $planStatusModel->where('plan_id',$plan_id)->where('a3_action','Approval')->where('is_active',1)->findAll();
- $a3ApproveSum = 0;
- $a3ApproveCount = 0;
- if(count($a3))
- {
- $a3ApproveSum = array_sum(array_column($a3, 'is_a3_action_done'));
- $a3ApproveCount = count($a3);
- }
-
- $a4 = $planStatusModel->where('plan_id',$plan_id)->where('a4_action','Approval')->where('is_active',1)->findAll();
- $a4ApproveSum = 0;
- $a4ApproveCount = 0;
- if(count($a4))
- {
- $a4ApproveSum = array_sum(array_column($a4, 'is_a4_action_done'));
- $a4ApproveCount = count($a4);
- }
-
-
- $count = ( $a1ApproveCount + $a2ApproveCount + $a3ApproveCount + $a4ApproveCount);
- $sum = ( $a1ApproveSum + $a2ApproveSum + $a3ApproveSum + $a4ApproveSum);
-
-
- if($count == $sum)
- {
- // Approved
- $planModel->set(['status'=>3])->where('plan_id',$plan_id)->update();
-
- }else if($count != $sum && $sum > 0)
- {
- //Partially Approved
- $planModel->set(['status'=>2])->where('plan_id',$plan_id)->update();
- }
-
- return true;
-
- }
-}
-
-if (!function_exists('getCurrentPlanStatus')) {
- function getCurrentPlanStatus($plan_id)
- {
-
- $planStatusModel = new PlanStatusModel();
- $userModel = new UserModel();
- $currentStatus = [];
-
- $a1 = $planStatusModel->where('plan_id',$plan_id)->where('a1_action','Approval')->where('is_active',1)->findAll();
-
- if(count($a1))
- {
-
- $user1 = $userModel->where('user_id', $a1[0]['a1_action_done_by'])->first();
- if(!$user1){
- $user1 = $userModel->where('user_id', $a1[0]['a1_id'])->first();
- }
-
- $hasRejectReason = !empty(array_filter($a1, fn($row) => !empty($row['a1_reject_reason'])));
- if($user1)
- {
-
- $userId = $user1['user_id'];
-
- $a1ApproveSum = array_sum(array_column($a1, 'is_a1_action_done'));
- $a1ApproveCount = count($a1);
-
- $a1Status['a1_id'] = $userId;
- if($a1ApproveSum == $a1ApproveCount)
- {
- $a1Status['a1_status'] = 'Plan approved by '.$user1['first_name'].' '.$user1['last_name'];
- }else if($hasRejectReason){
- $a1Status['a1_status'] = 'Plan rejected by '.$user1['first_name'].' '.$user1['last_name'].', Reason-'.$a1[0]['a1_reject_reason'];
- }else{
- $a1Status['a1_status'] = 'Plan approval pending from '.$user1['first_name'].' '.$user1['last_name'];
- }
- array_push($currentStatus,$a1Status);
- }
-
- }
-
-
- $a2 = $planStatusModel->where('plan_id',$plan_id)->where('a2_action','Approval')->where('is_active',1)->findAll();
- if(count($a2))
- {
- $user2 = $userModel->where('user_id', $a2[0]['a2_action_done_by'])->first();
- if(!$user2){
- $user2 = $userModel->where('user_id', $a2[0]['a2_id'])->first();
- }
- $hasRejectReason = !empty(array_filter($a2, fn($row) => !empty($row['a2_reject_reason'])));
- if($user2)
- {
- $userId = $user2['user_id'];
-
- $a2ApproveSum = array_sum(array_column($a2, 'is_a2_action_done'));
- $a2ApproveCount = count($a2);
-
- $a2Status['a2_id'] = $userId;
- if($a2ApproveSum == $a2ApproveCount)
- {
- $a2Status['a2_status'] = 'Plan approved by '.$user2['first_name'].' '.$user2['last_name'];
- }else if($hasRejectReason){
- $a2Status['a2_status'] = 'Plan rejected by '.$user2['first_name'].' '.$user2['last_name'].', Reason-'.$a2[0]['a2_reject_reason'];
- }else{
- $a2Status['a2_status'] = 'Plan approval pending from '.$user2['first_name'].' '.$user2['last_name'];
- }
- array_push($currentStatus,$a2Status);
- }
- }
-
-
- $a3 = $planStatusModel->where('plan_id',$plan_id)->where('a3_action','Approval')->where('is_active',1)->findAll();
- if(count($a3))
- {
- $user3 = $userModel->where('user_id', $a3[0]['a3_action_done_by'])->first();
- if(!$user3){
- $user3 = $userModel->where('user_id', $a3[0]['a3_id'])->first();
- }
- $hasRejectReason = !empty(array_filter($a3, fn($row) => !empty($row['a3_reject_reason'])));
- if($user3)
- {
- $userId = $user3['user_id'];
-
- $a3ApproveSum = array_sum(array_column($a3, 'is_a3_action_done'));
- $a3ApproveCount = count($a3);
-
- $a3Status['a3_id'] = $userId;
- if($a3ApproveSum == $a3ApproveCount)
- {
- $a3Status['a3_status'] = 'Plan approved by '.$user3['first_name'].' '.$user3['last_name'];
- }else if($hasRejectReason){
- $a3Status['a3_status'] = 'Plan rejected by '.$user3['first_name'].' '.$user3['last_name'].', Reason-'.$a3[0]['a3_reject_reason'];
- }else{
- $a3Status['a3_status'] = 'Plan approval pending from '.$user3['first_name'].' '.$user3['last_name'];
- }
- array_push($currentStatus,$a3Status);
- }
- }
-
- $a4 = $planStatusModel->where('plan_id',$plan_id)->where('a4_action','Approval')->where('is_active',1)->findAll();
- if(count($a4))
- {
- $user4 = $userModel->where('user_id', $a4[0]['a4_action_done_by'])->first();
- if(!$user4){
- $user4 = $userModel->where('user_id', $a4[0]['a4_id'])->first();
- }
- $hasRejectReason = !empty(array_filter($a4, fn($row) => !empty($row['a4_reject_reason'])));
- if($user4)
- {
- $userId = $user4['user_id'];
-
- $a4ApproveSum = array_sum(array_column($a4, 'is_a4_action_done'));
- $a4ApproveCount = count($a4);
-
- $a4Status['a4_id'] = $userId;
- if($a4ApproveSum == $a4ApproveCount)
- {
- $a4Status['a4_status'] = 'Plan approved by '.$user4['first_name'].' '.$user4['last_name'];
- }else if($hasRejectReason){
- $a4Status['a4_status'] = 'Plan rejected by '.$user4['first_name'].' '.$user4['last_name'].', Reason-'.$a4[0]['a4_reject_reason'];
- }else{
- $a4Status['a4_status'] = 'Plan approval pending from '.$user4['first_name'].' '.$user4['last_name'];
- }
- array_push($currentStatus,$a4Status);
- }
- }
-
-
- return $currentStatus;
-
- }
-}
-
-if (!function_exists('getPlanApproverAction')) {
- // initially written code without parallel , sequential
- // function getPlanApproverAction($plan_id , )
- // {
-
- // $planStatusModel = new PlanStatusModel();
- // $userModel = new UserModel();
- // $result['approver_data'] = [];
- // $serviceIds = [];
-
- // $a1 = $planStatusModel->where('plan_id',$plan_id)->whereIn('a1_action',['Approval','Notification'])->where('is_active',1)->findAll();
- // if(count($a1))
- // {
- // $serviceId = array_column($a1, 'service_id');
- // $serviceIds = array_merge($serviceIds, $serviceId);
- // $user = $userModel->where('user_id', $a1[0]['a1_id'])->first();
- // if($user)
- // {
- // $approvalCount = 0;
- // $notificationCount = 0;
-
- // foreach ($a1 as $item) {
- // if ($item['a1_action'] === 'Approval') {
- // $approvalCount++;
- // } elseif ($item['a1_action'] === 'Notification') {
- // $notificationCount++;
- // }
- // }
-
- // if($approvalCount != 0)
- // {
- // array_push($result['approver_data'] , ['approver'=>1, 'user_id'=>$a1[0]['a1_id'], 'email'=> $user['email'], 'action'=>'Approval', 'is_action_done'=>$a1[0]['is_a1_action_done']] );
- // }else if($notificationCount != 0){
- // array_push($result['approver_data'] , ['approver'=>1, 'user_id'=>$a1[0]['a1_id'], 'email'=> $user['email'], 'action'=>'Notification', 'is_action_done'=>$a1[0]['is_a1_action_done']] );
- // }
- // }
-
- // }
-
-
-
- // $a2 = $planStatusModel->where('plan_id',$plan_id)->whereIn('a2_action',['Approval','Notification'])->where('is_active',1)->findAll();
- // if(count($a2))
- // {
- // $serviceId = array_column($a2, 'service_id');
- // $serviceIds = array_merge($serviceIds, $serviceId);
- // $user = $userModel->where('user_id', $a1[0]['a2_id'])->first();
- // if($user)
- // {
- // $approvalCount = 0;
- // $notificationCount = 0;
-
- // foreach ($a1 as $item) {
- // if ($item['a2_action'] === 'Approval') {
- // $approvalCount++;
- // } elseif ($item['a2_action'] === 'Notification') {
- // $notificationCount++;
- // }
- // }
-
- // if($approvalCount != 0)
- // {
- // array_push($result['approver_data'] , ['approver'=>2, 'user_id'=>$a1[0]['a2_id'], 'email'=> $user['email'], 'action'=>'Approval', 'is_action_done'=>$a2[0]['is_a2_action_done']] );
- // }else if($notificationCount != 0){
- // array_push($result['approver_data'] , ['approver'=>2, 'user_id'=>$a1[0]['a2_id'], 'email'=> $user['email'], 'action'=>'Notification', 'is_action_done'=>$a2[0]['is_a2_action_done']] );
- // }
- // }
-
- // }
-
- // $a3 = $planStatusModel->where('plan_id',$plan_id)->whereIn('a3_action',['Approval','Notification'])->where('is_active',1)->findAll();
- // if(count($a3))
- // {
- // $serviceId = array_column($a3, 'service_id');
- // $serviceIds = array_merge($serviceIds, $serviceId);
- // $user = $userModel->where('user_id', $a1[0]['a3_id'])->first();
- // if($user)
- // {
- // $approvalCount = 0;
- // $notificationCount = 0;
-
- // foreach ($a1 as $item) {
- // if ($item['a3_action'] === 'Approval') {
- // $approvalCount++;
- // } elseif ($item['a3_action'] === 'Notification') {
- // $notificationCount++;
- // }
- // }
-
- // if($approvalCount != 0)
- // {
- // array_push($result['approver_data'] , ['approver'=>3, 'user_id'=>$a1[0]['a3_id'], 'email'=> $user['email'], 'action'=>'Approval', 'is_action_done'=>$a3[0]['is_a3_action_done']] );
- // }else if($notificationCount != 0){
- // array_push($result['approver_data'] , ['approver'=>3, 'user_id'=>$a1[0]['a3_id'], 'email'=> $user['email'], 'action'=>'Notification', 'is_action_done'=>$a3[0]['is_a3_action_done']] );
- // }
- // }
-
- // }
-
-
- // $statusData = $planStatusModel->where('plan_id',$plan_id)->where('is_active',1)->first();
- // $result['parallel_process_from'] = $statusData['parallel_process_from'];
-
- // return $result;
-
- // }
-
- // 3 level of parallel , sequential
- // function getPlanApproverAction($plan_id)
- // {
- // $planStatusModel = new PlanStatusModel();
- // $userModel = new UserModel();
- // $result = ['approver_data' => []];
- // $serviceIds = [];
-
- // // A1, A2, A3 - handle all same way
- // $approverAction = [
- // ['key' => 'a1', 'approver' => 1],
- // ['key' => 'a2', 'approver' => 2],
- // ['key' => 'a3', 'approver' => 3],
- // ];
-
- // foreach ($approverAction as $stage) {
- // $field = $stage['key'];
- // $approverNumber = $stage['approver'];
- // $actionField = "{$field}_action";
- // $idField = "{$field}_id";
- // $doneField = "is_{$field}_action_done";
-
- // $record = $planStatusModel->where('plan_id', $plan_id)
- // ->whereIn($actionField, ['Approval', 'Notification', 'None'])
- // ->where('is_active', 1)
- // ->first();
-
- // if ($record) {
- // $user = $userModel->where('user_id', $record[$idField])->first();
- // if ($user) {
- // $result['approver_data'][] = [
- // 'approver' => $approverNumber,
- // 'user_id' => $record[$idField],
- // 'email' => $user['email'],
- // 'action' => $record[$actionField],
- // 'is_action_done' => $record[$doneField],
- // 'where_key' => $idField,
- // 'action_key' => $actionField,
- // 'action_done_key' => $doneField,
- // ];
- // }
- // }
- // }
-
- // // Get parallel process value
- // $statusData = $planStatusModel->where('plan_id', $plan_id)->where('is_active', 1)->first();
- // $result['parallel_process_from'] = $statusData['parallel_process_from'] ?? null;
-
-
- // $parallelFrom = (int) $result['parallel_process_from'];
-
- // foreach ($result['approver_data'] as $key => &$approver) {
- // $approver['status'] = 'pending'; // default
-
- // if ($parallelFrom === 1) {
- // // All parallel
- // $approver['status'] = 'active';
- // } elseif ($parallelFrom === 2) {
- // if ($approver['approver'] === 1) {
- // $approver['status'] = 'active';
- // } elseif (in_array($approver['approver'], [2, 3])) {
- // // Check if approver 1 is done
- // $a1Done = false;
- // foreach ($result['approver_data'] as $a) {
- // if ($a['approver'] === 1 && $a['is_action_done']) {
- // $a1Done = true;
- // break;
- // }
- // }
- // $approver['status'] = $a1Done ? 'active' : 'waiting';
- // }
- // } elseif ($parallelFrom === 3) {
- // // Sequential: 1 -> 2 -> 3
- // $a1Done = false;
- // $a2Done = false;
-
- // foreach ($result['approver_data'] as $a) {
- // if ($a['approver'] === 1 && $a['is_action_done']) $a1Done = true;
- // if ($a['approver'] === 2 && $a['is_action_done']) $a2Done = true;
- // }
-
- // if ($approver['approver'] === 1) {
- // $approver['status'] = 'active';
- // } elseif ($approver['approver'] === 2) {
- // $approver['status'] = $a1Done ? 'active' : 'waiting';
- // } elseif ($approver['approver'] === 3) {
- // $approver['status'] = ($a1Done && $a2Done) ? 'active' : 'waiting';
- // }
- // }
- // }
- // unset($approver); // best practice when using & reference in foreach
-
-
- // return $result;
- // }
-
-
- // latest 4 level of parallel , sequential
- function getPlanApproverAction($plan_id)
- {
- $planStatusModel = new PlanStatusModel();
- $userModel = new UserModel();
- $result = ['approver_data' => []];
-
- $approverAction = [
- ['key' => 'a1', 'approver' => 1],
- ['key' => 'a2', 'approver' => 2],
- ['key' => 'a3', 'approver' => 3],
- ['key' => 'a4', 'approver' => 4],
- ];
-
- foreach ($approverAction as $stage) {
- $field = $stage['key'];
- $approverNumber = $stage['approver'];
- $actionField = "{$field}_action";
- $idField = "{$field}_id";
- $doneField = "is_{$field}_action_done";
- $mailField = "is_{$field}_mail_send";
-
- $record = $planStatusModel->where('plan_id', $plan_id)
- ->whereIn($actionField, ['Approval', 'Notification', 'None'])
- ->where('is_active', 1)
- ->first();
- if ($record) {
- $user = $userModel->where('user_id', $record[$idField])->first();
- if ($user) {
- $result['approver_data'][] = [
- 'approver' => $approverNumber,
- 'user_id' => $record[$idField],
- 'email' => $user['email'],
- 'action' => $record[$actionField],
- 'is_action_done' => $record[$doneField],
- 'where_key' => $idField,
- 'action_key' => $actionField,
- 'action_done_key' => $doneField,
- 'mail_send_key' => $mailField,
- 'is_mail_send' => $record[$mailField],
- ];
- }
- }
- }
-
- $statusData = $planStatusModel->where('plan_id', $plan_id)->where('is_active', 1)->first();
- $result['parallel_process_from'] = $statusData['parallel_process_from'] ?? null;
-
- $parallelFrom = (int) $result['parallel_process_from'];
-
- foreach ($result['approver_data'] as &$approver) {
- $approver['status'] = 'pending'; // default
-
- // Flags
- $a1Done = $a2Done = $a3Done = false;
- foreach ($result['approver_data'] as $a) {
- if ($a['approver'] === 1 && $a['is_action_done']) $a1Done = true;
- if ($a['approver'] === 2 && $a['is_action_done']) $a2Done = true;
- if ($a['approver'] === 3 && $a['is_action_done']) $a3Done = true;
- }
-
- if ($parallelFrom === 1) {
- // All approvers active
- $approver['status'] = 'active';
-
- } elseif ($parallelFrom === 2) {
- if ($approver['approver'] === 1) {
- $approver['status'] = 'active';
- } elseif (in_array($approver['approver'], [2, 3, 4])) {
- $approver['status'] = $a1Done ? 'active' : 'waiting';
- }
-
- } elseif ($parallelFrom === 3) {
- if ($approver['approver'] === 1) {
- $approver['status'] = 'active';
- } elseif ($approver['approver'] === 2) {
- $approver['status'] = $a1Done ? 'active' : 'waiting';
- } elseif (in_array($approver['approver'], [3, 4])) {
- $approver['status'] = ($a1Done && $a2Done) ? 'active' : 'waiting';
- }
-
- } elseif ($parallelFrom === 4) {
- if ($approver['approver'] === 1) {
- $approver['status'] = 'active';
- } elseif ($approver['approver'] === 2) {
- $approver['status'] = $a1Done ? 'active' : 'waiting';
- } elseif ($approver['approver'] === 3) {
- $approver['status'] = ($a1Done && $a2Done) ? 'active' : 'waiting';
- } elseif ($approver['approver'] === 4) {
- $approver['status'] = ($a1Done && $a2Done && $a3Done) ? 'active' : 'waiting';
- }
- } else {
- $approver['status'] = 'pending'; // fallback
- }
- }
- unset($approver); // clean reference
-
- return $result;
- }
-
-
-
-
-
-}
-
-if (!function_exists('getApproverCurrentAction')) {
- function getApproverCurrentAction($plan_id,$user_id)
- {
-
- $planStatusModel = new PlanStatusModel();
- $userModel = new UserModel();
-
- $a1 = $planStatusModel->where('plan_id',$plan_id)->where('a1_id',$user_id)->where('a1_action','Approval')->where('is_active',1)->findAll();
- if(count($a1))
- {
- $hasRejectReason = !empty(array_filter($a1, fn($row) => !empty($row['a1_reject_reason'])));
- $a1ApproveSum = array_sum(array_column($a1, 'is_a1_action_done'));
- $a1ApproveCount = count($a1);
-
- if($a1ApproveSum == $a1ApproveCount)
- {
- return 'Approved';
- }else if($hasRejectReason){
- return 'Rejected';
- }else{
- return 'Approval pending';
- }
- }
-
- $a2 = $planStatusModel->where('plan_id',$plan_id)->where('a2_id',$user_id)->where('a2_action','Approval')->where('is_active',1)->findAll();
- if(count($a2))
- {
- $hasRejectReason = !empty(array_filter($a2, fn($row) => !empty($row['a2_reject_reason'])));
- $a2ApproveSum = array_sum(array_column($a2, 'is_a2_action_done'));
- $a2ApproveCount = count($a2);
-
- if($a2ApproveSum == $a2ApproveCount)
- {
- return 'Approved';
- }else if($hasRejectReason){
- return 'Rejected';
- }else{
- return 'Approval pending';
- }
- }
-
- $a3 = $planStatusModel->where('plan_id',$plan_id)->where('a3_id',$user_id)->where('a3_action','Approval')->where('is_active',1)->findAll();
- if(count($a3))
- {
- $hasRejectReason = !empty(array_filter($a3, fn($row) => !empty($row['a3_reject_reason'])));
- $a3ApproveSum = array_sum(array_column($a3, 'is_a3_action_done'));
- $a3ApproveCount = count($a3);
-
- if($a3ApproveSum == $a3ApproveCount)
- {
- return 'Approved';
- }else if($hasRejectReason){
- return 'Rejected';
- }else{
- return 'Approval pending';
- }
- }
-
- $a4 = $planStatusModel->where('plan_id',$plan_id)->where('a4_id',$user_id)->where('a4_action','Approval')->where('is_active',1)->findAll();
- if(count($a4))
- {
- $hasRejectReason = !empty(array_filter($a4, fn($row) => !empty($row['a4_reject_reason'])));
- $a4ApproveSum = array_sum(array_column($a4, 'is_a4_action_done'));
- $a4ApproveCount = count($a4);
-
- if($a4ApproveSum == $a4ApproveCount)
- {
- return 'Approved';
- }else if($hasRejectReason){
- return 'Rejected';
- }else{
- return 'Approval pending';
- }
- }
-
- }
-}
-
diff --git a/app/Models/ClaimModel.php b/app/Models/ClaimModel.php
new file mode 100644
index 0000000..c00e6ff
--- /dev/null
+++ b/app/Models/ClaimModel.php
@@ -0,0 +1,42 @@
+