FEAT_QUEUE_SERVER,FEAT_EMP_UPLOAD

This commit is contained in:
velz 2024-02-16 16:26:45 +05:30
parent 86912e956c
commit 2e3d8fcb67
20 changed files with 1211 additions and 3 deletions

View File

@ -41,8 +41,8 @@ class Filters extends BaseConfig
*/
public array $globals = [
'before' => [
'HttpRequestLog',
'csrf',
'HttpRequestLog' => ['except' => 'processjob'],
// 'csrf',
// 'invalidchars',
],
'after' => [

View File

@ -59,3 +59,16 @@ $routes->group("/client", ["filter" => "authMVC"], function($routes){
});
});
$routes->group("/employee", ["filter" => "authMVC"], function($routes){
$routes->get("list", "EmployeeController::list");
$routes->get("search", "EmployeeController::search");
$routes->get("bulk-event-uplod", "EmployeeController::employeesUplodWithEvents");
$routes->post("bulk-event-uplod", "EmployeeController::employeesUplodWithEvents");
});
$routes->group("/util", ["filter" => "authMVC"], function($routes){
$routes->get("clients-with-policies", "EmployeeController::getClientWithPolicies");
});
$routes->cli('processjob', 'JobWorker::processJob');

View File

@ -59,7 +59,7 @@ abstract class BaseController extends Controller
}
public function loadLayout($view_name,$data)
public function loadLayout($view_name,$data = [])
{
echo view('layout/header',$data);
echo view($view_name, $data);

View File

@ -0,0 +1,140 @@
<?php
namespace App\Controllers;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;
use App\Models\EmployeeModel;
use App\Models\EmployeePolicyModel;
use App\Models\ClientModel;
use App\Models\FileModel;
use App\Controllers\Jobs ;
use App\Controllers\JobWorker ;
use CodeIgniter\API\ResponseTrait;
class EmployeeController extends AdminController
{
use ResponseTrait;
protected $myLogger;
protected $employeeModel;
protected $employeePolicyModel;
protected $clientModel;
protected $fileModel;
public function __construct()
{
// helper('utility');
set_session_context('Employee');
$this->myLogger = \Config\Services::mylogger();
$this->employeeModel = new EmployeeModel();
$this->employeePolicyModel = new EmployeePolicyModel();
$this->clientModel = new ClientModel();
$this->fileModel = new FileModel();
}
public function list()
{
// $model = new UserModel();
$data = [];
if(count($this->request->getGet()))
{
$filterData = $this->request->getGet();
$data['employees'] = $this->employeePolicyModel->getEmployeePolicy(client_id: $filterData['client_id'],policy_id: $filterData['policy_id']);
}
$this->myLogger->logme('error','list called');
$this->loadLayout('employee_list',$data);
}
public function getClientWithPolicies()
{
//echo $this->request->isAJAX();die();
$result = $this->clientModel->clientsWithPolicies();
// print_r($result);die();
if(!count($result))
{
return $this->respond(['dataStatus' => false,'code' => 404,'message' => 'no data found'], 200);
}
else
{
return $this->respond(['dataStatus' => true,'code' => 200,'data' => $result], 200);
}
}
//handles employee & dependent bulk upload with events like inception,addition,deletion, correction and SI enhancements
public function employeesUplodWithEvents()
{
// $job_details = new Jobs();
// $r = Jobs::addJob(['job_name' => 'add','payload' => ['a' => 10, 'b' => 35]]);
// print_r($r);//die();
// // $jobWorker = new JobWorker();
// JobWorker::processJob($r);
// die();
// echo $this->request->getMethod();die();
// print_r($this->request->getFiles('emplist'));print_r($this->request->getPost('emplist'));
// print_r($this->request->getPost('clients'));
// print_r($this->request->getPost('policies'));
// print_r($this->request->getPost('upload-action-type'));
// die();
if($this->request->getMethod() == 'post')
{
$filename = '';
$validated = $this->validate([
'emplist' => [
'uploaded[emplist]',
'mime_in[emplist,application/vnd.ms-excel,application/vnd,application/pdf]',
'max_size[emplist,8192]',
],
]);
if ($validated) {
$avatar = $this->request->getFile('emplist');
$is_moved = $avatar->move(WRITEPATH . 'uploads/excel/');
$filename = $avatar->getName();
}
else
{
return $this->respond(['dataStatus' => false,'code' => 404,'message' => 'invalid file'], 200);
}
//process post variable entry in file table
$loggedInUserID = get_session_userid();
$client_id = $this->request->getPost('client_id');
$policy_id = $this->request->getPost('policy_id');
$action = $this->request->getPost('upload-action-type');
$status = 'inprogress';
$file_id = $this->fileModel->insert(['file_name' => $filename,'client_id' => $client_id,'policy_id' => $policy_id,'created_by' => $loggedInUserID,'status' => $status,'action' => $action]);
//die();
$this->myLogger->logme("error",'{file_id} uploaded success',['file_id' => $file_id]);
return $this->respond(['dataStatus' => true,'code' => 200,'data' => 'file upload success'], 200);
}
$data['actions'] = ['inception' => 'Inception','addition' => 'Addition','deletion' => 'Deletion','si_enhancement' =>'SI Enhancement'];
$data['fileList'] = $this->fileModel
->select(['files.*','up.emp_code','up.first_name'])
->join('user_profiles up','files.created_by = up.id')
->where('files.created_by',8)->orderBy('files.created_at','desc')->findAll();
// print_r($data['fileList']);die();
if($this->request->getMethod() == "get")
{
$this->loadLayout('employee_upload',$data);
}
}
}

View File

@ -22,4 +22,10 @@ class Home extends PublicController
return 'from test service';
}
public function addTwoNumbers($payload)
{
//echo $payload['a'] + $payload['b'];
return $payload['a'] + $payload['b'];
}
}

View File

@ -0,0 +1,154 @@
<?php
namespace App\Controllers;
use App\Models\JobModel;
class JobWorker extends AdminController
{
const STATUS_DONE = 'done';
const STATUS_QUEUED = 'queued';
const STATUS_RUNNING = 'running';
const STATUS_FAILED = 'failed';
/**
* Constructs the class
*/
private static $event_class_mapping = ['add' => ['type' => 'HC','handler' => 'App\\Helpers\\HttpRequestHelper'], 'sub' => ['type' => 'CC','handler' => 'App\\Controllers\\Jobs\SubJob'],'fancy_date_time_format' => [ 'type' => 'HF','handler' => 'fancy_date_time_format'],'addNumber' => ['type' => 'HC','handler' => 'App\\Model\\HttpRequestHelper']];
public function __construct()
{
// echo 'HiC';//die();
// parent::__construct();
// $this->load->model('JobModel');
// $this->dbm = $this->users_model;
// if (php_sapi_name() !== 'cli')
// {
// die('Invalid context');
// }
}
/**
* process jobs
*/
public static function processJob(array $jobdata = [])
{
// echo 'listen';//die();
$query = "
SELECT id, name, payload, uuid
FROM jobs
WHERE status=?
ORDER BY created_dt ASC
LIMIT 1 FOR UPDATE";
$where_condition = [self::STATUS_QUEUED];
if(isset($jobdata) && count($jobdata))
{
$query = "
SELECT id, name, payload, uuid
FROM jobs
WHERE status=? AND id=? AND uuid=?
ORDER BY created_dt ASC
LIMIT 1 FOR UPDATE";
$where_condition = [self::STATUS_QUEUED,$jobdata['id'],$jobdata['uuid']];
}
$db = \Config\Database::connect();
$job = $db->query($query, $where_condition)->getResult();
// print_r($job);die();
if ($job !== [])
{
$job = $job[0];
echo "\nProcessing job id - " . $job->id . "\n";
echo "Job name - " . $job->name . "\n";
try
{
$start = microtime(true);
$runtime = null;
$job_status = self::STATUS_RUNNING;
$db->query("UPDATE jobs SET status=? WHERE id=? AND uuid=?", [$job_status, $job->id,$job->uuid]);
if (!array_key_exists($job->name,SeLf::$event_class_mapping))
{
throw new \RuntimeException('Job ' . $job->name . ' handler not registered');
}
$handler = SELF::$event_class_mapping[$job->name];
$handleInstance = null;
if($handler['type'] == 'CC' || $handler['type'] == 'HC')
{
// echo 'CLASS - ' . $handler['type'].' - ' . $handler['handler'];
$handlerClass = $handler['handler'];
if(class_exists($handlerClass))
{
$handleInstance = new $handlerClass();
}
else
{
throw new \RuntimeException('Job ' . $job->name . ' or handler class not found');
// echo $e->getMessage();
}
if (method_exists($handleInstance, $job->name))
{
$jobHandler = [$handleInstance, $job->name];
//throw new \RuntimeException('Job ' . $job->name . ' not found');
}
else if(method_exists($handleInstance, 'handle'))
{
$jobHandler = [$handleInstance, 'handle'];
}
else
{
throw new \RuntimeException('Job ' . $job->name . ' or handler not found');
}
}
else if($handler['type'] == 'HF')
{
// echo 'HF - ' . $handler['type'];
$jobHandler = $handleInstance = $handler['handler'];
// echo $jobHandler;
}
else{
throw new \RuntimeException('Job ' . $job->name . ' Invalid job type');
}
$payload = json_decode($job->payload, true);
if (!is_array($payload))
{
throw new \InvalidArgumentException('Invalid payload format here');
}
$payload = is_array($payload) ? $payload : [];
$response = $jobHandler($payload,$job->id);
$runtime = microtime(true) - $start;
$job_status = self::STATUS_DONE;
}
catch (\Exception $e)
{
//die();
$job_status = self::STATUS_FAILED;
$runtime = $runtime === null ? microtime(true) - $start : $runtime;
$response = $e->getMessage();
}
$db->query("UPDATE jobs SET status=?, run_time=?, response=? WHERE id=? AND uuid=?", [
$job_status,
$runtime,
json_encode($response),
$job->id,$job->uuid
]);
echo "Job $job->id $job_status. Response - $response \n";
}
else
{
echo 'no job found in queue';
}
}
}

64
app/Controllers/Jobs.php Normal file
View File

@ -0,0 +1,64 @@
<?php
namespace App\Controllers;
use App\Models\JobModel;
class Jobs extends AdminController
{
const STATUS_DONE = 'done';
const STATUS_QUEUED = 'queued';
const STATUS_RUNNING = 'running';
const STATUS_FAILED = 'failed';
protected $job_payload = [];
protected $myLogger;
/**
* Constructs the class
*/
// public function __construct(array $payload = ['job_name' => 'check','payload' => ['a' => 10]])
public function __construct()
{
// $this->job_payload = $payload;
// $this->myLogger = \Config\Services::mylogger();
}
/**
* add jobs to queue
*/
public static function addJob(array $payload)
{
$jobModel = new JobModel();
$myLogger = \Config\Services::mylogger();
try
{
if(!is_array($payload))
{
throw new \InvalidArgumentException('Invalid payload format while add job');
}
if(!isset($payload['job_name']))
{
throw new \InvalidArgumentException('Job name not found while add job');
}
if(!isset($payload['payload']))
{
throw new \InvalidArgumentException('Job payload not found while add job');
}
$uuid = generate_uuid();
$jobid = $jobModel->insert(['name' => $payload['job_name'],'uuid' => $uuid,'payload' => json_encode($payload['payload'])]);
// echo $jobid;
$myLogger->logme('error','new job {jobid} added to queue',['jobid' => $jobid]);
return ['id' => $jobid,'uuid' => $uuid,'job_name' => $payload['job_name']];
}
catch(\Exception $e)
{
$message = $e->getMessage();
$myLogger->logme('error','{messgae}',['messgae' => $message]);
}
}
}

View File

@ -0,0 +1,15 @@
<?php
namespace App\Controllers\Jobs;
use App\Controllers\PublicController;
class AddJob extends PublicController
{
public function handle($payload)
{
//echo $payload['a'] + $payload['b'];
return $payload['a'] + $payload['b'];
}
}

View File

@ -0,0 +1,14 @@
<?php
namespace App\Controllers\Jobs;
use App\Controllers\PublicController;
class SubJob extends PublicController
{
public function handle($payload)
{
return $payload['a'] - $payload['b'];
}
}

View File

@ -22,4 +22,6 @@ class HttpRequestHelper
$data['postparams'] = is_array($data['postparams']) ? json_encode($data['postparams']) : $data['postparams'];
return $data;
}
public static function add($payload)
{return $payload['a'] + $payload['b'];}
}

View File

@ -70,3 +70,49 @@ if (!function_exists('fileUpload')) {
}
}
if (!function_exists('fancy_date_time_format'))
{
function fancy_date_time_format($datetime,$return_type = 'fancy') {
$currentDateTime = new DateTime();
$passedDateTime = new DateTime($datetime);
// Calculate the interval between the current time and the passed datetime
$interval = $currentDateTime->diff($passedDateTime);
// return change_date_format($datetime,'Y-m-d H:i:s','d M Y h:i a');
// If the interval is more than 1 month, return the original datetime
if ($interval->m > 1 || $interval->y > 0) {
if($return_type = 'fancy'){ return change_date_format($datetime,'Y-m-d H:i:s','d M Y h:i a'); }
return $datetime;
} elseif ($interval->m == 1 && $interval->y == 0) {
return "1 month ago";
} elseif ($interval->d >= 7) {
$weeks = floor($interval->d / 7);
return $weeks == 1 ? "1 week ago" : "$weeks weeks ago";
} elseif ($interval->d >= 1) {
return $interval->d == 1 ? "1 day ago" : $interval->d . " days ago";
} elseif ($interval->h >= 1) {
return $interval->h == 1 ? "1 hour ago" : $interval->h . " hours ago";
} elseif ($interval->i >= 1) {
return $interval->i == 1 ? "1 minute ago" : $interval->i . " minutes ago";
} else {
return "Just now";
}
}
}
if(!function_exists('check_string_date'))
{
function check_string_date($str)
{
if (DateTime::createFromFormat('Y-m-d H:i:s', $str) !== false) {
return true;
}
return false;
}
}

View File

@ -3,6 +3,7 @@
namespace App\Models;
use CodeIgniter\Model;
use App\Models\ClientPolicyModel;
class ClientModel extends Model
{
@ -25,4 +26,28 @@ class ClientModel extends Model
"is_active",
];
//get client and its associated policies in same array
public function clientsWithPolicies()
{
$columns = ['id', 'client_name','short_name'];
$clients = $this->select($columns)->where('is_active',1)->findAll();
foreach ($clients as &$client) {
$clientPolicyModel = new ClientPolicyModel();
$clientPolicies = $clientPolicyModel->select(['client_policy.id','p.name'])
->join('policies p', 'p.id = client_policy.policy_id')
->where('client_policy.client_id',$client['id'])
->where('client_policy.is_active', 1)
->findAll();
$client['policies'] = $clientPolicies;
}
//print_r(($clients));die();
return $clients;
}
}

View File

@ -0,0 +1,29 @@
<?php
namespace App\Models;
use CodeIgniter\Model;
class EmployeeModel extends Model
{
protected $table = 'employees';
protected $primaryKey = 'id';
protected $allowedFields = [
"id",
"employee_id",
"change_event",
"relationship_id",
"batch_id",
"emp_code",
"name",
"email_personal",
"email_corporate",
"mobile",
"gender",
"dob",
"emp_status",
"created_by",
"updated_by",
"is_active",
];
}

View File

@ -0,0 +1,48 @@
<?php
namespace App\Models;
use CodeIgniter\Model;
class EmployeePolicyModel extends Model
{
protected $table = 'employee_polices';
protected $primaryKey = 'id';
protected $allowedFields = [
"id",
"employee_id",
"client_policy_id",
"tpa_id",
"uhid",
"status",
"pre_existing_alignments",
"basic_cover_si",
"date_coverage",
"policy_end_date",
"days",
"premium",
"rata_premimum",
"gst",
"created_by",
"updated_by",
"is_active",
];
public function getEmployeePolicy($client_id,$policy_id)
{
$result = $this->select(['employee_polices.*','pm.name as policy_name','im.short_name as insurer_short_name','ib.branch_name as insurer_branch_name','ib.branch_code as insurer_branch_code','tpam.name as tpa_name','tpam.short_name as tpa_short_name','tpab.branch_code as tpa_branch_code','cm.client_name','cm.short_name as client_short_name','emp.relationship','emp.relationship_code','emp.change_event','emp.emp_code','emp.name','emp.email_corporate','emp.dob','emp.gender','emp.emp_status','emp.is_active as emp_is_active'])
->join('employees emp', 'employee_polices.employee_id = emp.id')
->join('client_policy cp', 'employee_polices.client_policy_id = cp.id') //cp - client policy
->join('policies pm', 'cp.policy_id = pm.id') //pm - policy master
->join('insurers im', 'cp.insurer_id = im.id') //im - insurar master
->join('insurer_branch ib', 'cp.insurer_branch_id = ib.id') //ib - insurar branch
->join('tpa tpam', 'cp.tpa_id = tpam.id') //tpam - tpa master
->join('tpa_branch tpab', 'cp.tpa_branch_id = tpab.id') //tpab - tpa brach
->join('clients cm', 'cp.client_id = cm.id') //cm - client master
->where('emp.client_id',$client_id)
->where('employee_polices.client_policy_id',$policy_id)
->findAll();
return ($result);
}
}

25
app/Models/FileModel.php Normal file
View File

@ -0,0 +1,25 @@
<?php
namespace App\Models;
use CodeIgniter\Model;
class FileModel extends Model
{
protected $table = 'files';
protected $primaryKey = 'id';
protected $allowedFields = [
"id",
"file_name",
"created_by",
"is_active",
"status",
"reason",
"action",
"client_id",
"policy_id"
];
}

20
app/Models/JobModel.php Normal file
View File

@ -0,0 +1,20 @@
<?php
namespace App\Models;
use CodeIgniter\Model;
class JobModel extends Model
{
protected $table = 'jobs';
protected $primaryKey = 'id';
protected $allowedFields = [
"id",
"name",
"payload",
"response",
"status",
"run_time",
"uuid"
];
}

255
app/Views/employee_list.php Normal file
View File

@ -0,0 +1,255 @@
<br>
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-body">
<!-- <div class="text-center"> -->
<div class="row">
<div class="col-md-6 col-xl-3">
<div class="form-group mb-3">
<label>Client</label> <br/>
<select class="form-control" id="clients">
<option value="0">Select</option>
</select>
</div>
</div>
<div class="col-md-6 col-xl-3">
<div class="form-group mb-3">
<label>Policy</label> <br/>
<select class="form-control" id="policies">
<option value="0">Select</option>
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-12" style="text-align: right;">
<a href="<?= base_url("employee/list"); ?>" class="btn btn-primary waves-effect waves-light" id="get-emp-list" onclick="fetchEmpolyeeList(event);">Submit</a>
</div>
</div>
<!-- </div> -->
</div>
</div>
</div>
</div>
</div>
<!-- start page title -->
<div class="row">
<div class="col-12">
<div class="page-title-box page-title-box-alt">
<h4 class="page-title"></h4>
<div class="page-title-right">
</div>
</div>
</div>
</div>
<!-- end page title -->
<div class="row" id="client_list">
<div class="col-12">
<div class="card">
<div class="card-body">
<div class="row" style="padding-bottom: 10px;">
<div class="col-6" style="align-self: center;">
<h4 class="header-title" style="position: relative;">Employees</h4>
</div>
</div>
<table class="table table-hover m-0 table-centered dt-responsive nowrap w-100" cellspacing="0" id="tickets-table">
<thead class="bg-light">
<tr>
<th class="font-weight-medium">SNO</th>
<th class="font-weight-medium">Employee code</th>
<th class="font-weight-medium">Name</th>
<th class="font-weight-medium">Policy name</th>
<th class="font-weight-medium">Insurar name</th>
<th class="font-weight-medium">TPA ID</th>
<th class="font-weight-medium">UHID ID</th>
<th class="font-weight-medium">Policy status</th>
<th class="font-weight-medium">Premium</th>
<th class="font-weight-medium">Action</th>
</tr>
</thead>
<tbody class="font-12">
<?php
if(isset($employees))
{
foreach ($employees as $key => $employee) { ?>
<tr>
<td><b><?php echo ($key + 1)?></b></td>
<td><?php echo $employee['emp_code']?></td>
<td><?php echo $employee['name']?></td>
<td><?php echo $employee['policy_name']?></td>
<td><?php echo $employee['insurer_short_name']?></td>
<td><?php echo $employee['tpa_id']?></td>
<td><?php echo $employee['uhid']?></td>
<td><span class="badge badge-success">active</span></td>
<td><?php echo $employee['premium']?></td>
<td>
<div class="btn-group dropdown">
<a href="javascript: void(0);" class="dropdown-toggle arrow-none btn btn-light btn-sm" data-toggle="dropdown" aria-expanded="false"><i class="mdi mdi-dots-horizontal"></i></a>
<div class="dropdown-menu dropdown-menu-right">
<a class="dropdown-item" href="#"><i class="mdi mdi-pencil mr-2 text-muted font-18 vertical-middle"></i>Edit Ticket</a>
<a class="dropdown-item" href="#"><i class="mdi mdi-check-all mr-2 text-muted font-18 vertical-middle"></i>Close</a>
<a class="dropdown-item" href="#"><i class="mdi mdi-delete mr-2 text-muted font-18 vertical-middle"></i>Remove</a>
<a class="dropdown-item" href="#"><i class="mdi mdi-star mr-2 font-18 text-muted vertical-middle"></i>Mark as Unread</a>
</div>
</div>
</td>
</tr>
<?php }}?>
</tbody>
</table>
</div>
</div>
</div><!-- end col -->
</div>
<!-- end row -->
<div id="loader" class="loader" style="display:none;">SPINNER</div>
<script>
// Declare a global variable to store API response data
var clientPolicies = [];
$( document ).ready(function() {
console.log( "document loaded" );
//fetchClientPolicies();
});
$( window ).on( "load", function() {
console.log( "window loaded" );
fetchClientPolicies();
});
function fetchClientPolicies() {
$('#loader').show();
var apiURL = '<?php echo base_url();?>' + 'util/clients-with-policies';
console.log('fetchClientPolicies');
console.log(apiURL);
$.ajax({
url: apiURL,
method: 'GET',
headers: {
"Content-Type": "application/json",
"X-Requested-With": "XMLHttpRequest"
},
success: function(response) {
// console.log(response.code);
// console.log(response.dataStatus);
// console.log(response.data);
if (response.code === 200 && response.dataStatus === true && response.data !== "") {
try {
clientPolicies = (response.data);
// console.log(clientPolicies);
appendClients(clientPolicies);
} catch (error)
{
console.error('Error parsing API response data:', error);
}
} else if(response.code === 404 && response.dataStatus === false){
console.error('no data found', response);
}
else
{
console.error('Something went wrong!');
}
},
error: function(xhr, status, error) {
console.error('Error fetching data from API:', error);
}
});
$('#loader').hide();
}
function appendClients(data) {
$.each(data, function(index, item) {
$('#clients').append($('<option>', {
value: item.id,
text: item.client_name
}));
});
}
function appendPolicies(data) {
$('#policies').empty();
$('#policies').append($('<option>', { value: '0',text: 'Select'}));
$.each(data, function(index, item) {
$('#policies').append($('<option>', {
value: item.id,
text: item.name
}));
});
}
$('#clients').on('change', function() {
var selectedClient = $(this).val();
console.log(selectedClient);
// $('#selectedOptionInfo').text('Selected option: ' + selectedOption);
// Check if the selected option exists in apiData
var foundPolicies = clientPolicies.find(function(item) {
return item.id === selectedClient;
});
console.log(foundPolicies.policies);
appendPolicies(foundPolicies.policies);
});
// Function to convert object to query parameters
function objectToQueryString(obj) {
return Object.keys(obj).map(key => `${encodeURIComponent(key)}=${encodeURIComponent(obj[key])}`).join('&');
}
function fetchEmpolyeeList(event) {
event.preventDefault(); // Prevent default action
var client_id = $('#clients').val();
var policy_id = $('#policies').val();
console.log(client_id+'-'+policy_id);
if (client_id == '0' || policy_id == '0' ) {
alert('Please select values in both dropdowns.');
return;
}
var queryParams = {
client_id: client_id,
policy_id: policy_id
};
const queryString = objectToQueryString(queryParams);
const apiURL = $('#get-emp-list').attr('href')+"?" + queryString;
console.log(apiURL);
window.location.href = apiURL;
// var apiURL2 = $('#get-emp-list').attr('href'); // Get href attribute value
// console.log(apiURL);
// $.ajax({
// url: apiURL,
// method: 'GET',
// data: queryParams,
// success: function(response) {
// // Assuming response is a JSON array
// // displayDataTables(response);
// console.log(response);
// },
// error: function(xhr, status, error) {
// console.error('Error:', error);
// }
// });
}
</script>

View File

@ -0,0 +1,305 @@
<?php //echo fancy_date_time_format('2024-01-01 15:40:32');echo '<br>';?>
<?php //echo fancy_date_time_format('2024-02-01 15:40:32');echo '<br>';?>
<!-- <?php echo fancy_date_time_format('2024-02-10 15:40:32');echo '<br>';?> -->
<!-- <?php echo fancy_date_time_format('2024-02-13 14:40:32');echo '<br>';?> -->
<!-- <?php echo fancy_date_time_format('2024-02-13 14:58:00');echo '<br>';?> -->
<br>
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-body">
<!-- <div class="text-center"> -->
<form id="emp-upload-form" action="<?php echo base_url().'employee/bulk-event-uplod'?>" method="post">
<input type="hidden" name="<?= csrf_token() ?>" value="<?= csrf_hash() ?>" id="csrf_token">
<div class="row">
<div class="col-md-4 col-xl-3">
<div class="form-group mb-3">
<label>Client</label> <br/>
<select name="client_id" class="form-control" id="client_id">
<option value="0">Select</option>
</select>
</div>
</div>
<div class="col-md-4 col-xl-3">
<div class="form-group mb-3">
<label>Policy</label> <br/>
<select name="policy_id" class="form-control" id="policy_id">
<option value="0">Select</option>
</select>
</div>
</div>
<div class="col-md-4 col-xl-3">
<div class="form-group mb-3">
<label>Action</label> <br/>
<select name="upload-action-type" class="form-control" id="upload-action-type">
<option value="0">Select</option>
<?php
if(isset($actions) && count($actions))
{
foreach($actions as $key => $action)
{
echo "<option value=".$key.">".$action."</option>";
}
}
?>
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-md-4 col-xl-3">
<div class="form-group mb-3">
<label>Choose file</label> <br/>
<input type="file" name="emplist" id="emplist">
</div></div>
<div class="col-8" style="text-align: right;">
<button type="submit" class="btn btn-primary waves-effect waves-light">Submit</button>
</div>
</div>
</form>
<!-- </div> -->
</div>
</div>
</div>
</div>
</div>
<!-- start page title -->
<div class="row">
<div class="col-12">
<div class="page-title-box page-title-box-alt">
<h4 class="page-title"></h4>
<div class="page-title-right">
</div>
</div>
</div>
</div>
<!-- end page title -->
<div class="row" id="file_list">
<?php include('file_list.php');?>
</div>
<!-- end row -->
<!-- Center modal content -->
<div class="modal fade" id="file-err-modal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myCenterModalLabel">File Rejected Reason</h4>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body">
<h5>Overflowing text to show scroll behavior</h5>
<p>Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.</p>
<p>Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.</p>
</div>
</div>
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<div id="loader" class="loader" style="display:none;">SPINNER</div>
<script>
// Declare a global variable to store API response data
var clientPolicies = [];
$( document ).ready(function() {
console.log( "document loaded" );
//fetchClientPolicies();
//for modal pop up
$('#file-err-modal').on('show.bs.modal', function (event) {
var myVal = $(event.relatedTarget).data('err');
$(this).find(".modal-body").text(myVal);
});
//for form submit
$("#emp-upload-form").submit(function(event) {
event.preventDefault(); // Prevent default form submission
console.log('submit called');
// Check required fields
if (!$(this)[0].checkValidity()) {
// Form is invalid, handle error or notify user
console.log('failed');
return false;
}
console.log($(this));
console.log($(this)[0]);
// Create FormData object
var formData = new FormData($(this)[0]);
for (var pair of formData.entries()) {
console.log(pair[0]+ ', ' + pair[1]);
}
// var formData = $("#emp-upload-form").serialize();
// var file = document.getElementById('emplist').files[0];
// formData.append('file', file);
console.log(formData);
// return false;
// AJAX request
$.ajax({
url: $(this).attr("action"),
type: "POST",
data: formData,
processData: false, // Prevent jQuery from automatically processing the data
contentType: false, // Let jQuery handle the content type
headers: {
// "Content-Type":"multipart/form-data",
"X-Requested-With": "XMLHttpRequest"
},
success: function(response) {
// Request successful, handle response
console.log(response);
alert('success');
window.location.reload();
},
error: function(xhr, status, error) {
// Request failed, handle error
console.error("Request failed:", status, error);
alert('falied try again');
}
});
});//end
});
$( window ).on( "load", function() {
console.log( "window loaded" );
fetchClientPolicies();
});
function fetchClientPolicies() {
$('#loader').show();
var apiURL = '<?php echo base_url();?>' + 'util/clients-with-policies';
console.log('fetchClientPolicies');
console.log(apiURL);
$.ajax({
url: apiURL,
method: 'GET',
headers: {
"Content-Type": "application/json",
"X-Requested-With": "XMLHttpRequest"
},
success: function(response) {
// console.log(response.code);
// console.log(response.dataStatus);
// console.log(response.data);
if (response.code === 200 && response.dataStatus === true && response.data !== "") {
try {
clientPolicies = (response.data);
// console.log(clientPolicies);
appendClients(clientPolicies);
} catch (error)
{
console.error('Error parsing API response data:', error);
}
} else if(response.code === 404 && response.dataStatus === false){
console.error('no data found', response);
}
else
{
console.error('Something went wrong!');
}
},
error: function(xhr, status, error) {
console.error('Error fetching data from API:', error);
}
});
$('#loader').hide();
}
function appendClients(data) {
$.each(data, function(index, item) {
$('#client_id').append($('<option>', {
value: item.id,
text: item.client_name
}));
});
}
function appendPolicies(data) {
$('#policy_id').empty();
$('#policy_id').append($('<option>', { value: '0',text: 'Select'}));
$.each(data, function(index, item) {
$('#policy_id').append($('<option>', {
value: item.id,
text: item.name
}));
});
}
$('#client_id').on('change', function() {
var selectedClient = $(this).val();
console.log(selectedClient);
// $('#selectedOptionInfo').text('Selected option: ' + selectedOption);
// Check if the selected option exists in apiData
var foundPolicies = clientPolicies.find(function(item) {
return item.id === selectedClient;
});
console.log(foundPolicies.policies);
appendPolicies(foundPolicies.policies);
});
// Function to convert object to query parameters
function objectToQueryString(obj) {
return Object.keys(obj).map(key => `${encodeURIComponent(key)}=${encodeURIComponent(obj[key])}`).join('&');
}
function fetchEmpolyeeList(event) {
event.preventDefault(); // Prevent default action
var client_id = $('#client_id').val();
var policy_id = $('#policy_id').val();
console.log(client_id+'-'+policy_id);
if (client_id == '0' || policy_id == '0' ) {
alert('Please select values in both dropdowns.');
return;
}
var queryParams = {
client_id: client_id,
policy_id: policy_id
};
const queryString = objectToQueryString(queryParams);
const apiURL = $('#get-emp-list').attr('href')+"?" + queryString;
console.log(apiURL);
window.location.href = apiURL;
// var apiURL2 = $('#get-emp-list').attr('href'); // Get href attribute value
// console.log(apiURL);
// $.ajax({
// url: apiURL,
// method: 'GET',
// data: queryParams,
// success: function(response) {
// // Assuming response is a JSON array
// // displayDataTables(response);
// console.log(response);
// },
// error: function(xhr, status, error) {
// console.error('Error:', error);
// }
// });
}
</script>

41
app/Views/file_list.php Normal file
View File

@ -0,0 +1,41 @@
<div class="col-12">
<div class="card">
<div class="card-body">
<div class="row" style="padding-bottom: 10px;">
<div class="col-6" style="align-self: center;">
<h4 class="header-title" style="position: relative;">Files</h4>
</div>
</div>
<table class="table table-hover m-0 table-centered dt-responsive nowrap w-100" cellspacing="0" id="tickets-table">
<thead class="bg-light">
<tr>
<th class="font-weight-medium">SNO</th>
<th class="font-weight-medium">File name</th>
<th class="font-weight-medium">User/Time</th>
<th class="font-weight-medium">Status</th>
</tr>
</thead>
<tbody class="font-12">
<?php
if(isset($fileList))
{
foreach ($fileList as $key => $file) { ?>
<tr>
<td><b><?php echo ($key + 1)?></b></td>
<td><?php echo $file['file_name']?></td>
<td><?php echo fancy_date_time_format($file['created_at']).' by <strong>'.$file['first_name'].'</strong>'?></td>
<td><?php echo $file['status']; if($file['status'] == 'failed')
{
echo '<span class="col-xl-3 col-lg-4 col-sm-6"> <i class="fe-alert-circle" data-toggle="modal" data-target="#file-err-modal" data-err="'.$file['reason'].'"></i></span>';
}?></td>
</tr>
<?php }}?>
</tbody>
</table>
</div>
</div>
</div><!-- end col -->

View File

@ -525,6 +525,12 @@
<li class="nav-item">
<a class="nav-link" href="<?= base_url('/client/list')?>">Clients</a>
</li>
<li class="nav-item">
<a class="nav-link" href="<?= base_url('/employee/list')?>">Employees</a>
</li>
<li class="nav-item">
<a class="nav-link" href="<?= base_url('/employee/bulk-event-uplod')?>">Employees Upload</a>
</li>
<li class="nav-item">
<a class="nav-link" href="dashboard-analytics.html">Analytics</a>
</li>