Files
streamline-emr/docker/streamline-src/Modules/Patients/Http/Controllers/ConsultationController.php
T
alec.turner 4a89356390 Import latest app updates from streamline
An updated set of source files and initialization was provided by streamline to
address issues observed during initial testing. These files have been updated in
order to generate a new set of app images.
2024-04-11 11:16:51 -07:00

1497 lines
76 KiB
PHP
Executable File

<?php
namespace Modules\Patients\Http\Controllers;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Streamline\Models\Clinic;
use Streamline\Models\MentalHealthConsultation;
use Streamline\Models\Patient;
use Streamline\Models\InpatientInfo;
use Illuminate\Support\Facades\Auth;
use Streamline\Models\PatientAppointment;
use Streamline\Models\Triage;
use Streamline\Models\PatientEpisode;
use Illuminate\Support\Carbon;
use Streamline\Models\Consultation;
use Streamline\Models\Treatment;
use Streamline\Models\OrderedInvestigation;
use Streamline\Models\OrderedProcedure;
use Streamline\Models\OrderedSundry;
use Streamline\Models\InvestigationResults;
use Streamline\Models\User;
use Streamline\Models\CardioEchoResult;
use Barryvdh\Snappy\Facades\SnappyPdf;
use Streamline\Models\Investigation;
use Streamline\Models\Outcome;
class ConsultationController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
//
}
public function create()
{
if (!session()->has('patient_id') || !session()->has('episode_id')) :
flash('Patient is not selected')->error();
return view('home');
endif;
$clinics = Clinic::orderBy('name')->pluck("name", "id")->toArray();
$clinics = ['0' => "Don't assign clinic"] + $clinics;
$users = User::orderBy('first_name')->select("id", "first_name", "last_name")->get();
$episode_id = session()->get('episode_id');
$patient_id = session()->get('patient_id');
if (session()->get('consultation_with_notes') == 1) {
$consultation_with_notes = true;
} else {
$consultation_with_notes = false;
}
$patient = Patient::where('id', $patient_id)->first();
$episode = PatientEpisode::where('id', $episode_id)->first();
$triage = Triage::where(['id' => $episode->triage_id])->first();
$is_mental_health_clinic = false;
// fetch the clinic id and determine if this is a mental health consultation
$clinic_slug = get_name($episode->clinic_id, "id", "slug", "clinics");
if ($clinic_slug == "mental_health") {
session()->put(['is_mental_health_clinic' => 1]);
$is_mental_health_clinic = true;
}
/*==== do this for assignment of mental clinic from patient home page ===*/
if (session()->get("is_mental_health_clinic") == 1) {
$is_mental_health_clinic = true;
}
// unset the session for is_mental_health_clinic
session()->forget('is_mental_health_clinic');
/*====== end that thing for assignment of mental clinic from patient home page =================*/
$documents = DB::table('patient_documents')->whereNull('deleted_at')->where('patient_id', $patient_id)->orderBy('date_taken', 'desc')->get();
$categories = DB::table('patient_categories')->where('available', 1)->pluck("name", "id");
$drug_categories = DB::table('drug_categories')->orderBy('name', 'asc')->get();
$diagnoses = DB::table('diagnoses')->whereNull('deleted_at')->where('available', 1)->orderBy('name')->pluck("name", "id")->prepend('- select -', '');
$outcomes = DB::table('outcomes')->whereNull('deleted_at')->orderBy('name')->pluck('name', 'id')->prepend('- select -', '');
$wards = DB::table('wards')->where('available', 1)->whereNull('deleted_at')->orderBy('name')->pluck('name', 'id')->prepend('- select -', '');
$referrals = DB::table('referral_hospitals')->whereNull('deleted_at')->orderBy('name')->pluck('name', 'id')->prepend('- select -', '');
//select treatment
$treatments = Treatment::where(['patient_id' => $patient_id, 'episode_id' => $episode_id, 'tta' => 0])->get();
//symptoms
$symptoms = DB::table('symptoms')->whereNull('deleted_at')->orderBy('name')->pluck("name", "id")->toArray();
$symptoms = ['' => '- select -'] + $symptoms;
$symptoms_periods = ['' => '- select -', 'Hours' => 'Hours', 'Days' => 'Days', 'Weeks' => 'Weeks', 'Months' => 'Months', 'Years' => 'Years'];
//allergies and alerts
$known_patient_allergies = \Streamline\Models\Allergy::where('patient_id', $patient_id)->orderBy('created_at', 'desc')->take(2)->get();
$known_patient_alerts = \Streamline\Models\Alert::where('patient_id', $patient_id)->orderBy('created_at', 'desc')->take(2)->get();
$drug_categories_array = DB::table('drug_categories')->pluck('name', 'id');
/* get ordered procedures */
$ordered_procedures = OrderedProcedure::where(['patient_id' => $patient_id, 'episode_id' => $episode_id])->get();
//check for ordered investigations,procedures and treatment
$ordered_investigations = OrderedInvestigation::where(['patient_id' => $patient_id, 'episode_id' => $episode_id])->get();
/* get ordered sundries */
$ordered_sundries = OrderedSundry::where(['patient_id' => $patient_id, 'episode_id' => $episode_id])->get();
//check for authenticated investigations
$investigation_results = InvestigationResults::where(['patient_id' => $patient_id, 'episode_id' => $episode_id])->get();
$diagnoses_all = DB::table('diagnoses')->whereNull('deleted_at')->select('id', 'prompts', 'reference_areas', 'reference_names')->get();
/* ======== added to cater for review episode =========*/
$is_episode_a_review = check_if_episode_is_a_followup($episode->id);
$parent_episode_treatments = [];
$parent_episode_ordered_procedures = [];
$parent_episode_ordered_investigations = [];
$parent_episode_ordered_sundries = [];
$parent_episode_investigation_results = [];
if ($is_episode_a_review) {
$parent_episode_details = PatientEpisode::find($episode->parent_episode_id);
$parent_episode_treatments = Treatment::where(['patient_id' => $patient_id, 'episode_id' => $parent_episode_details->id, 'tta' => 0])->get();
$parent_episode_ordered_procedures = OrderedProcedure::where(['patient_id' => $patient_id, 'episode_id' => $parent_episode_details->id])->get();
$parent_episode_ordered_investigations = OrderedInvestigation::where(['patient_id' => $patient_id, 'episode_id' => $parent_episode_details->id])->get();
/* get ordered sundries */
$parent_episode_ordered_sundries = OrderedSundry::where(['patient_id' => $patient_id, 'episode_id' => $parent_episode_details->id])->get();
//check for authenticated investigations
$parent_episode_investigation_results = InvestigationResults::where(['patient_id' => $patient_id, 'episode_id' => $parent_episode_details->id])->get();
}
/* ========end of variables added to cater for review episodes ========*/
$users_collection = DB::table('users')->orderBy("first_name", "asc")->select("id")->get()->toArray();
$users_array = [];
foreach ($users_collection as $value) {
$user = User::find($value->id);
if (!is_null($user)) {
$users_array[$value->id] = get_full_name($value->id, 'id', 'first_name', 'last_name', 'users');
}
}
$users_array = ['' => '- select -'] + $users_array;
$hmis_categories = DB::table('hmis_categories')->orderBy('title', 'asc')->pluck('title', 'id')->toArray();
$hmis_categories = ['' => '- select -'] + $hmis_categories;
$cardio_echo = CardioEchoResult::where('episode_id', $episode_id)->first();
$patient_episodes = DB::table('patient_episodes')->where('patient_id', $patient_id)->whereNotIn('id', [$episode_id])->latest()->take(5)->get();
$past_episodes_info = [];
$counter = 0;
foreach ($patient_episodes as $patient_episode) {
if ($counter == 5) {
break;
}
if (!is_episode_safe_to_delete($patient_episode->id) && isset($patient_episode->consultation_id)) { // exclude empty episodes
$consultations_details = DB::table('consultations')->find($patient_episode->consultation_id);
if ($consultations_details) {
$past_episodes_info[$counter]["start_date"] = streamline_date_time($patient_episode->created_at);
$past_episodes_info[$counter]["episode_id"] = $patient_episode->id;
$past_episodes_info[$counter]["primary_diagnosis"] = $consultations_details->primary_diagnosis ?? 0;
if (unserialize($consultations_details->other_diagnoses)) {
$past_episodes_info[$counter]["other_diagnoses"] = unserialize($consultations_details->other_diagnoses);
} else {
$past_episodes_info[$counter]["other_diagnoses"] = [];
}
$past_episodes_info[$counter]["outcome"] = $consultations_details->outcome_id ?? 0;
$doctor_id = $consultations_details->consultation_done_by ?? $consultations_details->created_by;
$past_episodes_info[$counter]["doctor"] = get_full_name($doctor_id, 'id', 'first_name', 'last_name', 'users');
$past_episodes_info[$counter]["clinic"] = isset($patient_episode->clinic_id) ? get_name($patient_episode->clinic_id, 'id', 'name', 'clinics') : "N/A";
if (isset($patient_episode->triage_id)) {
$triage_details = DB::table('triage')->find($patient_episode->triage_id);
if ($triage_details) {
$past_episodes_info[$counter]["symptoms"] = [
"symptom_duration" => $triage_details->symptom_duration,
"symptoms" => $triage_details->symptoms
];
$observations = explode(",", $triage_details->observations);
$past_episodes_info[$counter]["resp"] = "N/A";
$past_episodes_info[$counter]["mmhg"] = "N/A";
$past_episodes_info[$counter]["pulse"] = "N/A";
$past_episodes_info[$counter]["temp"] = "N/A";
foreach ($observations as $observation) {
if (strpos($observation, "Temperature") !== false) {
$past_episodes_info[$counter]["temp"] = explode("=", $observation)[1];
}
if (strpos($observation, "Pulse") !== false) {
$past_episodes_info[$counter]["pulse"] = explode("=", $observation)[1];
}
if (strpos($observation, "Systolic bp") !== false) {
$past_episodes_info[$counter]["mmhg"] = explode("=", $observation)[1];
}
if (strpos($observation, "Diastolic bp") !== false) {
$past_episodes_info[$counter]["mmhg"] = $past_episodes_info[$counter]["mmhg"] . " / " . explode("=", $observation)[1];
}
if (strpos($observation, "Respirations") !== false) {
$past_episodes_info[$counter]["resp"] = explode("=", $observation)[1];
}
}
} else {
$past_episodes_info[$counter]["symptoms"] = [];
$past_episodes_info[$counter]["resp"] = "N/A";
$past_episodes_info[$counter]["mmhg"] = "N/A";
$past_episodes_info[$counter]["pulse"] = "N/A";
$past_episodes_info[$counter]["temp"] = "N/A";
}
} else {
$past_episodes_info[$counter]["symptoms"] = [];
$past_episodes_info[$counter]["resp"] = "N/A";
$past_episodes_info[$counter]["mmhg"] = "N/A";
$past_episodes_info[$counter]["pulse"] = "N/A";
$past_episodes_info[$counter]["temp"] = "N/A";
}
$counter++;
}
}
}
return view('patients::consultations.create', compact(
'patient',
'triage',
'episode',
'diagnoses',
'outcomes',
'consultation_with_notes',
'wards',
'categories',
'drug_categories',
'referrals',
'documents',
'treatments',
'symptoms',
'known_patient_allergies',
'is_mental_health_clinic',
'known_patient_alerts',
'drug_categories_array',
'ordered_procedures',
'ordered_investigations',
'investigation_results',
'ordered_sundries',
'users',
'clinics',
'diagnoses_all',
'parent_episode_treatments',
'parent_episode_ordered_procedures',
'parent_episode_ordered_sundries',
'parent_episode_ordered_investigations',
'parent_episode_investigation_results',
'users_array',
'hmis_categories',
'cardio_echo',
'past_episodes_info',
'symptoms_periods'
));
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
*/
public function store(Request $request)
{
if (!session()->has('patient_id') || !session()->has('episode_id')) :
flash('Patient is not selected')->error();
return view('home');
endif;
$consultation = new Consultation;
$patient_id = session()->get('patient_id');
$episode_id = session()->get('episode_id');
$consultation->patient_id = $patient_id;
$consultation->episode_id = $episode_id;
$symptoms_array = $request->symptoms ?? [];
$duration_array = $request->duration ?? [];
$time_array = $request->time ?? [];
// Build symptoms and duration variables
$durations_final = [];
for ($x = 0; $x < count($symptoms_array); $x++) {
$durations_final[] = $duration_array[$x] . " " . $time_array[$x];
}
$consultation->symptoms = implode(",", $symptoms_array);
$consultation->symptom_duration = implode(",", $durations_final);
$consultation->primary_diagnosis = $request->primary_diagnosis;
$consultation->other_diagnoses = (!empty($request->other_diagnosis[0])) ? serialize($request->other_diagnosis) : null;
$consultation->comments = $request->comments;
$consultation->history_comments = $request->history_comments;
$consultation->clinic_examination_comments = $request->clinic_examination_comments;
$consultation->investigation_and_management_plan_comments = $request->investigation_and_management_plan_comments;
$consultation->outcome_id = $request->outcome;
if ($request->died_on) $consultation->died_on = $request->died_on;
$consultation->rdt = $request->rdt;
if($request->attendance) $consultation->attendance = $request->attendance;
$consultation->rbs = $request->rbs;
$consultation->referral_notes = $request->referral_notes;
$consultation->tb_status_assessment = $request->tb_status_assessment;
$consultation->created_by = Auth::user()->id;
//$consultation->consultation_done_by = Auth::user()->id; still contemplating on whether to do update record
// begin saving for discharge mortality risk
$discharge_mortality = DB::table('discharge_mortality_risk')->where('patient_id', $patient_id)
->where('episode_id', $episode_id)
->first();
if ($discharge_mortality) {
DB::table('discharge_mortality_risk')
->where('id', $discharge_mortality->id)
->update(['malaria_test' => $request->rdt]);
}
// end discharge mortality risk save
// performing an ordered procedure.
if (!is_null($request->perform_selected)) {
foreach ($request->perform_selected as $procedure_array_id) {
$arr = explode(",", get_name($request->procedure_order_perform[$procedure_array_id], 'id', 'performed', 'ordered_procedures'));
$arr_id = explode(",", get_name($request->procedure_order_perform[$procedure_array_id], 'id', 'performed_id', 'ordered_procedures'));
$performed_id = record_staff_that_has_performed_the_service(
$patient_id,
$episode_id,
1,
$request->perform[$procedure_array_id],
0,
$request->procedure_performed_by[$procedure_array_id]
);
if (isset($arr[$request->procedure_performed_position[$procedure_array_id]])) {
$arr[$request->procedure_performed_position[$procedure_array_id]] = 1;
$arr_id[$request->procedure_performed_position[$procedure_array_id]] = $performed_id;
$update = DB::table('ordered_procedures')->where('id', $request->procedure_order_perform[$procedure_array_id])
->update(['performed' => implode(",", $arr), 'performed_id' => implode(",", $arr_id)]);
}
}
}
// performing an ordered services.
if (!is_null($request->service_perform_selected)) {
foreach ($request->service_perform_selected as $service_array_id) {
$arr = explode(",", get_name($request->service_order_perform[$service_array_id], 'id', 'performed', 'ordered_services'));
$arr_id = explode(",", get_name($request->service_order_perform[$service_array_id], 'id', 'performed_id', 'ordered_services'));
$performed_id = record_staff_that_has_performed_the_service(
$patient_id,
$episode_id,
3,
$request->service_perform[$service_array_id],
0,
$request->service_performed_by[$service_array_id]
);
if (isset($arr[$request->service_performed_position[$service_array_id]])) {
$arr[$request->service_performed_position[$service_array_id]] = 1;
$arr_id[$request->service_performed_position[$service_array_id]] = $performed_id;
$update = DB::table('ordered_services')->where('id', $request->service_order_perform[$service_array_id])
->update(['performed' => implode(",", $arr), 'performed_id' => implode(",", $arr_id)]);
}
}
}
// mental health consultation
if (isset($request->mental_health_clinic)) {
$mental_health_consultation = new MentalHealthConsultation();
$mental_health_consultation->patient_id = $patient_id;
$mental_health_consultation->episode_id = $episode_id;
$mental_health_consultation->hallucinations = $request->hallucinations;
$mental_health_consultation->delusions = $request->delusions;
$mental_health_consultation->disorganised_speech = $request->disorganised_speech;
$mental_health_consultation->abnormal_psychomotor_behaviour = $request->abnormal_psychomotor_behaviour;
$mental_health_consultation->impaired_cognition = $request->impaired_cognition;
$mental_health_consultation->depression = $request->depression;
$mental_health_consultation->mania = $request->mania;
$mental_health_consultation->hamilton_anxiety_score = $request->hamilton_anxiety_score;
$mental_health_consultation->alcohol_screening_score = $request->alcohol_screening_score;
$mental_health_consultation->patient_satisfaction_score = $request->patient_satisfaction_score;
$mental_health_consultation->caregiver_satisfaction_score = $request->caregiver_satisfaction_score;
$mental_health_consultation->created_by = Auth::user()->id;
$mental_health_consultation->save();
}
switch ($request->outcome):
case 1: //Admitted
// check to see that the ward is valid
if (is_numeric($request->ward_id)) {
// check if the patient is currently admitted and just update their status
$inpatient_info = InpatientInfo::where(['patient_id' => $patient_id, 'episode_id' => $episode_id, 'discharged' => 0])->orderBy('created_at', 'desc')->first();
if ($inpatient_info) {
$inpatient_info->ward_id = $request->ward_id;
$inpatient_info->primary_diagnosis = $request->primary_diagnosis;
$inpatient_info->other_diagnoses = (!empty($request->other_diagnosis[0])) ? serialize($request->other_diagnosis) : null;
$inpatient_info->comments = $request->comments;
$inpatient_info->updated_by = Auth::user()->id;
$inpatient_info->save();
$discharge_mortality_inpatient_id = $inpatient_info->id;
} else {
$inpatient = new InpatientInfo;
$inpatient->patient_id = $patient_id;
$inpatient->episode_id = $episode_id;
$inpatient->admitted_on = Carbon::parse($request->admitted_on)->format('Y-m-d');
$inpatient->ward_id = $request->ward_id;
$inpatient->primary_diagnosis = $request->primary_diagnosis;
$inpatient->other_diagnoses = (!empty($request->other_diagnosis[0])) ? serialize($request->other_diagnosis) : null;
$inpatient->comments = $request->comments;
$inpatient->created_by = Auth::user()->id;
$inpatient->save();
$discharge_mortality_inpatient_id = $inpatient->id;
}
$consultation->ward_id = $request->ward_id;
$consultation->admitted_on = Carbon::parse($request->admitted_on)->format('Y-m-d');
if ($discharge_mortality) {
DB::table('discharge_mortality_risk')
->where('id', $discharge_mortality->id)
->update(['inpatient_id' => $discharge_mortality_inpatient_id]);
}
}
break;
case 3: // Home with followup
$consultation->followup_where = "Hospital";
$consultation->followup_when = Carbon::parse($request->followup_when)->format('Y-m-d');
// save information to the follow-up table
$appointment = new PatientAppointment();
$appointment->patient_id = $patient_id;
$appointment->incharge_id = $request->followup_in_charge;
$appointment->clinic_allocation = $request->followup_clinic_allocation;
$appointment->episode_id = $episode_id;
$appointment->appointment_date = Carbon::parse($request->followup_when)->format('Y-m-d');
$appointment->appointment_time = $request->followup_in_time;
$appointment->created_from = "Consultation";
$appointment->created_by = Auth::user()->id;
$appointment->updated_by = Auth::user()->id;
$appointment->save();
break;
case 4: // Referred
$consultation->referred_to = $request->referral_id;
break;
default:
break;
endswitch;
//handle clinic transfer
$outcome_slug = get_name($request->outcome, "id", "slug", "outcomes");
if ($outcome_slug == "internal_transfer") {
$transfer = new \Streamline\Models\PatientClinicTransfers;
$transfer->patient_id = $patient_id;
$transfer->episode_id = $episode_id;
$transfer->old_clinic = $request->current_clinic_id;
$transfer->new_clinic = $request->transfer_to_clinic;
$transfer->created_by = Auth::user()->id;
$transfer->save();
$episode = PatientEpisode::find($episode_id);
$episode->clinic_id = $request->transfer_to_clinic;
$episode->update();
if ($request->current_triage_id != 0) {
$triage = Triage::find($request->current_triage_id);
$triage->clinic_allocation = $request->transfer_to_clinic;
$triage->update();
}
}
$episode = PatientEpisode::find($episode_id);
// Handle the buttons on the consultation page
switch ($request->get('submit-btn')):
case 'investigation':
$consultation->save();
$episode->consultation_id = $consultation->id;
$episode->save();
session()->put('redirect_to_consultation', '/consultation/route');
$url = '/investigations/investigations_review';
break;
case 'treatment':
$consultation->save();
$episode->consultation_id = $consultation->id;
$episode->save();
session()->put('redirect_to_consultation', '/consultation/route');
$url = '/prescriptions/create/';
break;
case 'procedures':
$consultation->save();
$episode->consultation_id = $consultation->id;
$episode->save();
session()->put('redirect_to_consultation', '/consultation/route');
$url = '/order_procedures/';
break;
case 'sundries':
$consultation->save();
$episode->consultation_id = $consultation->id;
$episode->save();
session()->put('redirect_to_consultation', '/consultation/route');
$url = '/order_sundries/';
break;
case 'save_consultation':
$consultation->save();
$episode->consultation_id = $consultation->id;
$episode->save();
$dob = new Carbon(get_name($patient_id, 'id', 'date_of_birth', 'patients'));
$age_diff_months = $dob->diffInMonths(Carbon::now());
if (is_smart_discharge_enabled() && $request->outcome == 1 && $age_diff_months < 61 && $discharge_mortality && is_null($discharge_mortality->post_discharge_mortality_risk)) {
flash("Patient is being monitored for post discharge risk. Please fill the questions below")->success();
return redirect('/triage/edit_for_post_discharge/' . $episode_id);
} else {
$url = '/patient_flow_monitoring/index';
}
break;
case 'services':
$consultation->save();
$episode->consultation_id = $consultation->id;
$episode->save();
session()->put('redirect_to_consultation', '/consultation/route');
$url = '/order_services';
break;
case 'complete':
$consultation->completed = 1;
$consultation->save();
$episode->consultation_id = $consultation->id;
$episode->save();
session()->forget('consultation_with_notes');
add_doctors_fee_to_patient_services($consultation->id, auth()->user()->id);
$dob = new Carbon(get_name($patient_id, 'id', 'date_of_birth', 'patients'));
$age_diff_months = $dob->diffInMonths(Carbon::now());
if (is_smart_discharge_enabled() && $request->outcome == 1 && $age_diff_months < 61 && $discharge_mortality && is_null($discharge_mortality->post_discharge_mortality_risk)) {
flash("Patient is being monitored for post discharge risk. Please fill the questions below")->success();
return redirect('/triage/edit_for_post_discharge/' . $episode_id);
} else {
$url = '/patient_flow_monitoring/index';
}
break;
default:
$url = '/patient_flow_monitoring/index';
break;
endswitch;
return redirect($url);
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function show($id)
{
$consultation = Consultation::where(['id' => $id])->first();
$patient = Patient::where('id', $consultation->patient_id)->first();
$episode = PatientEpisode::where('id', $consultation->episode_id)->first();
$triage = Triage::where(['id' => $episode->triage_id])->first();
if (session()->get('consultation_with_notes') == 1) {
$consultation_with_notes = true;
} else {
$consultation_with_notes = false;
}
$is_mental_health_clinic = false;
// fetch the clinic id and determine if this is a mental health consultation
$clinic_slug = get_name($episode->clinic_id, "id", "slug", "clinics");
if ($clinic_slug == "mental_health") {
$is_mental_health_clinic = true;
}
$mental_health_consultation = MentalHealthConsultation::where(['patient_id' => $consultation->patient_id, 'episode_id' => $consultation->episode_id])->first();
//Dropdowns
$diagnoses = DB::table('diagnoses')->whereNull('deleted_at')->where('available', 1)->orderBy('name')->pluck("name", "id")->prepend('- select -', '');
$diagnoses_all = DB::table('diagnoses')->whereNull('deleted_at')->select('id', 'prompts', 'reference_areas', 'reference_names')->get();
$outcomes = DB::table('outcomes')->orderBy('name')->pluck('name', 'id')->prepend('- select -', '');
$wards = DB::table('wards')->where('available', 1)->whereNull('deleted_at')->orderBy('name')->pluck('name', 'id')->prepend('- select -', '');
$referrals = DB::table('referral_hospitals')->whereNull('deleted_at')->orderBy('name')->pluck('name', 'id')->prepend('- select -', '');
//symptoms
$symptoms = DB::table('symptoms')->where('available', 1)->pluck("name", "id");
//check for ordered investigations,procedures and treatment
$ordered_investigations = OrderedInvestigation::where(['patient_id' => $consultation->patient_id, 'episode_id' => $consultation->episode_id])->get();
//check for authenticated investigations
$investigation_results = InvestigationResults::where(['patient_id' => $consultation->patient_id, 'episode_id' => $consultation->episode_id])->get();
$treatments = Treatment::where(['patient_id' => $consultation->patient_id, 'episode_id' => $consultation->episode_id])->get();
$ordered_procedures = OrderedProcedure::where(['patient_id' => $consultation->patient_id, 'episode_id' => $consultation->episode_id])->get();
/* get ordered sundries */
$ordered_sundries = OrderedSundry::where(['patient_id' => $consultation->patient_id, 'episode_id' => $consultation->episode_id])->get();
// variables used by the allergies header modal
$categories = DB::table('patient_categories')->where('available', 1)->pluck("name", "id");
$drug_categories = DB::table('drug_categories')->get();
$documents = \Streamline\Models\PatientDocument::where('patient_id', $consultation->patient_id)->orderBy('created_at', 'desc')->take(2)->get();
$known_patient_allergies = \Streamline\Models\Allergy::where('patient_id', $consultation->patient_id)->orderBy('created_at', 'desc')->get();
$known_patient_alerts = \Streamline\Models\Alert::where('patient_id', $consultation->patient_id)->orderBy('created_at', 'desc')->take(2)->get();
$drug_categories_array = DB::table('drug_categories')->pluck('name', 'id');
/* get ordered sundries */
$ordered_sundries = OrderedSundry::where(['patient_id' => $consultation->patient_id, 'episode_id' => $consultation->episode_id])->get();
/* ======== added to cater for review episode =========*/
$is_episode_a_review = check_if_episode_is_a_followup($episode->id);
$parent_episode_treatments = [];
$parent_episode_ordered_procedures = [];
$parent_episode_ordered_investigations = [];
$parent_episode_ordered_sundries = [];
$parent_episode_investigation_results = [];
if ($is_episode_a_review) {
$parent_episode_details = PatientEpisode::find($episode->parent_episode_id);
$parent_episode_treatments = Treatment::where(['patient_id' => $consultation->patient_id, 'episode_id' => $parent_episode_details->id, 'tta' => 0])->get();
$parent_episode_ordered_procedures = OrderedProcedure::where(['patient_id' => $consultation->patient_id, 'episode_id' => $parent_episode_details->id])->get();
$parent_episode_ordered_investigations = OrderedInvestigation::where(['patient_id' => $consultation->patient_id, 'episode_id' => $parent_episode_details->id])->get();
/* get ordered sundries */
$parent_episode_ordered_sundries = OrderedSundry::where(['patient_id' => $consultation->patient_id, 'episode_id' => $parent_episode_details->id])->get();
//check for authenticated investigations
$parent_episode_investigation_results = InvestigationResults::where(['patient_id' => $consultation->patient_id, 'episode_id' => $parent_episode_details->id])->get();
}
/* ========end of varibales added to cater for review episodes ========*/
$cardio_echo = CardioEchoResult::where('episode_id', $consultation->episode_id)->first();
return view('patients::consultations.show', compact(
'consultation',
'patient',
'episode',
'triage',
'documents',
'categories',
'drug_categories',
'diagnoses',
'diagnoses_all',
'outcomes',
'wards',
'referrals',
'symptoms',
'known_patient_allergies',
'drug_categories_array',
'ordered_investigations',
'treatments',
'ordered_procedures',
'consultation_with_notes',
'investigation_results',
'known_patient_alerts',
'ordered_sundries',
'is_mental_health_clinic',
'mental_health_consultation',
'parent_episode_treatments',
'parent_episode_ordered_procedures',
'parent_episode_ordered_sundries',
'parent_episode_ordered_investigations',
'parent_episode_investigation_results',
'cardio_echo'
));
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function edit($id)
{
$consultation = Consultation::where(['id' => $id])->first();
$clinics = Clinic::orderBy('name')->pluck("name", "id")->toArray();
$clinics = ['0' => "Don't assign clinic"] + $clinics;
$users = User::orderBy('first_name')->select("id", "first_name", "last_name")->get();
//Patient, Triage and Episode
$patient = Patient::where('id', $consultation->patient_id)->first();
$episode = PatientEpisode::where('id', $consultation->episode_id)->first();
$triage = Triage::where(['id' => $episode->triage_id])->first();
if (session()->get('consultation_with_notes') == 1) {
$consultation_with_notes = true;
} else {
$consultation_with_notes = false;
}
$is_mental_health_clinic = false;
// fetch the clinic id and determine if this is a mental health consultation
$clinic_slug = get_name($episode->clinic_id, "id", "slug", "clinics");
if ($clinic_slug == "mental_health") {
session()->put(['is_mental_health_clinic' => 1]);
$is_mental_health_clinic = true;
}
/*==== do this for assignment of mental clinic from patient home page ===*/
if (session()->get("is_mental_health_clinic") == 1) {
$is_mental_health_clinic = true;
}
$mental_health_consultation = MentalHealthConsultation::where(['patient_id' => $consultation->patient_id, 'episode_id' => $consultation->episode_id])->first();
$documents = DB::table('patient_documents')->whereNull('deleted_at')->where('patient_id', $consultation->patient_id)->orderBy('date_taken', 'desc')->get();
$categories = DB::table('patient_categories')->where('available', 1)->pluck("name", "id");
$drug_categories = DB::table('drug_categories')->get();
$diagnoses = DB::table('diagnoses')->whereNull('deleted_at')->where('available', 1)->orderBy('name')->pluck("name", "id")->prepend('- select -', '');
$diagnoses_all = DB::table('diagnoses')->whereNull('deleted_at')->select('id', 'prompts', 'reference_areas', 'reference_names')->get();
$outcomes = DB::table('outcomes')->whereNull('deleted_at')->orderBy('name')->pluck('name', 'id')->prepend('- select -', '');
$wards = DB::table('wards')->where('available', 1)->whereNull('deleted_at')->orderBy('name')->pluck('name', 'id')->prepend('- select -', '');
$referrals = DB::table('referral_hospitals')->whereNull('deleted_at')->orderBy('name')->pluck('name', 'id')->prepend('- select -', '');
//symptoms
$symptoms = DB::table('symptoms')->whereNull('deleted_at')->orderBy('name')->pluck("name", "id")->toArray();
$symptoms = ['' => '- select -'] + $symptoms;
$symptoms_periods = ['' => '- select -', 'Hours' => 'Hours', 'Days' => 'Days', 'Weeks' => 'Weeks', 'Months' => 'Months', 'Years' => 'Years'];
//allergies and alerts
$known_patient_allergies = \Streamline\Models\Allergy::where('patient_id', $consultation->patient_id)->orderBy('created_at', 'desc')->take(2)->get();
$known_patient_alerts = \Streamline\Models\Alert::where('patient_id', $consultation->patient_id)->orderBy('created_at', 'desc')->take(2)->get();
$drug_categories_array = DB::table('drug_categories')->pluck('name', 'id');
//check for ordered investigations,procedures and treatment
$ordered_investigations = OrderedInvestigation::where(['patient_id' => $consultation->patient_id, 'episode_id' => $consultation->episode_id])->get();
//check for authenticated investigations
$investigation_results = InvestigationResults::where(['patient_id' => $consultation->patient_id, 'episode_id' => $consultation->episode_id])->get();
$treatments = Treatment::where(['patient_id' => $consultation->patient_id, 'episode_id' => $consultation->episode_id])->get();
$ordered_procedures = OrderedProcedure::where(['patient_id' => $consultation->patient_id, 'episode_id' => $consultation->episode_id])->get();
/* get ordered sundries */
$ordered_sundries = OrderedSundry::where(['patient_id' => $consultation->patient_id, 'episode_id' => $consultation->episode_id])->get();
/* ======== added to cater for review episode =========*/
$is_episode_a_review = check_if_episode_is_a_followup($episode->id);
$parent_episode_treatments = [];
$parent_episode_ordered_procedures = [];
$parent_episode_ordered_investigations = [];
$parent_episode_ordered_sundries = [];
$parent_episode_investigation_results = [];
if ($is_episode_a_review) {
$parent_episode_details = PatientEpisode::find($episode->parent_episode_id);
$parent_episode_treatments = Treatment::where(['patient_id' => $consultation->patient_id, 'episode_id' => $parent_episode_details->id, 'tta' => 0])->get();
$parent_episode_ordered_procedures = OrderedProcedure::where(['patient_id' => $consultation->patient_id, 'episode_id' => $parent_episode_details->id])->get();
$parent_episode_ordered_investigations = OrderedInvestigation::where(['patient_id' => $consultation->patient_id, 'episode_id' => $parent_episode_details->id])->get();
/* get ordered sundries */
$parent_episode_ordered_sundries = OrderedSundry::where(['patient_id' => $consultation->patient_id, 'episode_id' => $parent_episode_details->id])->get();
//check for authenticated investigations
$parent_episode_investigation_results = InvestigationResults::where(['patient_id' => $consultation->patient_id, 'episode_id' => $parent_episode_details->id])->get();
}
/* ========end of varibales added to cater for review episodes ========*/
$users_collection = DB::table('users')->orderBy("first_name", "asc")->select("id")->get()->toArray();
$users_array = [];
foreach ($users_collection as $value) {
$user = User::find($value->id);
if (!is_null($user)) {
$users_array[$value->id] = get_full_name($value->id, 'id', 'first_name', 'last_name', 'users');
}
}
$users_array = ['' => '- select -'] + $users_array;
$hmis_categories = DB::table('hmis_categories')->orderBy('title', 'asc')->pluck('title', 'id')->toArray();
$hmis_categories = ['' => '- select -'] + $hmis_categories;
$cardio_echo = CardioEchoResult::where('episode_id', $consultation->episode_id)->first();
$patient_episodes = DB::table('patient_episodes')->where('patient_id', $consultation->patient_id)->whereNotIn('id', [$consultation->episode_id])->latest()->take(5)->get();
$past_episodes_info = [];
$counter = 0;
foreach ($patient_episodes as $patient_episode) {
if ($counter == 5) {
break;
}
if (!is_episode_safe_to_delete($patient_episode->id) && isset($patient_episode->consultation_id)) { // exclude empty episodes
$consultations_details = DB::table('consultations')->find($patient_episode->consultation_id);
if ($consultations_details) {
$past_episodes_info[$counter]["start_date"] = streamline_date_time($patient_episode->created_at);
$past_episodes_info[$counter]["episode_id"] = $patient_episode->id;
$past_episodes_info[$counter]["primary_diagnosis"] = $consultations_details->primary_diagnosis ?? 0;
if (unserialize($consultations_details->other_diagnoses)) {
$past_episodes_info[$counter]["other_diagnoses"] = unserialize($consultations_details->other_diagnoses);
} else {
$past_episodes_info[$counter]["other_diagnoses"] = [];
}
$past_episodes_info[$counter]["outcome"] = $consultations_details->outcome_id ?? 0;
$doctor_id = $consultations_details->consultation_done_by ?? $consultations_details->created_by;
$past_episodes_info[$counter]["doctor"] = get_full_name($doctor_id, 'id', 'first_name', 'last_name', 'users');
$past_episodes_info[$counter]["clinic"] = isset($patient_episode->clinic_id) ? get_name($patient_episode->clinic_id, 'id', 'name', 'clinics') : "N/A";
if (isset($patient_episode->triage_id)) {
$triage_details = DB::table('triage')->find($patient_episode->triage_id);
if ($triage_details) {
$past_episodes_info[$counter]["symptoms"] = [
"symptom_duration" => $triage_details->symptom_duration,
"symptoms" => $triage_details->symptoms
];
$observations = explode(",", $triage_details->observations);
$past_episodes_info[$counter]["resp"] = "N/A";
$past_episodes_info[$counter]["mmhg"] = "N/A";
$past_episodes_info[$counter]["pulse"] = "N/A";
$past_episodes_info[$counter]["temp"] = "N/A";
foreach ($observations as $observation) {
if (strpos($observation, "Temperature") !== false) {
$past_episodes_info[$counter]["temp"] = explode("=", $observation)[1];
}
if (strpos($observation, "Pulse") !== false) {
$past_episodes_info[$counter]["pulse"] = explode("=", $observation)[1];
}
if (strpos($observation, "Systolic bp") !== false) {
$past_episodes_info[$counter]["mmhg"] = explode("=", $observation)[1];
}
if (strpos($observation, "Diastolic bp") !== false) {
$past_episodes_info[$counter]["mmhg"] = $past_episodes_info[$counter]["mmhg"] . " / " . explode("=", $observation)[1];
}
if (strpos($observation, "Respirations") !== false) {
$past_episodes_info[$counter]["resp"] = explode("=", $observation)[1];
}
}
} else {
$past_episodes_info[$counter]["symptoms"] = [];
$past_episodes_info[$counter]["resp"] = "N/A";
$past_episodes_info[$counter]["mmhg"] = "N/A";
$past_episodes_info[$counter]["pulse"] = "N/A";
$past_episodes_info[$counter]["temp"] = "N/A";
}
} else {
$past_episodes_info[$counter]["symptoms"] = [];
$past_episodes_info[$counter]["resp"] = "N/A";
$past_episodes_info[$counter]["mmhg"] = "N/A";
$past_episodes_info[$counter]["pulse"] = "N/A";
$past_episodes_info[$counter]["temp"] = "N/A";
}
$counter++;
}
}
}
return view('patients::consultations.edit', compact(
'consultation',
'patient',
'episode',
'triage',
'documents',
'categories',
'drug_categories',
'diagnoses',
'diagnoses_all',
'outcomes',
'wards',
'referrals',
'symptoms',
'known_patient_allergies',
'known_patient_alerts',
'drug_categories_array',
'ordered_investigations',
'past_episodes_info',
'symptoms_periods',
'treatments',
'ordered_procedures',
'investigation_results',
'ordered_sundries',
'is_mental_health_clinic',
'mental_health_consultation',
'consultation_with_notes',
'users',
'clinics',
'parent_episode_treatments',
'parent_episode_ordered_procedures',
'parent_episode_ordered_sundries',
'parent_episode_ordered_investigations',
'parent_episode_investigation_results',
'users_array',
'is_mental_health_clinic',
'hmis_categories',
'cardio_echo'
));
}
public function update(Request $request, $id)
{
if (!session()->has('patient_id') || !session()->has('episode_id')) :
flash('Patient is not selected')->error();
return view('home');
endif;
$consultation = Consultation::find($id);
$patient_id = session()->get('patient_id');
$episode_id = session()->get('episode_id');
$symptoms_array = $request->symptoms ?? [];
$duration_array = $request->duration ?? [];
$time_array = $request->time ?? [];
// Build symptoms and duration variables
$durations_final = [];
for ($x = 0; $x < count($symptoms_array); $x++) {
$durations_final[] = $duration_array[$x] . " " . $time_array[$x];
}
$consultation->symptoms = implode(",", $symptoms_array);
$consultation->symptom_duration = implode(",", $durations_final);
$consultation->primary_diagnosis = $request->primary_diagnosis;
$consultation->other_diagnoses = (!empty($request->other_diagnosis[0])) ? serialize($request->other_diagnosis) : null;
$consultation->comments = $request->comments;
$consultation->outcome_id = $request->outcome;
if ($request->died_on) $consultation->died_on = $request->died_on;
$consultation->rdt = $request->rdt;
if($request->attendance) $consultation->attendance = $request->attendance;
$consultation->rbs = $request->rbs;
$consultation->history_comments = $request->history_comments;
$consultation->clinic_examination_comments = $request->clinic_examination_comments;
$consultation->investigation_and_management_plan_comments = $request->investigation_and_management_plan_comments;
$consultation->referral_notes = $request->referral_notes;
$consultation->tb_status_assessment = $request->tb_status_assessment;
$consultation->updated_by = Auth::user()->id;
//$consultation->consultation_done_by = Auth::user()->id; still contemplating on whether to update field
// begin saving for discharge mortality risk
$discharge_mortality = DB::table('discharge_mortality_risk')->where('patient_id', $patient_id)
->where('episode_id', $episode_id)
->first();
if ($discharge_mortality) {
DB::table('discharge_mortality_risk')
->where('id', $discharge_mortality->id)
->update(['malaria_test' => $request->rdt]);
}
// end discharge mortality risk save
// performing an ordered procedure.
if (!is_null($request->perform_selected)) {
foreach ($request->perform_selected as $procedure_array_id) {
$arr = explode(",", get_name($request->procedure_order_perform[$procedure_array_id], 'id', 'performed', 'ordered_procedures'));
$arr_id = explode(",", get_name($request->procedure_order_perform[$procedure_array_id], 'id', 'performed_id', 'ordered_procedures'));
$performed_id = record_staff_that_has_performed_the_service(
$patient_id,
$episode_id,
1,
$request->perform[$procedure_array_id],
0,
$request->procedure_performed_by[$procedure_array_id]
);
if (isset($arr[$request->procedure_performed_position[$procedure_array_id]])) {
$arr[$request->procedure_performed_position[$procedure_array_id]] = 1;
$arr_id[$request->procedure_performed_position[$procedure_array_id]] = $performed_id;
$update = DB::table('ordered_procedures')->where('id', $request->procedure_order_perform[$procedure_array_id])
->update(['performed' => implode(",", $arr), 'performed_id' => implode(",", $arr_id)]);
}
}
}
// performing an ordered services.
if (!is_null($request->service_perform_selected)) {
foreach ($request->service_perform_selected as $service_array_id) {
$arr = explode(",", get_name($request->service_order_perform[$service_array_id], 'id', 'performed', 'ordered_services'));
$arr_id = explode(",", get_name($request->service_order_perform[$service_array_id], 'id', 'performed_id', 'ordered_procedures'));
$performed_id = record_staff_that_has_performed_the_service(
$patient_id,
$episode_id,
3,
$request->service_perform[$service_array_id],
0,
$request->service_performed_by[$service_array_id]
);
if (isset($arr[$request->service_performed_position[$service_array_id]])) {
$arr[$request->service_performed_position[$service_array_id]] = 1;
$arr_id[$request->service_performed_position[$service_array_id]] = $performed_id;
$update = DB::table('ordered_services')->where('id', $request->service_order_perform[$service_array_id])
->update(['performed' => implode(",", $arr), 'performed_id' => implode(",", $arr_id)]);
}
}
}
switch ($request->outcome):
case 1: //Admitted
if (is_numeric($request->ward_id)) {
/* check if this episode already exists in the inpatients table before inserting new record else update */
$existing_inpatient = InpatientInfo::where(['episode_id' => $episode_id])->first();
$inpatient = is_null($existing_inpatient) ? new InpatientInfo : $existing_inpatient;
$inpatient->patient_id = $patient_id;
$inpatient->episode_id = $episode_id;
$inpatient->admitted_on = $request->admitted_on;
$inpatient->ward_id = $request->ward_id;
$inpatient->primary_diagnosis = $request->primary_diagnosis;
$inpatient->other_diagnoses = (!empty($request->other_diagnosis[0])) ? serialize($request->other_diagnosis) : null;
$inpatient->comments = $request->comments;
$inpatient->created_by = Auth::user()->id;
is_null($existing_inpatient) ? $inpatient->save() : $inpatient->update(); // Save/update inpatient info
$consultation->ward_id = $request->ward_id;
$consultation->admitted_on = Carbon::parse($request->admitted_on)->format('Y-m-d');
if ($discharge_mortality) {
DB::table('discharge_mortality_risk')
->where('id', $discharge_mortality->id)
->update(['inpatient_id' => $inpatient->id]);
}
}
break;
case 3: // Home with followup
$consultation->followup_where = "Hospital";
$consultation->followup_when = Carbon::parse($request->followup_when)->format('Y-m-d');
// get current clinic of patient if available
$episode_information = PatientEpisode::find($episode_id);
if ($episode_information->clinic_id) {
$clinic_allocation_id = $episode_information->clinic_id;
} else {
$clinic_allocation_id = 0;
}
// check if there is an appointment for this episode
$previous_appointment = PatientAppointment::where(['episode_id' => $episode_id])->first();
if ($previous_appointment) {
$appointment = $previous_appointment;
} else {
$appointment = new PatientAppointment();
$appointment->patient_id = $patient_id;
$appointment->created_by = Auth::user()->id;
$appointment->episode_id = $episode_id;
}
$appointment->incharge_id = $request->followup_in_charge;
$appointment->clinic_allocation = $request->followup_clinic_allocation;
$appointment->appointment_date = Carbon::parse($request->followup_when)->format('Y-m-d');
$appointment->appointment_time = $request->followup_in_time;
$appointment->created_from = "Consultation";
$appointment->updated_by = Auth::user()->id;
$appointment->save();
break;
case 4: // Referred
$consultation->referred_to = $request->referral_id;
break;
endswitch;
//handle clinic transfer
$outcome_slug = get_name($request->outcome, "id", "slug", "outcomes");
if ($outcome_slug == "internal_transfer") {
$transfer = new \Streamline\Models\PatientClinicTransfers;
$transfer->patient_id = $patient_id;
$transfer->episode_id = $episode_id;
$transfer->old_clinic = $request->current_clinic_id;
$transfer->new_clinic = $request->transfer_to_clinic;
$transfer->created_by = Auth::user()->id;
$transfer->save();
$episode = PatientEpisode::find($episode_id);
$episode->clinic_id = $request->transfer_to_clinic;
$episode->update();
if ($request->current_triage_id != 0) {
$triage = Triage::find($request->current_triage_id);
$triage->clinic_allocation = $request->transfer_to_clinic;
$triage->update();
}
}
// mental health consultation
if (isset($request->mental_health_id)) {
$mental_health_consultation = MentalHealthConsultation::find($request->mental_health_id);
$mental_health_consultation->patient_id = $patient_id;
$mental_health_consultation->episode_id = $episode_id;
$mental_health_consultation->hallucinations = $request->hallucinations;
$mental_health_consultation->delusions = $request->delusions;
$mental_health_consultation->disorganised_speech = $request->disorganised_speech;
$mental_health_consultation->abnormal_psychomotor_behaviour = $request->abnormal_psychomotor_behaviour;
$mental_health_consultation->impaired_cognition = $request->impaired_cognition;
$mental_health_consultation->depression = $request->depression;
$mental_health_consultation->mania = $request->mania;
$mental_health_consultation->hamilton_anxiety_score = $request->hamilton_anxiety_score;
$mental_health_consultation->alcohol_screening_score = $request->alcohol_screening_score;
$mental_health_consultation->patient_satisfaction_score = $request->patient_satisfaction_score;
$mental_health_consultation->caregiver_satisfaction_score = $request->caregiver_satisfaction_score;
$mental_health_consultation->updated_by = Auth::user()->id;
$mental_health_consultation->update();
}
switch ($request->get('submit-btn')):
case 'investigation':
$consultation->save();
session()->put('redirect_to_consultation', '/consultation/route');
$url = '/investigations/investigations_review';
break;
case 'treatment':
$consultation->save();
session()->forget('alter_episode_id');
session()->forget('alter_patient_id');
session()->put('redirect_to_consultation', '/consultation/route');
$url = '/prescriptions/create/';
break;
case 'procedures':
$consultation->save();
session()->put('redirect_to_consultation', '/consultation/route');
$url = '/order_procedures/';
break;
case 'sundries':
$consultation->save();
session()->put('redirect_to_consultation', '/consultation/route');
$url = '/order_sundries/';
break;
case 'services':
$consultation->save();
session()->put('redirect_to_consultation', '/consultation/route');
$url = '/order_services';
break;
case 'save_consultation':
$consultation->save();
$dob = new Carbon(get_name($patient_id, 'id', 'date_of_birth', 'patients'));
$age_diff_months = $dob->diffInMonths(Carbon::now());
if (is_smart_discharge_enabled() && $request->outcome == 1 && $age_diff_months < 61 && $discharge_mortality && is_null($discharge_mortality->post_discharge_mortality_risk)) {
flash("Patient is being monitored for post discharge risk. Please fill the questions below")->success();
return redirect('/triage/edit_for_post_discharge/' . $episode_id);
} else {
$url = '/patient_flow_monitoring/index';
}
break;
case 'complete':
$consultation->completed = 1;
$consultation->save();
session()->forget('consultation_with_notes');
add_doctors_fee_to_patient_services($consultation->id, auth()->user()->id);
$dob = new Carbon(get_name($patient_id, 'id', 'date_of_birth', 'patients'));
$age_diff_months = $dob->diffInMonths(Carbon::now());
if (is_smart_discharge_enabled() && $request->outcome == 1 && $age_diff_months < 61 && $discharge_mortality && is_null($discharge_mortality->post_discharge_mortality_risk)) {
flash("Patient is being monitored for post discharge risk. Please fill the questions below")->success();
return redirect('/triage/edit_for_post_discharge/' . $episode_id);
} else {
$url = '/patient_flow_monitoring/index';
}
break;
default:
$url = '/patient_flow_monitoring/index';
break;
endswitch;
return redirect($url);
}
public function destroy($id)
{
//
}
public function route()
{
/*
* Check if a consultation is pending and then route it to edit page
* If a consultation is completed, route to the view page
*/
$patient_id = session()->get('patient_id');
$episode_id = session()->get('episode_id');
$consultation = DB::table('consultations')->where(['patient_id' => $patient_id, 'episode_id' => $episode_id])->first();
$clinic_id = get_name($episode_id, "id", "clinic_id", "patient_episodes");
// check if patient is in the diabetes program - get with the program 'un
$clinic_slug = get_name($clinic_id, "id", "slug", "clinics");
if ($clinic_slug == "diabetes") {
return redirect('diabetes_clinic/clinic_registration');
}
if ($clinic_slug == "ante_natal") {
return redirect('ante_natal_clinic_menu');
}
if ($clinic_slug == "art") {
return redirect("hiv_menu");
}
if ($clinic_slug == "mental_health") {
$is_mental_health_clinic = true;
session()->put(['is_mental_health_clinic' => 1]);
}
if ($consultation) {
switch ($consultation->completed) {
case '0': // Pending
return self::edit($consultation->id);
break;
case '1': // Completed
return self::show($consultation->id);
break;
default: // Not created yet
return self::create();
break;
}
} else {
return self::create();
}
}
public function edit_patient_consultation()
{
$patient_id = session()->get('patient_id');
$episode_id = session()->get('episode_id');
// update the completed column back to '0' so that it redirects to consultation@edit method
$consultation = Consultation::where(['patient_id' => $patient_id, 'episode_id' => $episode_id])->first();
$consultation->completed = 0;
$consultation->update();
return redirect('/consultation/route');
}
public function create_with_notes()
{
session()->put('consultation_with_notes', 1);
return redirect('/consultation/route');
}
public function add_diagnosis(Request $request)
{
$diagnosis = new \Streamline\Models\Diagnosis;
$diagnosis->name = $request->diagnosis_name;
$diagnosis->icd10_code = $request->icd10_code;
$diagnosis->hmis_no_outpatient = $request->hmis_no_outpatient;
$diagnosis->hmis_no_inpatient = $request->hmis_no_inpatient;
$diagnosis->prompts = $request->diagnosis_prompts;
$diagnosis->chronic_status = $request->chronic_status;
$diagnosis->hmis_category = $request->hmis_category;
$diagnosis->available = isset($request->available)? $request->available:1;
$diagnosis->diagnosis_category = $request->diagnosis_category?? null;
$diagnosis->created_by = auth()->user()->id;
try {
$diagnosis->save();
return $diagnosis->id;
} catch (QueryException $e) {
$errorCode = $e->errorInfo[1];
if ($errorCode == 1062) { //error code for duplicate entry to a unique field
return response()->json(['error' => $e]);
}
}
}
public function review_episode($current_episode_id, $parent_episode_id, $type)
{
$episode = PatientEpisode::find($current_episode_id);
$episode->parent_episode_id = $parent_episode_id;
$episode->updated_by = auth()->user()->id;
$episode->save();
if ($type == 0) {
return redirect('/consultation/route');
} else {
return redirect('/consultation/create_with_notes');
}
}
public function opd_referral_notes_print($patient_id, $episode_id)
{
$patient = Patient::find($patient_id);
$hospitalInfo = DB::table('hospital_information')->find(1);
$consultation = Consultation::where(['patient_id' => $patient_id, 'episode_id' => $episode_id])->orderBy('created_at', 'desc')->first();
$patient_discount = \Streamline\Models\PatientDiscount::where(['patient_category' => $patient->category_id])->select("discount", "pay_later")->first();
if (!is_null($patient_discount)) {
$patient_discount->toArray();
}
/* ====== start work on investigations */
// prep the inpatient investigation arrays and counters
$opd_investigations = [];
$opd_investigations_position = [];
$opd_investigations_date = [];
$ward_investigations = [];
$ward_investigations_position = [];
$ward_investigations_date = [];
// get all investigations ordered in this episode
$ordered_investigations = OrderedInvestigation::where(['episode_id' => $episode_id])->get();
// get all results
$investigation_results_order_ids = InvestigationResults::pluck('order_id', 'id')->toArray();
foreach ($ordered_investigations as $investigation) {
if (isset($ward_investigations['id'])) {
$ward_investigations_position[] = count($ward_investigations['id']);
} else {
$ward_investigations_position[] = 0;
}
if (isset($opd_investigations['id'])) {
$opd_investigations_position[] = count($opd_investigations['id']);
} else {
$opd_investigations_position[] = 0;
}
$ward_investigations_date[] = "Ordered on " . streamline_date_time($investigation->created_at) . " by " .
get_full_name($investigation->created_by, 'id', 'first_name', 'last_name', 'users');
$opd_investigations_date[] = streamline_date_time($investigation->created_at);
$investigation_ids = explode(",", $investigation->investigation_id);
$inpatient_status = explode(",", $investigation->for_inpatient);
// check if results are available for this investigation
if (in_array($investigation->id, $investigation_results_order_ids)) {
// get the key if available
$key = array_search($investigation->id, $investigation_results_order_ids);
// get the results object
$results = InvestigationResults::find($key);
// exclude obstetric u/s results
if ($results->result_type != "Ultrasound_Obstetric") {
$investigation_results = explode(",", $results->value);
$investigation_per_valid = explode(",", $results->per_investigation);
$investigation_comments = explode(",", $results->comment);
if ($results->all_authenticated == 1) {
for ($i = 0; $i < count($inpatient_status); $i++) {
if (isset($inpatient_status[$i]) && $inpatient_status[$i] == 0) {
$result = Investigation::withTrashed()->find($investigation_ids[$i]);
$opd_investigations['id'][] = $result->id;
$opd_investigations['name'][] = $result->name;
$opd_investigations['type'][] = $result->type;
$opd_investigations['slug'][] = $result->slug;
$opd_investigations['value'][] = $investigation_results[$i];
$opd_investigations['comment'][] = $investigation_comments[$i];
} else {
$result = Investigation::withTrashed()->find($investigation_ids[$i]);
$ward_investigations['id'][] = $result->id;
$ward_investigations['name'][] = $result->name;
$ward_investigations['type'][] = $result->type;
$ward_investigations['slug'][] = $result->slug;
$ward_investigations['value'][] = isset($investigation_results[$i]) ? $investigation_results[$i] : "";
$ward_investigations['comment'][] = isset($investigation_comments[$i]) ? $investigation_comments[$i] : "";
}
}
} else {
for ($i = 0; $i < count($inpatient_status); $i++) {
$investigation = \Streamline\Models\Investigation::withTrashed()->find($investigation_ids[$i]);
if (isset($investigation_per_valid[$i]) && $investigation_per_valid[$i] == 1) {
// this investigation is authenticated
if (isset($inpatient_status[$i]) && $inpatient_status[$i] == 0) {
$opd_investigations['id'][] = $investigation->id;
$opd_investigations['name'][] = $investigation->name;
$opd_investigations['type'][] = $investigation->type;
$opd_investigations['slug'][] = $investigation->slug;
$opd_investigations['value'][] = $investigation_results[$i];
$opd_investigations['comment'][] = $investigation_comments[$i];
} else {
$ward_investigations['id'][] = $investigation->id;
$ward_investigations['name'][] = $investigation->name;
$ward_investigations['type'][] = $investigation->type;
$ward_investigations['slug'][] = $investigation->slug;
$ward_investigations['value'][] = $investigation_results[$i];
$ward_investigations['comment'][] = $investigation_comments[$i];
}
} else {
if (isset($investigation_per_valid[$i]) && $inpatient_status[$i] == 0) {
$opd_investigations['id'][] = $investigation->id;
$opd_investigations['name'][] = $investigation->name;
$opd_investigations['type'][] = $investigation->type;
$opd_investigations['slug'][] = $investigation->slug;
$opd_investigations['value'][] = "Pending";
$opd_investigations['comment'][] = "Pending";
} else {
$ward_investigations['id'][] = $investigation->id;
$ward_investigations['name'][] = $investigation->name;
$ward_investigations['type'][] = $investigation->type;
$ward_investigations['slug'][] = $investigation->slug;
$ward_investigations['value'][] = "Pending";
$ward_investigations['comment'][] = "Pending";
}
}
}
}
}
} else {
for ($i = 0; $i < count($inpatient_status); $i++) {
if (isset($inpatient_status[$i]) && $inpatient_status[$i] == 0) {
$result = Investigation::withTrashed()->find($investigation_ids[$i]);
$opd_investigations['id'][] = $result->id;
$opd_investigations['name'][] = $result->name;
$opd_investigations['type'][] = $result->type;
$opd_investigations['slug'][] = $result->slug;
$opd_investigations['value'][] = "Pending";
$opd_investigations['comment'][] = "Pending";
} else {
$result = Investigation::withTrashed()->find($investigation_ids[$i]);
$ward_investigations['id'][] = $result->id;
$ward_investigations['name'][] = $result->name;
$ward_investigations['type'][] = $result->type;
$ward_investigations['slug'][] = $result->slug;
$ward_investigations['value'][] = "Pending";
$ward_investigations['comment'][] = "Pending";
}
}
}
}
/* ====== end work on investigations */
$data = [
'patient' => $patient,
'consultation' => $consultation,
'patient_id' => $patient_id,
'hospitalInfo' => $hospitalInfo,
'patient_discount' => $patient_discount,
'ward_investigations' => $ward_investigations,
'opd_investigations' => $opd_investigations,
'opd_investigations_position' => $opd_investigations_position,
'ward_investigations_position' => $ward_investigations_position,
'opd_investigations_date' => $opd_investigations_date,
'ward_investigations_date' => $ward_investigations_date
];
$pdf = SnappyPDF::loadView('patients::consultations/referral_notes_print', $data)
->setOrientation('portrait')
->setOption('margin-bottom', 7)
->setOption('margin-top', 5)
->setOption('footer-html', '<i>Stre@mline</i>');
return $pdf->inline('Referral Notes' . date("y-m-d h:ia") . '.pdf');
}
public function get_outcome_slug($id)
{
$outcome = Outcome::find($id);
if ($outcome) {
return $outcome->slug;
}
return "";
}
}