FIX_MERGE_CONFLICT : RV

This commit is contained in:
VENKATESHWARAN 2024-09-11 17:23:07 +05:30
commit d6a7a7c485
10 changed files with 423 additions and 28 deletions

View File

@ -292,6 +292,8 @@ $routes->group("/util", ["filter" => "authMVC"], function ($routes) {
$routes->get("remove_co_share_data/(:any)", "PolicyTransactionController::removeCoShareData/$1");
$routes->get("check_cost_center/(:any)", "ClientController::check_cost_center/$1");
$routes->get("getPTCOShareCount/(:any)", "PolicyTransactionController::getPTCOShareCount/$1");
$routes->get("test_mail", "MasterController::testGmailAPI");
$routes->post("test_mail", "MasterController::testGmailAPI");
});
@ -321,6 +323,8 @@ $routes->cli('cli/processjob', 'JobWorker::processJob');
$routes->cli('cli/processjobs', 'JobWorker::processJobs');
$routes->cli('cli/enrollment_status', 'JobWorker::enrollment_status');
$routes->get("processjob", "JobWorker::processJob");
$routes->cli('cli/new_gmail_token', 'MasterController::generateNewGmailAPIToken');
$routes->cli('cli/send_mail_cli', 'MasterController::testGmailAPIViaCLI');

View File

@ -5,6 +5,7 @@ namespace Config;
use CodeIgniter\Config\BaseService;
use App\Libraries\Slug;
use App\Libraries\MyLogger;
use App\Libraries\GmailAPI;
use App\Libraries\DataServiceSqlite;
use App\Controllers\Home;
@ -60,5 +61,14 @@ class Services extends BaseService
return new DataServiceSqlite();
}
public static function gmailapi($getShared = true)
{
if ($getShared) {
return static::getSharedInstance('gmailapi');
}
return new GmailAPI();
}
}

View File

@ -326,21 +326,27 @@ class EmployeeRestController extends AdminController
foreach ($response[$emp_code] as $key => $value)
{
$checkIfExist = $this->employeePolicyModel->where('employee_id', $value['temp']['emp_id'])
if(isset($value['temp']))
{
$checkIfExist = $this->employeePolicyModel->where('employee_id', $value['temp']['emp_id'])
->where('client_policy_id', $value['policy_details']['client_policy_id'])
->where('is_active', 1 )
->findAll();
if($checkIfExist)
{
$this->employeePolicyModel
->where('client_policy_id',$value['policy_details']['client_policy_id'] )
->where('employee_id' , $value['temp']['emp_id'] )
->where('is_active', 1 )
->set(array('premium'=> $value['policy_details']['premium'] , 'rata_premimum'=> $value['policy_details']['rata_premimum'] , 'gst'=> $value['policy_details']['gst'] ))
->update();
if($checkIfExist)
{
$this->employeePolicyModel
->where('client_policy_id',$value['policy_details']['client_policy_id'] )
->where('employee_id' , $value['temp']['emp_id'] )
->where('is_active', 1 )
->set(array('premium'=> $value['policy_details']['premium'] , 'rata_premimum'=> $value['policy_details']['rata_premimum'] , 'gst'=> $value['policy_details']['gst'] ))
->update();
}
}
}
}
}
@ -834,7 +840,7 @@ class EmployeeRestController extends AdminController
$emp_id =0;
$data_after_gpa_or_gmc =[];
if ($policy['policy_type_id'] == 1) {
if ($client_policy['policy_type_id'] == 1) {
if (strtolower($dataToInsert[$a]['relationship']) == 'self') {
$data_after_gpa_or_gmc = $dataToInsert[$a];
}
@ -2199,9 +2205,11 @@ class EmployeeRestController extends AdminController
function getEmployeeActiveOrInactivePolicy()
{
if($this->request->getGet('type') == 'Active'){ $policy_status = 1; }else{ $policy_status = 0; }
$ClientPolicyData = $this->clientPolicyModel->select('client_policy.* , policies.name as policy_name , policy_type.policy_type as policy_type')
->join('policies', 'client_policy.policy_id = policies.id', 'left')
if($this->request->getGet('type') == 'Active'){ $policy_status = 1; }else{ $policy_status = 0; }
$ClientPolicyData = $this->clientPolicyModel->select('client_policy.* , policy_type.policy_type as policy_type,insurers.name as insurer_name,tpa.name as tpa_name')
->join('insurers', 'client_policy.insurer_id = insurers.id', 'left')
->join('tpa', 'client_policy.tpa_id = tpa.id', 'left')
->join('policy_type', 'client_policy.policy_type_id = policy_type.id', 'left')
->where('client_policy.client_id', $this->request->getGet('client_id') )
->where('client_policy.client_branch_id', $this->request->getGet('client_branch_id') )
@ -2209,7 +2217,7 @@ class EmployeeRestController extends AdminController
->where('client_policy.policy_status', $policy_status)
->orderby('client_policy.id' , 'ASC')
->findAll();
// dd($ClientPolicyData);
// Retrieve employee and dependents data by passing the employee code
$employeeData = $this->employeeModel->where('emp_code',$this->request->getGet('emp_code'))
->where('client_id',$this->request->getGet('client_id'))
@ -2232,15 +2240,22 @@ class EmployeeRestController extends AdminController
$terms = json_decode($ClientPolicyValue['policy_terms']);
if($ClientPolicyValue['policy_type_id'] == 1){ $data['policy_terms'] = $this->policyTermsFiter($terms,'gpa'); }
else{ $data['policy_terms'] = $this->policyTermsFiter($terms,'gmc'); }
if($ClientPolicyValue['policy_type_id'] == 1)
{
$data['policy_terms'] = $this->policyTermsFiter($terms,'gpa');
$data['department_id'] = 3;
}else{
$data['policy_terms'] = $this->policyTermsFiter($terms,'gmc');
$data['department_id'] = 4;
}
$data['client_id'] = $ClientPolicyValue['client_id'];
$data['client_policy_id'] = $ClientPolicyValue['id'];
$data['policy_name'] = $ClientPolicyValue['policy_name'];
$data['policy_type'] = $ClientPolicyValue['policy_type'];
$data['policy_name'] = $ClientPolicyValue['policy_type'];
$data['policy_type'] = $ClientPolicyValue['policy_type'];
$data['policy_no'] = $ClientPolicyValue['policy_no'];
$data['insurer_name'] = $ClientPolicyValue['insurer_name'];
$data['tpa_name'] = $ClientPolicyValue['tpa_name'];
$data['policy_start_date'] = $this->convertDateFormatDisplay($ClientPolicyValue['policy_start_date']);
$data['policy_end_date'] = $this->convertDateFormatDisplay($ClientPolicyValue['policy_end_date']);
// $data['policy_terms'] = $terms;
@ -2482,7 +2497,7 @@ class EmployeeRestController extends AdminController
public function sendPushNotification()
{
$deviceToken = 'ffvc39yhRk-J-vGE9luw6l:APA91bFgNv7lzvA3lGuJ_pMDHdZ_rey6SMg11P2DvJk-WWiBs0nXWCF0lo5nEka3dn3DeTCS5yx0WrHs1yKj5faitBQYKeKxLg2VpUkDcmk3FrTDGkZdHcnW1Go0G0K8dYAkajRIjSEJ';
$deviceToken = 'cMVKESh8QzqIl8nh_yqbcl:APA91bHKm87Sh1goVJNKZtctV4etgLMQboI0eyDVn3MH1yf9cO-2RtQRlFnKLdataOxosoxm7a4JvATKjfI1_Bids46mGw5m8zesp90mR4odCbD_cJtGmBeMYt4hssSY0YtAht1emK_H';
$title = 'Nhance';
$body = 'All your policy enrolled successfully ..!';

View File

@ -10,6 +10,7 @@ use CodeIgniter\API\ResponseTrait;
use CodeIgniter\Files\File;
use App\Helpers\DepositHelper;
use App\Helpers\MailHelper;
use App\Models\UserModel;
use App\Models\ClientModel;
@ -1478,4 +1479,59 @@ class MasterController extends AdminController
]);
}
}
public function generateNewGmailAPIToken()
{
$gmailapi = \Config\Services::gmailapi();
$gmailapi->generateNewToken();
}
//testing a sample mail from front end
public function testGmailAPI()
{
if ($this->request->getMethod() == 'post') {
$gmailapi = \Config\Services::gmailapi();
$to = $this->request->getPost('to');
$subject = $this->request->getPost('subject');
$mail_content = $this->request->getPost('content');
/*****CHOOSE ANY ONE AT A TIME, COMMENT ANOTHER ONE******/
/*****CALLING DIRECLT USING LIB******/
// $res = $gmailapi->sendMessage($to, $subject, $mail_content, 'info@nhanceindia.in', 'info@nhanceindia.in', $cc = [], $bcc = []);
// if($res['status'])
// {
// return $this->respond(['status' => 'success','code' => 200,'data' => $res],200);
// }
// else
// {
// $this->respond(['status' => 'failed','code' => 500,'data' => $res],200);
// }
/*****CALLING DIRECLT USING LIB******/
/*****CALLING VIA MAIL HELPER******/
$res = MailHelper::send_email(['mail' => $to, 'subject' => $subject, 'message' => $mail_content]);
return $this->respond(['status' => 'success','code' => 200,'data' => $res],200);
/*****CALLING VIA MAIL HELPER******/
}
$this->loadLayout('mail_test');
}
//testing a sample mail from cli
public function testGmailAPIViaCLI()
{
$gmailapi = \Config\Services::gmailapi();
$res = MailHelper::send_email(['mail' => 'velmurugan.s@venbainfotech.com', 'subject' => 'Mail Via CLI', 'message' => 'This is sample mail sent via CLI mode']);
print_r($res);
}
}

View File

@ -14,7 +14,7 @@ use App\Models\JobModel;
class MailHelper
{
public static function send_email($params)
public static function send_email_smtp($params)
{
// print_r($params);die;
@ -63,7 +63,7 @@ class MailHelper
}
}
public static function bulk_mail(array $mails = [])
public static function bulk_mail_smtp(array $mails = [])
{
// print_r();die;
$model = new JobModel();
@ -82,5 +82,69 @@ class MailHelper
}
}
//using GmailAPI
public static function send_email($params)
{
// print_r($params);die;
$myLogger = \Config\Services::mylogger();
$gmailapi = \Config\Services::gmailapi();
$emaill = $params['mail'];
$subject = $params['subject'];
$message = $params['message'];
if (isset($params['bcc'])) {
$bcc = $params['bcc'];
}else{
$bcc = [];
}
if (isset($params['cc'])) {
$cc = $params['cc'];
}else{
$cc = [];
}
try {
$res = $gmailapi->sendMessage($emaill, $subject, $message, 'info@nhanceindia.in', 'info@nhanceindia.in', $cc, $bcc);
if($res['status'])
{
return json_encode(['status' => 'success','code' => 200, 'message'=>('Email Sent Successfully...'.$emaill),'data' => $res,],200);
}
else
{
$myLogger->logme('error', "mail sent failed - $emaill");
return json_encode(['status' => 'failed','code' => 404,'message'=>( 'Email Sent Failed...' . $emaill ),'data' => $res ],404);
}
} catch (Exception $e) {
$msg = $e->getMessage();
$myLogger->logme('error', "mail sent failed - $msg");
return json_encode(['status' => 'failed','code' => 500,'data' => $msg],500);
}
}
public static function bulk_mail(array $mails = [])
{
// print_r();die;
$model = new JobModel();
$start = microtime(true);
$runtime= 0;
try {
foreach ( $mails as $index=>$mail) {
$runtime = microtime(true) - $start;
$send_mail = self::send_email($mail);
}
return json_encode(['status' => 'success','code' => 200, 'message'=>'Email Sent Successfully...'],200);
} catch (\Throwable $th) {
return json_encode(['status' => 'failed','code' => 500],500);
}
}
}
?>

View File

@ -234,7 +234,7 @@ if(!function_exists('check_si'))
$is_si_found = false;
$is_age_slab_found = false;
if($policy_details['policy_type_id'] == 1 && $slab_details[0]['policy_grid_id'] == 1 && $slab_details[0]['si_or_bp'] == 2) // GPA && grid type 1 for GPA && sub type is basic pay
if($policy_details['policy_type_id'] == 1 && $slab_details['slab_rates'][0]['policy_grid_id'] == 1 && $slab_details['slab_rates'][0]['si_or_bp'] == 2) // GPA && grid type 1 for GPA && sub type is basic pay
{
$is_si_found = true;
$is_age_slab_found = true;

180
app/Libraries/GmailAPI.php Normal file
View File

@ -0,0 +1,180 @@
<?php
namespace App\Libraries;
use Google\Client;
use Google\Service\Gmail;
use Google\Service\Gmail\Message;
use App\Models\SettingsModel;
use CodeIgniter\CLI\CLI;
class GmailAPI
{
protected $client;
protected $service;
protected $tokenField = 'email_token';
protected $myLogger = '';
protected $authField = 'gmail_api_oauth_credentials';
public function __construct()
{
$this->myLogger = \Config\Services::mylogger();
$this->client = new Client();
$this->client->setApplicationName('Nhance GmailAPI');
$this->client->setScopes([
'https://www.googleapis.com/auth/gmail.addons.current.message.readonly',
'https://www.googleapis.com/auth/gmail.readonly',
'https://www.googleapis.com/auth/gmail.labels',
'https://www.googleapis.com/auth/gmail.send'
]);
$this->setAuthConfig();
//die();
$this->client->setAccessType('offline');
$this->client->setPrompt('select_account consent');
if (php_sapi_name() !== 'cli' || (uri_string() == 'cli/send_mail_cli' || uri_string() == 'cli/processjob') )
{
$this->setTokenFromDB(); // Call only if not in CLI
}
$this->service = new Gmail($this->client);
}
protected function setAuthConfig()
{
$settingsModel = new SettingsModel();
$credentials = $settingsModel->where('id', 1)->first();
if (!$credentials) {
$this->myLogger->logme('error','OAuth credentials for GmailAPI not found in database.');
throw new \Exception('OAuth credentials for GmailAPI not found in database.');
}
// print_r($credentials[$this->authField]);//die();
// $accessToken = $credentials[$this->authField];
$this->client->setAuthConfig(json_decode($credentials[$this->authField],true));
// if ($this->client->isAccessTokenExpired()) {
// if ($this->client->getRefreshToken()) {
// $this->client->fetchAccessTokenWithRefreshToken($this->client->getRefreshToken());
// $this->storeTokenToDB($this->client->getAccessToken());
// } else {
// $this->myLogger->logme('error', 'Access token expired and no refresh token available.');
// throw new \Exception('Access token expired and no refresh token available.');
// }
// }
}
protected function setTokenFromDB()
{
$settingsModel = new SettingsModel();
$token = $settingsModel->where('id', 1)->first();
// dd(is_array($token) && is_null($token[$this->tokenField]));
if (is_array($token) && is_null($token[$this->tokenField])) {
$this->myLogger->logme('error','Email Token not found in database.');
throw new \Exception('Email Token not found in database.');
}
$accessToken = json_decode($token[$this->tokenField], true);
$this->client->setAccessToken($accessToken);
if ($this->client->isAccessTokenExpired()) {
if ($this->client->getRefreshToken()) {
$this->client->fetchAccessTokenWithRefreshToken($this->client->getRefreshToken());
$this->storeTokenToDB($this->client->getAccessToken());
} else {
$this->myLogger->logme('error', 'Access token expired and no refresh token available.');
throw new \Exception('Access token expired and no refresh token available.');
}
}
}
protected function storeTokenToDB($token)
{
$settingsModel = new SettingsModel();
$token = json_encode($token);
// $settingsModel->update(['id' => $this->tokenField], ['value' => json_encode($token)]);
$settingsModel->where('id', 1)->set([$this->tokenField => $token])->update();
}
public function createMessage($to, $subject, $htmlContent, $from, $replyTo, $cc = [], $bcc = [])
{
$boundary = uniqid(rand(), true);
$rawMessageString = "From: $from\r\n";
$rawMessageString .= "To: $to\r\n";
$rawMessageString .= "Reply-To: $replyTo\r\n";
if (!empty($cc)) {
$rawMessageString .= "Cc: " . implode(',', $cc) . "\r\n";
}
if (!empty($bcc)) {
$rawMessageString .= "Bcc: " . implode(',', $bcc) . "\r\n";
}
$rawMessageString .= "Subject: $subject\r\n";
$rawMessageString .= "MIME-Version: 1.0\r\n";
$rawMessageString .= "Content-Type: multipart/alternative; boundary=\"$boundary\"\r\n\r\n";
$rawMessageString .= "--$boundary\r\n";
$rawMessageString .= "Content-Type: text/html; charset=UTF-8\r\n";
$rawMessageString .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$rawMessageString .= $htmlContent . "\r\n";
$rawMessageString .= "--$boundary--";
$rawMessage = base64_encode($rawMessageString);
$rawMessage = str_replace(['+', '/', '='], ['-', '_', ''], $rawMessage);
$message = new Message();
$message->setRaw($rawMessage);
return $message;
}
public function sendMessage($to, $subject, $htmlContent, $from, $replyTo, $cc = [], $bcc = [])
{
try {
$message = $this->createMessage($to, $subject, $htmlContent, $from, $replyTo, $cc, $bcc);
$res = $this->service->users_messages->send('me', $message);
return array('status' => true, 'data' => $res);
} catch (\Exception $e) {
$err_msg = 'An error occurred while sending the mail: ' . $e->getMessage();
$this->myLogger->logme('error', $err_msg);
// throw new \Exception('An error occurred while sending the mail: ' . $e->getMessage());
return array('status' => false, 'data' =>$e->getMessage());
}
}
public function generateNewToken()
{
// dd('called');
if (!is_cli()) {
throw new \RuntimeException('This method can only be accessed via the command line.');
}
if (php_sapi_name() != 'cli') {
throw new Exception('This application must be run on the command line.');
}
$authUrl = $this->client->createAuthUrl();
CLI::write('Open the following link in your browser');
CLI::write("\n");
CLI::write($authUrl);
// printf ("Open the following link in your browser:\n%s\n", $authUrl);
CLI::write('Enter verification code: ');
// print 'Enter verification code: ';
$authCode = trim(fgets(STDIN));
$accessToken = $this->client->fetchAccessTokenWithAuthCode($authCode);
if (array_key_exists('error', $accessToken)) {
$this->myLogger->logme('error', 'Error in getting access token from authCode' . join(', ', $accessToken));
throw new \Exception(join(', ', $accessToken));
}
$this->storeTokenToDB($accessToken);
$this->myLogger->logme('error', 'New token generated and stored in the database.');
print 'New token generated and stored in the database.';
}
}

View File

@ -0,0 +1,20 @@
<?php
namespace App\Models;
use CodeIgniter\Model;
class SettingsModel extends Model
{
protected $table = 'settings';
protected $primaryKey = 'id';
protected $allowedFields = [
'mail_host',
'mail_port',
'mail_username',
'mail_password',
'email_token',
'created_by',
'updated_by'
];
}

44
app/Views/mail_test.php Normal file
View File

@ -0,0 +1,44 @@
<div class="container mt-2">
<h2>Send Test Mail Using Gmail API</h2>
<form id="mailForm">
<div class="form-group">
<label for="to">To:</label>
<input type="email" class="form-control" id="to" name="to" value="velmurugan.s@venbainfotech.com" required>
</div>
<div class="form-group">
<label for="subject">Subject:</label>
<input type="text" class="form-control" id="subject" name="subject" value="Gmail API Test - . <?php echo date('Y-m-d h:i:s');?>" required>
</div>
<div class="form-group">
<label for="content">Content:</label>
<textarea class="form-control" id="content" name="content" rows="5" required><H1>Gmail API Test </H1><a target="_blank" href="<?php echo base_url('util/test_mail')?>">Click me</a>
</textarea>
</div>
<button type="submit" class="btn btn-primary">Send Mail</button>
</form>
<div id="responseMessage" class="mt-3"></div>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function() {
$('#mailForm').on('submit', function(e) {
e.preventDefault();
$.ajax({
url: '<?= base_url('util/test_mail') ?>', // Replace with your controller method URL
type: 'POST',
data: $(this).serialize(),
success: function(response) {
$('#responseMessage').html('<div class="alert alert-success">' + JSON.stringify(response.data) + '</div>');
},
error: function(xhr, status, error) {
$('#responseMessage').html('<div class="alert alert-danger">Error: ' + xhr.responseText + '</div>');
}
});
});
});
</script>

View File

@ -716,18 +716,20 @@
function displayData(data)
{
displayTable(data.new,"restablebody");
if(data.old.length())
if(data.old.length)
{
$('#oldrestablebody').prop('display','block');
displayTable(data.new,"oldrestablebody");
displayTable(data.old,"oldrestablebody");
}
}
function displayTable(data,tableID)
{
var old_data = data.old;
var old_data = data.old;
const tableBody = document.getElementById(tableID);
$(("#".tableID)).empty();
// $(("#".tableID)).empty();
$("#restable tbody").empty();
$('#oldrestable tbody').empty();
const existingRowCount = tableBody.rows.length;
for(i = 0; i < data.length; i++)
{