get_date_range($request);
$start_date = $dates_array[0];
$end_date = $dates_array[1];
$drugs = [];
$merge_values = [];
$pharmacy_names = [];
$pharmacy_figures = [];
$cash_drugs_array = [];
$insurance_drugs_array = [];
$total_drugs_paid_via_cash = 0;
$purchased_elsewhere_counts = [];
$paid_prescriptions_percentage = 0;
$total_drugs_paid_via_insurance = 0;
$unpaid_prescriptions_percentage = 0;
$invoiced_prescriptions_percentage = 0;
$pharmacy_most_active_staff_figures = [];
$pharmacy_most_active_staff_members = [];
$most_active_pharmacy_staff_results = [];
$purchased_elsewhere_prescriptions_percentage = 0;
$display_text = "Showing results between " . streamline_date($start_date) . " and " . streamline_date($end_date);
//1. PHARMACY EPISODES VS PRESCRIPIONS
$patient_episodes = DB::table('patient_episodes')->
whereBetween('patient_episodes.created_at', [$start_date, $end_date])
->get()
->count();
$pharmacy_patients = DB::table('patient_episodes')
->whereBetween('patient_episodes.created_at', [$start_date, $end_date])
->join('patients', 'patients.id', '=', 'patient_episodes.patient_id')
->select(
'patient_episodes.patient_id', 'patient_episodes.treatment_id')->where('treatment_id', '>=', 1)
->get()->count();
$up = DB::table('treatments')
->whereBetween('treatments.created_at', [$start_date, $end_date])
->join('patients', 'patients.id', '=', 'treatments.patient_id')
->where('payment_status', 0)
->get()->count();
$pp = DB::table('treatments')
->whereBetween('treatments.created_at', [$start_date, $end_date])
->join('patients', 'patients.id', '=', 'treatments.patient_id')
->where('payment_status', 1)
->get()->count();
$ip = DB::table('treatments')
->whereBetween('treatments.created_at', [$start_date, $end_date])
->join('patients', 'patients.id', '=', 'treatments.patient_id')
->join('patient_category_invoices', 'patient_category_invoices.patient_id', '=', 'treatments.patient_id')
->select('treatments.dispense_status', 'patient_category_invoices.status', 'treatments.episode_id',
'treatments.patient_id', 'patient_category_invoices.payment_complete',
'patient_category_invoices.invoice_generated', 'patient_category_invoices.tag_id')
->where('patient_category_invoices.tag_id', 3)->distinct('episode_id')
->get()->count();
$pharmacy_prescriptions = $up + $pp + $ip;
$pharmacy_names[] = ['Prescriptions', 'Patients', 'Episodes'];
$pharmacy_figures[] = $pharmacy_patients;
$pharmacy_figures[] = $patient_episodes;
$pharmacy_figures[] = $pharmacy_prescriptions;
//2. PHARMACY DISPENSING PATTERN
$pharmacy_dispensing_labels = ['Paid & Dispensed', 'Unpaid & Dispensed', 'Invoiced & Dispensed'];
$paid_and_dispensed_prescriptions = DB::table('treatments')->whereBetween('created_at', [$start_date, $end_date])->where('dispense_status', 1)->where('payment_status', 1)->get()->count();
$paid_and_undispensed_prescriptions = DB::table('treatments')->whereBetween('created_at', [$start_date, $end_date])->where('dispense_status', 0)->where('payment_status', 1)->get()->count();
$unpaid_and_dispensed_prescriptions = DB::table('treatments')->whereBetween('created_at', [$start_date, $end_date])->where('dispense_status', 1)->where('payment_status', 0)->get()->count();
$invoiced_and_dispensed_prescriptions = DB::table('treatments')
->whereBetween('treatments.created_at', [$start_date, $end_date])
->join('patient_category_invoices', 'patient_category_invoices.patient_id', '=', 'treatments.patient_id')
->select('treatments.dispense_status', 'patient_category_invoices.status', 'treatments.episode_id',
'treatments.patient_id', 'patient_category_invoices.payment_complete',
'patient_category_invoices.invoice_generated', 'patient_category_invoices.tag_id')
->where('dispense_status', 1)->where('patient_category_invoices.tag_id', 3)
->get()->count();
$invoiced_and_undispensed_prescriptions = DB::table('treatments')
->whereBetween('treatments.created_at', [$start_date, $end_date])
->join('patient_category_invoices', 'patient_category_invoices.patient_id', '=', 'treatments.patient_id')
->select('treatments.dispense_status', 'patient_category_invoices.status', 'treatments.episode_id',
'treatments.patient_id', 'patient_category_invoices.payment_complete',
'patient_category_invoices.invoice_generated', 'patient_category_invoices.tag_id')
->where('dispense_status', 0)->where('patient_category_invoices.tag_id', 3)
->get()->count();
$pharmacy_dispensing_datasets[] = $paid_and_dispensed_prescriptions;
$pharmacy_dispensing_datasets[] = $paid_and_undispensed_prescriptions;
$pharmacy_dispensing_datasets[] = $unpaid_and_dispensed_prescriptions;
$pharmacy_dispensing_datasets[] = $invoiced_and_dispensed_prescriptions;
$pharmacy_dispensing_datasets[] = $invoiced_and_undispensed_prescriptions;
$total_dispensed = $paid_and_dispensed_prescriptions + $paid_and_undispensed_prescriptions + $unpaid_and_dispensed_prescriptions
+ $invoiced_and_dispensed_prescriptions + $invoiced_and_undispensed_prescriptions;
if($total_dispensed !== 0){
$paid_and_dispensed_prescriptions_percentage = ($paid_and_dispensed_prescriptions / ($total_dispensed)) * 100;
$paid_and_undispensed_prescriptions_percentage = ($paid_and_undispensed_prescriptions / ($total_dispensed)) * 100;
$unpaid_and_dispensed_prescriptions_percentage = ($unpaid_and_dispensed_prescriptions / ($total_dispensed)) * 100;
$invoiced_and_dispensed_prescriptions_percentage = ($invoiced_and_dispensed_prescriptions / ($total_dispensed)) * 100;
$invoiced_and_undispensed_prescriptions_percentage = ($invoiced_and_undispensed_prescriptions / ($total_dispensed)) * 100;
} else{
$paid_and_undispensed_prescriptions_percentage = 0;
$unpaid_and_dispensed_prescriptions_percentage = 0;
$invoiced_and_dispensed_prescriptions_percentage = 0;
$invoiced_and_undispensed_prescriptions_percentage = 0;
$paid_and_dispensed_prescriptions_percentage = 0;
$paid_prescriptions_percentage = 0;
$unpaid_prescriptions_percentage = 0;
$invoiced_prescriptions_percentage = 0;
$purchased_elsewhere_prescriptions_percentage = 0;
}
//3. PHARMACY PRESCRIPTIONS PATTERN
//Invoiced Pharmacy Prescriptions
$invoiced_prescriptions = DB::table('treatments')
->whereBetween('treatments.created_at', [$start_date, $end_date])
->join('patient_category_invoices', 'patient_category_invoices.patient_id', '=', 'treatments.patient_id')
->select('treatments.dispense_status', 'patient_category_invoices.status', 'treatments.episode_id',
'treatments.patient_id', 'patient_category_invoices.payment_complete',
'patient_category_invoices.invoice_generated', 'patient_category_invoices.tag_id')
->where('patient_category_invoices.tag_id', 3)
//->distinct('episode_id')
->get()->count();
//Unpaid Pharmacy Prescriptions
$unpaid_prescriptions = DB::table('treatments')
->whereBetween('treatments.created_at', [$start_date, $end_date])
->where('payment_status', 0)
->get();
if(count($unpaid_prescriptions) > 0) {
$unpaid_merge_values = count($unpaid_prescriptions);
} else {
$unpaid_merge_values = 0;
}
//Paid Pharmacy Prescriptions
$paid_prescriptions = DB::table('treatments')
->whereBetween('treatments.created_at', [$start_date, $end_date])
->where('payment_status', 1)
->get();
$invoice_prescriptions = DB::table('patient_category_invoices')
->whereBetween('patient_category_invoices.created_at', [$start_date, $end_date])
->select('patient_id')
->get();
//$paid_prescriptions = count($paid_prescriptions) - count($invoice_prescriptions);
if(count($paid_prescriptions) > 0){
$paid_merge_values = count($paid_prescriptions);
} else {
$paid_merge_values = 0;
}
//Purchased Elsewhere Prescriptions
$purchased_elsewhere_prescriptions = DB::table('treatments')
->whereBetween('treatments.created_at', [$start_date, $end_date])
->select('purchased_elsewhere')
->where('purchased_elsewhere', '!=', NULL)
->get();
if(count($purchased_elsewhere_prescriptions) > 0) {
$purchased_elsewhere_counts = [];
foreach($purchased_elsewhere_prescriptions as $pew){
$purchased_elsewhere_results = explode(',', $pew->purchased_elsewhere);
foreach($purchased_elsewhere_results as $per){
if($per == 1){
$purchased_elsewhere_counts[] = $per;
}
}
}
} else {
$purchased_elsewhere_prescriptions = 0;
}
//Computations for Pharmacy Dashboard
$purchased_elsewhere_prescriptions = count($purchased_elsewhere_counts);
$unpaid_prescriptions = $unpaid_merge_values;
$paid_prescriptions = $paid_merge_values;
$pharmacy_patient_prescriptions_datasets[] = $invoiced_prescriptions;
$pharmacy_patient_prescriptions_datasets[] = $unpaid_prescriptions;
$pharmacy_patient_prescriptions_datasets[] = $paid_prescriptions;
$total_prescriptions = $invoiced_prescriptions + $unpaid_prescriptions + $paid_prescriptions;
if($total_prescriptions !== 0) {
$invoiced_prescriptions_percentage = ($invoiced_prescriptions / ($total_prescriptions)) * 100;
$unpaid_prescriptions_percentage = ($unpaid_prescriptions / ($total_prescriptions)) * 100;
$paid_prescriptions_percentage = ($paid_prescriptions / ($total_prescriptions)) * 100;
$purchased_elsewhere_prescriptions_percentage = ($purchased_elsewhere_prescriptions / ($total_prescriptions)) * 100;
} else {
}
//4. PHARMACY TOP DRUGS
$patient_dispensings = DB::table('patient_dispensings')
->whereBetween('created_at', [$start_date, $end_date])
->select('drugs', 'quantity_dispensed', 'patient_id')
->get();
$drug_id_array = [];
$drug_male_array = [];
$drug_female_array = [];
foreach ($patient_dispensings as $drug) {
// split into an array for drugs
$temp_drugs_array = explode(",", $drug->drugs);
$temp_dispensed_array = explode(",", $drug->quantity_dispensed);
for ($i = 0; $i < count($temp_dispensed_array); $i++) {
if ($temp_dispensed_array[$i] == "") {
$temp_dispensed_array[$i] = 0;
}
if (array_key_exists($temp_drugs_array[$i], $drug_id_array)) {
$drug_id_array[$temp_drugs_array[$i]] = $drug_id_array[$temp_drugs_array[$i]] + $temp_dispensed_array[$i];
if (get_name($drug->patient_id, 'id', 'gender', 'patients') == 1 && isset($drug_male_array[$temp_drugs_array[$i]])) {
$drug_male_array[$temp_drugs_array[$i]] = $drug_male_array[$temp_drugs_array[$i]] + $temp_dispensed_array[$i];
} elseif (get_name($drug->patient_id, 'id', 'gender', 'patients') == 2 && isset($drug_female_array[$temp_drugs_array[$i]])) {
$drug_female_array[$temp_drugs_array[$i]] = $drug_female_array[$temp_drugs_array[$i]] + $temp_dispensed_array[$i];
}
} else {
$drug_id_array[$temp_drugs_array[$i]] = $temp_dispensed_array[$i];
if (get_name($drug->patient_id, 'id', 'gender', 'patients') == 1) {
$drug_male_array[$temp_drugs_array[$i]] = $temp_dispensed_array[$i];
} else {
$drug_female_array[$temp_drugs_array[$i]] = $temp_dispensed_array[$i];
}
}
}
}
arsort($drug_id_array);
$drug_id_array = array_slice($drug_id_array, 0, 10, true);
$drugs = [];
$drugs_names = [];
$drugs_figures = [];
foreach ($drug_id_array as $key => $value) {
$male = $drug_male_array[$key] ?? 0;
$female = $drug_female_array[$key] ?? 0;
$drugs[] = [
"id" => $key,
"name" => get_name($key, 'id', 'name', 'drugs'),
"male" => $male,
"female" => $female,
"total" => $male + $female,
];
$drugs_names[] = get_name($key, 'id', 'name', 'drugs');
$drugs_figures[] = $male + $female;
}
//5. PHARMACY MOST ACTIVE STAFF
$most_active_pharmacy_staff = DB::table('patient_dispensings')
->whereBetween('patient_dispensings.created_at', [$start_date, $end_date])
->join('users', 'users.id', '=', 'patient_dispensings.created_by')
->select(DB::raw('count(*) as user_activity_count'))->addSelect('users.first_name', 'users.last_name',
'patient_dispensings.created_by as treatment_deposits_creator_id',
'users.phone as staff_number')
->groupBy('patient_dispensings.created_by')
->take(5)
->get();
foreach($most_active_pharmacy_staff as $maps) {
$most_active_pharmacy_staff_results[] = $maps;
$pharmacy_most_active_staff_members[] = $maps->first_name. " ".$maps->last_name;
$pharmacy_most_active_staff_figures[] = $maps->user_activity_count;
}
//6. DRUGS PAID BY CASH VS DRUGS PAID BY INVOICE
$drugs_paid_via_insurance = $invoiced_prescriptions;
$drugs_paid_via_cash = $paid_prescriptions;
if($drugs_paid_via_insurance > 0) {
$total_drugs_paid_via_insurance = $drugs_paid_via_insurance;
}
if($drugs_paid_via_cash > 0) {
$total_drugs_paid_via_cash = $drugs_paid_via_cash;
}
$pharmacy_drugs_via_cash = $total_drugs_paid_via_cash;
$pharmacy_drugs_via_insurance = $total_drugs_paid_via_insurance;
if($total_drugs_paid_via_insurance !== 0 && $total_drugs_paid_via_cash !== 0) {
$pharmacy_drugs_via_cash_percentage = ($total_drugs_paid_via_cash / ($total_drugs_paid_via_cash + $total_drugs_paid_via_insurance)) * 100;
$pharmacy_drugs_via_insurance_percentage = ($total_drugs_paid_via_insurance / ($total_drugs_paid_via_cash + $total_drugs_paid_via_insurance)) * 100;
} else {
$pharmacy_drugs_via_cash_percentage = 0;
$pharmacy_drugs_via_insurance_percentage = 0;
}
$drugs_paid_via_cash = $total_drugs_paid_via_cash;
$drugs_paid_via_insurance = $total_drugs_paid_via_insurance;
$pharmacy_drugs_via_cash_vs_drugs_via_insurance_figures[] = $drugs_paid_via_cash;
$pharmacy_drugs_via_cash_vs_drugs_via_insurance_figures[] = $drugs_paid_via_insurance;
//GRAPHS
//Pharmacy top drugs chart
$pharmacy_top_drugs_chart = app()->chartjs
->name('drugsChart')
->type('bar')
->size(['width' => 600, 'height' => 400])
->labels($drugs_names)
->datasets([
[
"label" => "No. of drugs sold",
'backgroundColor' => ['#355070', '#6d597a', '#b56576', '#e56b6f', '#eaac8b', '#461220', '#8c2f39', '#b23a48', '#d9f2b4', '#353831'],
'data' => $drugs_figures
]
])
->optionsRaw([
'legend' => [
'display' => false,
],
'scales' => [
'yAxes' => [['ticks' => ['beginAtZero' => true],
'scaleLabel' => [
'display' => true,
'labelString' => 'No. of drugs sold'
],
],],
'xAxes' => [['ticks' => ['autoSkip' => false,],]]
],
])
->options([]);
//Pharmacy prescription chart
$pharmacy_prescription_pattern_chart = app()->chartjs
->name('pharmacy_patient_prescriptions')
->type('pie')
->size(['width' => 700, 'height' => 300])
->labels(['Invoiced', 'Unpaid', 'Paid'])
->datasets([
[
"label" => 'Pharmacy Statistics',
'backgroundColor' => ['#809848', '#E03123', '#4AB64F'],
'data' => $pharmacy_patient_prescriptions_datasets
]
])
->options([]);
//Pharmacy dispensing chart
$pharmacy_dispensing_pattern_chart = app()->chartjs
->name('pharmacy_patient_dispensing')
->type('pie')
->size(['width' => 700, 'height' => 300])
->labels(['P & D', 'P & U', 'U & D', 'I & D', 'I & U'])
->datasets([
[
"label" => 'Pharmacy Statistics',
'backgroundColor' => ['#319B79', '#00bfb2', '#028090', '#f0f3bd', '#c64191'],
'data' => $pharmacy_dispensing_datasets,
]
])
->options([]);
//Pharmacy episodes vs prescriptions chart
$pharmacy_episodes_vs_prescriptions_chart = app()->chartjs
->name('pharmacy_patient_statistics')
->type('bar')
->size(['width' => 800, 'height' => 200])
->labels(['Patients', 'Episodes', 'Prescriptions'])
->datasets([
[
"label" => 'Pharmacy Statistics',
'backgroundColor' => ['#9ed8db','#467599', '#1d3354'],
'data' => $pharmacy_figures
]
])
->optionsRaw([
'scales' => [
'yAxes' => [['ticks' => ['beginAtZero' => true],],],
'xAxes' => [['ticks' => ['autoSkip' => false,],]]
]
])
->options([]);
//Pharmacy most active staff chart
$pharmacy_most_active_pharmacy_staff_chart = app()->chartjs
->name('pharmacy_most_active_staff')
->type('bar')
->size(['width' => 800, 'height' => 200])
->labels($pharmacy_most_active_staff_members)
->datasets([
[
"label" => 'Number of Prescriptions Dispensed',
'backgroundColor' => ['#55dde0', '#33658a', '#2f4858', '#f6ae2d', '#f26419'],
'data' => $pharmacy_most_active_staff_figures
]
])
->optionsRaw([
'scales' => [
'yAxes' => [['ticks' => ['beginAtZero' => true],],],
'xAxes' => [['ticks' => ['autoSkip' => false,],]]
]
])
->options([]);
//Pharmacy drugs purchased by cash vs other payment options chart
$pharmacy_drugs_via_cash_vs_drugs_via_insurance_chart = app()->chartjs
->name('pharmacy_drugs_via_cash_vs_drugs_via_insurance')
->type('pie')
->size(['width' => 700, 'height' => 300])
->labels(['Prescriptions Paid By Cash', 'Invoiced'])
->datasets([
[
"label" => 'Cash Vs Insurance',
'backgroundColor' => ['#aa4465','#592e83'],
'data' => $pharmacy_drugs_via_cash_vs_drugs_via_insurance_figures
]
])
->options([]);
return view('reports::reports_dashboard.pharmacy_overview', compact('pharmacy_patients', 'patient_episodes','pharmacy_prescriptions', 'pharmacy_dispensing_pattern_chart',
'paid_and_dispensed_prescriptions', 'unpaid_and_dispensed_prescriptions', 'paid_and_undispensed_prescriptions',
'unpaid_and_dispensed_prescriptions', 'invoiced_and_undispensed_prescriptions', 'invoiced_and_dispensed_prescriptions',
'paid_and_undispensed_prescriptions_percentage','unpaid_and_dispensed_prescriptions_percentage',
'invoiced_and_dispensed_prescriptions_percentage','invoiced_and_undispensed_prescriptions_percentage', 'paid_and_dispensed_prescriptions_percentage',
'pharmacy_dispensing_datasets', 'pharmacy_episodes_vs_prescriptions_chart', 'pharmacy_prescription_pattern_chart',
'paid_prescriptions_percentage', 'unpaid_prescriptions_percentage',
'invoiced_prescriptions_percentage', 'purchased_elsewhere_prescriptions_percentage',
'invoiced_prescriptions', 'unpaid_prescriptions', 'paid_prescriptions', 'purchased_elsewhere_prescriptions',
'pharmacy_patient_prescriptions_datasets', 'pharmacy_top_drugs_chart', 'drugs', 'display_text', 'pharmacy_drugs_via_cash', 'pharmacy_drugs_via_insurance',
'pharmacy_drugs_via_cash_vs_drugs_via_insurance_chart', 'pharmacy_drugs_via_cash_percentage',
'pharmacy_drugs_via_cash_vs_drugs_via_insurance_figures', 'pharmacy_drugs_via_insurance_percentage', 'most_active_pharmacy_staff_results',
'pharmacy_most_active_pharmacy_staff_chart', 'pharmacy_most_active_staff_members'));
}
//pharmacy top drugs
public function pharmacy_top_drugs(Request $request)
{
$dates_array = $this->get_date_range($request);
$start_date = $dates_array[0];
$end_date = $dates_array[1];
$display_text = "Showing results between " . streamline_date($start_date) . " and " . streamline_date($end_date);
$patient_dispensings = DB::table('patient_dispensings')
->whereBetween('created_at', [$start_date, $end_date])
->select('drugs', 'quantity_dispensed', 'patient_id')
->get();
$drug_id_array = [];
$drug_male_array = [];
$drug_female_array = [];
foreach ($patient_dispensings as $drug) {
// split into an array for drugs
$temp_drugs_array = explode(",", $drug->drugs);
$temp_dispensed_array = explode(",", $drug->quantity_dispensed);
for ($i = 0; $i < count($temp_dispensed_array); $i++) {
if ($temp_dispensed_array[$i] == "") {
$temp_dispensed_array[$i] = 0;
}
if (array_key_exists($temp_drugs_array[$i], $drug_id_array)) {
$drug_id_array[$temp_drugs_array[$i]] = $drug_id_array[$temp_drugs_array[$i]] + $temp_dispensed_array[$i];
if (get_name($drug->patient_id, 'id', 'gender', 'patients') == 1 && isset($drug_male_array[$temp_drugs_array[$i]])) {
$drug_male_array[$temp_drugs_array[$i]] = $drug_male_array[$temp_drugs_array[$i]] + $temp_dispensed_array[$i];
} elseif (get_name($drug->patient_id, 'id', 'gender', 'patients') == 2 && isset($drug_female_array[$temp_drugs_array[$i]])) {
$drug_female_array[$temp_drugs_array[$i]] = $drug_female_array[$temp_drugs_array[$i]] + $temp_dispensed_array[$i];
}
} else {
$drug_id_array[$temp_drugs_array[$i]] = $temp_dispensed_array[$i];
if (get_name($drug->patient_id, 'id', 'gender', 'patients') == 1) {
$drug_male_array[$temp_drugs_array[$i]] = $temp_dispensed_array[$i];
} else {
$drug_female_array[$temp_drugs_array[$i]] = $temp_dispensed_array[$i];
}
}
}
}
arsort($drug_id_array);
$drug_id_array = array_slice($drug_id_array, 0, 10, true);
$drugs = [];
$drugs_names = [];
$drugs_figures = [];
foreach ($drug_id_array as $key => $value) {
$male = $drug_male_array[$key] ?? 0;
$female = $drug_female_array[$key] ?? 0;
$drugs[] = [
"id" => $key,
"name" => get_name($key, 'id', 'name', 'drugs'),
"male" => $male,
"female" => $female,
"total" => $male + $female,
];
$drugs_names[] = get_name($key, 'id', 'name', 'drugs');
$drugs_figures[] = $male + $female;
}
return view('reports::reports_dashboard.pharmacy_top_drugs', compact('display_text', 'drugs', 'drugs_names'));
}
//pharmacy lists
public function pharmacy_lists(Request $request)
{
$dates_array = $this->get_date_range($request);
$start_date = $dates_array[0];
$end_date = $dates_array[1];
$display_text = "Showing results between " . streamline_date($start_date) . " and " . streamline_date($end_date);
if($request->pharmacy_dispensing_pattern == 'pharmacy_dispensing_pattern') {
return $this->pharmacy_dispensing_pattern($request);
} elseif($request->pharmacy_prescription_pattern == 'pharmacy_prescription_pattern') {
return $this->pharmacy_prescription_pattern($request);
} elseif($request->pharmacy_top_drugs == 'pharmacy_top_drugs') {
return $this->pharmacy_top_drugs($request);
} elseif($request->pharmacy_episodes_vs_prescriptions == 'pharmacy_episodes_vs_prescriptions') {
return $this->pharmacy_episodes_vs_prescriptions($request);
}
}
//top diagnoses
public function top_diagnoses(Request $request)
{
$dates_array = $this->get_date_range($request);
$start_date = $dates_array[0];
$end_date = $dates_array[1];
$display_text = "Showing results between " . streamline_date($start_date) . " and " . streamline_date($end_date);
$diagnoses_array = DB::table('consultations')
->whereBetween('created_at', [$start_date, $end_date])
->selectRaw('primary_diagnosis, COUNT(*) as count')
->groupBy('primary_diagnosis')
->orderBy('count', 'desc')
->limit(10)
->get()
->toArray();
$diagnoses = [];
$diagnoses_names = [];
$diagnoses_figures = [];
foreach ($diagnoses_array as $diagnosis) {
$records = DB::table('consultations')
->whereBetween('created_at', [$start_date, $end_date])
->where('primary_diagnosis', $diagnosis->primary_diagnosis)
->get(['patient_id']);
$male = 0;
$female = 0;
foreach ($records as $record) {
if (get_name($record->patient_id, 'id', 'gender', 'patients') == 1) {
$male++;
} else {
$female++;
}
}
$diagnoses[] = [
"id" => $diagnosis->primary_diagnosis,
"name" => get_name($diagnosis->primary_diagnosis, 'id', 'name', 'diagnoses'),
"male" => $male,
"female" => $female,
"total" => ($male + $female),
];
$diagnoses_names[] = get_name($diagnosis->primary_diagnosis, 'id', 'name', 'diagnoses');
$diagnoses_figures[] = $male + $female;
}
$diagnoses_chart = app()->chartjs
->name('diagnosisChart')
->type('horizontalBar')
->size(['width' => 600, 'height' => 400])
->labels($diagnoses_names)
->datasets([
[
"label" => "Top Recorded Diagnoses",
'backgroundColor' => '#9a04f0',
'data' => $diagnoses_figures
]
])
->optionsRaw([
'scales' => [
'yAxes' => [['ticks' => ['autoSkip' => false],],],
'xAxes' => [['ticks' => ['beginAtZero' => true,],]]
]
])
->options([]);
return view('reports::reports_dashboard.top_diagnoses', compact('diagnoses', 'diagnoses_chart', 'diagnoses_names', 'diagnoses_figures', 'display_text'));
}
//top investigations
public function top_investigations(Request $request)
{
$dates_array = $this->get_date_range($request);
$start_date = $dates_array[0];
$end_date = $dates_array[1];
$display_text = "Showing results between " . streamline_date($start_date) . " and " . streamline_date($end_date);
$investigations_with_results = DB::table('investigation_results')
->whereBetween('created_at', [$start_date, $end_date])
->get();
$investigation_id_array = [];
$investigation_male_array = [];
$investigation_female_array = [];
foreach ($investigations_with_results as $value) {
// split into an array for labs
$temp_investigations_array = explode(",", $value->investigation_id);
// loop through the temporary arrays
for ($i = 0; $i < count($temp_investigations_array); $i++) {
// check if we have already recorded the diagnosis
if (array_key_exists($temp_investigations_array[$i], $investigation_id_array)) {
$investigation_id_array[$temp_investigations_array[$i]] = $investigation_id_array[$temp_investigations_array[$i]] + 1;
if (get_name($value->patient_id, 'id', 'gender', 'patients') == 1 && isset($investigation_male_array[$temp_investigations_array[$i]])) {
$investigation_male_array[$temp_investigations_array[$i]] = $investigation_male_array[$temp_investigations_array[$i]] + 1;
} elseif (get_name($value->patient_id, 'id', 'gender', 'patients') == 2 && isset($investigation_female_array[$temp_investigations_array[$i]])) {
$investigation_female_array[$temp_investigations_array[$i]] = $investigation_female_array[$temp_investigations_array[$i]] + 1;
}
} else {
if (get_name($value->patient_id, 'id', 'gender', 'patients') == 1) {
$investigation_male_array[$temp_investigations_array[$i]] = 1;
} else {
$investigation_female_array[$temp_investigations_array[$i]] = 1;
}
$investigation_id_array[$temp_investigations_array[$i]] = 1;
}
}
}
arsort($investigation_id_array);
$investigation_id_array = array_slice($investigation_id_array, 0, 10, true);
$investigations = [];
$investigations_names = [];
$investigations_figures = [];
foreach ($investigation_id_array as $key => $value) {
$male = $investigation_male_array[$key] ?? 0;
$female = $investigation_female_array[$key] ?? 0;
$investigations[] = [
"id" => $key,
"name" => get_name($key, 'id', 'name', 'investigations'),
"male" => $male,
"female" => $female,
"total" => $male + $female,
];
$investigations_names[] = get_name($key, 'id', 'name', 'investigations');
$investigations_figures[] = $male + $female;
}
$investigation_chart = app()->chartjs
->name('investigationChart')
->type('horizontalBar')
->size(['width' => 600, 'height' => 400])
->labels($investigations_names)
->datasets([
[
"label" => "Top Recorded Investigations",
'backgroundColor' => '#9a04f0',
'data' => $investigations_figures
]
])
->optionsRaw([
'scales' => [
'yAxes' => [['ticks' => ['autoSkip' => false],],],
'xAxes' => [['ticks' => ['beginAtZero' => true,],]]
]
])
->options([]);
return view('reports::reports_dashboard.top_investigations', compact('investigations', 'investigation_chart', 'display_text'));
}
//diagnoses details
public function diagnosis_details($id)
{
$months = [];
$male_figures = [];
$female_figures = [];
for ($i = 0; $i < 14; $i++) {
$start_date_search = Carbon::now()->subMonthsNoOverflow($i)->firstOfMonth()->startOfDay();
$end_date_search = Carbon::now()->subMonthsNoOverflow($i)->lastOfMonth()->endOfDay();
$diagnoses = DB::table('consultations')
->where('primary_diagnosis', $id)
->whereBetween('created_at', [$start_date_search, $end_date_search])
->get(['patient_id']);
$male = 0;
$female = 0;
foreach ($diagnoses as $diagnosis) {
if (get_name($diagnosis->patient_id, 'id', 'gender', 'patients') == 1) {
$male++;
} else {
$female++;
}
}
$months[] = Carbon::now()->subMonthsNoOverflow($i)->englishMonth . " " . Carbon::now()->subMonthsNoOverflow($i)->yearIso;
$male_figures[] = $male;
$female_figures[] = $female;
}
return view('reports::reports_dashboard.diagnosis_details', compact('months', 'male_figures', 'female_figures', 'id'));
}
//top suppliers
public function top_suppliers(Request $request)
{
$dates_array = $this->get_date_range($request);
$start_date = $dates_array[0];
$end_date = $dates_array[1];
$display_text = "Showing results between " . streamline_date($start_date) . " and " . streamline_date($end_date);
$suppliers = DB::table('suppliers')
->get(['id', 'name']);
$top_suppliers = [];
foreach ($suppliers as $supplier) {
$quotations = DB::table('quotations')
->whereBetween('created_at', [$start_date, $end_date])
->whereNotNull('total_price')
->where('supplier_id', $supplier->id)
->get();
$total = 0;
foreach ($quotations as $quotation) {
$total += $quotation->total_price;
}
$top_suppliers[$supplier->id] = $total;
}
arsort($top_suppliers);
$top_suppliers = array_slice($top_suppliers, 0, 10, true);
$names = [];
$amounts = [];
foreach ($top_suppliers as $key => $value) {
$names[] = get_name($key, 'id', 'name', 'suppliers');
$amounts[] = $value;
}
return view('reports::reports_dashboard.top_suppliers', compact('names', 'amounts', 'display_text'));
}
/**
* Staff Reports including doctors, pharmacists, lab attendants, nurses and receptionists
*/
public function top_staff(Request $request)
{
$dates_array = $this->get_date_range($request);
$start_date = $dates_array[0];
$end_date = $dates_array[1];
$consultation = [];
$colors = ['#55dde0', '#33658a', '#2f4858',
'#f6ae2d', '#f26419', '#2d2d2a', '#353831', '#38423b',
'#3f5e5a', '#20fc8f', '#f19a3e', '#98d9c2', '#403233',
'#840032', '#002642', '#ff57bb', '#e01a4f', '#f15946',
'#0d0630', '#a2a392'];
$top_performing_lab_attendants_results = [];
$top_performing_lab_attendants_members = [];
$top_performing_lab_attendants_figures = [];
$top_performing_nurses_at_triage_members = [];
$top_performing_nurses_at_triage_figures = [];
$top_performing_lab_attendants_received_by = [];
$top_performing_lab_attendants_entered_by = [];
$top_performing_lab_attendants_authenticated_by = [];
$top_performing_receptionists_at_triage_members = [];
$top_performing_receptionists_at_triage_figures = [];
$pharmacy_most_active_staff_members = [];
$most_active_pharmacy_staff_results = [];
$pharmacy_most_active_staff_figures = [];
$top_performing_doctor_members = [];
$top_performing_doctor_figures = [];
$users = User::all();
$display_text = "Showing results between " . streamline_date($start_date) . " and " . streamline_date($end_date);
// 1.TOP PERFORMIMG DOCTORS AT OPD
$consultations = DB::table('consultations')->whereNull('deleted_at')
->whereBetween('created_at', [$start_date, $end_date])
->where('completed', 1)
->get(['consultation_done_by', 'created_by', 'updated_by', 'episode_id']);
$doctors = [];
foreach ($consultations as $consultation) {
if (!is_null($consultation->consultation_done_by)) {
$doctor_id = $consultation->consultation_done_by;
} else {
$doctor_id = $consultation->created_by;
}
if (isset($doctors[$doctor_id])) {
$doctors[$doctor_id] = $doctors[$doctor_id] + 1;
} else {
$doctors[$doctor_id] = 1;
}
}
arsort($doctors);
if (count($doctors) > 10) {
$doctors = array_slice($doctors, 0, 10, true);
}
foreach ($doctors as $doctor_id => $doctor) {
$top_performing_doctor_members[] = get_full_name($doctor_id, 'id', 'first_name', 'last_name', 'users');
$top_performing_doctor_figures[] = $doctor;
}
//displaying graphical data of top doctor performers
$top_performing_doctors_chart = app()->chartjs
->name('top_performing_doctors')
->type('bar')
->size(['width' => 800, 'height' => 400])
->labels($top_performing_doctor_members)
->datasets([
[
"label" => 'Consultations at OPD',
'backgroundColor' => $colors,
'data' => $top_performing_doctor_figures
]
])
->optionsRaw([
'legend' => [
'display' => false,
],
'scales' => [
'yAxes' => [['ticks' => ['beginAtZero' => true],
'scaleLabel' => [
'display' => true,
'labelString' => 'No. of consultations at OPD'
],
],],
'xAxes' => [['ticks' => ['autoSkip' => false,
'scaleLabel' => [
'display' => true,
'labelString' => 'Staff Names'
],
],]]
]
])
->options([]);
// 2.TOP PERFORMING LAB ATTENDANTS
//results received by
$requests_received_by = DB::table('ordered_investigations')
->whereBetween('ordered_investigations.created_at', [$start_date, $end_date])
->join('users', 'users.id', '=', 'ordered_investigations.request_received_by')
->select('ordered_investigations.created_at as created_at',
'ordered_investigations.request_received_by as request_received_by',
'users.id as user_id', 'users.first_name', 'users.last_name')
->get();
//results entered by
$requests_entered_by = DB::table('investigation_results')
->whereBetween('investigation_results.created_at', [$start_date, $end_date])
->join('users', 'users.id', '=', 'investigation_results.created_by')
->select('investigation_results.created_at as created_at', 'investigation_results.created_by as request_entered_by','users.id as user_id', 'users.first_name', 'users.last_name')
->get();
//results authenticated by
$requests_authenticated_by = DB::table('investigation_results')
->whereBetween('investigation_results.created_at', [$start_date, $end_date])
->join('users', 'users.id', '=', 'investigation_results.authenticated_by')
->select('investigation_results.created_at as created_at', 'investigation_results.authenticated_by as request_authenticated_by','users.id as user_id', 'users.first_name', 'users.last_name')
->get();
$members = [];
//merge all collections to array and group by user_id
$array_merges = array_merge($requests_received_by->toArray(), $requests_entered_by->toArray(), $requests_authenticated_by->toArray());
$array_groups = array_group_by_key($array_merges, 'user_id');
//sorting by descending order
arsort($array_groups);
//pick the top 10 elements in the array
$array_groups = array_slice($array_groups, 0, 10, true);
//loop through list assigning corresponding values to each member
foreach($array_groups as $array_group){
$collected = collect($array_group);
$user_id = null;
$group_received_by = $collected->groupBy('request_received_by')->all();
$group_entered_by = $collected->groupBy('request_entered_by')->all();
$group_authenticated_by = $collected->groupBy('request_authenticated_by')->all();
$group_received_by = count(array_shift($group_received_by));
$group_entered_by = count(array_pop($group_entered_by));
$group_authenticated_by = count(array_pop($group_authenticated_by));
$top_performing_lab_attendants_figures[] = $group_received_by + $group_entered_by + $group_authenticated_by;
$top_performing_lab_attendants_received_by[] = $group_received_by;
$top_performing_lab_attendants_entered_by[] = $group_entered_by;
$top_performing_lab_attendants_authenticated_by[] = $group_authenticated_by;
}
//extract keys as user ids
$keys = array_keys($array_groups);
//store user ids
foreach($keys as $key){
$members[] = User::find($key);
}
//create a list of members to populate on graph
foreach($members as $member){
$top_performing_lab_attendants_members[] = $member->first_name. " ".$member->last_name;
}
//displaying graphical data of lab performers
$top_performing_lab_attendants_chart = app()->chartjs
->name('top_performing_lab_attendants')
->type('bar')
->size(['width' => 800, 'height' => 400])
->labels($top_performing_lab_attendants_members)
->datasets([
[
'label' => 'Requests received + Results entered + Results authenticated',
// 'label' => 'Requests received '.'('.$top_performing_lab_attendants_received_by[$i].')'.
// '+ Results entered ' .'('.$top_performing_lab_attendants_entered_by[$i].')'.
// '+ Results authenticated '.'('.($top_performing_lab_attendants_authenticated_by[$i].')'),
'backgroundColor' => $colors,
'data' => $top_performing_lab_attendants_figures
]
])
->optionsRaw([
'legend' => [
'display' => false,
],
'scales' => [
'yAxes' => [['ticks' => ['beginAtZero' => true],
'scaleLabel' => [
'display' => true,
'labelString' => 'No of requests received, entered and authenticated'
],
],],
'xAxes' => [['ticks' => ['autoSkip' => false,
'scaleLabel' => [
'display' => true,
'labelString' => 'Staff Names'
],
],]]
]
])
->options([]);
// 3.TOP PERFORMING NURSES AT TRIAGE
//triage created by
$triage_created_by = DB::table('triage')
->whereBetween('triage.created_at', [$start_date, $end_date])
->join('users', 'users.id', '=', 'triage.created_by')
->select('triage.created_at as created_at',
'triage.created_by as episode_created_by',
'users.id as user_id', 'users.first_name', 'users.last_name')
->get();
$members = [];
//merge all collections to array and group by user_id
$array_merges = array_merge($triage_created_by->toArray());
$array_groups = array_group_by_key($array_merges, 'user_id');
//sorting by descending order
arsort($array_groups);
//pick the top 10 elements in the array
$array_groups = array_slice($array_groups, 0, 10, true);
//loop through list assigning corresponding values to each member
foreach($array_groups as $array_group){
$top_performing_nurses_at_triage_figures[] = count($array_group);
}
//extract keys as user ids
$keys = array_keys($array_groups);
//store user ids for only doctors
foreach($keys as $key){
$members[] = User::find($key);
}
//create a list of members to populate on graph
foreach($members as $member){
$top_performing_nurses_at_triage_members[] = $member->first_name. " ".$member->last_name;
}
//displaying graphical data of top nurse performers
$top_performing_nurses_at_triage_chart = app()->chartjs
->name('top_performing_nurses_at_triage')
->type('bar')
->size(['width' => 800, 'height' => 400])
->labels($top_performing_nurses_at_triage_members)
->datasets([
[
"label" => 'Number of Triage records submitted',
'backgroundColor' => $colors,
'data' => $top_performing_nurses_at_triage_figures
]
])
->optionsRaw([
'legend' => [
'display' => false,
],
'scales' => [
'yAxes' => [['ticks' => ['beginAtZero' => true],
'scaleLabel' => [
'display' => true,
'labelString' => 'No of triage records submitted'
],
],],
'xAxes' => [['ticks' => ['autoSkip' => false,],]]
]
])
->options([]);
// 4.TOP PERFORMING STAFF AT PHARMACY
//treatment created by
$treatment_created_by = DB::table('treatments')
->whereBetween('treatments.created_at', [$start_date, $end_date])
->join('users', 'users.id', '=', 'treatments.created_by')
->select('treatments.created_at as created_at',
'treatments.dispense_status as dispense_status',
'treatments.created_by as treatment_created_by',
'users.id as user_id', 'users.first_name', 'users.last_name')
->get();
//patient dispensing dispensed by
$treatment_dispensed_by = DB::table('patient_dispensings')
->whereBetween('patient_dispensings.created_at', [$start_date, $end_date])
->join('users', 'users.id', '=', 'patient_dispensings.created_by')
->select('patient_dispensings.created_at as created_at',
'patient_dispensings.dispensed as is_dispensed',
'patient_dispensings.created_by as treatment_created_by',
'users.id as user_id', 'users.first_name', 'users.last_name')
->get();
//ward dispensing dispensed by
$ward_dispensed_by = DB::table('ward_dispensings')
->whereBetween('ward_dispensings.created_at', [$start_date, $end_date])
->join('users', 'users.id', '=', 'ward_dispensings.created_by')
->select('ward_dispensings.created_at as created_at',
'ward_dispensings.received_by as received_by',
'ward_dispensings.created_by as ward_dispensed_by',
'users.id as user_id', 'users.first_name', 'users.last_name')
->get();
$members = [];
//merge all collections to array and group by user_id
$array_merges = array_merge($treatment_created_by->toArray(), $treatment_dispensed_by->toArray(), $ward_dispensed_by->toArray());
$array_groups = array_group_by_key($array_merges, 'user_id');
//sorting by descending order
arsort($array_groups);
//pick the top 10 elements in the array
$array_groups = array_slice($array_groups, 0, 10, true);
//loop through list assigning corresponding values to each member
foreach($array_groups as $array_group){
$pharmacy_most_active_staff_figures[] = count($array_group);
}
//extract keys as user ids
$keys = array_keys($array_groups);
//store user ids for only doctors
foreach($keys as $key){
$members[] = User::find($key);
}
//create a list of members to populate on graph
foreach($members as $member){
if ($member) {
$pharmacy_most_active_staff_members[] = $member->first_name. " ".$member->last_name;
}
}
//displaying graphical data of top pharmacy performers
$top_performing_pharmacy_staff_chart = app()->chartjs
->name('top_performing_pharmacy_staff')
->type('bar')
->size(['width' => 800, 'height' => 400])
->labels($pharmacy_most_active_staff_members)
->datasets([
[
"label" => 'No of ward dispensings + patient dispensings + treatments created',
'backgroundColor' => $colors,
'data' => $pharmacy_most_active_staff_figures
]
])
->optionsRaw([
'legend' => [
'display' => false,
],
'stacked' => true,
'scales' => [
'yAxes' => [['ticks' => ['beginAtZero' => true],
'scaleLabel' => [
'display' => true,
'labelString' => 'No. of Contributions'
],
],],
'xAxes' => [['ticks' => ['autoSkip' => false,],
'scaleLabel' => [
'display' => true,
'labelString' => 'Staff Names'
],
]]
],
])
->options([]);
// 5.TOP PERFORMING RECEPTIONISTS AT TRIAGE
//patient episodes created by
$episodes_created_by = DB::table('patient_episodes')
->whereBetween('patient_episodes.created_at', [$start_date, $end_date])
->join('users', 'users.id', '=', 'patient_episodes.created_by')
->select('patient_episodes.created_at as created_at',
'patient_episodes.created_by as episode_created_by',
'users.id as user_id', 'users.first_name', 'users.last_name')
->get();
$members = [];
//merge all collections to array and group by user_id
$array_merges = array_merge($episodes_created_by->toArray());
$array_groups = array_group_by_key($array_merges, 'user_id');
//sorting by descending order
arsort($array_groups);
//pick the top 10 elements in the array
$array_groups = array_slice($array_groups, 0, 10, true);
//loop through list assigning corresponding values to each member
foreach($array_groups as $array_group){
$top_performing_receptionists_at_triage_figures[] = count($array_group);
}
//extract keys as user ids
$keys = array_keys($array_groups);
//store user ids for only doctors
foreach($keys as $key){
$members[] = User::find($key);
}
//create a list of members to populate on graph
foreach($members as $member){
if ($member) {
$pharmacy_most_active_staff_members[] = $member->first_name. " ".$member->last_name;
}
}
//displaying graphical data of top reception performers
$top_performing_receptionists_at_triage_chart = app()->chartjs
->name('top_performing_receptionists_at_triage')
->type('bar')
->size(['width' => 800, 'height' => 400])
->labels($top_performing_receptionists_at_triage_members)
->datasets([
[
"label" => 'No of patients created + episodes started',
'backgroundColor' => $colors,
'data' => $top_performing_receptionists_at_triage_figures
]
])
->optionsRaw([
'legend' => [
'display' => false,
],
'scales' => [
'yAxes' => [['ticks' => ['beginAtZero' => true],
'scaleLabel' => [
'display' => true,
'labelString' => 'Patients created + Episodes started'
],
],],
'xAxes' => [['ticks' => ['autoSkip' => false,
'scaleLabel' => [
'display' => true,
'labelString' => 'Staff Names'
],
],]]
]
])
->options([]);
$date = $request->dates;
if(!empty($request->print)){
$pdf = SnappyPDF::loadView('reports::reports_dashboard.print_top_doctors_and_staff',compact('display_text', 'top_performing_receptionists_at_triage_chart',
'top_performing_nurses_at_triage_chart', 'top_performing_doctors_chart', 'top_performing_lab_attendants_chart', 'top_performing_pharmacy_staff_chart'))
->setOrientation('landscape')
->setOption('margin-bottom', 7)
->setOption('margin-top', 5)
->setOption('enable-javascript', true)
->setOption('javascript-delay', 13500)
->setOption('enable-smart-shrinking', true)
->setOption('no-stop-slow-scripts', true)
->setOption('footer-html', ''.config('app.name').' - Printed On ' . date('Y-m-d') . ' By ' . auth()->user()->first_name . " " . auth()->user()->last_name . '');
return $pdf->inline('Staff Overview' . date(" d-m-y h:ia") . '.pdf');
}else return view('reports::reports_dashboard.top_doctors_and_staff', compact('display_text', 'date','top_performing_receptionists_at_triage_chart',
'top_performing_nurses_at_triage_chart', 'top_performing_doctors_chart', 'top_performing_lab_attendants_chart', 'top_performing_pharmacy_staff_chart'));
}
//average patient wait times
public function average_patient_wait_times(Request $request)
{
//return $this->average_wait_time_reception_to_triage($request);
$dates_array = $this->get_date_range($request);
$start_date = $dates_array[0];
$end_date = $dates_array[1];
$display_text = "Showing results between " . streamline_date($start_date) . " and " . streamline_date($end_date);
$days = [];
$times = [];
$dates = [];
$counter = 0;
$mon_total_time = 0;
$mon_patients = 0;
$tue_total_time = 0;
$tue_patients = 0;
$wed_total_time = 0;
$wed_patients = 0;
$thu_total_time = 0;
$thu_patients = 0;
$fri_total_time = 0;
$fri_patients = 0;
$sat_total_time = 0;
$sat_patients = 0;
$sun_total_time = 0;
$sun_patients = 0;
$more_than_day_time = 0;
$more_than_day_patients = 0;
//Average wait time for patients to see doctor
$patient_episodes = DB::table('patient_episodes')
->whereBetween('created_at', [$start_date, $end_date])
->get(['id', 'created_at']);
foreach ($patient_episodes as $episode) {
$consultation = DB::table('consultations')
->where('episode_id', $episode->id)
->first();
if ($consultation) {
$start_date = new DateTime($episode->created_at);
$end_date = new DateTime($consultation->created_at);
$dates[$counter]["id"] = 1;
$dates[$counter]["start"] = $episode->created_at;
$dates[$counter]["end"] = $consultation->created_at;
$interval = date_diff($start_date, $end_date);
$minutes = $interval->days * 24 * 60;
$minutes += $interval->h * 60;
$minutes += $interval->i;
$dates[$counter]["diff"] = $minutes;
if (Carbon::instance($start_date)->isSameDay($end_date)) {
switch ($start_date->format('l')) {
case 'Monday':
$mon_total_time += $minutes;
$mon_patients++;
break;
case 'Tuesday':
$tue_total_time += $minutes;
$tue_patients++;
break;
case 'Wednesday':
$wed_total_time += $minutes;
$wed_patients++;
break;
case 'Thursday':
$thu_total_time += $minutes;
$thu_patients++;
break;
case 'Friday':
$fri_total_time += $minutes;
$fri_patients++;
break;
case 'Saturday':
$sat_total_time += $minutes;
$sat_patients++;
break;
case 'Sunday':
$sun_total_time += $minutes;
$sun_patients++;
break;
}
} else {
$more_than_day_time += $minutes;
$more_than_day_patients++;
}
$counter++;
}
$days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
$mon_average = ($mon_patients == 0) ? 0 : (int)round($mon_total_time / $mon_patients);
$tue_average = ($tue_patients == 0) ? 0 : (int)round($tue_total_time / $tue_patients);
$wed_average = ($wed_patients == 0) ? 0 : (int)round($wed_total_time / $wed_patients);
$thu_average = ($thu_patients == 0) ? 0 : (int)round($thu_total_time / $thu_patients);
$fri_average = ($fri_patients == 0) ? 0 : (int)round($fri_total_time / $fri_patients);
$sat_average = ($sat_patients == 0) ? 0 : (int)round($sat_total_time / $sat_patients);
$sun_average = ($sun_patients == 0) ? 0 : (int)round($sun_total_time / $sun_patients);
$times = [$mon_average, $tue_average, $wed_average, $thu_average, $fri_average, $sat_average, $sun_average];
}
//Average wait time for patients from reception to triage
$episode_creation_to_triage_taken_results = DB::table('patient_episodes')
->whereBetween('patient_episodes.created_at', [$start_date, $end_date])
->join('triage', 'triage.patient_id', '=', 'patient_episodes.patient_id')
// ->select('patient_episodes.patient_id as patient_id', 'patient_episodes.created_at as patient_episode_creation_date',
// 'triage.created_at as triage_creation_date')
->get();
foreach ($episode_creation_to_triage_taken_results as $episode) {
$consultation = DB::table('consultations')
->where('episode_id', $episode->id)
->first();
if ($consultation) {
$start_date = new DateTime($episode->created_at);
$end_date = new DateTime($consultation->created_at);
$dates[$counter]["id"] = 1;
$dates[$counter]["start"] = $episode->created_at;
$dates[$counter]["end"] = $consultation->created_at;
$interval = date_diff($start_date, $end_date);
$minutes = $interval->days * 24 * 60;
$minutes += $interval->h * 60;
$minutes += $interval->i;
$dates[$counter]["diff"] = $minutes;
if (Carbon::instance($start_date)->isSameDay($end_date)) {
switch ($start_date->format('l')) {
case 'Monday':
$mon_total_time += $minutes;
$mon_patients++;
break;
case 'Tuesday':
$tue_total_time += $minutes;
$tue_patients++;
break;
case 'Wednesday':
$wed_total_time += $minutes;
$wed_patients++;
break;
case 'Thursday':
$thu_total_time += $minutes;
$thu_patients++;
break;
case 'Friday':
$fri_total_time += $minutes;
$fri_patients++;
break;
case 'Saturday':
$sat_total_time += $minutes;
$sat_patients++;
break;
case 'Sunday':
$sun_total_time += $minutes;
$sun_patients++;
break;
}
} else {
$more_than_day_time += $minutes;
$more_than_day_patients++;
}
$counter++;
}
$days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
$mon_average = ($mon_patients == 0) ? 0 : (int)round($mon_total_time / $mon_patients);
$tue_average = ($tue_patients == 0) ? 0 : (int)round($tue_total_time / $tue_patients);
$wed_average = ($wed_patients == 0) ? 0 : (int)round($wed_total_time / $wed_patients);
$thu_average = ($thu_patients == 0) ? 0 : (int)round($thu_total_time / $thu_patients);
$fri_average = ($fri_patients == 0) ? 0 : (int)round($fri_total_time / $fri_patients);
$sat_average = ($sat_patients == 0) ? 0 : (int)round($sat_total_time / $sat_patients);
$sun_average = ($sun_patients == 0) ? 0 : (int)round($sun_total_time / $sun_patients);
$times = [$mon_average, $tue_average, $wed_average, $thu_average, $fri_average, $sat_average, $sun_average];
}
//Average wait time for patients from triage to doctor
$wait_time_from_triage_to_doctors = DB::table('patient_episodes')
->whereBetween('patient_episodes.created_at', [$start_date, $end_date])
->join('triage', 'triage.patient_id', '=', 'patient_episodes.patient_id')
->select(
'patient_episodes.patient_id as patient_id', 'patient_episodes.created_at as patient_episode_creation_date',
'triage.created_at as triage_creation_date')
->get();
foreach ($wait_time_from_triage_to_doctors as $episode) {
$consultation = DB::table('consultations')
->where('episode_id', $episode->patient_id)
->first();
if ($consultation) {
$start_date = new DateTime($episode->patient_episode_creation_date);
$end_date = new DateTime($consultation->created_at);
$dates[$counter]["id"] = 1;
$dates[$counter]["start"] = $episode->patient_episode_creation_date;
$dates[$counter]["end"] = $consultation->created_at;
$interval = date_diff($start_date, $end_date);
$minutes = $interval->days * 24 * 60;
$minutes += $interval->h * 60;
$minutes += $interval->i;
$dates[$counter]["diff"] = $minutes;
if (Carbon::instance($start_date)->isSameDay($end_date)) {
switch ($start_date->format('l')) {
case 'Monday':
$mon_total_time += $minutes;
$mon_patients++;
break;
case 'Tuesday':
$tue_total_time += $minutes;
$tue_patients++;
break;
case 'Wednesday':
$wed_total_time += $minutes;
$wed_patients++;
break;
case 'Thursday':
$thu_total_time += $minutes;
$thu_patients++;
break;
case 'Friday':
$fri_total_time += $minutes;
$fri_patients++;
break;
case 'Saturday':
$sat_total_time += $minutes;
$sat_patients++;
break;
case 'Sunday':
$sun_total_time += $minutes;
$sun_patients++;
break;
}
} else {
$more_than_day_time += $minutes;
$more_than_day_patients++;
}
$counter++;
}
$days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
$mon_average = ($mon_patients == 0) ? 0 : (int)round($mon_total_time / $mon_patients);
$tue_average = ($tue_patients == 0) ? 0 : (int)round($tue_total_time / $tue_patients);
$wed_average = ($wed_patients == 0) ? 0 : (int)round($wed_total_time / $wed_patients);
$thu_average = ($thu_patients == 0) ? 0 : (int)round($thu_total_time / $thu_patients);
$fri_average = ($fri_patients == 0) ? 0 : (int)round($fri_total_time / $fri_patients);
$sat_average = ($sat_patients == 0) ? 0 : (int)round($sat_total_time / $sat_patients);
$sun_average = ($sun_patients == 0) ? 0 : (int)round($sun_total_time / $sun_patients);
$times = [$mon_average, $tue_average, $wed_average, $thu_average, $fri_average, $sat_average, $sun_average];
}
//Average wait time for patients from doctor to lab
//Average wait time for patients from treatments submission to confirmation
//Average wait time for patients from treatments submission to dispensation
return view('reports::reports_dashboard.average_patient_wait_times', compact('display_text', 'dates', 'days', 'times'));
}
//average wait time reception to triage
public function average_wait_time_reception_to_triage(Request $request)
{
$dates_array = $this->get_date_range($request);
$start_date = $dates_array[0];
$end_date = $dates_array[1];
$display_text = "Showing results between " . streamline_date($start_date) . " and " . streamline_date($end_date);
$days = [];
$times = [];
$dates = [];
$counter = 0;
$mon_total_time = 0;
$mon_patients = 0;
$tue_total_time = 0;
$tue_patients = 0;
$wed_total_time = 0;
$wed_patients = 0;
$thu_total_time = 0;
$thu_patients = 0;
$fri_total_time = 0;
$fri_patients = 0;
$sat_total_time = 0;
$sat_patients = 0;
$sun_total_time = 0;
$sun_patients = 0;
$more_than_day_time = 0;
$more_than_day_patients = 0;
$patient_episodes = DB::table('patient_episodes')
->whereBetween('created_at', [$start_date, $end_date])
->get(['id', 'created_at']);
foreach ($patient_episodes as $episode) {
$consultation = DB::table('consultations')
->where('episode_id', $episode->id)
->first();
if ($consultation) {
$start_date = new DateTime($episode->created_at);
$end_date = new DateTime($consultation->created_at);
$dates[$counter]["id"] = 1;
$dates[$counter]["start"] = $episode->created_at;
$dates[$counter]["end"] = $consultation->created_at;
$interval = date_diff($start_date, $end_date);
$minutes = $interval->days * 24 * 60;
$minutes += $interval->h * 60;
$minutes += $interval->i;
$dates[$counter]["diff"] = $minutes;
if (Carbon::instance($start_date)->isSameDay($end_date)) {
switch ($start_date->format('l')) {
case 'Monday':
$mon_total_time += $minutes;
$mon_patients++;
break;
case 'Tuesday':
$tue_total_time += $minutes;
$tue_patients++;
break;
case 'Wednesday':
$wed_total_time += $minutes;
$wed_patients++;
break;
case 'Thursday':
$thu_total_time += $minutes;
$thu_patients++;
break;
case 'Friday':
$fri_total_time += $minutes;
$fri_patients++;
break;
case 'Saturday':
$sat_total_time += $minutes;
$sat_patients++;
break;
case 'Sunday':
$sun_total_time += $minutes;
$sun_patients++;
break;
}
} else {
$more_than_day_time += $minutes;
$more_than_day_patients++;
}
$counter++;
}
$days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
$mon_average = ($mon_patients == 0) ? 0 : (int)round($mon_total_time / $mon_patients);
$tue_average = ($tue_patients == 0) ? 0 : (int)round($tue_total_time / $tue_patients);
$wed_average = ($wed_patients == 0) ? 0 : (int)round($wed_total_time / $wed_patients);
$thu_average = ($thu_patients == 0) ? 0 : (int)round($thu_total_time / $thu_patients);
$fri_average = ($fri_patients == 0) ? 0 : (int)round($fri_total_time / $fri_patients);
$sat_average = ($sat_patients == 0) ? 0 : (int)round($sat_total_time / $sat_patients);
$sun_average = ($sun_patients == 0) ? 0 : (int)round($sun_total_time / $sun_patients);
$times = [$mon_average, $tue_average, $wed_average, $thu_average, $fri_average, $sat_average, $sun_average];
}
return compact('days', 'times', 'display_text', 'dates');
}
//attendance
public function attendance(Request $request)
{
$male = 0;
$female = 0;
$periods = array();
$period_header = "Months";
$display_text = "Showing this Year's results";
$consultations_figures = array();
$religions_figures = array();
$occupations_figures = array();
$districts_figures = array();
$start_date = Carbon::today()->startOfYear();
$end_date = Carbon::today()->endOfYear();
$religions = DB::table('religions')->whereNull('deleted_at')->pluck('name');
$occupations = DB::table('occupations')->whereNull('deleted_at')->pluck('name');
$districts = DB::table('districts')->whereNull('deleted_at')->pluck('name');
$this_year = Carbon::today()->year;
$consultations = DB::table('consultations')
->whereNotNull("primary_diagnosis")
->whereBetween('created_at', [$start_date, $end_date])
->select(
DB::raw('GROUP_CONCAT(DISTINCT patient_id) as `patientIds`'),
DB::raw('COUNT(id) as `consultationsInMonth`'),
DB::raw('YEAR(created_at) year, MONTH(created_at) month')
)
->groupBy('year', 'month')
->get();
// Religions
foreach (range(0, count($religions) - 1) as $number) {
$religions_figures[$number] = 0;
}
// Occupations
foreach (range(0, count($occupations) - 1) as $number) {
$occupations_figures[$number] = 0;
}
// Districts
foreach (range(0, count($districts) - 1) as $number) {
$districts_figures[$number] = 0;
}
if (isset($request->dates)) {
switch ($request->dates):
case 'week':
$period_header = "Last Week";
$display_text = "Showing results for the last Week";
$start_date = Carbon::today()->startOfWeek();
$end_date = Carbon::today()->endOfWeek();
$consultations = DB::table('consultations')
->whereNotNull("primary_diagnosis")
->whereBetween('created_at', [$start_date, $end_date])
->select(
DB::raw('GROUP_CONCAT(DISTINCT patient_id) as `patientIds`'),
DB::raw('COUNT(id) as `consultationsInDay`'),
DB::raw('DAY(created_at) day')
)
->groupBy('day')
->get();
$periods = getDaysList();
foreach (range(0, 7) as $number) {
$consultations_figures[$number] = 0;
}
foreach ($consultations as $consultation) {
if ($consultation->day > 0) {
$consultations_figures[$consultation->day] = $consultation->consultationsInDay;
$patient_ids = explode(',', $consultation->patientIds);
foreach ($patient_ids as $patient_id) {
// Male vs Female
if (get_name($patient_id, 'id', 'gender', 'patients') == 1) {
$male++;
} else {
$female++;
}
// Religions
$religion = get_name($patient_id, 'id', 'religion_id', 'patients');
if (!is_null($religion) && $religion != 0) {
if (isset($religions_figures[$religion - 1])) {
$religions_figures[$religion - 1] += 1;
}
}
// Occupations
$occupation = get_name($patient_id, 'id', 'occupation_id', 'patients');
if (!is_null($occupation) && $occupation != 0) {
if (isset($occupations_figures[$occupation - 1])) {
$occupations_figures[$occupation - 1] += 1;
}
}
// Districts
$district = get_name($patient_id, 'id', 'district_id', 'patients');
if (!is_null($district) && $district != 0) {
if (isset($districts_figures[$district - 1])) {
$districts_figures[$district - 1] += 1;
}
}
}
}
}
break;
case 'month':
$period_header = "Last Month";
$display_text = "Showing results for the last Month";
$start_date = Carbon::today()->startOfMonth();
$end_date = Carbon::today()->endOfMonth();
$consultations = DB::table('consultations')
->whereNotNull("primary_diagnosis")
->whereBetween('created_at', [$start_date, $end_date])
->select(
DB::raw('GROUP_CONCAT(DISTINCT patient_id) as `patientIds`'),
DB::raw('COUNT(id) as `consultationsInDay`'),
DB::raw('DAY(created_at) day')
)
->groupBy('day')
->get();
foreach (range(0, 31) as $number) {
$consultations_figures[$number] = 0;
$periods[$number] = $number;
}
foreach ($consultations as $consultation) {
if ($consultation->day > 0) {
$consultations_figures[$consultation->day] = $consultation->consultationsInDay;
$patient_ids = explode(',', $consultation->patientIds);
foreach ($patient_ids as $patient_id) {
// Male vs Female
if (get_name($patient_id, 'id', 'gender', 'patients') == 1) {
$male++;
} else {
$female++;
}
// Religions
$religion = get_name($patient_id, 'id', 'religion_id', 'patients');
if (!is_null($religion) && $religion != 0) {
if (isset($religions_figures[$religion - 1])) {
$religions_figures[$religion - 1] += 1;
}
}
// Occupations
$occupation = get_name($patient_id, 'id', 'occupation_id', 'patients');
if (!is_null($occupation) && $occupation != 0) {
if (isset($occupations_figures[$occupation - 1])) {
$occupations_figures[$occupation - 1] += 1;
}
}
// Districts
$district = get_name($patient_id, 'id', 'district_id', 'patients');
if (!is_null($district) && $district != 0) {
if (isset($districts_figures[$district - 1])) {
$districts_figures[$district - 1] += 1;
}
}
}
}
}
break;
case 'year':
$periods = getMonthsList();
foreach (range(0, 12) as $number) {
$consultations_figures[$number] = 0;
}
foreach ($consultations as $consultation) {
if ($consultation->month > 0) {
$consultations_figures[$consultation->month] = $consultation->consultationsInMonth;
$patient_ids = explode(',', $consultation->patientIds);
foreach ($patient_ids as $patient_id) {
// Male vs Female
if (get_name($patient_id, 'id', 'gender', 'patients') == 1) {
$male++;
} else {
$female++;
}
// Religions
$religion = get_name($patient_id, 'id', 'religion_id', 'patients');
if (!is_null($religion) && $religion != 0) {
if (isset($religions_figures[$religion - 1])) {
$religions_figures[$religion - 1] += 1;
}
}
// Occupations
$occupation = get_name($patient_id, 'id', 'occupation_id', 'patients');
if (!is_null($occupation) && $occupation != 0) {
if (isset($occupations_figures[$occupation - 1])) {
$occupations_figures[$occupation - 1] += 1;
}
}
// Districts
$district = get_name($patient_id, 'id', 'district_id', 'patients');
if (!is_null($district) && $district != 0) {
if (isset($districts_figures[$district - 1])) {
$districts_figures[$district - 1] += 1;
}
}
}
}
}
break;
default:
$periods = getMonthsList();
foreach (range(0, 12) as $number) {
$consultations_figures[$number] = 0;
}
foreach ($consultations as $consultation) {
if ($consultation->month > 0) {
$consultations_figures[$consultation->month] = $consultation->consultationsInMonth;
$patient_ids = explode(',', $consultation->patientIds);
foreach ($patient_ids as $patient_id) {
// Male vs Female
if (get_name($patient_id, 'id', 'gender', 'patients') == 1) {
$male++;
} else {
$female++;
}
// Religions
$religion = get_name($patient_id, 'id', 'religion_id', 'patients');
if (!is_null($religion) && $religion != 0) {
if (isset($religions_figures[$religion - 1])) {
$religions_figures[$religion - 1] += 1;
}
}
// Occupations
$occupation = get_name($patient_id, 'id', 'occupation_id', 'patients');
if (!is_null($occupation) && $occupation != 0) {
if (isset($occupations_figures[$occupation - 1])) {
$occupations_figures[$occupation - 1] += 1;
}
}
// Districts
$district = get_name($patient_id, 'id', 'district_id', 'patients');
if (!is_null($district) && $district != 0) {
if (isset($districts_figures[$district - 1])) {
$districts_figures[$district - 1] += 1;
}
}
}
}
}
break;
endswitch;
} else {
$periods = getMonthsList();
foreach (range(0, 12) as $number) {
$consultations_figures[$number] = 0;
}
foreach ($consultations as $consultation) {
if ($consultation->month > 0) {
$consultations_figures[$consultation->month] = $consultation->consultationsInMonth;
$patient_ids = explode(',', $consultation->patientIds);
foreach ($patient_ids as $patient_id) {
// Male vs Female
if (get_name($patient_id, 'id', 'gender', 'patients') == 1) {
$male++;
} else {
$female++;
}
// Religions
$religion = get_name($patient_id, 'id', 'religion_id', 'patients');
if (!is_null($religion) && $religion != 0) {
if (isset($religions_figures[$religion - 1])) {
$religions_figures[$religion - 1] += 1;
}
}
// Occupations
$occupation = get_name($patient_id, 'id', 'occupation_id', 'patients');
if (!is_null($occupation) && $occupation != 0) {
if (isset($occupations_figures[$occupation - 1])) {
$occupations_figures[$occupation - 1] += 1;
}
}
// Districts
$district = get_name($patient_id, 'id', 'district_id', 'patients');
if (!is_null($district) && $district != 0) {
if (isset($districts_figures[$district - 1])) {
$districts_figures[$district - 1] += 1;
}
}
}
}
}
}
$consultationsYearVsYear = DB::table('consultations')
->whereNotNull("primary_diagnosis")
->where('created_at', '>=', '2017-01-01 00:00:00') // Starting from 2017
->select(
DB::raw('COUNT(id) as `consultationsInMonth`'),
DB::raw('YEAR(created_at) year, MONTH(created_at) month')
)
->groupBy('year', 'month')
->get();
$consultations_year_vs_year = array();
$periods_year_vs_year = getMonthsList();
foreach (range(2017, $this_year) as $year) {
foreach (range(0, 12) as $number) {
$consultations_year_vs_year[$year][$number] = 0;
}
}
foreach ($consultationsYearVsYear as $consultation) {
if ($consultation->month > 0) {
$consultations_year_vs_year[$consultation->year][$consultation->month] = $consultation->consultationsInMonth;
}
}
// Districts (Top 10)
sort($districts_figures, SORT_NUMERIC);
$districts_figures_sorted = array_reverse($districts_figures, true); // true to preserve keys
$districts_figures_top_10_sliced = array_slice($districts_figures_sorted, 0, 10, true);
$districts_top_10 = array();
$districts_figures_top_10 = array();
foreach ($districts_figures_top_10_sliced as $key => $value) {
array_push($districts_top_10, $districts[$key]);
array_push($districts_figures_top_10, $value);
}
$date = $request->dates;
if(!empty($request->print)) {
$pdf = SnappyPDF::loadView('reports::reports_dashboard.print_attendance',compact('periods',
'this_year','consultations_figures','display_text','period_header','consultations_year_vs_year',
'periods_year_vs_year','male','female','religions_figures','religions','occupations_figures',
'occupations','districts_figures_top_10','districts_top_10'))
->setOrientation('landscape')
->setOption('margin-bottom', 7)
->setOption('margin-top', 5)
->setOption('enable-javascript', true)
->setOption('javascript-delay', 13500)
->setOption('enable-smart-shrinking', true)
->setOption('no-stop-slow-scripts', true)
->setOption('footer-html', ''.config('app.name').' - Printed On ' . date('Y-m-d') . ' By ' . auth()->user()->first_name . " " . auth()->user()->last_name . '');
return $pdf->inline('Hospital Attendance' . date(" d-m-y h:ia") . '.pdf');
}
else return view('reports::reports_dashboard.attendance', compact(
'periods',
'this_year',
'consultations_figures',
'display_text',
'period_header',
'consultations_year_vs_year',
'periods_year_vs_year',
'male','date',
'female',
'religions_figures',
'religions',
'occupations_figures',
'occupations',
'districts_figures_top_10',
'districts_top_10'
));
}
//get date range
public function get_date_range($request)
{
if (in_array($request->dates, ['week', 'month', 'year', 'custom'])) {
if ($request->dates == 'week') {
$start_date = Carbon::today()->subWeek()->startOfDay();
$end_date = Carbon::today()->endOfDay();
} elseif ($request->dates == 'month') {
$start_date = Carbon::today()->subMonth()->startOfDay();
$end_date = Carbon::today()->endOfDay();
} elseif ($request->dates == 'year') {
$start_date = Carbon::today()->subYear()->startOfDay();
$end_date = Carbon::today()->endOfDay();
} elseif ($request->dates == 'custom' && isset($request->start_date) && isset($request->end_date)) {
$start_date = Carbon::createFromFormat('d-m-Y', $request->start_date)->startOfDay();
$end_date = Carbon::createFromFormat('d-m-Y', $request->end_date)->endOfDay();
} else {
$start_date = Carbon::today()->startOfMonth()->startOfDay();
$end_date = Carbon::today()->endOfDay();
}
} else {
$start_date = Carbon::today()->startOfMonth()->startOfDay();
$end_date = Carbon::today()->endOfDay();
}
return [$start_date, $end_date];
}
//inpatient statistics
public function inpatient_statistics(Request $request)
{
//average admission bills i.e accrual
//total cost i.e total bills in accrual
//average days admitted
//total patients seen
$average_admission_bills = 0;
$total_accrual_bills = 0;
$average_days_admitted = 0;
$total_patients_seen = 0;
$duration_days_array = [];
$admission_diagnoses_array = [];
$periods = "";
$consultations_figures = "";
$period_header = "Time Period";
$display_text = "Showing results for";
$today = Carbon::today()->toDateTimeString();
$last_24_hours = Carbon::now()->subDay();
$last_month = Carbon::now()->subMonth();
$month_of_admissions_array = [];
$patients_admissions_array = [];
$admissions_months_for_plotting_array = [];
$admissions_patient_nos__for_plotting_array = [];
$average_stay_in_days_plotting_array = [];
$inpatient_info_records = null;
$inpatient_bills_records = null;
if (is_null($request->dates)) {
//default
$display_text .= " last 24 hours";
$inpatient_info_records = InpatientInfo::where('created_at', '>', $last_24_hours)->get();
$inpatient_bills_records = InpatientBill::where('created_at', '>', $last_24_hours)->get();
} else {
if (isset($request->dates)) {
switch ($request->dates):
case 'week':
$period_header = "Last Week";
$display_text = "Showing results for the last Week";
$start_date = Carbon::today()->startOfWeek();
$end_date = Carbon::today()->endOfWeek();
//do this
break;
case 'month':
$period_header = "Last Month";
$display_text = "Showing results for the last Month";
$start_date = Carbon::today()->startOfMonth();
$end_date = Carbon::today()->endOfMonth();
//do this
break;
case 'year':
$period_header = "Last 1 Year";
$display_text = "Showing results for the last 1 Year";
$start_date = Carbon::today()->startOfYear();
$end_date = Carbon::today()->endOfYear();
//do sub year
break;
case 'custom':
$start_date = Carbon::createFromFormat('d-m-Y', $request->start_date)->startOfDay();
$end_date = Carbon::createFromFormat('d-m-Y', $request->end_date)->endOfDay();
break;
default:
//do defualt
break;
endswitch;
$inpatient_info_records = InpatientInfo::where([['created_at', '>', $start_date], ['created_at', '<', $end_date]])->get();
$inpatient_bills_records = InpatientBill::where([['created_at', '>', $start_date], ['created_at', '<', $end_date]])->get();
}
}
foreach ($inpatient_info_records as $inpatient_info) {
$admitted_on = Carbon::parse($inpatient_info->admitted_on);
$currentDateTimeStamp = Carbon::now();
if (is_null($inpatient_info->discharged_on)) {
$duration = $admitted_on->diffInDays($currentDateTimeStamp);
$duration = $duration == 0 ? 1 : $duration; // if the they have been admitted in less than a day count it
$duration_days_array[] = $duration;
} else {
$duration = $admitted_on->diffInDays($inpatient_info->discharged_on);
$duration = $duration == 0 ? 1 : $duration; // if the they have been admitted in less than a day count it
$duration_days_array[] = $duration;
}
/*== handle primary diagnosis ==*/
if (array_key_exists($inpatient_info->primary_diagnosis, $admission_diagnoses_array)) {
$diagnosed_patients = $admission_diagnoses_array[$inpatient_info->primary_diagnosis];
$admission_diagnoses_array[$inpatient_info->primary_diagnosis] = $diagnosed_patients + 1;
} else {
$admission_diagnoses_array[$inpatient_info->primary_diagnosis] = 1;
}
/*====*/
/*== handle other diagnosis ==*/
$other_diagnoses_array = is_null($inpatient_info->other_diagnoses) ? [] : @unserialize($inpatient_info->other_diagnoses);
if (is_array($other_diagnoses_array)) {
for ($i = 0; $i < count($other_diagnoses_array); $i++) {
if (array_key_exists($other_diagnoses_array[$i], $admission_diagnoses_array)) {
$diagnosed_patients = $admission_diagnoses_array[$other_diagnoses_array[$i]];
$admission_diagnoses_array[$other_diagnoses_array[$i]] = $diagnosed_patients + 1;
} else {
$admission_diagnoses_array[$other_diagnoses_array[$i]] = 1;
}
}
}
/*====*/
$month_of_admissions_array[] = $inpatient_info->created_at->format('M Y');
$patients_admissions_array[] = $inpatient_info->patient_id;
}
arsort($admission_diagnoses_array);
$admission_diagnoses_array = array_slice($admission_diagnoses_array, 0, 10, true);
unset($admission_diagnoses_array[""]); //remove empty diagnosis with a ""
$total_patients_seen = count($inpatient_info_records);
foreach ($inpatient_bills_records as $inpatient_bill) {
$total_accrual_bills += $inpatient_bill->amount_to_pay + $inpatient_bill->amount_paid + $inpatient_bill->invoices_amount;
}
$average_admission_bills = $total_patients_seen == 0 ? 0 : ($total_accrual_bills / $total_patients_seen);
$average_admission_bills = intval($average_admission_bills);
$no_of_items_in_duration_array = count($duration_days_array) == 0 ? 1 : count($duration_days_array); //handle division by zero
$average_days_admitted = array_sum($duration_days_array) / $no_of_items_in_duration_array;
$average_days_admitted = intval($average_days_admitted);
/*== do this for organising graph data ==*/
$month_admission_number_ass_array = [];
for ($i = 0; $i < count($month_of_admissions_array); $i++) {
if (array_key_exists($month_of_admissions_array[$i], $month_admission_number_ass_array)) {
$month_admission_number_ass_array[$month_of_admissions_array[$i]] += 1;
} else {
$month_admission_number_ass_array[$month_of_admissions_array[$i]] = 1;
}
}
$admissions_months_for_plotting_array = array_keys($month_admission_number_ass_array);
$admissions_patient_nos__for_plotting_array = array_values($month_admission_number_ass_array);
/*== end of graph data stuff ==*/
return view('reports::reports_dashboard.inpatient_statistics', compact('periods', 'consultations_figures', 'display_text', 'period_header', 'average_admission_bills', 'total_accrual_bills', 'average_days_admitted', 'total_patients_seen', 'admission_diagnoses_array', 'admissions_patient_nos__for_plotting_array', 'admissions_months_for_plotting_array'));
}
public function staff_overview_investigations(Request $request) {
$search_text = "";
$filters = [];
switch ($request->search_date_by){
case 'yesterday':
$end_date = Carbon::yesterday()->endOfDay();
$start_date = Carbon::yesterday()->startOfDay();
$search_text .= "Yesterday ";
break;
case 'custom_date':
$end_date = Carbon::parse($request->start_date)->endOfDay();
$start_date = Carbon::parse($request->start_date)->startOfDay();
$search_text .= "From: " . streamline_date($start_date) . " ";
break;
case 'custom_date_range':
$end_date = Carbon::parse($request->end_date)->endOfDay();
$start_date = Carbon::parse($request->start_date)->startOfDay();
$search_text .= "From: " . streamline_date($start_date) . " to " . streamline_date($end_date) . " ";
break;
case 'today':
default:
$end_date = Carbon::today()->endOfDay();
$start_date = Carbon::today()->startOfDay();
$search_text .= "Today ";
break;
}
if (isset($request->user_id) && $request->user_id != 0) {
$filters[] = ['investigation_results.created_by', '=', $request->user_id];
$search_text .= "| User: " . get_full_name($request->user_id, 'id', 'first_name', 'last_name', 'users');
}
$investigations = DB::table('investigation_results')
->leftJoin('users', 'users.id', '=', 'investigation_results.created_by')
->whereNull('investigation_results.deleted_at')
->whereBetween('investigation_results.created_at', [$start_date, $end_date])
->where($filters)
->get(['users.first_name', 'users.last_name', 'investigation_results.created_at', 'investigation_results.investigation_id']);
$investigation_names = DB::table('investigations')->pluck('name', 'id');
return view('reports::reports_dashboard.staff_overview_investigations', compact('search_text', 'investigations', 'investigation_names'));
}
public function print_top_diagnoses(Request $request){
$diagnoses = unserialize($request->diagnoses);
$diagnoses_names = unserialize($request->diagnoses_names);
$diagnoses_figures= unserialize($request->diagnoses_figures);
$display_text = $request->display_text;
$diagnoses_chart = app()->chartjs
->name('diagnosisChart')
->type('horizontalBar')
->size(['width' => 600, 'height' => 400])
->labels($diagnoses_names)
->datasets([
[
"label" => "Top Recorded Diagnoses",
'backgroundColor' => '#9a04f0',
'data' => $diagnoses_figures
]
])
->optionsRaw([
'scales' => [
'yAxes' => [['ticks' => ['autoSkip' => false],],],
'xAxes' => [['ticks' => ['beginAtZero' => true,],]]
]
])
->options([]);
$pdf = SnappyPDF::loadView('reports::reports_dashboard.print_top_diagnoses',compact('diagnoses', 'diagnoses_chart', 'diagnoses_names', 'diagnoses_figures', 'display_text'))
->setOrientation('landscape')
->setOption('margin-bottom', 7)
->setOption('margin-top', 5)
->setOption('enable-javascript', true)
->setOption('javascript-delay', 13500)
->setOption('enable-smart-shrinking', true)
->setOption('no-stop-slow-scripts', true)
->setOption('footer-html', ''.config('app.name').' - Printed On ' . date('Y-m-d') . ' By ' . auth()->user()->first_name . " " . auth()->user()->last_name . '');
return $pdf->inline('Top Recorded Diagnoses' . date(" d-m-y h:ia") . '.pdf');
}
}