diff --git a/app/Config/Routes.php b/app/Config/Routes.php index c110322..798f021 100755 --- a/app/Config/Routes.php +++ b/app/Config/Routes.php @@ -34,6 +34,8 @@ $routes->group('api', ['filter' => 'appSignature'], function ($routes) { $routes->get('master/getRoleMaster', 'MasterController::getRoleMaster'); $routes->get('master/getVehicleTypeMaster', 'MasterController::getVehicleTypeMaster'); $routes->get('master/getInsurancePlanTypeMaster', 'MasterController::getInsurancePlanTypeMaster'); + $routes->get('master/getClaimMaster', 'MasterController::getClaimMaster'); + $routes->get('master/getEndorsementMaster', 'MasterController::getEndorsementMaster'); $routes->get('master/getInsurersMaster', 'MasterController::getInsurersMaster'); $routes->get('master/getStaffMaster', 'MasterController::getStaffMaster'); @@ -66,6 +68,22 @@ $routes->group('api', ['filter' => 'appSignature'], function ($routes) { $routes->post('enquiry/updateEnquiry', 'EnquiryController::updateEnquiry'); $routes->get('enquiry/downloadEnquiryFile', 'EnquiryController::downloadEnquiryFile'); + //Quotation + $routes->get('quotation/quotationList', 'QuotationController::quotationList'); + $routes->get('quotation/findQuotation', 'QuotationController::findQuotation'); + $routes->post('quotation/createQuotation', 'QuotationController::createQuotation'); + $routes->post('quotation/updateQuotation', 'QuotationController::updateQuotation'); + $routes->post('quotation/acceptOrRejectQuotation', 'QuotationController::acceptOrRejectQuotation'); + $routes->get('quotation/downloadAdditionalUploadedFile', 'QuotationController::downloadAdditionalUploadedFile'); + + + //policy + $routes->get('policy/policyList', 'PolicyController::policyList'); + $routes->get('policy/findPolicy', 'PolicyController::findPolicy'); + $routes->post('policy/createPolicy', 'PolicyController::createPolicy'); + $routes->post('policy/updatePolicy', 'PolicyController::updatePolicy'); + $routes->get('policy/downloadPolicyFile', 'PolicyController::downloadPolicyFile'); + }); diff --git a/app/Controllers/EnquiryController.php b/app/Controllers/EnquiryController.php index a67670f..a878fc0 100644 --- a/app/Controllers/EnquiryController.php +++ b/app/Controllers/EnquiryController.php @@ -11,6 +11,7 @@ use App\Models\PolicyModel; class EnquiryController extends ResourceController { + protected $db; protected $enquiryModel; protected $AgentModel; protected $QuotationModel; @@ -18,10 +19,12 @@ class EnquiryController extends ResourceController public function __construct() { + + $this->db = db_connect(); $this->enquiryModel = new EnquiryModel(); $this->AgentModel = new AgentModel(); - $this->enquiryModel = new QuotationModel(); - $this->AgentModel = new PolicyModel(); + $this->QuotationModel = new QuotationModel(); + $this->PolicyModel = new PolicyModel(); } // List all enquiries @@ -60,15 +63,42 @@ class EnquiryController extends ResourceController $enquiry_id = $this->request->getGet('enquiry_id'); - - - return $this->respond(['status' => 'success', 'code' => 200, 'data' => []], 200); - + if (!$enquiry_id) { + return $this->respond(['status' => 'failed','code' => 400,'data' => 'enquiry_id is required'], 200); + } + + //Get enquiry details + $enquiry = $this->enquiryModel->where('id', $enquiry_id)->where('is_active', 1)->first(); + + if (!$enquiry) { + return $this->respond(['status' => 'failed','code' => 404,'data' => 'Enquiry not found'], 200); + } + + //Get related quotations + $quotations = $this->QuotationModel->where('enquiry_id', $enquiry_id)->where('is_active', 1)->orderBy('id', 'DESC')->findAll(); + + //Get related policies + $policies = []; + if (!empty($quotations)) { + $quotationIds = array_column($quotations, 'id'); + $policies = $this->PolicyModel->whereIn('quotation_id', $quotationIds)->where('is_active', 1)->findAll(); + } + + // Final response + $data = [ + 'enquiry' => $enquiry, + 'quotations' => $quotations, + 'policies' => $policies + ]; + + return $this->respond(['status' => 'success','code' => 200,'data' => $data], 200); + } catch (\Exception $e) { - return $this->respond(['status' => 'failed', 'code' => 500, 'error' => $e->getMessage()], 500); + return $this->respond(['status' => 'failed','code' => 500,'error' => $e->getMessage()], 500); } } + // CREATE enquiry public function createEnquiry() { @@ -108,11 +138,19 @@ class EnquiryController extends ResourceController $previousPolicy->move($uploadPath, $previousPolicyFileName); } + //get insurer_branch_id + $query = $this->db->query("SELECT id FROM insurer_branch WHERE insurer_id = ? LIMIT 1", [$data['insurer_id']]); + $insurerBranchresult = $query->getRowArray(); + $insertData = [ 'agent_id' => $data['agent_id'], + 'name' => $data['name'], + 'mobile' => $data['mobile'], + 'email' => $data['email'], 'reg_no' => $data['reg_no'], 'vehicle_type_id' => $data['vehicle_type_id'], 'insurer_id' => $data['insurer_id'], + 'insurer_branch_id' => $insurerBranchresult['id'] ?? null, 'rc_file_name' => $rcFileName, 'id_proof_file_name' => $idProofFileName, 'previous_policy_file_name' => $previousPolicyFileName, @@ -147,13 +185,21 @@ class EnquiryController extends ResourceController return $this->respond(['status' => 'failed', 'code' => 200, 'error' => 'Data Not Found'], 200); } + //get insurer_branch_id + $query = $this->db->query("SELECT id FROM insurer_branch WHERE insurer_id = ? LIMIT 1", [$data['insurer_id']]); + $insurerBranchresult = $query->getRowArray(); + $updateData = [ - 'agent_id' => $data['agent_id'] ?? $enquiry['agent_id'], - 'reg_no' => $data['reg_no'] ?? $enquiry['reg_no'], - 'vehicle_type_id' => $data['vehicle_type_id'] ?? $enquiry['vehicle_type_id'], - 'insurer_id' => $data['insurer_id'] ?? $enquiry['insurer_id'], - 'remarks' => $data['remarks'] ?? $enquiry['remarks'], - 'updated_by' => $data['updated_by'] ?? null, + 'agent_id' => $data['agent_id'] ?? $enquiry['agent_id'], + 'name' => $data['name'] ?? $enquiry['name'], + 'mobile' => $data['mobile'] ?? $enquiry['mobile'], + 'email' => $data['email'] ?? $enquiry['email'], + 'reg_no' => $data['reg_no'] ?? $enquiry['reg_no'], + 'vehicle_type_id' => $data['vehicle_type_id'] ?? $enquiry['vehicle_type_id'], + 'insurer_id' => $data['insurer_id'] ?? $enquiry['insurer_id'], + 'insurer_branch_id' => $insurerBranchresult['id'] ?? $enquiry['insurer_branch_id'], + 'remarks' => $data['remarks'] ?? $enquiry['remarks'], + 'updated_by' => $data['updated_by'] ?? null, ]; // File updates diff --git a/app/Controllers/MasterController.php b/app/Controllers/MasterController.php index 1af2405..a06f7f2 100644 --- a/app/Controllers/MasterController.php +++ b/app/Controllers/MasterController.php @@ -6,6 +6,8 @@ use CodeIgniter\RESTful\ResourceController; use App\Models\RoleMasterModel; use App\Models\VehicleTypeMasterModel; use App\Models\InsurancePlanTypeMasterModel; +use App\Models\ClaimTypeModel; +use App\Models\EndorsementTypeModel; use App\Models\InsurersModel; use App\Models\StaffModel; @@ -17,6 +19,8 @@ class MasterController extends ResourceController protected $RoleMasterModel; protected $VehicleTypeMasterModel; protected $InsurancePlanTypeMasterModel; + protected $ClaimTypeModel; + protected $EndorsementTypeModel; protected $InsurersModel; protected $StaffModel; @@ -27,6 +31,8 @@ class MasterController extends ResourceController $this->RoleMasterModel = new RoleMasterModel(); $this->VehicleTypeMasterModel = new VehicleTypeMasterModel(); $this->InsurancePlanTypeMasterModel = new InsurancePlanTypeMasterModel(); + $this->ClaimTypeModel = new ClaimTypeModel(); + $this->EndorsementTypeModel = new EndorsementTypeModel(); $this->InsurersModel = new InsurersModel(); $this->StaffModel = new StaffModel(); @@ -72,6 +78,28 @@ class MasterController extends ResourceController return $this->respond(['status' => 200,'message' => 'success','data' => $data]); } + public function getClaimMaster() + { + $data = $this->ClaimTypeModel->select('id,claim_type')->where('is_active',1)->findAll(); + + if (!$data) { + return $this->failNotFound('No data found'); + } + + return $this->respond(['status' => 200,'message' => 'success','data' => $data]); + } + + public function getEndorsementMaster() + { + $data = $this->EndorsementTypeModel->select('id,endorsement_type')->where('is_active',1)->findAll(); + + if (!$data) { + return $this->failNotFound('No data found'); + } + + return $this->respond(['status' => 200,'message' => 'success','data' => $data]); + } + public function getInsurersMaster() { $data = $this->InsurersModel->select('id,name')->where('is_active',1)->findAll(); diff --git a/app/Controllers/PolicyController.php b/app/Controllers/PolicyController.php index ad7f3d2..3e2d4ba 100644 --- a/app/Controllers/PolicyController.php +++ b/app/Controllers/PolicyController.php @@ -3,21 +3,30 @@ namespace App\Controllers; use CodeIgniter\RESTful\ResourceController; use App\Models\PolicyModel; +use App\Models\EnquiryModel; +use App\Models\QuotationModel; class PolicyController extends ResourceController { protected $PolicyModel; + protected $QuotationModel; + protected $EnquiryModel; public function __construct() { $this->PolicyModel = new PolicyModel(); + $this->QuotationModel = new QuotationModel(); + $this->EnquiryModel = new EnquiryModel(); } // List policies public function policyList() { try { - $data = $this->PolicyModel->findAll(); + $manager_id = $this->request->getGet('manager_id'); + + $data = $this->PolicyModel ->where('manager_id',$manager_id)->findAll(); + return $this->respond(['status' => 'success', 'code' => 200, 'data' => $data], 200); } catch (\Exception $e) { return $this->respond(['status' => 'failed', 'code' => 500, 'data' => $e->getMessage()], 500); @@ -31,6 +40,10 @@ class PolicyController extends ResourceController $id = $this->request->getGet('id'); $record = $this->PolicyModel->find($id); + $record['issued_date'] = format_date_for_client($record['issued_date']); + $record['start_date'] = format_date_for_client($record['start_date']); + $record['end_date'] = format_date_for_client($record['end_date']); + if (!$record) { return $this->respond(['status' => 'failed', 'code' => 404, 'data' => []], 200); } @@ -74,18 +87,51 @@ class PolicyController extends ResourceController $policyReceipt->move($receiptPath, $receiptFileName); } + //fetch enquiry_id & agent_id + $quotData = $this->QuotationModel->select('partner_quotation.*,E.agent_id') + ->join('partner_enquiry E', 'E.id = partner_quotation.enquiry_id', 'left') + ->where('partner_quotation.id',$data['quotation_id']) + ->first(); + $insertData = [ + 'enquiry_id' => $quotData['enquiry_id'], 'quotation_id' => $data['quotation_id'], 'insured_name' => $data['insured_name'], + 'issued_date' => format_date_for_database($data['issued_date']), + 'start_date' => format_date_for_database($data['start_date']), + 'end_date' => format_date_for_database($data['end_date']), 'premium_amount' => $data['premium_amount'], 'policy_number' => $data['policy_number'], 'payment_mode' => $data['payment_mode'], + 'manager_id' => $data['manager_id'], + 'agent_id' => $quotData['agent_id'], 'policy_pdf_file_name' => $pdfFileName, 'policy_payment_receipt_file_name' => $receiptFileName, - 'created_by' => $data['created_by'] ?? null + 'created_by' => $data['created_by'] ]; + $this->PolicyModel->insert($insertData); + $policyId = $this->PolicyModel->getInsertID(); + + //update enquiry status + $quotationData = $this->QuotationModel->where('id',$data['quotation_id'])->first(); + if (!empty($quotationData)){ + $this->EnquiryModel->update($quotationData['enquiry_id'], ['status'=> 'Policy Created' ]); + } + + // Call helper to create BDS record after creating client,clientPolicy,vehicle records + $policyData = $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.id',$policyId) + ->first(); + $bdsLogs = createBDS($policyData, $policyId); + if (!empty($bdsLogs)) { + foreach ($bdsLogs as $msg) { + log_message('info', '[BDS Entry] ' . $msg); + } + } return $this->respond(['status' => 'success', 'code' => 200, 'data' => []], 200); @@ -112,6 +158,9 @@ class PolicyController extends ResourceController $updateData = [ 'quotation_id' => $data['quotation_id'] ?? $policy['quotation_id'], 'insured_name' => $data['insured_name'] ?? $policy['insured_name'], + 'issued_date' => format_date_for_database($data['issued_date']), + 'start_date' => format_date_for_database($data['start_date']), + 'end_date' => format_date_for_database($data['end_date']), 'premium_amount' => $data['premium_amount'] ?? $policy['premium_amount'], 'policy_number' => $data['policy_number'] ?? $policy['policy_number'], 'payment_mode' => $data['payment_mode'] ?? $policy['payment_mode'], @@ -153,27 +202,52 @@ class PolicyController extends ResourceController } } - // Active / Deactive policy - public function toggleActiveStatus() + // Download policy file + public function downloadPolicyFile() { try { - $id = $this->request->getPost('id'); - if (!$id) { - return $this->respond(['status' => 'failed', 'code' => 200, 'data' => 'ID Required'], 200); + $policyId = $this->request->getGet('policy_id'); + $fileType = $this->request->getGet('file_type'); // policy_pdf , policy_payment_receipt + + if (!$policyId || !$fileType) { + return $this->respond(['status' => 'failed','code' => 400,'data' => 'policy_id and file_type are required'], 200); } - $policy = $this->PolicyModel->find($id); - if (!$policy) { - return $this->respond(['status' => 'failed', 'code' => 200, 'data' => 'Data Not Found'], 200); + // Map file_type to DB column and folder + $fileMap = [ + 'policy_pdf' => ['column' => 'policy_pdf_file_name', 'folder' => 'policy_pdf'], + 'policy_payment_receipt'=> ['column' => 'policy_payment_receipt_file_name', 'folder' => 'policy_payment_receipt'], + ]; + + if (!array_key_exists($fileType, $fileMap)) { + return $this->respond(['status' => 'failed','code' => 400,'data' => 'Invalid file_type'], 200); } - $newStatus = ($policy['is_active'] == 1) ? 0 : 1; - $this->PolicyModel->update($id, ['is_active' => $newStatus]); + $fileColumn = $fileMap[$fileType]['column']; + $folder = $fileMap[$fileType]['folder']; - return $this->respond(['status' => 'success', 'code' => 200, 'data' => ['is_active' => $newStatus]], 200); + // Fetch record from DB + $fileRecord = $this->PolicyModel->where('is_active', 1)->find($policyId); + + if (!$fileRecord || empty($fileRecord[$fileColumn])) { + return $this->respond([ 'status' => 'failed','code' => 404,'data' => 'File not found in database'], 200); + } + + $filePath = WRITEPATH . "uploads/policy/{$folder}/" . $fileRecord[$fileColumn]; + + if (!file_exists($filePath)) { + return $this->respond(['status' => 'failed','code' => 404,'data' => 'File missing on server'], 200); + } + + // Force file download + return $this->response->download($filePath, null); } catch (\Exception $e) { - return $this->respond(['status' => 'failed', 'code' => 500, 'data' => $e->getMessage()], 500); + return $this->respond(['status' => 'failed','code' => 500,'message' => $e->getMessage() ], 500); } } + + + + } diff --git a/app/Controllers/QuotationController.php b/app/Controllers/QuotationController.php index f8512c3..13437aa 100644 --- a/app/Controllers/QuotationController.php +++ b/app/Controllers/QuotationController.php @@ -3,21 +3,31 @@ namespace App\Controllers; use CodeIgniter\RESTful\ResourceController; use App\Models\QuotationModel; +use App\Models\EnquiryModel; class QuotationController extends ResourceController { protected $QuotationModel; + protected $EnquiryModel; public function __construct() { $this->QuotationModel = new QuotationModel(); + $this->EnquiryModel = new EnquiryModel(); } // List quotations public function quotationList() { try { - $data = $this->QuotationModel->findAll(); + + $manager_id = $this->request->getGet('manager_id'); + + $data = $this->QuotationModel->select('partner_quotation.* , IT.insurance_plan_type') + ->join('partner_insurance_plan_type_master IT', 'IT.id = partner_quotation.insurance_plan_type_id', 'left') + ->where('partner_quotation.manager_id',$manager_id) + ->findAll(); + return $this->respond(['status' => 'success', 'code' => 200, 'data' => $data], 200); } catch (\Exception $e) { return $this->respond(['status' => 'failed', 'code' => 500, 'data' => $e->getMessage()], 500); @@ -65,11 +75,16 @@ class QuotationController extends ResourceController 'premium_amount' => $data['premium_amount'], 'insurance_plan_type_id' => $data['insurance_plan_type_id'], 'additional_uploaded_file_name' => $uploadedFileName, - 'created_by' => $data['created_by'] ?? null + 'created_by' => $data['created_by'], + 'manager_id' => $data['manager_id'] ]; $this->QuotationModel->insert($insertData); + //update enquiry status + $enquiryData = $this->EnquiryModel->where('id',$data['enquiry_id'])->where('status','Awaiting Quotation')->first(); + if (!empty($enquiryData)){ $this->EnquiryModel->update($data['enquiry_id'], ['status'=>'Quotation Created']); } + return $this->respond(['status' => 'success', 'code' => 200, 'data' => []], 200); } catch (\Exception $e) { @@ -123,27 +138,77 @@ class QuotationController extends ResourceController } } - // Active / Deactive quotation - public function toggleActiveStatus() + // Quotation status update + public function acceptOrRejectQuotation() { try { - $id = $this->request->getPost('id'); - if (!$id) { + $data = $this->request->getJSON(true); + if (!isset($data['id'])) { return $this->respond(['status' => 'failed', 'code' => 200, 'data' => 'ID Required'], 200); } + $id = $data['id']; + $quotation = $this->QuotationModel->find($id); if (!$quotation) { return $this->respond(['status' => 'failed', 'code' => 200, 'data' => 'Data Not Found'], 200); } - $newStatus = ($quotation['is_active'] == 1) ? 0 : 1; - $this->QuotationModel->update($id, ['is_active' => $newStatus]); + $newStatus = $data['status']; - return $this->respond(['status' => 'success', 'code' => 200, 'data' => ['is_active' => $newStatus]], 200); + $this->QuotationModel->update($id, ['status' => $newStatus]); + + //update enquiry status + $enquiryData = $this->EnquiryModel->where('id',$quotation['enquiry_id'])->where('status','Quotation Created')->first(); + $enqStatus = 'Quotation '.$data['status']; + if (!empty($enquiryData)){ + $this->EnquiryModel->update($data['enquiry_id'], ['status'=> $enqStatus]); + if( $newStatus == 'Accepted'){ + $this->QuotationModel + ->where('enquiry_id', $quotation['enquiry_id']) + ->where('id !=', $id) + ->set(['status' => 'Rejected', 'updated_on' => date('Y-m-d H:i:s')]) + ->update(); + } + } + + + + return $this->respond(['status' => 'success', 'code' => 200, 'data' => 'Updated Successfully'], 200); } catch (\Exception $e) { return $this->respond(['status' => 'failed', 'code' => 500, 'data' => $e->getMessage()], 500); } } + + // Download additional file + public function downloadAdditionalUploadedFile() + { + try { + $id = $this->request->getGet('id'); + + if (!$id) { + return $this->respond(['status' => 'failed', 'code' => 400, 'data' => 'ID is required'], 200); + } + + // Fetch record from DB + $fileRecord = $this->QuotationModel->where('is_active',1)->find($id); + + if (!$fileRecord) { + return $this->respond(['status' => 'failed', 'code' => 404, 'data' => 'File not found'], 200); + } + + $filePath = WRITEPATH . 'uploads/quotation/' . $fileRecord['incentive_file_name']; + + if (!file_exists($filePath)) { + return $this->respond(['status' => 'failed', 'code' => 404, 'data' => 'File missing on server'], 200); + } + + // Force file download + return $this->response->download($filePath, null); + + } catch (\Exception $e) { + return $this->respond(['status' => 'failed', 'code' => 500, 'message' => $e->getMessage()], 500); + } + } } diff --git a/app/Helpers/common_helper.php b/app/Helpers/common_helper.php index 92c426d..dccbf3a 100644 --- a/app/Helpers/common_helper.php +++ b/app/Helpers/common_helper.php @@ -1,375 +1,295 @@ where('email', $email)->first(); + $enquiryModel = new EnquiryModel(); + $quotationModel = new QuotationModel(); + $policyModel = new PolicyModel(); + $clientModel = new ClientModel(); + $clientPolicyModel = new ClientPolicyModel(); + $policyTransactionModel = new PolicyTransactionModel(); + $ptCoShareDetailsModel = new PtCoShareDetailsModel(); + $vehicleModel = new VehicleModel(); - return $user ? $user : false; - } -} + $log = []; // collect logs -if (!function_exists('checkUserExist')) { - function checkUserExist($first_name, $email) - { - $userModel = new UserModel(); + // 1. Create or fetch client + $client = $clientModel->where([ + 'client_name' => $policyData['client_name'], + 'phone' => $policyData['client_mobile'], + 'email' => $policyData['client_email'] + ])->first(); - // Check if email already exists - $user = $userModel->where('email', $email)->first(); - if ($user) { - return ['status' => true,'data' => $user ,'message' => 'User already exists']; + if ($client) { + $clientId = $client['id']; + $log[] = "Existing client found (ID: {$clientId})"; + } else { + $clientData = [ + 'client_type' => 2, + 'client_name' => $policyData['client_name'], + 'short_name' => $policyData['client_name'], + 'phone' => $policyData['client_mobile'], + 'email' => $policyData['client_email'], + 'created_by' => $policyData['created_by'] + ]; + $clientId = $clientModel->insert($clientData, true); + $log[] = "New client created (ID: {$clientId})"; } - // Insert new user - $userId = $userModel->insert([ - 'first_name' => $first_name, - 'email' => $email, - 'org_id' => env('ORG_id') + // 2. Create or fetch client policy + $clientPolicy = $clientPolicyModel->where([ + 'client_id' => $clientId, + 'policy_id' => $policyId, + 'policy_no' => $policyData['policy_number'] + ])->first(); + + if ($clientPolicy) { + $clientPolicyId = $clientPolicy['id']; + $log[] = "Existing client policy found (ID: {$clientPolicyId})"; + } else { + $clientPolicyData = [ + 'client_id' => $clientId, + 'policy_id' => $policyId, + 'policy_type_id' => 8, + 'insurer_id' => $policyData['insurer_id'], + 'insurer_branch_id' => $policyData['insurer_branch_id'], + 'policy_start_date' => $policyData['start_date'], + 'policy_end_date' => $policyData['end_date'], + 'policy_no' => $policyData['policy_number'] + ]; + $clientPolicyId = $clientPolicyModel->insert($clientPolicyData, true); + $log[] = "New client policy created (ID: {$clientPolicyId})"; + } + + // 3. Create or fetch vehicle + $vehicle = $vehicleModel->where([ + 'vehicle_no' => $policyData['reg_no'], + 'owner' => $clientId + ])->first(); + + if ($vehicle) { + $vehicleId = $vehicle['id']; + $log[] = "Existing vehicle found (ID: {$vehicleId})"; + } else { + $vehicleData = [ + 'vehicle_no' => $policyData['reg_no'], + 'type' => $policyData['vehicle_type_id'], + 'description' => 'Motor Vehicle', + 'owner' => $clientId, + 'rc' => $policyData['reg_no'], + 'created_by' => $policyData['created_by'] + ]; + $vehicleId = $vehicleModel->insert($vehicleData, true); + $log[] = "New vehicle created (ID: {$vehicleId})"; + } + + // 4. Always create policy transaction + $policyTransactionData = [ + 'issuer' => 2, + 'issue_type' => 1, + 'client_id' => $clientId, + 'policy_type_id' => 8, + 'client_policy_id' => $clientPolicyId, + 'insurer_id' => $policyData['insurer_id'], + 'insurer_branch_id' => $policyData['insurer_branch_id'], + 'vehicle_id' => $vehicleId, + 'policy_no' => $policyData['policy_number'], + 'policy_issue_date' => $policyData['issued_date'], + 'month' => $policyData['issued_date'], + 'policy_start_date' => $policyData['start_date'], + 'policy_end_date' => $policyData['end_date'], + 'endorsement_no' => null, + 'action_type' => 'inception', + 'revenue_type' => "NA", + 'status' => 'completed', + 'policy_holder_name' => $policyData['insured_name'], + 'ct_type' => 1, + 'sales_generated_by' => null, + 'serviced_by' => null, + 'policy_with_corr' => 0, + 'is_active' => 1, + 'ref' => null, + 'co_share' => 0, + 'endorse_eff_date' => null, + 'pre_payable_by' => 1, + 'bro_payable_by' => 1, + ]; + $policyTransactionId = $policyTransactionModel->insert($policyTransactionData, true); + $log[] = "Policy transaction created (ID: {$policyTransactionId})"; + + // 5. Always create pt co-share details + $ptCoShareDetails = [ + 'pt_id' => $policyTransactionId, + 'insurer_id' => $policyData['insurer_id'], + 'insurer_branch_id' => $policyData['insurer_branch_id'], + 'co_share_type' => 1, + 'co_share_per' => 100, + 'bp_amt' => $policyData['premium_amount'], + 'cop_amt' => $policyData['premium_amount'], + ]; + $ptCoShareId = $ptCoShareDetailsModel->insert($ptCoShareDetails, true); + $log[] = "PT Co-Share details created (ID: {$ptCoShareId})"; + + // 6. Update policy with IDs + $policyModel->update($policyId, [ + 'client_id' => $clientId, + 'client_policy_id' => $clientPolicyId, + 'vehicle_id' => $vehicleId, + 'policy_transaction_id' => $policyTransactionId, + 'pt_oc_share_details_id'=> $ptCoShareId, + 'updated_by' => $policyData['created_by'], + 'updated_on' => date('Y-m-d H:i:s') ]); + $log[] = "Policy updated with references (Policy ID: {$policyId})"; - if($userId){ - $user = $userModel->where('user_id', $userId)->first(); - return ['status' => true,'data' => $user ,'message' => 'User created successfully']; - }else{ - return ['status' => false, 'message' => 'Something wend wrong']; - } - - + return $log; // return logs for debugging } + + + + // function createClientAndVehicle(array $policyData, int $policyId) + // { + // $enquiryModel = new EnquiryModel(); + // $quotationModel = new QuotationModel(); + // $policyModel = new PolicyModel(); + // $clientModel = new ClientModel(); + // $clientPolicyModel = new ClientPolicyModel(); + // $policyTransactionModel = new PolicyTransactionModel(); + // $ptCoShareDetailsModel = new PtCoShareDetailsModel(); + // $vehicleModel = new VehicleModel(); + + // // 1. Create client + // $clientData = [ + // 'client_type' => 2, + // 'client_name' => $policyData['client_name'], + // 'short_name' => $policyData['client_name'], + // 'phone' => $policyData['client_mobile'], + // 'email' => $policyData['client_email'], + // 'created_by' => $policyData['created_by'] + // ]; + // $clientId = $clientModel->insert($clientData, true); // returns insert ID + + // // 2. Create client policy + // $clientPolicyData = [ + // 'client_id' => $clientId, + // 'policy_id' => $policyData['id'], + // 'policy_type_id' => 8, + // 'insurer_id' => $policyData['insurer_id'], + // 'insurer_branch_id'=> $policyData['insurer_branch_id'], + // 'policy_start_date'=> $policyData['start_date'], + // 'policy_end_date' => $policyData['end_date'], + // 'policy_no' => $policyData['policy_number'] + // ]; + // $clientPolicyId = $clientPolicyModel->insert($clientPolicyData, true); // returns insert ID + + // // 3. Create vehicle + // $vehicleData = [ + // 'vehicle_no' => $policyData['reg_no'], + // 'type' => $policyData['vehicle_type_id'], + // 'description' => 'Motor Vehicle', + // 'owner' => $clientId, + // 'rc' => $policyData['reg_no'], + // 'created_by' => $policyData['created_by'] + // ]; + // $vehicleId = $vehicleModel->insert($vehicleData, true); + + + // // 4. Create policy transaction + // $policyTransactionData = [ + + // 'issuer' => 2, + // 'issue_type' => 1, + // 'client_id' => $clientId ?? null, + // 'policy_type_id' => 8 , + // 'client_policy_id' => $clientPolicyId ?? null, + // 'insurer_id' => $policyData['insurer_id'] ?? null, + // 'insurer_branch_id' => $policyData['insurer_branch_id'], + // 'vehicle_id' => $vehicleId ?? null, + // 'policy_no' => $policyData['policy_number'] ?? null, + // 'policy_issue_date' => $policyData['issued_date'], + // 'month' => $policyData['issued_date'], // policy_issue_month + // 'policy_start_date' => $policyData['start_date'], + // 'policy_end_date' => $policyData['end_date'], + // 'endorsement_no' => null, + // 'action_type' => 'inception', + // 'revenue_type' => "NA" ?? null, + // 'status' => 'completed', + // 'policy_holder_name' => $policyData['insured_name'], // insured name + // 'ct_type' => 1, + // 'sales_generated_by' => null, // ask this doubt + // 'serviced_by' => null, // ask this doubt + // 'policy_with_corr' => 0, + // 'is_active' => 1, + // 'ref' => null, + // 'co_share' => 0, + // 'endorse_eff_date' => null, + // 'pre_payable_by' => 1, + // 'bro_payable_by' => 1, + // ]; + // $policyTransactionId = $policyTransactionModel->insert($policyTransactionData, true); + + + // // 5. Create pt co share details + // $pt_co_share_details = [ + + // 'pt_id' => $policyTransactionId, + // 'insurer_id' => $policyData['insurer_id'], + // 'insurer_branch_id' => $policyData['insurer_branch_id'], + // 'co_share_type' => 1, + // 'co_share_per' => 100, + // 'bp_amt' => $policyData['premium_amount'], // premium amt + // 'cop_amt' => $policyData['premium_amount'], // premium amt + + // ]; + // $ptCoShareId = $ptCoShareDetailsModel->insert($vehicleData, true); + + + + + + // // Finally Update policy with client_id & vehicle_id + // $policyModel->update($policyId, [ + // 'client_id' => $clientId, + // 'client_policy_id' => $clientPolicyId, + // 'vehicle_id' => $vehicleId, + // 'policy_transaction_id' => $policyTransactionId, + // 'pt_oc_share_details_id'=> $ptCoShareId, + // 'updated_by' => $policyData['created_by'], + // 'updated_on' => date('Y-m-d H:i:s') + // ]); + // } } -if (!function_exists('getUserPlanCreationRestrictionStatus')) { - function getUserPlanCreationRestrictionStatus($user) + + +if (!function_exists('format_date_for_database')) { + /** + * Converts a date from 'd-m-Y' to 'Y-m-d'. + * + * @param string $date + * @return string|null + */ + function format_date_for_database(string $date): ?string { - if($user['group_id'] != null) - { - $groupModel = new GroupModel(); - $groupData = $groupModel->find($user['group_id']); - if($groupData) - { - $domesticPolicyId = $groupData['domestic_policy_id']; - $internationalPolicyId = $groupData['international_policy_id']; - $policyDetailsModel = new PolicyDetailsModel(); - - if($domesticPolicyId != null && $internationalPolicyId != null) - { - $domesticPolicy = $policyDetailsModel->where('policy_id',$domesticPolicyId)->where('service_id', 1)->find(); - $domesticCheck = checkApproverSetOrNotBasedOnPolicy($domesticPolicy,$user); - $internationalPolicy = $policyDetailsModel->where('policy_id',$internationalPolicyId)->where('service_id', 1)->find(); - $internationalCheck = checkApproverSetOrNotBasedOnPolicy($internationalPolicy,$user); - - if($domesticCheck == true && $internationalCheck == true) - return 'Both Type Plan Creation Allowed'; - else - return 'Plan Creation Not Allowed'; - - } - else if($domesticPolicyId != null) - { - $domesticPolicy = $policyDetailsModel->where('policy_id',$domesticPolicyId)->where('service_id', 1)->find(); - $check = checkApproverSetOrNotBasedOnPolicy($domesticPolicy,$user); - $internationalPolicy = $policyDetailsModel->where('policy_id',$domesticPolicyId)->where('service_id', 1)->find(); - $check = checkApproverSetOrNotBasedOnPolicy($internationalPolicy,$user); - - if($check == true) - return 'Only Domestic Plan Creation Allowed'; - else - return 'Plan Creation Not Allowed'; - - } - else if($internationalPolicyId != null) - { - - $internationalPolicy = $policyDetailsModel->where('policy_id',$internationalPolicyId)->where('service_id', 1)->find(); - $check = checkApproverSetOrNotBasedOnPolicy($internationalPolicy,$user); - - if($check == true) - return 'Only International Plan Creation Allowed'; - else - return 'Plan Creation Not Allowed'; - - } - - - }else{ - return 'Plan Creation Not Allowed'; - } - - }else{ - return 'Plan Creation Not Allowed'; - } - - - } -} - -function checkApproverSetOrNotBasedOnPolicy($Policy,$user) -{ - // Step 1: Determine required approver levels (a1 to a4) - $requiredApprovers = []; - - foreach (['', '_exceptional', '_amendment'] as $type) { - for ($i = 1; $i <= 4; $i++) { - $key = "a{$i}{$type}_action"; - if (isset($Policy[0][$key]) && $Policy[0][$key] === 'Approval') { - $requiredApprovers[] = $i; // add level (1 to 4) - } - } - } - - // Remove duplicates (in case multiple types require same level) - $requiredApprovers = array_unique($requiredApprovers); - - // Step 2: Check user profile for each required approver level - $missingApprovers = []; - - foreach ($requiredApprovers as $level) { - $profileKey = match ($level) { - 1 => 'first_approver', - 2 => 'second_approver', - 3 => 'third_approver', - 4 => 'fourth_approver', - }; - - if (empty($user[$profileKey]) || $user[$profileKey] == 0) { - $missingApprovers[] = $profileKey; - } - } - - // Step 3: Final check - if (!empty($missingApprovers)) { - // One or more approvers missing - // echo "Missing approvers in user profile: " . implode(', ', $missingApprovers); - return false; - } else { - // echo "All required approvers are set in user profile."; - return true; - } - -} - -if (!function_exists('isDataChanged')) { - function isDataChanged($model, $id, array $newData): bool - { - // Step 1: Fetch old data from the model - $oldData = $model->where('plan_id', $id)->where('is_active', 1)->findAll(); - - if (!$oldData) { - return true; - } - - // Step 2: Define keys to exclude - $excludeKeys = ['created_by', 'updated_by', 'created_on', 'updated_on']; - - // Step 3: Clean both old and new data arrays - $cleanOldData = array_map(function($item) use ($excludeKeys) { - foreach ($excludeKeys as $key) { - unset($item[$key]); - } - return $item; - }, $oldData); - - $cleanNewData = array_map(function($item) use ($excludeKeys) { - foreach ($excludeKeys as $key) { - unset($item[$key]); - } - return $item; - }, $newData); - - - // Step 4: Compare count - if (count($cleanOldData) !== count($cleanNewData)) { - return true; - } - - // Step 5: Check if there's any difference - return $cleanOldData !== $cleanNewData; - } - -} - -if (!function_exists('isFlightTripDataChanged')) { - function isFlightTripDataChanged($model, $id, array $newData): bool - { - - $newTripData = []; - $flightIds = array_column($newData, 'flight_id'); - foreach ($newData as $key1 => $value1) { - foreach ($value1['trips'] as $key => $value) { - array_push($newTripData , $value); - } + $dt = DateTime::createFromFormat('d-m-Y', $date); + if ($dt) { + return $dt->format('Y-m-d'); } - // Step 1: Fetch old data from the model - if(!empty($flightIds)) - $oldData = $model->whereIn('flight_id', $flightIds)->where('is_active', 1)->findAll(); - else - $oldData = []; - - - if (!$oldData) { - return true; - } - - // Step 2: Define keys to exclude - $excludeKeys = ['created_by', 'updated_by', 'created_on', 'updated_on']; - - // Step 3: Clean both old and new data arrays - $cleanOldData = array_map(function($item) use ($excludeKeys) { - foreach ($excludeKeys as $key) { - unset($item[$key]); - } - return $item; - }, $oldData); - - $cleanNewData = array_map(function($item) use ($excludeKeys) { - foreach ($excludeKeys as $key) { - unset($item[$key]); - } - return $item; - }, $newTripData); - - - // Step 4: Compare count - if (count($cleanOldData) !== count($cleanNewData)) { - return true; - } - - // Step 5: Check if there's any difference - return $cleanOldData !== $cleanNewData; + return null; } - -} - -function getDelegatedPlans($org_id, $id) -{ - $userModel = new UserModel(); - $planModel = new PlanModel(); - $planStatusModel = new PlanStatusModel(); - $delegatedUsers = $userModel->where('delegated_to_user_id', $id) - ->where('is_active', 1) - ->where('delegation_start_date <=', date('Y-m-d')) - ->where('delegation_end_date >=', date('Y-m-d')) - ->findAll(); - $allPlanData = []; - foreach ($delegatedUsers as $user) { - - $userId = $user['user_id']; - $startDate = $user['delegation_start_date']; - $endDate = $user['delegation_end_date']; - - $a1Data = $planStatusModel->select('plan_id,a1_id as user_id') - ->where('a1_id',$userId) - ->where('a1_action','Approval') - ->where('created_on >=', $startDate) - ->where('created_on <=', $endDate) - ->where('is_active',1) - ->findAll(); - - $a2Data = $planStatusModel->select('plan_id,a2_id as user_id') - ->where('a2_id',$userId) - ->where('a2_action','Approval') - ->where('created_on >=', $startDate) - ->where('created_on <=', $endDate) - ->where('is_active',1) - ->findAll(); - - $a3Data = $planStatusModel->select('plan_id,a3_id as user_id') - ->where('a3_id',$userId) - ->where('a3_action','Approval') - ->where('is_active',1) - ->where('created_on >=', $startDate) - ->where('created_on <=', $endDate) - ->findAll(); - - $a4Data = $planStatusModel->select('plan_id,a4_id as user_id') - ->where('a4_id',$userId) - ->where('a4_action','Approval') - ->where('is_active',1) - ->where('created_on >=', $startDate) - ->where('created_on <=', $endDate) - ->findAll(); - - // Merge results (each record has plan_id + user_id) - $merged = array_merge($a1Data, $a2Data, $a3Data, $a4Data); - - // Merge into final array - $allPlanData = array_merge($allPlanData, $merged); - - } - - //get already approved data in delegated flow - // $a1 = $planStatusModel->select('plan_id,a1_id as user_id')->where('a1_action_done_by',$id)->where('a1_action','Approval')->where('is_active',1)->findAll(); - // $a2 = $planStatusModel->select('plan_id,a2_id as user_id')->where('a2_action_done_by',$id)->where('a2_action','Approval')->where('is_active',1)->findAll(); - // $a3 = $planStatusModel->select('plan_id,a3_id as user_id')->where('a3_action_done_by',$id)->where('a3_action','Approval')->where('is_active',1)->findAll(); - - //need to discuss with sir - // $mergedApprovedArray = array_merge($a1, $a2, $a3); - $mergedApprovedArray = []; - - // Merge into main list - $allPlanData = array_merge($allPlanData, $mergedApprovedArray); - - // Remove duplicate associative arrays - $allPlanData = array_map('unserialize', array_unique(array_map('serialize', $allPlanData))); - - $plansWithUser = []; - - foreach ($allPlanData as $item) { - $planId = $item['plan_id']; - $userId = $item['user_id']; - $userData = $userModel->where('user_id',$userId)->first(); - $userName = $userData['first_name'].' '.$userData['last_name']; - - $planData = $planModel->getActivePlan($org_id, 'PLAN', null , $planId); - - if ($planData) { - $planData['approver_id'] = $userId; - $planData['approver_name'] = $userName; - $planData['delegater_id'] = $id; - $planData['approver_status'] = getApproverCurrentAction( $planData['plan_id'], $userId ); - $plansWithUser[] = $planData; - } - } - - return $plansWithUser; - -} - -function normalize_date(string $date): ?string -{ - $date = trim($date); - - // If already valid Y-m-d (e.g., 2025-03-20), return it as-is - $yFormat = DateTime::createFromFormat('Y-m-d', $date); - if ($yFormat && $yFormat->format('Y-m-d') === $date) { - return $date; - } - - // Try to convert from d-m-Y (e.g., 20-03-2025) - $dFormat = DateTime::createFromFormat('d-m-Y', $date); - if ($dFormat) { - return $dFormat->format('Y-m-d'); - } - - // Try from d/m/Y (optional) - $slashFormat = DateTime::createFromFormat('d/m/Y', $date); - if ($slashFormat) { - return $slashFormat->format('Y-m-d'); - } - - // Unknown format - return null; } if (!function_exists('format_date_for_client')) { @@ -389,103 +309,3 @@ if (!function_exists('format_date_for_client')) { return null; } } - -if (!function_exists('isValidUploadedFile')) { - function isValidUploadedFile($file): bool - { - return $file && $file->isValid(); - } -} - -if (!function_exists('isAllowedExtension')) { - function isAllowedExtension($file, array $allowedExtensions = [] ): bool - { - $ext = strtolower($file->getClientExtension()); - - $result = in_array($ext, $allowedExtensions); - - $result = empty($allowedExtensions) ? true : $result ; - - return $result; - } -} - -if (!function_exists('isExcelNotEmpty')) { - function isExcelNotEmpty(array $sheetData): bool - { - return !empty($sheetData) && count($sheetData) >= 2; - } -} - -if(!function_exists('createDirectoryWith0777Permission')){ - - function createDirectoryWith0777Permission( $uploadDir) - { - if (!is_dir($uploadDir)) { - mkdir($uploadDir, 0777, true); // recursive creation with full permission - } - - } - -} - -function getAllowedClassForUser($trip_type,$user_id) -{ - - $userModel = new UserModel(); - $groupModel = new GroupModel(); - $policyDetailsModel = new PolicyDetailsModel(); - $policyDetailsModel = new PolicyDetailsModel(); - - $user = $userModel->where('user_id', $user_id)->first(); - $groupData = $groupModel->find($user['group_id']); - - if($groupData) - { - if($trip_type == 1) { $policyId = $groupData['domestic_policy_id'];}else{ $policyId = $groupData['international_policy_id'];} - if($policyId != null) - { - $allowedFlightClass = $policyDetailsModel->select('c_policy_details.class, m_dropdown.dropdown_value as allowed_class') - ->join('m_dropdown', 'dropdown_key = c_policy_details.class AND dropdown = "flight_class"', 'left') - ->where('policy_id',$policyId) - ->where('service_id',1) - ->first(); - $data['flight'] = $allowedFlightClass['allowed_class'] ?? []; - - $allowedTrainClass = $policyDetailsModel->select('c_policy_details.class, m_dropdown.dropdown_value as allowed_class') - ->join('m_dropdown', 'dropdown_key = c_policy_details.class AND dropdown = "train_class"', 'left') - ->where('policy_id',$policyId) - ->where('service_id',2) - ->first(); - $data['train'] = $allowedTrainClass['allowed_class'] ?? []; - - $allowedHotelClass = $policyDetailsModel->select('c_policy_details.class, m_dropdown.dropdown_value as allowed_class') - ->join('m_dropdown', 'dropdown_key = c_policy_details.class AND dropdown = "hotel_class"', 'left') - ->where('policy_id',$policyId) - ->where('service_id',5) - ->first(); - $data['hotel'] = $allowedHotelClass['allowed_class'] ?? []; - } - - - return $data; - - } - - - -} - - - - - - - - - - - - - - diff --git a/app/Models/ClaimTypeModel.php b/app/Models/ClaimTypeModel.php new file mode 100644 index 0000000..c2402e4 --- /dev/null +++ b/app/Models/ClaimTypeModel.php @@ -0,0 +1,27 @@ +join('partner_quotation Q', 'Q.enquiry_id = partner_enquiry.id AND Q.status = "Accepted"', 'left') ->join('partner_policy P', 'P.quotation_id = Q.id', 'left') ->where('partner_enquiry.is_active', 1) - ->orderBy('partner_enquiry.created_on', 'ASC') ; + ->orderBy('partner_enquiry.created_on', 'ASC'); if($getBy == 'ALL') diff --git a/app/Models/PolicyModel.php b/app/Models/PolicyModel.php index ac6b4a3..1866547 100644 --- a/app/Models/PolicyModel.php +++ b/app/Models/PolicyModel.php @@ -8,15 +8,25 @@ class PolicyModel extends Model protected $table = 'partner_policy'; protected $primaryKey = 'id'; protected $allowedFields = [ + 'enquiry_id', 'quotation_id', 'insured_name', 'premium_amount', 'policy_number', + 'issued_date', + 'start_date', + 'end_date', 'payment_mode', 'policy_pdf_file_name', 'policy_payment_receipt_file_name', 'is_active', + 'agent_id', 'manager_id', + 'client_id', + 'client_policy_id', + 'vehicle_id', + 'policy_transaction_id', + 'pt_oc_share_details_id', 'created_by', 'updated_by' ]; diff --git a/app/Models/PolicyTransactionModel.php b/app/Models/PolicyTransactionModel.php new file mode 100644 index 0000000..eb75b11 --- /dev/null +++ b/app/Models/PolicyTransactionModel.php @@ -0,0 +1,92 @@ +