Files
streamline-emr/docker/streamline-src/Modules/Investigations/Http/Controllers/InvestigationController.php
T

3810 lines
175 KiB
PHP
Executable File

<?php
namespace Modules\Investigations\Http\Controllers;
use Carbon\Carbon;
use DateTime;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Spatie\Permission\Models\Role;
use Streamline\Http\Controllers\StreamlineSetupManager;
use Streamline\Models\Alert;
use Streamline\Models\Allergy;
use Streamline\Models\CardioEchoTemplate;
use Streamline\Models\ChartOfAccount;
use Streamline\Models\ChronicPatient;
use Streamline\Models\Diagnosis;
use Streamline\Models\DrugCategory;
use Streamline\Models\FamilyRelationship;
use Streamline\Models\HmisCategory;
use Streamline\Models\HmisCategoryOptions;
use Streamline\Models\HospitalInformation;
use Streamline\Models\InsuranceClaim;
use Streamline\Models\Investigation;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Streamline\Models\InvestigationCategory;
use Streamline\Models\InvestigationSpecialisedResult;
use Streamline\Models\InvestigationSpecialisedVariable;
use Streamline\Models\LaboratorySpecimen;
use Streamline\Models\MaritalStatus;
use Streamline\Models\InvestigationNormalRange;
use Streamline\Models\ObstetricUltrasoundReports;
use Streamline\Models\Occupation;
use Streamline\Models\OrderedInvestigation;
use Streamline\Models\InvestigationResults;
use Streamline\Models\Consultation;
use Streamline\Models\Patient;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\Session;
use Streamline\Models\PatientCategory;
use Streamline\Models\PatientDocument;
use Streamline\Models\PriceListCategories;
use Streamline\Models\StreamlineSetupStep;
use Streamline\Models\Supplier;
use Streamline\Models\UnitOfMeasure;
use Streamline\Models\User;
use Streamline\Models\CardioEchoResult;
use Barryvdh\Snappy\Facades\SnappyPdf;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Streamline\Services\StreamlineSetupServiceInterface;
class InvestigationController extends Controller
{
public function __construct(
protected StreamlineSetupServiceInterface $setupService
) {
$this->middleware('auth');
$this->middleware('permission:investigations-list', ['only' => ['index']]);
$this->middleware('permission:investigations-create', ['only' => ['create', 'store']]);
$this->middleware('permission:investigations-edit', ['only' => ['edit', 'update', 'edit_all', 'update_all']]);
$this->middleware('permission:investigations-delete', ['only' => ['destroy', 'inactive', 'activate']]);
$this->middleware('permission:investigations-incoming', ['only' => ['incoming_labs']]);
$this->middleware('permission:investigations-authenticate', ['only' => ['authenticate_labs', 'authenticate_investigations']]);
$this->middleware('permission:investigation-results-list', ['only' => ['view_results']]);
$this->middleware('permission:investigation-results-alter', ['only' => ['alter_results']]);
$this->middleware('permission:investigations-historical-list', ['only' => ['historical_labs']]);
/**
* Imaging
* */
$this->middleware('permission:imaging-incoming-radiology', ['only' => ['imaging-incoming-radiology']]);
$this->middleware('permission:imaging-incoming-ultrasound', ['only' => ['imaging-incoming-ultrasound']]);
$this->middleware('permission:imaging-incoming-ultrasound-obstetric', ['only' => ['imaging-incoming-ultrasound-obstetric']]);
$this->middleware('permission:imaging-radiology-results', ['only' => ['imaging-radiology-results']]);
$this->middleware('permission:imaging-ultrasound-results', ['only' => ['imaging-incoming-ultrasound']]);
$this->middleware('permission:imaging-ultrasound-obstetric-results', ['only' => ['imaging-incoming-ultrasound-obstetric']]);
$this->middleware('permission:imaging-alter-investigation-results', ['only' => ['alter_results_others']]);
$this->middleware('permission:imaging-view-historical-results', ['only' => ['imaging_historical_results']]);
$this->middleware('permission:cancel-investigation-order', ['only' => ['investigations_to_cancel', 'destroy_ordered_investigations']]);
$this->middleware('permission:restore-cancelled-investigation-order', ['only' => ['view_deleted_ordered_invetigations', 'restore_deleted_ordered_invetigations']]);
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$investigations = Investigation::orderBy('name', 'asc')->paginate(1000);
$ordered_investigations_array = [];
$ordered_investigations = OrderedInvestigation::distinct('investigation_id')->get(['investigation_id']);
foreach ($ordered_investigations as $ordered_investigation) {
$actual = explode(',', $ordered_investigation->investigation_id);
foreach ($actual as $value) $ordered_investigations_array[] = $value;
}
$ordered_investigations_ids = array_unique($ordered_investigations_array);
$investigation_categories = InvestigationCategory::orderBy('name', 'asc')->pluck('name', 'id');
$chart_of_accounts = ChartOfAccount::orderBy('name', 'asc')->pluck('name', 'id');
$inpatient_hmis_categories = HmisCategory::where('section_number', 5)->select('title', 'id', 'number', 'type', 'section_number')->get()->toArray();
$hmis_categories = DB::table('hmis_categories')->where('type', 0)->pluck('title', 'id')->toArray();
return view('investigations::investigations.index', compact('investigations', 'investigation_categories', 'chart_of_accounts', 'hmis_categories', 'ordered_investigations_ids', 'inpatient_hmis_categories'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
$suppliers = Supplier::orderBy('name', 'asc')->pluck('name', 'id');
$investigation_categories = InvestigationCategory::orderBy('name', 'asc')->pluck('name', 'id')->toArray();
$investigation_categories = ['' => '- select -'] + $investigation_categories;
$chart_of_accounts = ChartOfAccount::where('type', 1)->orderBy('name', 'asc')->pluck('name', 'id')->toArray();
$chart_of_accounts = ['' => '- select -'] + $chart_of_accounts;
$unit_of_measure = UnitOfMeasure::orderBy('name', 'asc')->pluck('name', 'id')->toArray();
$unit_of_measure = ['' => '- select -'] + $unit_of_measure;
$investigations = StreamlineSetupManager::get_investigations_array();
$hmis_categories = DB::table('hmis_categories')->where('type', 0)->pluck('title', 'id')->toArray();
$inpatient_hmis_categories = HmisCategory::where('section_number', 5)->select('title', 'id', 'number', 'type', 'section_number')->get()->toArray();
// $inpatient_hmis_category_options = DB::table('hmis_category_options')->where('hmis_category_id', $investigation->hmis_category_inpatient)->get()->toArray();
$hmis_categories = ['' => '- select -'] + $hmis_categories;
return view('investigations::investigations.create', compact('suppliers', 'investigation_categories', 'inpatient_hmis_categories', 'chart_of_accounts', 'unit_of_measure', 'investigations', 'hmis_categories'));
}
/**
* Store a newly created resource in storage.
*
*/
public function store(Request $request)
{
//if it for streamline setup then you can skip the request validation
if (session()->has('streamline_setup')) {
//skip validation
} else {
request()->validate([
'name' => 'required|unique:investigations',
'category' => 'required',
'units' => 'required',
'available' => 'required',
'account_id' => 'required',
'echo' => 'required_if:category,17',
'reference_text'=>'nullable|required_with:reference_link',
'reference_link'=>'nullable|url|required_with:reference_text'
],
[
'name.required' => 'The investigation name is required.',
'name.unique' => 'This investigation name already exists. Please choose a different name.',
'category.required' => 'Please select a category for the investigation.',
'units.required' => 'The units field is required.',
'available.required' => 'Please specify whether the investigation is available.',
'account_id.required' => 'The account ID is required.',
'echo.required_if' => 'An echo is required when the category is set to 17.',
'reference_text.required_with' => 'The reference text is required when a reference link is provided.',
'reference_link.required_with' => 'The reference link is required when reference text is provided.',
'reference_link.url' => 'The reference link must be a valid URL.'
]);
}
if (isset($request->skip)) {
//Artisan::call('db:seed', ['--class' => 'InvestigationSeeder']);
//update the streamline setup table with the new finished step
$this->setupService->saveStep("investigations registration", 1);
//flash("Default system investigations have been added")->success();
return redirect("drugs/create");
} else {
// get all current price lists
$price_list = PriceListCategories::withTrashed()->select('id')->get();
$price_list_category = [];
$price_list_price = [];
foreach ($price_list as $record) {
array_push($price_list_category, $record->id);
array_push($price_list_price, $request->non_insured_price);
}
$logged_in_user_id = Auth::user()->id;
$investigation = new Investigation;
$investigation->name = $request->name;
$investigation->code = $request->code;
$investigation->category = $request->category;
$investigation->units = $request->units;
$investigation->minimum = $request->minimum;
$investigation->sample_container = $request->sample_container;
$investigation->insurance_coverage = 0;
$investigation->comments = $request->comments;
$investigation->normal_ranges = $request->normal_ranges;
$investigation->lab_time = $request->lab_time;
$investigation->hmis_002_slug = $request->hmis_002_slug;
$investigation->non_insured_price = $request->non_insured_price;
$investigation->insured_price = 0;
/*$investigation->price_list_category = implode(",", $price_list_category);
$investigation->price_list_price = implode(",", $price_list_price);*/
$investigation->price_list_category = !is_null($request->price_list_category_id) ? implode(",", $request->price_list_category_id) : null;
$investigation->price_list_price = !is_null($request->price_list_price) ? implode(",", $request->price_list_price) : null;
$investigation->account_id = $request->account_id;
/* == hmis stuff ===== */
$investigation->hmis_no_outpatient = is_null($request->hmis_no_outpatient) ? null : implode(",", $request->hmis_no_outpatient);
$investigation->hmis_category = is_null($request->hmis_category) ? null : implode(",", $request->hmis_category);
$investigation->hmis_no_inpatient = $request->hmis_no_inpatient;
$investigation->hmis_category_inpatient = $request->hmis_category_inpatient;
/* =================== */
$investigation->available = $request->available;
$investigation->slug = !empty($request->echo) ? 'echo' : null;
$investigation->range_type = is_null($request->range_type) ? 0 : $request->range_type;
$investigation->is_chronic = $request->is_chronic;
$investigation->reference_text = $request->reference_text;
$investigation->reference_link = $request->reference_link;
$investigation->created_by = $logged_in_user_id;
$investigation->updated_by = $logged_in_user_id;
if ($investigation->name != "" && !is_null($investigation->name)) {
$investigation->save();
if ($request->range_type == 1) {
$age_id = $request->age_id;
$dynamic_range_male = $request->dynamic_range_male;
$dynamic_range_female = $request->dynamic_range_female;
for ($x = 0; $x < count($age_id); $x++) {
$new_range = new InvestigationNormalRange;
$new_range->male_range = $dynamic_range_male[$x];
$new_range->female_range = $dynamic_range_female[$x];
$new_range->age_group_id = $age_id[$x];
$new_range->test_id = $investigation->id;
$new_range->created_by = $logged_in_user_id;
$new_range->save();
}
}
}
try {
flash($request->name . " Investigation has been saved")->success();
if (session()->has('streamline_setup')) {
if (isset($request->selected_investigations)) {
$selected_investigations_array = $request->selected_investigations;
if (!empty($selected_investigations_array)) {
for ($i = 0; $i < count($selected_investigations_array); $i++) {
/* try this magic to get details for the selected service */
$investigations_array = StreamlineSetupManager::get_investigations_array();
$key = array_search($selected_investigations_array[$i], array_column($investigations_array, 'name'));
$inv_details = $investigations_array[$key];
/* end of magic trial */
$default_investigation = new Investigation;
$default_investigation->name = $inv_details['name'];
$default_investigation->category = $inv_details['category'];
$default_investigation->insured_price = 0;
$default_investigation->non_insured_price = 0;
$default_investigation->account_id = $inv_details['account_id'];
$default_investigation->save();
}
}
}
//update the streamline setup table with the new finished step
$this->setupService->saveStep("investigations registration", 1);
return redirect("drugs/create");
}
return redirect("/investigations/");
} catch (QueryException $e) {
flash($request->name . " Investigation already exists!")->error();
return back()->withInput();
}
}
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$investigation = Investigation::where(['id' => $id])->first();
$investigation_categories = InvestigationCategory::orderBy('name', 'asc')->pluck('name', 'id')->toArray();
$chart_of_accounts = ChartOfAccount::where('type', 1)->orderBy('name', 'asc')->pluck('name', 'id')->toArray();
$chart_of_accounts = ['' => '- select -'] + $chart_of_accounts;
$hmis_categories_opd = DB::table('hmis_categories')->where('type', 0)->pluck('title', 'id')->toArray();
$hmis_categories_opd = ['' => '- select -'] + $hmis_categories_opd;
$hmis_categories_ip = DB::table('hmis_categories')->where('type', 1)->pluck('title', 'id')->toArray();
$hmis_categories_ip = ['' => '- select -'] + $hmis_categories_ip;
$unit_of_measure = UnitOfMeasure::orderBy('name', 'asc')->pluck('name', 'id')->toArray();
$unit_of_measure = ['' => '- select -'] + $unit_of_measure;
$inpatient_hmis_categories = HmisCategory::where('section_number', 5)->select('title', 'id', 'number', 'type', 'section_number')->get()->toArray();
$inpatient_hmis_category_options = HmisCategoryOptions::where('hmis_category_id', $investigation->hmis_category_inpatient)->get()->toArray();
if (!$investigation) {
flash()->error("There is no such investigation");
return redirect('/investigations/');
} else {
return view('investigations::investigations.edit', compact('investigation', 'chart_of_accounts', 'inpatient_hmis_categories', 'investigation_categories', 'hmis_categories_opd', 'hmis_categories_ip', 'inpatient_hmis_category_options', 'unit_of_measure'));
}
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
request()->validate([
'name' => 'required',
'category' => 'required',
'available' => 'required',
'account_id' => 'required',
'echo' => 'required_if:category,17',
'reference_text' => 'nullable|required_with:reference_link',
'reference_link' => 'nullable|url|required_with:reference_text'
],
[
'name.required' => 'The investigation name is required.',
'name.unique' => 'This investigation name already exists. Please choose a different name.',
'category.required' => 'Please select a category for the investigation.',
'units.required' => 'The units field is required.',
'available.required' => 'Please specify whether the investigation is available.',
'account_id.required' => 'The account ID is required.',
'echo.required_if' => 'An echo is required when the category is set to 17.',
'reference_text.required_with' => 'The reference text is required when a reference link is provided.',
'reference_link.required_with' => 'The reference link is required when reference text is provided.',
'reference_link.url' => 'The reference link must be a valid URL.'
]);
$logged_in_user_id = Auth::user()->id;
$investigation = Investigation::find($id);
$investigation->name = $request->name;
$investigation->code = $request->code;
$investigation->category = $request->category;
$investigation->normal_ranges = $request->normal_ranges;
$investigation->units = $request->units;
$investigation->minimum = $request->minimum;
$investigation->sample_container = $request->sample_container;
$investigation->non_insured_price = $request->non_insured_price;
$investigation->price_list_category = !is_null($request->price_list_category_id) ? implode(",", $request->price_list_category_id) : null;
$investigation->price_list_price = !is_null($request->price_list_price) ? implode(",", $request->price_list_price) : null;
$investigation->insured_price = 0;
$investigation->comments = $request->comments;
$investigation->lab_time = $request->lab_time;
$investigation->hmis_002_slug = $request->hmis_002_slug;
$investigation->insurance_coverage = 0;
$investigation->available = $request->available;
$investigation->slug = !empty($request->echo) ? 'echo' : null;
$investigation->account_id = $request->account_id;
$investigation->range_type = $request->range_type;
$investigation->is_chronic = $request->is_chronic;
$investigation->reference_text = $request->reference_text;
$investigation->reference_link = $request->reference_link;
/* == hmis stuff ===== */
$investigation->hmis_no_outpatient = implode(",", $request->hmis_no_outpatient);
$investigation->hmis_category = implode(",", $request->hmis_category_opd);
$investigation->hmis_no_inpatient = $request->hmis_no_inpatient;
$investigation->hmis_category_inpatient = $request->hmis_category_inpatient;
/* =================== */
$investigation->updated_by = $logged_in_user_id;
if ($request->sub_tests) {
$investigation->type = 1;
$sub_test_array = $request->sub_tests;
for ($i = 0; $i < count($sub_test_array); $i++) {
$variable = new InvestigationSpecialisedVariable;
$variable->name = get_name($sub_test_array[$i], 'id', 'name', 'investigation_specialised_variables');
$variable->investigation_id = $id;
$variable->units = get_name($sub_test_array[$i], 'id', 'units', 'investigation_specialised_variables');
$variable->normal_ranges = get_name($sub_test_array[$i], 'id', 'normal_ranges', 'investigation_specialised_variables');
$variable->flags = get_name($sub_test_array[$i], 'id', 'flags', 'investigation_specialised_variables');
$variable->created_by = $logged_in_user_id;
$variable->updated_by = $logged_in_user_id;
$investigation = Investigation::find($request->investigation);
$investigation->type = 1;
try {
$variable->save();
flash('successfully attached subtest to investigation.')->success();
} catch (QueryException $e) {
flash('failed to attached subtest to investigation.')->error();
}
}
}
try {
$investigation->save();
if ($request->range_type == 1) {
$age_id = $request->age_id;
$dynamic_range_male = $request->dynamic_range_male;
$dynamic_range_female = $request->dynamic_range_female;
for ($x = 0; $x < count($age_id); $x++) {
$dynamic_normal_range = DB::table('investigations_normal_ranges')
->where('age_group_id', $age_id[$x])
->where('test_id', $investigation->id)
->first();
if (!$dynamic_normal_range) {
$dynamic_normal_range = new InvestigationNormalRange;
$dynamic_normal_range->created_by = $logged_in_user_id;
} else {
$dynamic_normal_range = InvestigationNormalRange::find($dynamic_normal_range->id);
$dynamic_normal_range->updated_by = $logged_in_user_id;
}
$dynamic_normal_range->female_range = $dynamic_range_female[$x];
$dynamic_normal_range->male_range = $dynamic_range_male[$x];
$dynamic_normal_range->age_group_id = $age_id[$x];
$dynamic_normal_range->test_id = $investigation->id;
$dynamic_normal_range->save();
}
}
flash($request->name . " Investigation has been updated")->success();
return redirect("/investigations/");
} catch (QueryException $e) {
flash("An error occurred")->error();
return back()->withInput();
}
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$investigation = Investigation::find($id);
if ($investigation->delete()):
flash("Investigation has been deleted.")->success();
return redirect('/investigations/');
endif;
}
/**
* Display a listing of the inactive resource(s).
*
* @return \Illuminate\Http\Response
*/
public function inactive()
{
$investigations = Investigation::onlyTrashed()->orderBy('name', 'asc')->paginate(50);
$investigation_categories = InvestigationCategory::orderBy('name', 'asc')->pluck('name', 'id');
$chart_of_accounts = ChartOfAccount::orderBy('name', 'asc')->pluck('name', 'id');
if (empty($investigations)) {
flash()->error("There is no inactive investigation");
return redirect('/investigations/');
} else {
return view('investigations::investigations.inactive', compact('investigations', 'investigation_categories', 'chart_of_accounts'));
}
}
/**
* Activate the specified resource in storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function activate($id)
{
$investigation = Investigation::withTrashed()->find($id);
if ($investigation->restore()):
flash("Investigation has been activated.")->success();
return redirect('/investigations/inactive');
endif;
}
/**
* Display a listing of the active resources for bulk editing.
*
* @return \Illuminate\Http\Response
*/
public function edit_all()
{
$investigations = Investigation::orderBy('name', 'asc')->get();
$investigation_categories = InvestigationCategory::orderBy('name', 'asc')->pluck('name', 'id')->toArray();
$investigation_categories = ['' => '- select -'] + $investigation_categories;
$chart_of_accounts = ChartOfAccount::where('type', 1)->orderBy('name', 'asc')->pluck('name', 'id');
if (count($investigations) < 1) {
flash()->error("There is no active investigation");
return redirect('/investigations/');
} else {
return view('investigations::investigations.edit.all', compact('investigations', 'chart_of_accounts', 'investigation_categories'));
}
}
/**
* Display a listing of the active resources for editing HMIS Options
*
* @return \Illuminate\Http\Response
*/
public function edit_hmis_options()
{
$investigations = Investigation::orderBy('name', 'asc')->get();
$investigation_categories = InvestigationCategory::orderBy('name', 'asc')->pluck('name', 'id')->toArray();
$investigation_categories = ['' => '- select -'] + $investigation_categories;
$hmis_categories = DB::table('hmis_categories')->where('type', 0)->pluck('title', 'id')->toArray();
$hmis_categories = ['' => '- select -'] + $hmis_categories;
$category_ids = [];
$hmis_categories_ip = DB::table('hmis_categories')->where('type', 1)->pluck('title', 'id')->toArray();
$hmis_categories_ip = ['' => '- select -'] + $hmis_categories_ip;
$inpatient_hmis_categories = HmisCategory::where('section_number', 5)->select('title', 'id', 'number', 'type', 'section_number')->get()->toArray();
foreach ($inpatient_hmis_categories as $inpatient_hmis_category) $category_ids[] = $inpatient_hmis_category['id'];
$inpatient_hmis_category_options = HmisCategoryOptions::whereIn('hmis_category_id', $category_ids)->get()->toArray();
if (count($investigations) < 1) {
flash()->error("There is no active investigation");
return redirect('/investigations/');
} else {
return view('investigations::investigations.edit.hmis-options', compact('investigations', 'investigation_categories', 'hmis_categories', 'inpatient_hmis_category_options', 'inpatient_hmis_categories', 'hmis_categories_ip'));
}
}
/**
* Update all the resources in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function update_all(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'required',
'available' => 'required',
'account_id' => 'required'
]);
if ($validator->fails()) {
$string = "";
foreach ($validator->errors()->getMessages() as $item) {
$string .= "{$item[0]}<br>";
}
// flash($string)->error();
return back()->withErrors($validator)->withInput();
} else {
$logged_in_user_id = Auth::user()->id;
$id_array = $request->id;
$name_array = $request->name;
$category_array = $request->category;
$normal_ranges_array = $request->normal_ranges;
$minimum_array = $request->minimum;
$sample_container_array = $request->sample_container;
$non_insured_price_array = $request->non_insured_price;
$comments_array = $request->comments;
$lab_time_array = $request->lab_time;
$available_array = $request->available;
$account_id_array = $request->account_id;
for ($x = 0; $x < count($id_array); $x++):
$investigation = Investigation::find($id_array[$x]);
$investigation->name = $name_array[$x];
$investigation->category = $category_array[$x];
$investigation->normal_ranges = $normal_ranges_array[$x];
$investigation->minimum = $minimum_array[$x];
$investigation->sample_container = $sample_container_array[$x];
$investigation->non_insured_price = $non_insured_price_array[$x];
$investigation->insured_price = 0;
$investigation->comments = $comments_array[$x];
$investigation->lab_time = $lab_time_array[$x];
$investigation->insurance_coverage = 0;
$investigation->available = $available_array[$x];
$investigation->account_id = $account_id_array[$x];
$investigation->updated_by = $logged_in_user_id;
try {
$investigation->save();
} catch (QueryException $e) {
flash("An error occurred")->error();
return back()->withInput();
}
endfor;
flash("Investigations have been updated")->success();
return redirect("/investigations/");
}
}
public function update_hmis_options(Request $request)
{
$logged_in_user_id = Auth::user()->id;
$id_array = $request->id;
$name_array = $request->name;
/* == hmis stuff ===== */
$hmis_no_outpatient_array = $request->hmis_no_outpatient;
$hmis_category_outpatient_array = $request->hmis_category;
$hmis_no_inpatient_array = $request->hmis_no_inpatient;
$hmis_category_inpatient_array = $request->hmis_category_inpatient;
/* =================== */
for ($x = 0; $x < count($id_array); $x++):
$investigation = Investigation::find($id_array[$x]);
$investigation->name = $name_array[$x];
/* == hmis stuff ===== */
$investigation->hmis_no_outpatient = $hmis_no_outpatient_array[$x];
$investigation->hmis_category = $hmis_category_outpatient_array[$x];
$investigation->hmis_no_inpatient = $hmis_no_inpatient_array[$x];
$investigation->hmis_category_inpatient = $hmis_category_inpatient_array[$x];
/* =================== */
$investigation->updated_by = $logged_in_user_id;
try {
$investigation->save();
} catch (QueryException $e) {
flash("An error occurred")->error();
return back()->withInput();
}
endfor;
flash("Investigations have been updated")->success();
return redirect("/investigations/edit/hmis-options");
}
public function investigations_review()
{
$patient_id = session()->get('patient_id');
$episode_id = session()->get('episode_id');
$patient = Patient::find($patient_id);
$investigations_select_code = "<option value=''>-select-</option>";
$investigations_to_order = [];
$categories = DB::table('investigation_categories')->whereNull('deleted_at')->get()->toArray();
foreach ($categories as $category) {
$investigations = DB::table('investigations')->whereNull('deleted_at')->where('category', '=', $category->id)->where('available', 1)->orderBy('name', 'asc')->get(['id', 'name']);
if (count($investigations) > 0) {
$investigations_select_code .= "<optgroup label='" . $category->name . "'>";
foreach ($investigations as $investigation) {
$investigations_to_order[$investigation->id] = $investigation->name;
$investigations_select_code .= "<option value='" . $investigation->id . "'>" . $investigation->name . "</option>";
}
$investigations_select_code .= "</optgroup>";
}
}
$ordered_investigations = OrderedInvestigation::where('patient_id', '=', $patient_id)
->where('episode_id', $episode_id)
->where('investigation_status', '0')
->where('request_received', '0')
->where('payment_status', '0')
->where('inpatient_bill_generated', '0')
->get();
// collect chronic drug ids as array
$chronic_array = ChronicPatient::where('patient_id', $patient_id)->whereNotNull('investigation_id')->get(['investigation_id']);
$investigations = DB::table('investigations')->whereNull('deleted_at')->where('available', 1)->pluck('name', 'id');
return view('investigations::investigations.investigations_review', compact('patient', 'investigations_select_code', 'patient_id', 'ordered_investigations', 'investigations_to_order', 'chronic_array', 'investigations', 'episode_id'));
}
public function get_investigation_details(Request $request)
{
$patient_id = $request->patient_id;
$patient_insurance_status = $request->patient_insurance_status ?? 0;
$investigation = DB::table('investigations')->find($request->investigation_id);
if (is_numeric($patient_insurance_status) && $patient_insurance_status == 1 && $patient_id != 0 && is_numeric($patient_id)) {
$selling_price = get_item_insurance_co_payment($patient_id, $investigation->id, 3, false, 0);
} else {
// check if the patient category is attached to a price list
$price_list_id = is_patient_category_attached_to_price_list($patient_id);
if ($price_list_id) {
$selling_price = get_price_list_category_price($price_list_id, 2, $investigation->id);
} else {
$selling_price = $investigation->non_insured_price;
}
}
if (is_chi_enabled() && is_patient_item_covered($patient_id, $investigation->id, 3)) {
$covered_by_chi = '&nbsp;&nbsp;<br><span style="color: darkgreen"><b>Covered by CHI</b></span>';
} else {
$covered_by_chi = "";
}
return json_encode([
"comments" => $investigation->comments,
"selling_price" => $selling_price,
"covered_by_chi" => $covered_by_chi,
]);
}
/**
* Submit investigation orders.
*
* @return \Illuminate\Http\RedirectResponse
*/
public function submit_ordered_investigations(Request $request)
{
if (is_null($request->investigations_id) || is_null($request->investigations_id[0])) {
flash("No investigation has been selected")->error();
return back()->withInput();
}
$is_inpatient = session()->get('ward_investigation');
$inpatient = (isset($is_inpatient)) ? 1 : 0;
// unset the session for ward investigation
session()->forget('ward_investigation');
$investigation_ids = $request->investigations_id;
$order_comments_array = $request->order_comments;
$eye_array = $request->eye;
$urgent_ids = $request->urgent_id ?? [];
$patient_id = $request->patient_id;
$episode_id = $request->episode_id;
$investigation_codes_array = [];
$investigation_names_array = [];
$bc_sales_invoice_lines = [];
$investigations_array = [
"Lab" => ["ids" => [], "comments" => [], "urgent" => [], "eye" => [], "order_id" => 0],
"Imaging" => ["ids" => [], "comments" => [], "urgent" => [], "eye" => [], "order_id" => 0],
"Ultrasound" => ["ids" => [], "comments" => [], "urgent" => [], "eye" => [], "order_id" => 0],
"Ultrasound_Obstetric" => ["ids" => [], "comments" => [], "urgent" => [], "eye" => [], "order_id" => 0],
"Cardio" => ["ids" => [], "comments" => [], "urgent" => [], "eye" => [], "order_id" => 0]
];
$update_order_ids = $request->order_id;
if (isset($update_order_ids)) {
foreach ($update_order_ids as $update_order_id) {
$original_order_type = get_name($update_order_id, 'id', 'order_type', 'ordered_investigations');
$payment_status = get_name($update_order_id, 'id', 'payment_status', 'ordered_investigations');
if (array_key_exists($original_order_type, $investigations_array) && $payment_status != 1) {
$investigations_array[$original_order_type]["order_id"] = $update_order_id;
}
}
}
// iterate over the ordered investigations and divide them into categories
for ($i = 0; $i < count($investigation_ids); $i++) {
$inv_order_type = get_name(get_name($investigation_ids[$i], "id", "category", "investigations"), "id", "super_category_id", "investigation_categories");
$investigation_details = Investigation::find($investigation_ids[$i]);
$investigation_codes_array[] = $investigation_details->code;
$investigation_names_array[] = $investigation_details->name;
$bc_sales_invoice_lines[] = [
"invoiceDocType" => "Invoice",
"lineType" => "resource",
"lineObjectNumber" => $investigation_details->code,
"description" => $investigation_details->name
];
if ($inv_order_type == 1) {
$order_type_name = "Lab";
} elseif ($inv_order_type == 2) {
$order_type_name = "Imaging";
} elseif ($inv_order_type == 3) {
$order_type_name = "Ultrasound";
} elseif ($inv_order_type == 4) {
$order_type_name = "Ultrasound_Obstetric";
} elseif ($inv_order_type == 5) {
$order_type_name = "Cardio";
} else {
$order_type_name = "None";
}
$investigations_array[$order_type_name]["ids"][] = $investigation_ids[$i];
$investigations_array[$order_type_name]["comments"][] = $order_comments_array[$i];
$investigations_array[$order_type_name]["eye"][] = $eye_array[$i];
if (in_array($investigation_ids[$i], $urgent_ids)) {
$investigations_array[$order_type_name]["urgent"][] = $investigation_ids[$i];
}
if (is_investigation_chronic($investigation_ids[$i])) {
register_chronic_investigation($patient_id, $episode_id, $investigation_ids[$i]);
}
}
$logged_in_user_id = Auth::user()->id;
// iterate through the investigation array and place all orders in the respective table
foreach ($investigations_array as $order_type => $order_ids) {
if ($order_ids["order_id"] == 0) {
if (count($order_ids["ids"]) > 0) {
//create new order investigation
$order = new OrderedInvestigation;
$order->investigation_id = implode(",", $order_ids["ids"]);
$order->patient_id = $patient_id;
$order->episode_id = $episode_id;
$order->urgent = !empty($order_ids["urgent"]) ? 1 : 0;
$order->urgent_ids = implode(",", $order_ids["urgent"]);
$order->inpatient = $inpatient;
$order->for_inpatient = implode(",", array_fill(0, count($order_ids["ids"]), $inpatient));
$order->order_type = $order_type;
$order->eye = implode(",", $order_ids["eye"]);
$order->order_comments = implode(",", $order_ids["comments"]);
$order->created_by = $logged_in_user_id;
$order->save();
// create an insurance claim for the ordered items
if ($request->patient_insurance_status == 1) {
generate_insurance_claim($order->id, 3);
}
}
} else {
if (count($order_ids["ids"]) > 0) {
//update the ordered investigations
$order = OrderedInvestigation::find($order_ids["order_id"]);
// these are the investigations already recorded in the database
$current_investigation_ids_array = explode(",", $order->investigation_id);
$current_for_inpatient_array = explode(",", $order->for_inpatient);
$for_inpatient_array = [];
for ($i = 0; $i < count($order_ids["ids"]); $i++) {
/**
* We are now updating the order, we have to run through the
* for_inpatient column and make sure we keep them as they are
* for the current ones and the new ones assign them the
* current inpatient status
*/
if (in_array($order_ids["ids"][$i], $current_investigation_ids_array)) {
$for_inpatient_array[] = $current_for_inpatient_array[array_search($order_ids["ids"][$i], $current_investigation_ids_array)];
} else {
$for_inpatient_array[] = $inpatient;
}
}
$order->investigation_id = implode(",", $order_ids["ids"]);
$order->patient_id = $patient_id;
$order->episode_id = $episode_id;
$order->eye = implode(",", $order_ids["eye"]);
$order->urgent = !empty($order_ids["urgent"]) ? 1 : 0;
$order->urgent_ids = implode(",", $order_ids["urgent"]);
$order->inpatient = $inpatient;
$order->for_inpatient = implode(",", $for_inpatient_array);
$order->order_type = $order_type;
$order->order_comments = implode(",", $order_ids["comments"]);
$order->updated_by = $logged_in_user_id;
$order->save();
// create an insurance claim for the ordered items
if ($request->patient_insurance_status == 1 && $inpatient == 0) {
generate_insurance_claim($order->id, 3);
}
} else {
// this means that the order was previously made but was removed so delete
OrderedInvestigation::where('id', $order_ids["order_id"])->forceDelete();
}
}
}
flash("Ordered Investigation Added Successfully")->success();
/* start of talking to Business Central API for billing */
if (is_api_usage_enabled()) {
$patient_number = get_name($patient_id, "id", "number", "patients");
$patient_category_id = get_name($patient_id, "id", "category_id", "patients");
$patient_category_code = get_name($patient_category_id, "id", "code", "patient_categories");
$sales_header_url = "192.168.200.11:7048/BC240/api/hrpsolutions/lacorintegration/v2.0/salesinvoices";
$sales_invoice_lines_url = "192.168.200.11:7048/BC240/api/hrpsolutions/lacorintegration/v2.0/salesinvoicesLines";
$new_invoice_url = 'http://192.168.200.11:7048/BC240/api/hrpsolutions/lacorintegration/v2.0/salesInvoices?$expand=salesInvoicesLines';
$header_payload = [
//"data" => $request->all(),
"invoiceDate" => "2026-01-24", //Carbon::now()->format('Y-m-d'),//day that the transaction happened
"postingDate" => "2026-01-24", //Carbon::now()->format('Y-m-d'),//day that invoice is send to Navision
"invoiceDocType" => "Invoice",
"customerNumber" => $patient_number,
"billToCustomerNumber" => "50000", //$patient_category_id == 1 ? $patient_number : $patient_category_code,
"invoiceDepartment" => "SALES",
"invoiceCostcenter" => ""
];
$new_payload = [
"invoiceDocType" => "Invoice",
"customerNumber" => $patient_number,
"salesInvoicesLines" => $bc_sales_invoice_lines
];
try {
$new_sales_invoice_data = Http::timeout(120)->withBasicAuth(env('API_USERNAME'), env('API_PASSWORD'))->withHeaders([
'accept' => '*/*',
])->post($new_invoice_url, $new_payload)->json();
if ($new_sales_invoice_data && $new_sales_invoice_data['number']) {
$returned_invoice_no = $new_sales_invoice_data['number'];
flash("Invoice Number " . $returned_invoice_no . " created in Business Central")->success();
} else {
// Handle the error if the API request fails
return response()->json(['error' => 'Failed to fetch data from the sales lines API endpoint'], 500);
}
} catch (\Exception $e) {
Log::error($e->getMessage());
return response()->json([
'success' => false,
'error' => $e->getMessage()
]);
}
}
/* end of talking to the Business Central API */
/* redirect to consultation or patient_episode page depending on where the user is from */
if ($request->get('submit_button') == 'print_request') {
session()->put('investigation_ids', $investigation_ids);
session()->put('urgent_ids', $urgent_ids);
session()->put('order_comments', $order_comments_array);
return redirect('/investigations/print_request/0');
}
if ($inpatient == 1) {
return redirect('in_patient_sheet');
} else {
if (session()->has('redirect_to_consultation')) {
$url = session()->get('redirect_to_consultation');
session()->forget('redirect_to_consultation');
return redirect($url);
} elseif (session()->has('anc_visit_redirect')) {
$url = session()->get('anc_visit_redirect');
session()->forget('anc_visit_redirect');
return redirect($url);
} else {
if (session()->has('previous_action') && session()->get('previous_action') == 'anc_consultation_page') {
session()->forget('previous_action');
return redirect("ante_natal_clinic/route");
} else return redirect("/patient_episodes");
}
}
}
public function print_request($id)
{
if ($id == 0) {
if (session()->has("investigation_ids")) {
$patient_id = session()->get('patient_id');
$patient = Patient::find($patient_id);
$ordered_investigation = OrderedInvestigation::where('patient_id', '=', session()->get('patient_id'))
->where('episode_id', session()->get('episode_id'))
->where('investigation_status', '0')
->where('request_received', '0')
->where('payment_status', '0')
->where('inpatient_bill_generated', '0')
->first();
$investigation_ids_array = session()->get("investigation_ids");
$urgent_ids_array = session()->get("urgent_ids");
$order_comments_array = session()->get("order_comments");
session()->forget('investigation_ids');
session()->forget('urgent_ids');
session()->forget('order_comments');
} else {
return redirect('home');
}
} else {
$ordered_investigation = OrderedInvestigation::find($id);
$investigation_ids_array = explode(",", $ordered_investigation->investigation_id);
$urgent_ids_array = explode(",", $ordered_investigation->urgent_ids);
$order_comments_array = explode(",", $ordered_investigation->order_comments);
$patient_id = $ordered_investigation->patient_id;
$patient = Patient::find($ordered_investigation->patient_id);
}
// get unique category_ids
$category_ids_array = [];
$category_array = [];
for ($x = 0; $x < count($investigation_ids_array); $x++) {
$category_id = get_name($investigation_ids_array[$x], "id", "category", "investigations");
if (!array_key_exists($category_id, $category_array)) {
$category_ids_array[] = $category_id;
}
$category_array[$category_id][] = [
'id' => $investigation_ids_array[$x],
'comment' => $order_comments_array[$x]
];
}
$hospital_information = HospitalInformation::first();
return view('investigations::investigations.print_request', compact('ordered_investigation', 'hospital_information', 'patient', 'category_ids_array', 'category_array', 'urgent_ids_array'));
}
/**
* Gets all the incoming investigation request lab
*
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function incoming_labs(Request $request)
{
$search_text = "";
// if patient id is active, get all records regardless of date; else search by date
if (isset($request->patient_id) && $request->patient_id != 0) {
$search_text .= "Patient: " . get_full_name($request->patient_id, 'id', 'first_name', 'last_name', 'patients');
$search_text .= " (" . get_name($request->patient_id, 'id', 'number', 'patients') . ") ";
$incomings = OrderedInvestigation::where(['investigation_status' => 0])
->where('request_received', 0)
->where('order_type', 'Lab')
->where('patient_id', $request->patient_id)
->orderBy('id', 'desc')
->get(['id', 'payment_status', 'inpatient', 'episode_id', 'patient_id', 'created_at']);
$urgent_incomings = OrderedInvestigation::where(['investigation_status' => 0])
->where(['request_received' => 0])
->where('order_type', '=', 'Lab')->where('urgent_ids', '<>', '')
->where('patient_id', $request->patient_id)
->orderBy('id', 'desc')
->get();
} else {
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;
}
//by default load the last 24 hours
$incomings = OrderedInvestigation::where(['investigation_status' => 0])
->where(['request_received' => 0])
->where('order_type', '=', 'Lab')->where('urgent_ids', '=', '')
->whereBetween('created_at', [$start_date, $end_date])
->orderBy('id', 'desc')
->get();
$urgent_incomings = OrderedInvestigation::where(['investigation_status' => 0])
->where(['request_received' => 0])
->where('order_type', '=', 'Lab')->where('urgent_ids', '<>', '')
->whereBetween('created_at', [$start_date, $end_date])
->orderBy('id', 'desc')
->get();
}
$specimen = LaboratorySpecimen::orderBy('name', 'asc')->pluck('name', 'id')->toArray();
$specimen = ['' => '- select -'] + $specimen;
return view('investigations::investigations.incoming_labs', compact('incomings', 'specimen', 'search_text', 'urgent_incomings'));
}
public function incoming_imaging($imaging_type, Request $request)
{
$search_text = "";
$filters = [];
// if patient id is active, get all records regardless of date; else search by date
if (isset($request->patient_id) && $request->patient_id != 0) {
$filters[] = ['ordered_investigations.patient_id', '=', $request->patient_id];
$search_text .= "Patient: " . get_full_name($request->patient_id, 'id', 'first_name', 'last_name', 'patients');
$search_text .= " (" . get_name($request->patient_id, 'id', 'number', 'patients') . ") ";
} else {
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;
}
$filters[] = ['ordered_investigations.created_at', '>', $start_date];
$filters[] = ['ordered_investigations.created_at', '<', $end_date];
}
$incomings = OrderedInvestigation::where(['investigation_status' => 0])
->leftJoin('patients', 'ordered_investigations.patient_id', '=', 'patients.id')
->where('ordered_investigations.order_type', '=', $imaging_type)->where('urgent_ids', '=', '')
->where($filters)
->orderBy('ordered_investigations.id', 'desc')
->select('ordered_investigations.*', 'patients.number as patient_number', 'patients.category_id as patients_category_id')
->limit(200)
->get();
$urgent_incomings = OrderedInvestigation::where(['investigation_status' => 0])
->leftJoin('patients', 'ordered_investigations.patient_id', '=', 'patients.id')
->where('ordered_investigations.order_type', '=', $imaging_type)->where('urgent_ids', '<>', '')
->where($filters)
->orderBy('ordered_investigations.id', 'desc')
->select('ordered_investigations.*', 'patients.number as patient_number', 'patients.category_id as patients_category_id')
->limit(200)
->get();
$results = OrderedInvestigation::where(['investigation_status' => 1])
->leftJoin('patients', 'ordered_investigations.patient_id', '=', 'patients.id')
->leftJoin('investigation_results', 'investigation_results.order_id', '=', 'ordered_investigations.id')
->where('ordered_investigations.order_type', '=', $imaging_type)
->where($filters)
->orderBy('ordered_investigations.id', 'desc')
->select(
'ordered_investigations.*',
'investigation_results.created_at as results_created_at',
'patients.number as patient_number',
'patients.category_id as patients_category_id',
'investigation_results.id as results_id',
'investigation_results.value as results_value'
)
->limit(200)
->get();
$patient_categories = DB::table('patient_categories')->where('available', 1)->pluck('name', 'id');
return view('investigations::investigations.incoming_imaging', compact('incomings', 'search_text', 'imaging_type', 'results', 'patient_categories', 'urgent_incomings'));
}
/**
* View incoming labs request details
*
* @return \Illuminate\Http\Response
*/
public function ordered_results(Request $request)
{
$patient_id = $request->patient_id;
$episode_id = $request->episode_id;
// get all investigations that have specialised variables attached
$investigations_with_specialised_variables = DB::table('investigation_specialised_variables')
->whereNull('deleted_at')
->groupBy('investigation_id')
->pluck('investigation_id')
->toArray();
// declared variables needed for the top panes
$patient = Patient::where(['id' => $patient_id])->first();
$categories = DB::table('patient_categories')->where('available', 1)->pluck("name", "id");
$marital_statuses = DB::table('marital_statuses')->pluck("name", "id");
$known_patient_allergies = Allergy::where('patient_id', $patient_id)->orderBy('created_at', 'desc')->take(2)->get();
$known_patient_alerts = Alert::where('patient_id', $patient_id)->orderBy('created_at', 'desc')->take(2)->get();
$drug_categories_array = DB::table('drug_categories')->pluck('name', 'id');
$drug_categories = DB::table('drug_categories')->get();
// end of needed variables for the panes
$order_type = $request->order_type;
$order_id = $request->order_id;
$primary_diagnosis = 'N/A';
$other_diagnoses[0]['other'] = "N/A";
$results_count = 0;
$count = 0;
$results = [];
//check if results already exist
$investigation_results = InvestigationResults::where('patient_id', '=', $patient_id)
->where('episode_id', '=', $episode_id)
->where('result_type', '=', $order_type)
->where('order_id', '=', $order_id)
->first();
if ($investigation_results) {
// check if updated
if ($investigation_results->updated_by) {
$doctor_id = $investigation_results->updated_by;
} else {
$doctor_id = $investigation_results->created_by;
}
$investigation_ids = explode(",", $investigation_results->investigation_id);
$investigation_value = explode(",", $investigation_results->value);
$comments_array = explode(",", $investigation_results->comment);
$ordered_investigation_comments_string = "";
$ordered_investigation_comments_string = $investigation_results->order_comments;
$ordered_investigations_comments_explode = explode(",", $ordered_investigation_comments_string);
$results_comments_counter = 0;
foreach ($investigation_ids as $investigation_id) {
$inv_row = Investigation::where('id', '=', $investigation_id)->withTrashed()->first();
if ($inv_row) {
$result_document = PatientDocument::where([['patient_id', $patient_id], ['episode_id', $episode_id], ['investigation_result_id', $investigation_results->id], ['investigation_id', $investigation_id]])->first();
$results[$count]['id'] = $inv_row->id;
$results[$count]['name'] = $inv_row->name;
$results[$count]['insured'] = $inv_row->insurance_coverage;
$results[$count]['normal_range'] = ($inv_row->range_type == 1) ? get_dynamic_normal_range($inv_row->id, get_patient_age_group($patient_id), get_name($patient_id, 'id', 'gender', 'patients')) : $inv_row->normal_ranges;
$results[$count]['units'] = $inv_row->units;
$results[$count]['slug'] = $inv_row->slug;
$results[$count]['document'] = $result_document->id ?? null;
$results[$count]['title'] = $result_document->title ?? null;
$results[$count]['value'] = isset($investigation_value[$count]) ? $investigation_value[$count] : "";
$results[$count]['comment'] = isset($comments_array[$count]) ? $comments_array[$count] : "";
$results[$count]['order_comments'] = isset($ordered_investigations_comments_explode[$results_comments_counter]) ? $ordered_investigations_comments_explode[$results_comments_counter] : "";
$results[$count]['investigation_specialised_results_id'] = 0;
// check if investigation has specialised variables
if (in_array($investigation_id, $investigations_with_specialised_variables)) {
// get the specialised results and check if it is valid
if (isset($investigation_value[$count])) {
$specialised_results = InvestigationSpecialisedResult::find($investigation_value[$count]);
if ($specialised_results) {
// store the id for updating later
$results[$count]['investigation_specialised_results_id'] = $investigation_value[$count];
// for this one, the specialised_variable_ids are the keys and the comments or values are the, well, the values
$results[$count]['value'] = array_combine(explode(",", $specialised_results->specialised_variable_id), explode(",", $specialised_results->value));
$results[$count]['comment'] = array_combine(explode(",", $specialised_results->specialised_variable_id), explode(",", $specialised_results->comment));
} else {
$results[$count]['value'] = "";
$results[$count]['comment'] = "";
}
}
}
$count++;
$results_comments_counter++;
}
}
$results_count = count($results);
} else {
$ordered_results = OrderedInvestigation::where('id', '=', $order_id)->first();
//check if updated
if ($ordered_results->updated_by) {
$doctor_id = $ordered_results->updated_by;
} else {
$doctor_id = $ordered_results->created_by;
}
$investigation_ids = explode(",", $ordered_results->investigation_id);
$eyes = explode(",", $ordered_results->eye);
//ordered results with order comment
$ordered_investigation_comments_string = "";
$ordered_investigation_comments_string = $ordered_results->order_comments;
$ordered_investigations_comments_explode = explode(",", $ordered_investigation_comments_string);
$results_comments_counter = 0;
foreach ($investigation_ids as $investigation_id) {
$inv_row = Investigation::where('id', '=', $investigation_id)->first();
if ($inv_row) {
$results[$count]['id'] = $inv_row->id;
$results[$count]['name'] = $inv_row->name;
$results[$count]['insured'] = $inv_row->insurance_coverage;
$results[$count]['normal_range'] = ($inv_row->range_type == 1) ? get_dynamic_normal_range($inv_row->id, get_patient_age_group($patient_id), get_name($patient_id, 'id', 'gender', 'patients')) : $inv_row->normal_ranges;
$results[$count]['units'] = $inv_row->units;
$results[$count]['slug'] = $inv_row->slug;
$results[$count]['investigation_specialised_results_id'] = 0;
$results[$count]['value'] = '';
$results[$count]['comment'] = '';
$results[$count]['eye'] = isset($eyes[$results_comments_counter]) ? $eyes[$results_comments_counter] : '';
$results[$count]['order_comments'] = isset($ordered_investigations_comments_explode[$results_comments_counter]) ? $ordered_investigations_comments_explode[$results_comments_counter] : "";
$count++;
$results_comments_counter++;
}
}
}
//get the diagnosis
$consul = Consultation::where('patient_id', '=', $patient_id)->where('episode_id', '=', $episode_id)->first();
if ($consul) {
if ($consul->primary_diagnosis) {
$primary_diagnosis = get_name($consul->primary_diagnosis, 'id', 'name', 'diagnoses');
} else {
$primary_diagnosis = 'N/A';
}
$other_diagnoses = [];
$temp_count = 0;
if ($consul->other_diagnoses) {
$temp_array = unserialize($consul->other_diagnoses);
foreach ($temp_array as $value) {
$other_diagnoses[$temp_count]['other'] = get_name($value, 'id', 'name', 'diagnoses');
$temp_count++;
}
} else {
$other_diagnoses[$temp_count]['other'] = "N/A";
}
}
$doctor_name = get_name($doctor_id, 'id', 'first_name', 'users') . " " . get_name($doctor_id, 'id', 'last_name', 'users');
$doctor_phone = get_name($doctor_id, 'id', 'phone', 'users');
$consultation_details = Consultation::where('patient_id', '=', $patient_id)->where('episode_id', '=', $episode_id)->first();
$cardioEcho = CardioEchoResult::where('episode_id', $episode_id)->first();
$templates = CardioEchoTemplate::pluck('name', 'id')->toArray();
$templates = [0 => '- select template -'] + $templates;
return view('investigations::investigations.ordered_results', compact('cardioEcho', 'order_type', 'order_id', 'patient_id', 'episode_id', 'results', 'results_count', 'other_diagnoses', 'primary_diagnosis', 'doctor_phone', 'doctor_name', 'consultation_details', 'patient', 'categories', 'known_patient_allergies', 'known_patient_alerts', 'drug_categories_array', 'marital_statuses', 'drug_categories', 'investigations_with_specialised_variables', 'templates'));
}
/**
* Save incoming labs request details
*
* @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
*/
public function save_ordered_results(Request $request)
{
// get all investigations that have specialised variables attached
$investigations_with_specialised_variables = DB::table('investigation_specialised_variables')
->whereNull('deleted_at')
->groupBy('investigation_id')
->pluck('investigation_id')
->toArray();
$order_type = $request->order_type;
$order_id = $request->order_id;
$id = $request->id;
// Replacing the commas the incoming value and comments with full colons
$value = $request->value;
$comment = $request->comment;
$specialized_id_array = $request->specialized_id;
$specialized_value_array = $request->specialized_value;
$specialized_comment_array = $request->specialized_comment;
$investigation_specialised_results_id_array = $request->investigation_specialised_results_id;
$lab_result_document_array = $request->lab_result_document;
$patient_id = $request->patient_id;
$episode_id = $request->episode_id;
$investigation_ids = "";
$investigation_results = "";
$comments = "";
$per_investigation = "";
$per_investigation_array = [];
$investigation_ids_array = [];
$logged_in_user_id = Auth::user()->id;
for ($i = 0; $i < count($id); $i++) {
// check if this investigation is a specialized one
if (in_array($id[$i], $investigations_with_specialised_variables)) {
// get all the specialised variables available to it
$specialized_variables = DB::table('investigation_specialised_variables')->whereNull('deleted_at')->where('investigation_id', $id[$i])->orderBy('ranking', 'asc')->get();
$current_ids_array = [];
$current_values_array = [];
$current_comments_array = [];
// loop through the variables, finding out if any is coming from the form,
// because the specialized_id_array may contain multiple variables for multiple investigations
// so we need a way of picking the right ones.
foreach ($specialized_variables as $variable) {
$key = array_search($variable->id, $specialized_id_array);
if (is_integer($key)) {
$current_ids_array[] = $specialized_id_array[$key];
// clean up the values and comments for storing
$current_values_array[] = str_replace(',', ';', $specialized_value_array[$key]);
$current_comments_array[] = str_replace(',', ';', $specialized_comment_array[$key]);
}
}
// check using the investigation_specialised_results_id array if this is an update
if ($investigation_specialised_results_id_array[$i] != 0 && InvestigationSpecialisedResult::find($investigation_specialised_results_id_array[$i])) {
$investigation_specialised_results = InvestigationSpecialisedResult::find($investigation_specialised_results_id_array[$i]);
} else {
$investigation_specialised_results = new InvestigationSpecialisedResult();
}
$investigation_specialised_results->specialised_variable_id = implode(',', $current_ids_array);
$investigation_specialised_results->value = implode(',', $current_values_array);
$investigation_specialised_results->comment = implode(',', $current_comments_array);
$investigation_specialised_results->created_by = $logged_in_user_id;
$investigation_specialised_results->updated_by = $logged_in_user_id;
$investigation_specialised_results->save();
$value[$i] = $investigation_specialised_results->id;
$comment[$i] = "-";
}
if ($i == (count($id) - 1)) {
$investigation_ids .= $id[$i];
$investigation_ids_array[] = $id[$i];
$investigation_results .= str_replace(',', ';', $value[$i]);
$comments .= str_replace(',', ';', $comment[$i]);
$per_investigation .= "0";
} else {
$investigation_ids .= $id[$i] . ",";
$investigation_ids_array[] = $id[$i];
$investigation_results .= str_replace(',', ';', $value[$i]) . ",";
$comments .= str_replace(',', ';', $comment[$i]) . ",";
$per_investigation .= "0,";
}
}
//check if is inpatient
$inpatient = get_name($order_id, "id", "inpatient", "ordered_investigations");
//check if results already exist
$invest_results = InvestigationResults::where('patient_id', '=', $patient_id)
->where('episode_id', '=', $episode_id)
->where('result_type', '=', $order_type)
->where('order_id', '=', $order_id)
->first();
if ($invest_results) {
$order = InvestigationResults::find($invest_results->id);
if ($order_type != 'Lab') {
$order->value = $investigation_results;
$order->comment = $comments;
$order->all_authenticated = 1;
$order->result_type = $order_type;
$order->per_investigation = str_replace('0', '1', $per_investigation);
$order->authenticated_by = $logged_in_user_id;
$order->updated_by = $logged_in_user_id;
$order_status = 1;
} else {
$order->value = $investigation_results;
$order->comment = $comments;
$order->all_authenticated = 0;
$order->result_type = $order_type;
$order->updated_by = $logged_in_user_id;
}
try {
$order->save();
flash("Investigation results have been updated")->success();
if (isset($order_status)) {
//update ordered investigations status
$status = OrderedInvestigation::find($order_id);
$status->investigation_status = 1;
$status->save();
}
} catch (QueryException $e) {
return back()->withInput();
}
} else {
$order = new InvestigationResults;
if ($order_type != 'Lab') {
$order->value = $investigation_results;
$order->comment = $comments;
$order->all_authenticated = 1;
$order->result_type = $order_type;
$order->per_investigation = str_replace('0', '1', $per_investigation);
$order->authenticated_by = $logged_in_user_id;
$order->created_by = $logged_in_user_id;
$order->investigation_id = $investigation_ids;
$order->patient_id = $patient_id;
$order->episode_id = $episode_id;
$order->order_id = $order_id;
$order->inpatient = $inpatient;
$order_status = 1;
} else {
$order->investigation_id = implode(",", $investigation_ids_array); //$investigation_ids;
$order->value = $investigation_results;
$order->comment = $comments;
$order->patient_id = $patient_id;
$order->episode_id = $episode_id;
$order->order_id = $order_id;
$order->inpatient = $inpatient;
$order->per_investigation = $per_investigation;
$order->all_authenticated = 0;
$order->result_type = $order_type;
$order->created_by = $logged_in_user_id;
}
try {
$order->save();
flash("Investigation results have been submitted")->success();
if (isset($order_status)) {
//update ordered investigations status
$status = OrderedInvestigation::find($order_id);
$status->investigation_status = 1;
$status->save();
}
} catch (QueryException $e) {
return back()->withInput();
}
}
if (!empty($lab_result_document_array[0])) {
foreach ($request->file('lab_result_document') as $key => $lab_result_document) {
$patient_document = PatientDocument::where([['patient_id', $patient_id], ['episode_id', $episode_id], ['investigation_id', $id[$key]]])->first();
if (empty($patient_document)) {
$patient_document = new PatientDocument;
$patient_document->patient_id = $request->patient_id;
$patient_document->episode_id = $request->episode_id;
$patient_document->investigation_id = $id[$key];
$patient_document->investigation_result_id = $order->id;
$patient_document->created_by = Auth::id();
} else $patient_document->updated_by = Auth::id();
$patient_document->title = 'Lab Result document_' . get_name($id[$key], 'id', 'name', 'investigations');
$patient_document->description = 'Laboratory Result document of the ' . get_name($id[$key], 'id', 'name', 'investigations') . ' investigation.';
if ($lab_result_document->isValid()) {
$file = $lab_result_document;
$store = public_path() . '/uploads/patient-documents/';
$file_name = $file->getClientOriginalName();
$file->move($store, $file_name);
$patient_document->path = public_path() . '/uploads/patient-documents/' . $file_name;
}
$patient_document->date_taken = Carbon::now()->toDateString();
$patient_document->save();
}
}
// i took the road less taken, and that has made all the difference
if ($order_type == 'Lab') {
return redirect("/investigations/view_lab_results_details/" . $order_id);
} elseif ($order_type == 'Imaging') {
return redirect("/investigations/incoming_imaging/" . $order_type);
} elseif ($order_type == 'Ultrasound') {
return redirect("/investigations/incoming_imaging/" . $order_type);
} elseif ($order_type == 'Cardio') {
return redirect("/investigations/incoming_imaging/" . $order_type);
}
}
/**
* Authenticate lab investigations.
*
* @param Request $request
* @return \Illuminate\Contracts\View\Factory|\Illuminate\Foundation\Application|\Illuminate\Http\Response|\Illuminate\View\View
*/
public function authenticate_labs(Request $request)
{
$search_text = "";
$filters = [];
// if patient id is active, get all records regardless of date; else search by date
if (isset($request->patient_id) && $request->patient_id != 0) {
$filters[] = ['investigation_results.patient_id', '=', $request->patient_id];
$search_text .= "Patient: " . get_full_name($request->patient_id, 'id', 'first_name', 'last_name', 'patients');
$search_text .= " (" . get_name($request->patient_id, 'id', 'number', 'patients') . ") ";
} else {
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;
}
$filters[] = ['investigation_results.created_at', '>', $start_date];
$filters[] = ['investigation_results.created_at', '<', $end_date];
}
$invests = DB::table('investigation_results')
->join('ordered_investigations', 'investigation_results.order_id', '=', 'ordered_investigations.id')
->select('investigation_results.investigation_id', 'investigation_results.value', 'investigation_results.patient_id', 'investigation_results.created_by', 'investigation_results.created_at', 'investigation_results.order_id', 'investigation_results.per_investigation', 'ordered_investigations.id', 'ordered_investigations.investigation_status', 'ordered_investigations.urgent', 'ordered_investigations.urgent_ids', 'investigation_results.id as result_id')
->where($filters)
->where('investigation_results.all_authenticated', '=', 0)
->where('investigation_results.result_type', '=', 'Lab')
->orderBy('investigation_results.created_at', 'desc')
->get()
->toArray();
$orders = [];
$orders_count = 0;
$data = [];
$data_count = 0;
foreach ($invests as $invest) {
$orders[$orders_count]['order_id'] = $invest->order_id;
$orders[$orders_count]['date'] = streamline_date_time_short($invest->created_at);
$orders[$orders_count]['number'] = get_name($invest->patient_id, 'id', 'number', 'patients');
$orders[$orders_count]['id'] = $invest->patient_id;
$orders[$orders_count]['urgent_ids'] = $invest->urgent_ids;
$investigations = explode(",", $invest->investigation_id);
$values = explode(",", $invest->value);
$per_investigation = explode(",", $invest->per_investigation);
foreach ($investigations as $investigation) {
$result_document = PatientDocument::where([['patient_id', $invest->patient_id], ['investigation_result_id', $invest->result_id], ['investigation_id', $investigation]])->first();
$data[$data_count]['investigation_id'] = $investigation;
$data[$data_count]['name'] = get_name($investigation, 'id', 'name', 'investigations');
$data[$data_count]['value'] = $values[$data_count] ?? 'N/A';
$data[$data_count]['document'] = $result_document->id ?? null;
$data[$data_count]['title'] = $result_document->title ?? null;
$data[$data_count]['per_investigation'] = $per_investigation[$data_count] ?? 'N/A';
$data_count++;
}
$orders[$orders_count]['values'] = $data;
//reset data array
$data = [];
$data_count = 0;
$orders_count++;
}
return view('investigations::investigations.authenticate_labs', compact('orders', 'search_text'));
}
/**
* Authenticate investigations.
*
* @return \Illuminate\Http\Response
*/
public function authenticate_investigations(Request $request)
{
// check if user with details exists
$user = User::where('username', '=', $request->username)->first();
if (!$user) {
flash("Username does not exist in system")->error();
return back()->withInput();
}
if (!password_verify($request->password, $user->password)) {
flash("Password does not match username")->error();
return back()->withInput();
}
if ($user->can('investigations-authenticate')) {
$order_ids = $request->order_id;
$investigation_id = $request->investigation_id;
$count_orders = $request->count;
//loop through all the ordered investigations
for ($x = 0; $x < count($order_ids); $x++) {
//fill initial array with 0 values
$all_inv = [];
for ($y = 0; $y < $count_orders[$x]; $y++) {
$all_inv[] = 0;
}
for ($i = 0; $i < count($investigation_id); $i++) {
$inv = explode("/", $investigation_id[$i]);
if ($inv[0] == $order_ids[$x]) {
$all_inv[$inv[1]] = 1;
}
}
$per_inv = implode(",", $all_inv);
//prepare save data
$result = InvestigationResults::where('order_id', '=', $order_ids[$x])->first();
$logged_in_user_id = $user->id;
if (array_unique($all_inv) === array(1)) {
//all results have been authenticated
$result->all_authenticated = 1;
$result->per_investigation = $per_inv;
$result->authenticated_by = $logged_in_user_id;
//update ordered status
$order = OrderedInvestigation::find($order_ids[$x]);
if ($order) {
$order->investigation_status = 1;
$order->updated_by = $logged_in_user_id;
$order->save();
}
} else {
//not all results authenticated
$result->all_authenticated = 0;
$result->per_investigation = $per_inv;
$result->authenticated_by = $logged_in_user_id;
//update ordered status
$order = OrderedInvestigation::find($order_ids[$x]);
if ($order) {
$order->investigation_status = 0;
$order->updated_by = $logged_in_user_id;
$order->save();
}
}
//save result
$result->save();
}
flash("Lab results have been authenticated")->success();
return redirect("/investigations/authenticate_labs");
} else {
flash("You are not allowed to authenticate investigations")->error();
return back()->withInput();
}
}
/**
* View a patient's investigation results.
*
*/
public function view_patient_investigation($result_id)
{
$result = InvestigationResults::find($result_id);
if ($result) {
$patient_id = $result->patient_id;
$episode_id = $result->episode_id;
$result_type = $result->result_type;
$patient = Patient::where(['id' => $patient_id])->first();
$inv = [];
$inv['date'] = streamline_date(get_name($result->episode_id, 'id', 'created_at', 'patient_episodes'));
$investigations = explode(",", $result->investigation_id);
$values = explode(",", $result->value);
$comments = explode(",", $result->comment);
$data = [];
$count = 0;
foreach ($investigations as $investigation) {
$investigation_details = Investigation::find($investigation);
if ($investigation_details) {
$data[$count]['id'] = $investigation;
$data[$count]['name'] = $investigation_details->name;
$data[$count]['range'] = ($investigation_details->range_type == 1) ? get_dynamic_normal_range($investigation, get_patient_age_group($patient_id), get_name($patient_id, 'id', 'gender', 'patients')) : $investigation_details->normal_ranges;
$data[$count]['slug'] = $investigation_details->slug;
$data[$count]['result'] = $values[$count];
$data[$count]['comment'] = $comments[$count];
$data[$count]['type'] = $investigation_details->type;
$count++;
}
}
$inv['data'] = $data;
$order_id = $result->order_id;
return view('investigations::investigations.view_patient_investigation', compact('inv', 'patient', 'episode_id', 'result_type', 'result_id', 'order_id'));
} else {
flash("Unable to find investigation results. Please try again")->error();
return redirect('/home');
}
}
/**
* Update all the resources in storage.
*
* @return \Illuminate\Contracts\View\Factory|\Illuminate\Foundation\Application|\Illuminate\View\View
*/
public function alter_results(Request $request)
{
$search_text = "";
$filters = [];
// if patient id is active, get all records regardless of date; else search by date
if (isset($request->patient_id) && $request->patient_id != 0) {
$filters[] = ['patient_id', '=', $request->patient_id];
$search_text .= "Patient: " . get_full_name($request->patient_id, 'id', 'first_name', 'last_name', 'patients');
$search_text .= " (" . get_name($request->patient_id, 'id', 'number', 'patients') . ") ";
} else {
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;
}
$filters[] = ['created_at', '>', $start_date];
$filters[] = ['created_at', '<', $end_date];
}
$results = InvestigationResults::where('result_type', 'Lab')
->where('status', 0)
->where('all_authenticated', 1)
->where($filters)
->orderBy('id', 'desc')
->get();
return view('investigations::investigations.alter_results', compact('results', 'search_text'));
}
/**
* Update all the resources in storage.
*
* @return \Illuminate\Contracts\View\Factory|\Illuminate\Foundation\Application|\Illuminate\View\View
*/
public function alter_results_others(Request $request)
{
$search_text = "";
$filters = [];
// if patient id is active, get all records regardless of date; else search by date
if (isset($request->patient_id) && $request->patient_id != 0) {
$filters[] = ['ordered_investigations.patient_id', '=', $request->patient_id];
$search_text .= "Patient: " . get_full_name($request->patient_id, 'id', 'first_name', 'last_name', 'patients');
$search_text .= " (" . get_name($request->patient_id, 'id', 'number', 'patients') . ") ";
} else {
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;
}
$filters[] = ['ordered_investigations.created_at', '>', $start_date];
$filters[] = ['ordered_investigations.created_at', '<', $end_date];
}
$results = InvestigationResults::leftJoin('patients', 'investigation_results.patient_id', '=', 'patients.id')
->leftJoin('ordered_investigations', 'ordered_investigations.id', '=', 'investigation_results.order_id')
->whereIn('investigation_results.result_type', ['Imaging', 'Ultrasound', 'Cardio', 'Ultrasound_Obstetric'])
->where($filters)
->orderBy('investigation_results.id', 'desc')
->select(
'investigation_results.*',
'ordered_investigations.created_at as requested_at',
'patients.number as patient_number',
'patients.category_id as patients_category_id',
'ordered_investigations.inpatient',
'ordered_investigations.payment_status'
)
->limit(250)
->get();
$patient_categories = DB::table('patient_categories')->where('available', 1)->pluck('name', 'id');
return view('investigations::investigations.alter_results_others', compact('results', 'search_text', 'patient_categories'));
}
/**
* Update all the resources in storage.
*
* @return \Illuminate\Contracts\View\Factory|\Illuminate\Foundation\Application|\Illuminate\View\View
*/
public function alter_ordered_results(Request $request)
{
$patient = Patient::find($request->patient_id);
$id = $request->id;
$invs = [];
$count = 0;
$result_type = "";
$results = InvestigationResults::where('id', '=', $id)->get();
// get all investigations that have specialised variables attached
$investigations_with_specialised_variables = DB::table('investigation_specialised_variables')
->whereNull('deleted_at')
->groupBy('investigation_id')
->pluck('investigation_id')
->toArray();
foreach ($results as $result) {
$investigations = explode(",", $result->investigation_id);
$values = explode(",", $result->value);
$comments = explode(",", $result->comment);
$result_type = $result->result_type;
$episode_id = $result->episode_id;
foreach ($investigations as $investigation) {
$result_document = PatientDocument::where([['patient_id', $request->patient_id], ['episode_id', $episode_id], ['investigation_id', $investigation]])->first();
$invs[$count]['count'] = $count + 1;
$invs[$count]['id'] = $investigation;
$invs[$count]['name'] = get_name($investigation, 'id', 'name', 'investigations');
$invs[$count]['range'] = (get_name($investigation, 'id', 'range_type', 'investigations') == 1) ? get_dynamic_normal_range($investigation, get_patient_age_group($request->patient_id), get_name($request->patient_id, 'id', 'gender', 'patients')) : get_name($investigation, 'id', 'normal_ranges', 'investigations');
$invs[$count]['units'] = get_name($investigation, 'id', 'units', 'investigations');
$invs[$count]['slug'] = get_name($investigation, 'id', 'slug', 'investigations');
$invs[$count]['episode_id'] = $episode_id;
$invs[$count]['result'] = $values[$count];
$invs[$count]['comment'] = $comments[$count];
$invs[$count]['investigation_specialised_results_id'] = 0;
$invs[$count]['document'] = $result_document->id ?? null;
$invs[$count]['title'] = $result_document->title ?? null;
// check if investigation has specialised variables
if (in_array($investigation, $investigations_with_specialised_variables)) {
// get the specialised results and check if it is valid
$specialised_results = InvestigationSpecialisedResult::find($values[$count]);
if ($specialised_results) {
// store the id for updating later
$invs[$count]['investigation_specialised_results_id'] = $values[$count];
// for this one, the specialised_variable_ids are the keys and the comments or values are the, well, the values
$invs[$count]['value'] = array_combine(explode(",", $specialised_results->specialised_variable_id), explode(",", $specialised_results->value));
$invs[$count]['comment'] = array_combine(explode(",", $specialised_results->specialised_variable_id), explode(",", $specialised_results->comment));
} else {
$invs[$count]['value'] = "";
$invs[$count]['comment'] = "";
}
}
$count++;
}
}
return view('investigations::investigations.alter_ordered_results', compact('invs', 'id', 'investigations_with_specialised_variables', 'patient', 'result_type'));
}
/**
* Update all the resources in storage.
*
* @return \Illuminate\Foundation\Application|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
*/
public function save_altered_results(Request $request)
{
// get all investigations that have specialised variables attached
$investigations_with_specialised_variables = DB::table('investigation_specialised_variables')
->whereNull('deleted_at')
->groupBy('investigation_id')
->pluck('investigation_id')
->toArray();
// Replacing the commas the incoming value and comments with full colons
$id = $request->order_id;
$id_array = $request->id;
$value = $request->value;
$comment = $request->comment;
$specialized_id_array = $request->specialized_id;
$specialized_value_array = $request->specialized_value;
$specialized_comment_array = $request->specialized_comment;
$investigation_specialised_results_id_array = $request->investigation_specialised_results_id;
$investigation_results = "";
$comments = "";
$logged_in_user_id = Auth::user()->id;
for ($i = 0; $i < count($id_array); $i++) {
// check if this investigation is a specialized one
if (in_array($id_array[$i], $investigations_with_specialised_variables)) {
// get all the specialised variables available to it
$specialized_variables = DB::table('investigation_specialised_variables')->whereNull('deleted_at')->where('investigation_id', $id_array[$i])->get();
$current_ids_array = [];
$current_values_array = [];
$current_comments_array = [];
// loop through the variables, finding out if any is coming from the form,
// because the specialized_id_array may contain multiple variables for multiple investigations
// so we need a way of picking the right ones.
foreach ($specialized_variables as $variable) {
$key = array_search($variable->id, $specialized_id_array);
if (is_integer($key)) {
$current_ids_array[] = $specialized_id_array[$key];
// clean up the values and comments for storing
$current_values_array[] = str_replace(',', ';', $specialized_value_array[$key]);
$current_comments_array[] = str_replace(',', ';', $specialized_comment_array[$key]);
}
}
$investigation_specialised_results = InvestigationSpecialisedResult::find($investigation_specialised_results_id_array[$i]);
$investigation_specialised_results->specialised_variable_id = implode(',', $current_ids_array);
$investigation_specialised_results->value = implode(',', $current_values_array);
$investigation_specialised_results->comment = implode(',', $current_comments_array);
$investigation_specialised_results->created_by = $logged_in_user_id;
$investigation_specialised_results->updated_by = $logged_in_user_id;
$investigation_specialised_results->save();
$value[$i] = $investigation_specialised_results->id;
$comment[$i] = "-";
}
if ($i == (count($id_array) - 1)) {
$investigation_results .= str_replace(',', ';', $value[$i]);
$comments .= str_replace(',', ';', $comment[$i]);
} else {
$investigation_results .= str_replace(',', ';', $value[$i]) . ",";
$comments .= str_replace(',', ';', $comment[$i]) . ",";
}
}
if (!empty($request->lab_result_document[0])) {
foreach ($request->file('lab_result_document') as $key => $lab_result_document) {
$patient_document = PatientDocument::where([['patient_id', $request->patient_id], ['episode_id', $request->episode_ids[$key]], ['investigation_result_id', $request->order_id], ['investigation_id', $request->id[$key]]])->first();
if (empty($patient_document)) {
$patient_document = new PatientDocument;
$patient_document->patient_id = $request->patient_id;
$patient_document->episode_id = $request->episode_ids[$key];
$patient_document->investigation_id = $request->id[$key];
$patient_document->investigation_result_id = $request->order_id;
$patient_document->created_by = Auth::id();
} else $patient_document->updated_by = Auth::id();
$patient_document->title = 'Lab Result document_' . get_name($request->id[$key], 'id', 'name', 'investigations');
$patient_document->description = 'Laboratory Result document of the ' . get_name($request->id[$key], 'id', 'name', 'investigations') . ' investigation.';
if ($lab_result_document->isValid()) {
$file = $lab_result_document;
$store = public_path() . '/uploads/patient-documents/';
$file_name = $file->getClientOriginalName();
$file->move($store, $file_name);
$patient_document->path = public_path() . '/uploads/patient-documents/' . $file_name;
}
$patient_document->date_taken = Carbon::now()->toDateString();
$patient_document->save();
}
}
$result = InvestigationResults::find($id);
$result->value = $investigation_results;
$result->comment = $comments;
$result->updated_by = $logged_in_user_id;
try {
$result->save();
flash("Investigation results have been updated")->success();
} catch (QueryException $e) {
return back()->withInput();
}
if ($result->result_type == "Lab") {
return redirect('/investigations/alter_results');
} else {
return redirect('/investigations/alter_results_others');
}
}
/**
* Update all the resources in storage.
*
*/
public function historical_labs(Request $request)
{
$search_text = "";
$filters = [];
if (isset($request->patient_id) && $request->patient_id != 0) {
$filters[] = ['investigation_results.patient_id', '=', $request->patient_id];
$search_text .= "Patient: " . get_full_name($request->patient_id, 'id', 'first_name', 'last_name', 'patients');
$search_text .= " (" . get_name($request->patient_id, 'id', 'number', 'patients') . ") ";
}
$patients = InvestigationResults::leftJoin('patients', 'investigation_results.patient_id', '=', 'patients.id')
->where('investigation_results.result_type', '=', 'Lab')
->where('investigation_results.all_authenticated', '=', 1)
->where($filters)
->limit(250)
->distinct(['investigation_results.patient_id'])
->orderBy('investigation_results.id', 'desc')
->get(['investigation_results.patient_id', 'patients.number', 'patients.gender', 'patients.phone']);
return view('investigations::investigations.historical_labs', compact('patients', 'search_text'));
}
/**
* Update all the resources in storage.
*
*/
public function view_historical_results_labs($patient_id)
{
//prepare the arrays
$dates = array();
$invs_array = array();
$values = array();
$patients = InvestigationResults::where('patient_id', '=', $patient_id)
->where('result_type', '=', 'Lab')
->where('all_authenticated', '=', 1)
->orderBy('created_at', 'desc')
->limit(7)
->get();
foreach ($patients as $patient) {
$dates[] = streamline_date($patient->created_at);
$investigations = explode(",", $patient->investigation_id);
foreach ($investigations as $investigation) {
if (!in_array($investigation, $invs_array)) {
$invs_array[] = $investigation;
}
}
}
//loop through the investigation ids to add values
for ($i = 0; $i < count($invs_array); $i++) {
//count for the returnInvestigations
$count = 0;
foreach ($patients as $patient) {
//get values from csv to array
$investigations = explode(",", $patient->investigation_id);
$return_values = explode(",", $patient->value);
$comments = explode(",", $patient->comment);
//check if current investigation is in array
if (in_array($invs_array[$i], $investigations)) {
//get key of that investigation which exists
$key = array_search($invs_array[$i], $investigations);
if ($patient->result_type == 'Ultrasound_Obstetric') {
//assign real$return_values value
$values[$i][$count] = array($return_values[$key], $patient->order_id, $patient_id, $patient->episode_id);
} elseif (get_name($invs_array[$i], 'id', 'type', 'investigations') == 1) {
// assign real value representing id
$values[$i][$count] = $return_values[$key] ?? "";
} else {
//assign real value
$values[$i][$count] = ($return_values[$key] ?? "") . " - (" . ($comments[$key] ?? "") . ")";
}
} else {
//assign N/A
$values[$i][$count] = "";
}
$count++;
}
}
$patient = Patient::find($patient_id);
return view('investigations::investigations.view_historical_results_labs', compact(
'patient_id',
'patient',
'dates',
'invs_array',
'values'
));
}
public function imaging_historical_results(Request $request)
{
$search_text = "";
$filters = [];
if (isset($request->patient_id) && $request->patient_id != 0) {
$filters[] = ['investigation_results.patient_id', '=', $request->patient_id];
$search_text .= "Patient: " . get_full_name($request->patient_id, 'id', 'first_name', 'last_name', 'patients');
$search_text .= " (" . get_name($request->patient_id, 'id', 'number', 'patients') . ") ";
}
$patients = InvestigationResults::leftJoin('patients', 'investigation_results.patient_id', '=', 'patients.id')
->whereIn('investigation_results.result_type', ['Imaging', 'Ultrasound', 'Ultrasound_Obstetric'])
->where('investigation_results.all_authenticated', '=', 1)
->where($filters)
->limit(250)
->distinct()
->get(['investigation_results.patient_id', 'patients.number', 'patients.gender', 'patients.phone']);
return view('investigations::investigations.imaging_historical_results', compact('patients', 'search_text'));
}
public function investigations_review_ultrasound_obstetric()
{
$patient_id = session()->get('patient_id');
$episode_id = session()->get('episode_id');
$patient = Patient::find($patient_id);
$categories = DB::table('investigation_categories')->where('super_category_id', 4)->whereNull('deleted_at')->pluck('id')->toArray();
$investigations = DB::table('investigations')->whereNull('deleted_at')->whereIn('category', $categories)
->pluck('name', 'id')->toArray();
$investigations = ['' => '- select -'] + $investigations;
$anc_details = DB::table('ante_natal_clinic_registrations')->where('episode_id', $episode_id)->first();
return view('investigations::investigations.investigations_review_ultrasound_obstetric', compact('patient_id', 'episode_id', 'patient', 'investigations', 'anc_details'));
}
public function submit_ordered_obstetric_investigations(Request $request)
{
$patient_id = session()->get('patient_id');
$episode_id = session()->get('episode_id');
//create new order investigation
$order = new OrderedInvestigation;
$order->investigation_id = $request->investigations_id;
$order->patient_id = $patient_id;
$order->episode_id = $episode_id;
$order->urgent = 0;
$order->urgent_ids = "";
$order->inpatient = 0;
$order->for_inpatient = "";
$order->order_type = 'Ultrasound_Obstetric';
$order->comment = $request->comment;
$order->eye = "";
$order->order_comments = $request->comment;
$order->created_by = Auth::user()->id;
try {
$order->save();
flash("Ordered Investigation Added Successfully")->success();
} catch (QueryException $e) {
flash("An error occurred. Please try again or contact Stre@mline support")->error();
}
return redirect('ante_natal_clinic_follow_up/create');
}
public function ultrasound_obstetric_report(Request $request)
{
$order_id = $request->order_id;
$patient_id = $request->patient_id;
$episode_id = $request->episode_id;
$order_type = $request->order_type;
$patient = Patient::find($patient_id);
$categories = PatientCategory::pluck("name", "id");
$marital_statuses = MaritalStatus::pluck("name", "id");
$occupations = Occupation::pluck('name', 'id');
$drug_categories = DrugCategory::orderBy('name', 'asc')->get();
$documents = PatientDocument::where('patient_id', $patient_id)->orderBy('created_at', 'desc')->take(2)->get();
$known_patient_allergies = Allergy::where('patient_id', $patient_id)->orderBy('created_at', 'desc')->take(2)->get();
$drug_categories_array = DrugCategory::pluck('name', 'id');
return view('investigations::investigations.ultrasound_obstetric_report', compact('patient_id', 'episode_id', 'order_id', 'order_type', 'patient', 'categories', 'known_patient_allergies', 'drug_categories', 'drug_categories_array', 'documents', 'marital_statuses', 'occupations'));
}
public function submit_ultrasound_obstetric_report(Request $request)
{
// man the tanks
$crown_rump = $request->crown_rump1 . "," . $request->crown_rump2 . "," . $request->crown_rump3;
$bi_parietal_diameter = $request->bi_parietal_diameter1 . "," . $request->bi_parietal_diameter2 . "," . $request->bi_parietal_diameter3;
$head_circumference = $request->head_circumference1 . "," . $request->head_circumference2 . "," . $request->head_circumference3;
$abdominal_circumference = $request->abdominal_circumference1 . "," . $request->abdominal_circumference2 . "," . $request->abdominal_circumference3;
$femur_length = $request->femur_length1 . "," . $request->femur_length2 . "," . $request->femur_length3;
$estimated_foetal_weight = $request->estimated_foetal_weight1 . "," . $request->estimated_foetal_weight2 . "," . $request->estimated_foetal_weight3;
$average_gestational_age = $request->average_gestational_age1 . "," . $request->average_gestational_age2 . "," . $request->average_gestational_age3;
$expected_delivery_date = $request->expected_delivery_date1 . "," . $request->expected_delivery_date2 . "," . $request->expected_delivery_date3;
$presentation = $request->presentation1 . "," . $request->presentation2 . "," . $request->presentation3;
$placental_site = $request->placental_site1 . "," . $request->placental_site2 . "," . $request->placental_site3;
$liquor_volume = $request->liquor_volume1 . "," . $request->liquor_volume2 . "," . $request->liquor_volume3;
$cord_artery_doppler = $request->cord_artery_doppler1 . "," . $request->cord_artery_doppler2 . "," . $request->cord_artery_doppler3;
$comments = $request->comments1 . ",,," . $request->comments2 . ",,," . $request->comments3;
$logged_in_user_id = Auth::user()->id;
// check if this is an alter or new record
if (!empty($request->alter_obstetric)) {
// update report
$report = ObstetricUltrasoundReports::find($request->alter_obstetric);
$report->order_id = $request->order_id;
$report->scan_date = Carbon::createFromFormat('d-m-Y', $request->scan_date)->format('Y-m-d');
$report->sonographer = $request->sonographer;
$report->no_of_foetus = $request->no_of_foetus;
$report->crown_rump = $crown_rump;
$report->bi_parietal_diameter = $bi_parietal_diameter;
$report->head_circumference = $head_circumference;
$report->abdominal_circumference = $abdominal_circumference;
$report->femur_length = $femur_length;
$report->average_gestational_age = $average_gestational_age;
$report->estimated_foetal_weight = $estimated_foetal_weight;
$report->expected_delivery_date = $expected_delivery_date;
$report->presentation = $presentation;
$report->placental_site = $placental_site;
$report->liquor_volume = $liquor_volume;
$report->cord_artery_doppler = $cord_artery_doppler;
$report->comments = $comments;
$report->updated_by = $logged_in_user_id;
$report->save();
flash("Investigation Results Altered Successfully")->success();
return redirect("/investigations/alter_results_others");
} else {
// create new report
$report = new ObstetricUltrasoundReports;
$report->order_id = $request->order_id;
$report->scan_date = Carbon::createFromFormat('d-m-Y', $request->scan_date)->format('Y-m-d');
$report->sonographer = $request->sonographer;
$report->no_of_foetus = $request->no_of_foetus;
$report->crown_rump = $crown_rump;
$report->bi_parietal_diameter = $bi_parietal_diameter;
$report->head_circumference = $head_circumference;
$report->abdominal_circumference = $abdominal_circumference;
$report->femur_length = $femur_length;
$report->average_gestational_age = $average_gestational_age;
$report->estimated_foetal_weight = $estimated_foetal_weight;
$report->expected_delivery_date = $expected_delivery_date;
$report->presentation = $presentation;
$report->placental_site = $placental_site;
$report->liquor_volume = $liquor_volume;
$report->cord_artery_doppler = $cord_artery_doppler;
$report->comments = $comments;
$report->created_by = $logged_in_user_id;
$report->save();
// update investigation status
$status = OrderedInvestigation::find($request->order_id);
$status->investigation_status = 1;
$status->save();
// create new record in the investigation results
$order = new InvestigationResults;
$order->investigation_id = $status->investigation_id;
$order->value = $report->id;
$order->comment = $comments;
$order->all_authenticated = 1;
$order->result_type = 'Ultrasound_Obstetric';
$order->per_investigation = 1;
$order->authenticated_by = $logged_in_user_id;
$order->created_by = $logged_in_user_id;
$order->patient_id = $request->patient_id;
$order->episode_id = $request->episode_id;
$order->order_id = $request->order_id;
$order->inpatient = 0;
$order->save();
flash("Investigation Results Added Successfully")->success();
return redirect("/investigations/incoming_imaging/Ultrasound_Obstetric");
}
}
public function view_patient_investigation_obstetric($obstetric_result_id)
{
$report = ObstetricUltrasoundReports::where(['id' => $obstetric_result_id])->first();
// for old kisiizi records which use the order_id
if (!$report) {
$report = ObstetricUltrasoundReports::where(['order_id' => $obstetric_result_id])->first();
}
$invs_order = OrderedInvestigation::find($report->order_id);
// dd($report);
if ($invs_order) {
$patient_id = $invs_order->patient_id;
$episode_id = $invs_order->episode_id;
$patient = Patient::find($patient_id);
$anc_details = DB::table('ante_natal_clinic_registrations')->where('episode_id', $episode_id)->first();
return view('investigations::investigations.view_patient_investigation_obstetric', compact('episode_id', 'patient', 'report', 'obstetric_result_id', 'anc_details', 'invs_order'));
} else {
flash("Unable to find obstetric results")->error();
return redirect('/home');
}
}
public function alter_ordered_results_obstetric(Request $request)
{
$obstetric_ultrasound_report_id = $request->obstetric_ultrasound_report_id;
$patient_id = $request->patient_id;
$episode_id = $request->episode_id;
$order_id = $request->order_id;
$report = ObstetricUltrasoundReports::where(['id' => $obstetric_ultrasound_report_id])->first();
// for old kisiizi records which use the order_id
if (!$report) {
$report = ObstetricUltrasoundReports::where(['order_id' => $obstetric_ultrasound_report_id])->first();
}
$patient = Patient::find($patient_id);
$categories = PatientCategory::pluck("name", "id");
$marital_statuses = MaritalStatus::pluck("name", "id");
$occupations = Occupation::pluck('name', 'id');
$drug_categories = DrugCategory::orderBy('name', 'asc')->get();
$documents = PatientDocument::where('patient_id', $patient_id)->orderBy('created_at', 'desc')->take(2)->get();
$known_patient_allergies = Allergy::where('patient_id', $patient_id)->orderBy('created_at', 'desc')->take(2)->get();
$drug_categories_array = DrugCategory::pluck('name', 'id');
return view('investigations::investigations.alter_ordered_results_obstetric', compact('patient_id', 'episode_id', 'order_id', 'patient', 'categories', 'known_patient_allergies', 'drug_categories', 'drug_categories_array', 'documents', 'marital_statuses', 'occupations', 'report', 'obstetric_ultrasound_report_id'));
}
public function view_historical_results_imaging($patient_id)
{
//prepare the arrays
$dates = array();
$invs_array = array();
$values = array();
$patients = InvestigationResults::where('patient_id', '=', $patient_id)
->whereIn('investigation_results.result_type', ['Imaging', 'Ultrasound', 'Ultrasound_Obstetric'])
->limit(7)
->get();
foreach ($patients as $patient) {
$dates[] = streamline_date($patient->created_at);
$investigations = explode(",", $patient->investigation_id);
foreach ($investigations as $investigation) {
if (!in_array($investigation, $invs_array)) {
$invs_array[] = $investigation;
}
}
}
//loop through the investigation ids to add values
for ($i = 0; $i < count($invs_array); $i++) {
//count for the returnInvestigations
$count = 0;
foreach ($patients as $patient) {
//get values from csv to array
$investigations = explode(",", $patient->investigation_id);
$return_values = explode(",", $patient->value);
//check if current investigation is in array
if (in_array($invs_array[$i], $investigations)) {
//get key of that investigation which exists
$key = array_search($invs_array[$i], $investigations);
if ($patient->result_type == 'Ultrasound_Obstetric') {
//assign real value
$values[$i][$count] = array($return_values[$key], $patient->order_id, $patient_id, $patient->episode_id);
} else {
//assign real value
$values[$i][$count] = $return_values[$key];
}
} else {
//assign N/A
$values[$i][$count] = "N/A";
}
$count++;
}
}
$patient = Patient::find($patient_id);
return view('investigations::investigations.view_historical_results_imaging', compact('patient_id', 'patient', 'dates', 'invs_array', 'values'));
}
public function get_receive_request_details(Request $request)
{
$order = DB::table('ordered_investigations')
->where('id', $request->id)
->select('id', 'investigation_id', 'patient_id', 'episode_id', 'inpatient', 'created_at', 'created_by')
->first();
$html_text = "<table class='table table-bordered table-striped'>";
$investigations = explode(",", $order->investigation_id);
$html_text .= "<tr>";
$html_text .= "<th style='color: black'> Test Name </th>";
$html_text .= "<th style='color: black'> Date Requested </th>";
$html_text .= "</tr>";
foreach ($investigations as $investigation) {
$html_text .= "<tr>";
$html_text .= "<td>";
$html_text .= get_name($investigation, 'id', 'name', 'investigations');
$html_text .= "</td>";
$html_text .= "<td>";
$html_text .= streamline_date($order->created_at);
$html_text .= "</td>";
$html_text .= "</tr>";
}
$html_text .= "</table>";
$patient = Patient::withTrashed()->find($order->patient_id);
$patient_age = get_patients_age($patient->date_of_birth);
$patient_gender = $patient->gender == 1 ? "Male" : "Female";
if (is_lab_number_editing_enabled()) {
$lab_number = (sprintf("%05u", $order->id) . '/' . Carbon::parse($order->created_at)->month . '/' . Carbon::parse($order->created_at)->format('y') . '/' .
$patient->first_name[0] . $patient->last_name[0]);
} else {
$lab_number = $order->id;
}
return json_encode([
"patient_number" => get_name($order->patient_id, 'id', 'number', 'patients'),
"patient_name" => get_full_name($order->patient_id, 'id', 'first_name', 'last_name', 'patients'),
"source" => ($order->inpatient == 1) ? get_ward_name($order->patient_id, $order->episode_id) : 'OPD',
"lab_number" => $lab_number,
"order_id" => $order->id,
"requested_by" => get_full_name($order->created_by, 'id', 'first_name', 'last_name', 'users'),
"patient_age" => $patient_age,
"telephone_number" => $patient->phone,
"patient_gender" => $patient_gender,
"html" => $html_text
]);
}
public function save_receive_request_details(Request $request)
{
$id = $request->id;
$specimen_array = $request->specimen;
$status_array = $request->status;
$reason_array = $request->reason;
$ordered_investigation = OrderedInvestigation::find($id);
if ($ordered_investigation) {
$specimen_clean_array = [];
$status_clean_array = [];
$reason_clean_array = [];
// check string for 0 and remove
for ($i = 0; $i < count($specimen_array); $i++) {
if ($specimen_array[$i] != 0 && $status_array[$i] != 0) {
$specimen_clean_array[] = $specimen_array[$i];
$status_clean_array[] = $status_array[$i];
$reason_clean_array[] = $reason_array[$i];
}
}
$ordered_investigation->request_received_date = Carbon::now();
$ordered_investigation->specimen = implode(",", $specimen_clean_array);
$ordered_investigation->specimen_status = implode(",", $status_clean_array);
$ordered_investigation->specimen_reason = implode(",", $reason_clean_array);
$ordered_investigation->lab_number = $request->lab_number;
$ordered_investigation->request_received = 1;
$ordered_investigation->request_received_by = Auth::id();
return ($ordered_investigation->save()) ? 1 : 0;
} else {
return 0;
}
}
public function print_request_barcode($id)
{
// get the patient id then name
$patient_name = get_full_name(get_name($id, 'id', 'patient_id', 'ordered_investigations'), 'id', 'first_name', 'last_name', 'patients');
return view('investigations::investigations.print_request_barcode', compact('patient_name', 'id'));
}
public function view_lab_results(Request $request)
{
$search_text = "";
$filters = [];
// if patient id is active, get all records regardless of date; else search by date
if (isset($request->patient_id) && $request->patient_id != 0) {
$filters[] = ['ordered_investigations.patient_id', '=', $request->patient_id];
$search_text .= "Patient: " . get_full_name($request->patient_id, 'id', 'first_name', 'last_name', 'patients');
$search_text .= " (" . get_name($request->patient_id, 'id', 'number', 'patients') . ") ";
} elseif (isset($request->lab_number) && $request->lab_number != '') {
$filters[] = ['ordered_investigations.id', '=', $request->lab_number];
$search_text .= "Lab Number: " . $request->lab_number;
} else {
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;
}
$filters[] = ['ordered_investigations.created_at', '>', $start_date];
$filters[] = ['ordered_investigations.created_at', '<', $end_date];
}
$incomings = OrderedInvestigation::where('investigation_status', 0)
->where('request_received', 1)
->where('order_type', 'Lab')->where('urgent_ids', '=', '')
->where($filters)
->orderBy('id', 'desc')
->limit(250)
->get();
$urgent_incomings = OrderedInvestigation::where('investigation_status', 0)
->where('request_received', 1)
->where('order_type', 'Lab')->where('urgent_ids', '<>', '')
->where($filters)
->orderBy('id', 'desc')
->limit(250)
->get();
$all_complete = OrderedInvestigation::where(['ordered_investigations.investigation_status' => 1])
->where('ordered_investigations.request_received', 1)
->where('ordered_investigations.order_type', 'Lab')
->where($filters)
->leftJoin('investigation_results', 'investigation_results.order_id', '=', 'ordered_investigations.id')
->orderBy('ordered_investigations.id', 'desc')
->limit(250)
->get(['ordered_investigations.*', 'investigation_results.created_at as results_created_at']);
$specimen = LaboratorySpecimen::pluck('name', 'id')->toArray();
return view('investigations::investigations.view_lab_results', compact('incomings', 'specimen', 'all_complete', 'search_text', 'urgent_incomings'));
}
public function view_lab_results_quick_view(Request $request)
{
$order = DB::table('ordered_investigations')
->where('id', $request->id)
->select('investigation_id', 'patient_id', 'specimen', 'specimen_status')
->first();
$html_text = "<table class='table table-bordered table-striped'>";
if ($request->type == 1) {
$records = explode(",", $order->investigation_id);
} else {
$records = explode(",", $order->specimen);
}
// explode the status as well for specimen
$status_array = explode(",", $order->specimen_status);
$status_counter = 0;
$html_text .= "<tr>";
if ($request->type == 1) {
$html_text .= "<th style='color: black' class='text-center'> Test Name </th>";
} else {
$html_text .= "<th style='color: black' class='text-center'> Specimen Name </th>";
$html_text .= "<th style='color: black' class='text-center'> Status </th>";
}
$html_text .= "</tr>";
foreach ($records as $record) {
$html_text .= "<tr>";
if ($request->type == 1) {
$html_text .= "<td class='text-center'>";
$html_text .= get_name($record, 'id', 'name', 'investigations');
$html_text .= "</td>";
} else {
$html_text .= "<td class='text-center'>";
$html_text .= get_name($record, 'id', 'name', 'laboratory_specimens');
$html_text .= "</td>";
$html_text .= "<td class='text-center'>";
if ($status_array[$status_counter] == 1) {
$html_text .= "<font color='green'>Taken</font>";
} else if ($status_array[$status_counter] == 2) {
$html_text .= "<font color='orange'>Not Taken</font>";
} else if ($status_array[$status_counter] == 3) {
$html_text .= "<font color='#ff4500'>Rejected</font>";
}
$html_text .= "</td>";
$status_counter++;
}
$html_text .= "</tr>";
}
$html_text .= "</table>";
return json_encode([
"patient_number" => get_name($order->patient_id, 'id', 'number', 'patients'),
"patient_name" => get_full_name($order->patient_id, 'id', 'first_name', 'last_name', 'patients'),
"html" => $html_text
]);
}
public function view_lab_results_details($id)
{
$ordered_investigation = OrderedInvestigation::find($id);
$patient_id = $ordered_investigation->patient_id;
$results = [];
$investigation_results = InvestigationResults::where('order_id', '=', $id)->get();
foreach ($investigation_results as $result) {
$investigations = explode(",", $result->investigation_id);
$values = explode(",", $result->value);
$comments = explode(",", $result->comment);
$per_investigation = explode(",", $result->per_investigation);
$count_two = 0;
for ($i = 0; $i < count($investigations); $i++) {
$type = get_name($investigations[$i], 'id', 'type', 'investigations');
$result_document = PatientDocument::where([['patient_id', $patient_id], ['episode_id', $result->episode_id], ['investigation_result_id', $result->id], ['investigation_id', $investigations[$i]]])->first();
$results[$count_two]['id'] = $investigations[$i];
$results[$count_two]['name'] = get_name($investigations[$i], 'id', 'name', 'investigations');
$results[$count_two]['range'] = (get_name($investigations[$i], 'id', 'range_type', 'investigations') == 1) ? get_dynamic_normal_range($investigations[$i], get_patient_age_group($patient_id), get_name($patient_id, 'id', 'gender', 'patients')) : get_name($investigations[$i], 'id', 'normal_ranges', 'investigations');
$results[$count_two]['type'] = $type;
$results[$count_two]['units'] = get_name($investigations[$i], 'id', 'units', 'investigations');
$results[$count_two]['result'] = isset($values[$i]) ? $values[$i] : "";
$results[$count_two]['comment'] = isset($comments[$i]) ? $comments[$i] : "";
$results[$count_two]['document'] = $result_document->id ?? "";
$results[$count_two]['authenticated'] = isset($per_investigation[$i]) ? $per_investigation[$i] : "";
$count_two++;
}
}
$hospital_information = HospitalInformation::find(1);
return view('investigations::investigations.view_lab_results_details', compact('ordered_investigation', 'results', 'hospital_information', 'id', 'patient_id'));
}
public function view_lab_specialised_results($id)
{
$specialised_results = DB::table('investigation_specialised_results')
->find($id);
$html_text = "<table class='table table-bordered table-striped'>";
$records_id = explode(",", $specialised_results->specialised_variable_id);
$records_value = explode(",", $specialised_results->value);
$records_comment = explode(",", $specialised_results->comment);
$html_text .= "<tr>"
. "<th style='color: black' class='text-center'> Variable Name </th>"
. "<th style='color: black' class='text-center'> Value - (Comment) </th>"
. "</tr>";
for ($i = 0; $i < count($records_id); $i++) {
$html_text .= "<tr>";
$html_text .= "<td class='text-center'>";
$html_text .= get_name($records_id[$i], 'id', 'name', 'investigation_specialised_variables');
$html_text .= "</td>";
$html_text .= "<td class='text-center'>";
$html_text .= $records_value[$i] . " (" . $records_comment[$i] . ")";
$html_text .= "</td>";
$html_text .= "</tr>";
}
$html_text .= "</table>";
return json_encode([
"investigation_name" => get_name(get_name($records_id[0], 'id', 'investigation_id', 'investigation_specialised_variables'), 'id', 'name', 'investigations'),
"html" => $html_text,
]);
}
public function edit_investigation_specimen($id)
{
$ordered_investigation = OrderedInvestigation::find($id);
$specimen = LaboratorySpecimen::orderBy('name', 'asc')->pluck('name', 'id')->toArray();
$specimen = [0 => '- select -'] + $specimen;
return view('investigations::investigations.edit_investigation_specimen', compact('ordered_investigation', 'specimen'));
}
public function save_investigation_specimen(Request $request)
{
$id = $request->id;
$specimen_array = $request->specimen;
$status_array = $request->status;
$reason_array = $request->reason;
$ordered_investigation = OrderedInvestigation::find($id);
$specimen_clean_array = [];
$status_clean_array = [];
$reason_clean_array = [];
// check string for 0 and remove
for ($i = 0; $i < count($specimen_array); $i++) {
if ($specimen_array[$i] != 0 && $status_array[$i] != 0) {
$specimen_clean_array[] = $specimen_array[$i];
$status_clean_array[] = $status_array[$i];
$reason_clean_array[] = $reason_array[$i];
}
}
$ordered_investigation->specimen = implode(",", $specimen_clean_array);
$ordered_investigation->specimen_status = implode(",", $status_clean_array);
$ordered_investigation->specimen_reason = implode(",", $reason_clean_array);
$ordered_investigation->save();
flash("Lab specimen have been edited")->success();
return redirect('/investigations/view_lab_results_details/' . $id);
}
public function investigations_to_cancel(Request $request)
{
$search_by = $request->search_by;
if ($search_by == 1) {
// custom date
$start_date = Carbon::parse($request->reg_date)->startOfDay()->toDateTimeString();
$end_date = Carbon::parse($request->reg_date)->endOfDay()->toDateTimeString();
$date_search = streamline_date($start_date);
} elseif ($search_by == 2) {
// custom date range
$start_date = Carbon::parse($request->start_date)->startOfDay()->toDateTimeString();
$end_date = Carbon::parse($request->end_date)->endOfDay()->toDateTimeString();
$date_search = streamline_date($start_date) . " to " . streamline_date($end_date);
} else {
$start_date = Carbon::now()->startOfDay()->toDateTimeString();
$end_date = Carbon::now()->endOfDay()->toDateTimeString();
$date_search = "Today";
}
// use left join to exclude orders with results
$ordered_investigations = OrderedInvestigation::where('ordered_investigations.investigation_status', '=', '0')
->where('ordered_investigations.payment_status', '=', '0')
->whereBetween('ordered_investigations.created_at', [$start_date, $end_date])
->select('ordered_investigations.*')
->leftJoin('investigation_results', 'investigation_results.order_id', '=', 'ordered_investigations.id')
->whereNull('investigation_results.order_id')
->orderBy('ordered_investigations.id', 'desc')
->get();
return view('investigations::investigations.delete_investigations', compact('ordered_investigations', 'date_search'));
}
public function destroy_ordered_investigations($id)
{
$ordered_investigation = OrderedInvestigation::find($id);
try {
$ordered_investigation->delete();
// check if there are any insurance claims available
$claim = InsuranceClaim::where('order_id', $id)->where('item_type', 3)->first();
if ($claim) {
$claim->delete();
}
flash("Investigations order has been cancelled.")->success();
} catch (\Exception $exception) {
flash("Investigations order has not been cancelled.")->error();
}
return redirect('investigations_to_cancel');
}
public function view_deleted_ordered_invetigations(Request $request)
{
$search_by = $request->search_by;
$reg_date = $request->reg_date;
$start_date = $request->start_date;
$end_date = $request->end_date;
$filters = [];
if ($search_by == 0) {
// last 24 hours
$last_day = Carbon::now()->subDay();
$filters[] = ['deleted_at', '>', $last_day];
} elseif ($search_by == 1) {
// custom date
$start_date_search = Carbon::parse($reg_date)->startOfDay()->toDateTimeString();
$end_date_search = Carbon::parse($reg_date)->endOfDay()->toDateTimeString();
$filters[] = ['deleted_at', '>', $start_date_search];
$filters[] = ['deleted_at', '<', $end_date_search];
} elseif ($search_by == 2) {
// custom date range
$start_date_search = Carbon::parse($start_date)->startOfDay()->toDateTimeString();
$end_date_search = Carbon::parse($end_date)->endOfDay()->toDateTimeString();
$filters[] = ['deleted_at', '>', $start_date_search];
$filters[] = ['deleted_at', '<', $end_date_search];
}
$deleted_ordered_investigations = DB::table('ordered_investigations')->whereNotNull('deleted_at')->where($filters)->orderBy('id', 'desc')->get();
return view('investigations::investigations.view_deleted_ordered_investigations', compact('deleted_ordered_investigations'));
}
public function restore_deleted_ordered_invetigations($id)
{
$ordered_investigation = OrderedInvestigation::withTrashed()->find($id);
try {
$ordered_investigation->restore();
// check if there are any insurance claims available
$claim = InsuranceClaim::onlyTrashed()->where('order_id', $id)->where('service_type', 3)->first();
if ($claim) {
$claim->restore();
}
flash("Investigations order has been activated")->success();
} catch (\Exception $exception) {
flash("Investigations order has not been activated")->error();
}
return redirect('view_deleted_ordered_invetigations');
}
public function update_by_ordered_by(Request $request)
{
$update = OrderedInvestigation::where('id', $request->id)->update(['ordered_by' => $request->name]);
return $update;
}
public function view_investigation_normal_ranges($investigation_id)
{
$ranges = DB::table('investigations_normal_ranges')
->where('test_id', $investigation_id)
->select('age_group_id', 'female_range', 'male_range')
->get();
$male = [];
$female = [];
foreach ($ranges as $range) {
$male[$range->age_group_id] = $range->male_range;
$female[$range->age_group_id] = $range->female_range;
}
return json_encode([
"name" => get_name($investigation_id, 'id', 'name', 'investigations'),
"male" => $male,
"female" => $female
]);
}
public function view_specialised_investigation_normal_ranges($investigation_id)
{
$ranges = DB::table('investigations_normal_ranges')
->where('test_id', $investigation_id)
->where('is_specialised_variable', 1)
->select('age_group_id', 'female_range', 'male_range')
->get();
$male = [];
$female = [];
foreach ($ranges as $range) {
$male[$range->age_group_id] = $range->male_range;
$female[$range->age_group_id] = $range->female_range;
}
return json_encode([
"name" => get_name($investigation_id, 'id', 'name', 'investigation_specialised_variables'),
"male" => $male,
"female" => $female
]);
}
public function store_cardio_echo(Request $request)
{
$mode_measurements = [
'LAD' => $request->lad_result,
'IVS' => $request->ivs_result,
'FS (%)' => $request->fs_result,
'AO' => $request->ao_result,
'LVIDd' => $request->lvidd_result,
'EF (%)' => $request->ef_result,
'LA' => $request->la_result,
'LVPWd' => $request->lvpwd_result,
'E:A' => $request->ea_result,
'RVIDd' => $request->rvidd_result,
'SV' => $request->sv_result,
'TAPSE' => $request->tapse_result,
'LVIDs' => $request->lvids_result,
'RV' => $request->rv_result,
'RA' => $request->ra_result
];
$mode_measurements = serialize($mode_measurements);
$doppler_study = [
'Mitral Valve I' => $request->mitral_valve_insufficiency,
'Mitral Valve S' => $request->mitral_valve_stenosis,
'Aortic Valve I' => $request->aortic_valve_insufficiency,
'Aortic Valve S' => $request->aortic_valve_stenosis,
'Pulmonary Valve I' => $request->pulmonary_valve_insufficiency,
'Pulmonary Valve S' => $request->pulmonary_valve_stenosis,
'Tricuspid Valve I' => $request->tricuspid_valve_insufficiency,
'Tricuspid Valve S' => $request->tricuspid_valve_stenosis,
'AV Vmax' => $request->av_vmax,
'AV Vmean' => $request->av_mean,
'Mitral EA ratio' => $request->mitral_ea_ratio,
'TR PG' => $request->tr_pg,
'RAP' => $request->rap,
];
$doppler_study = serialize($doppler_study);
$descriptions = [
'left_ventricle_description' => $request->left_ventricle_description,
'right_ventricle_description' => $request->right_ventricle_description,
'right_atrium_description' => $request->right_atrium_description,
'left_atrium_description' => $request->left_atrium_description,
'aortic_valve_description' => $request->aortic_valve_description,
'mitral_valve_description' => $request->mitral_valve_description,
'pulmonary_valve_description' => $request->pulmonary_valve_description,
'tricuspid_valve_description' => $request->tricuspid_valve_description,
'aortic_root_and_arch_description' => $request->aortic_root_and_arch_description,
'pericardium_description' => $request->pericardium_description,
];
$descriptions = serialize($descriptions);
$descriptions_order = [
'left_ventricle_order' => $request->left_ventricle_order,
'right_ventricle_order' => $request->right_ventricle_order,
'right_atrium_order' => $request->right_atrium_order,
'left_atrium_order' => $request->left_atrium_order,
'aortic_valve_order' => $request->aortic_valve_order,
'mitral_valve_order' => $request->mitral_valve_order,
'pulmonary_valve_order' => $request->pulmonary_valve_order,
'tricuspid_valve_order' => $request->tricuspid_valve_order,
'aortic_root_and_arch_order' => $request->aortic_root_and_arch_order,
'pericardium_order' => $request->pericardium_order,
];
$descriptions_order = serialize($descriptions_order);
//First check if there is already a saved instance
$cardioCheck = CardioEchoResult::where('episode_id', $request->episode_id)->first();
if (is_null($cardioCheck)):
$cardio = new CardioEchoResult();
else:
$cardio = CardioEchoResult::find($cardioCheck->id);
endif;
$cardio->patient_id = $request->patient_id;
$cardio->episode_id = $request->episode_id;
$cardio->template_used = $request->cardio_template_selected;
$cardio->mode_measurements = $mode_measurements;
$cardio->doppler_study = $doppler_study;
$cardio->descriptions = $descriptions;
$cardio->descriptions_order = $descriptions_order;
$cardio->comments = $request->cardio_echo_comments;
$cardio->conclusion = $request->cardio_echo_conclusion;
$cardio->created_by = Auth::id();
$cardio->save();
//Bring staff payments to life
$echo_investigation = Investigation::where(['slug' => 'echo'])->first();
record_staff_that_has_performed_the_service($request->patient_id, $request->episode_id, 2, $echo_investigation->id, 0, $cardio->created_by);
//end of staff payments voodo
$arr = array(
'msg' => 'Successfully submit form using ajax',
'status' => false
);
return Response()->json($arr);
}
public function print_cardio_echo(Request $request)
{
$hospital_information = HospitalInformation::first();
$patient_id = $request->patient_id;
$episode_id = $request->episode_id;
$results = CardioEchoResult::where('episode_id', $episode_id)->first();
$patient = Patient::find($patient_id);
$measurements = unserialize($results->mode_measurements);
$doppler_study = unserialize($results->doppler_study);
$descriptions = unserialize($results->descriptions);
$descriptions_order = unserialize($results->descriptions_order);
$template_details = CardioEchoTemplate::find($results->template_used);
try {
$range = unserialize($template_details->range);
} catch (\Exception $exception) {
$range = [];
}
if (!$descriptions_order) {
$descriptions_order['left_ventricle_order'] = 1;
$descriptions_order['right_ventricle_order'] = 2;
$descriptions_order['right_atrium_order'] = 3;
$descriptions_order['left_atrium_order'] = 4;
$descriptions_order['aortic_valve_order'] = 5;
$descriptions_order['mitral_valve_order'] = 6;
$descriptions_order['pulmonary_valve_order'] = 7;
$descriptions_order['tricuspid_valve_order'] = 8;
$descriptions_order['aortic_root_and_arch_order'] = 9;
$descriptions_order['pericardium_order'] = 10;
}
// create the descriptions array
$descriptions_array = [];
$descriptions_array[$descriptions_order['left_ventricle_order']]['name'] = "Left Ventricle";
$descriptions_array[$descriptions_order['left_ventricle_order']]['value'] = $descriptions['left_ventricle_description'];
$descriptions_array[$descriptions_order['right_ventricle_order']]['name'] = "Right Ventricle";
$descriptions_array[$descriptions_order['right_ventricle_order']]['value'] = $descriptions['right_ventricle_description'];
$descriptions_array[$descriptions_order['right_atrium_order']]['name'] = "Right Atrium";
$descriptions_array[$descriptions_order['right_atrium_order']]['value'] = $descriptions['right_atrium_description'];
$descriptions_array[$descriptions_order['left_atrium_order']]['name'] = "Left Atrium";
$descriptions_array[$descriptions_order['left_atrium_order']]['value'] = $descriptions['left_atrium_description'];
$descriptions_array[$descriptions_order['aortic_valve_order']]['name'] = "Aortic Valve";
$descriptions_array[$descriptions_order['aortic_valve_order']]['value'] = $descriptions['aortic_valve_description'];
$descriptions_array[$descriptions_order['mitral_valve_order']]['name'] = "Mitral Valve";
$descriptions_array[$descriptions_order['mitral_valve_order']]['value'] = $descriptions['mitral_valve_description'];
$descriptions_array[$descriptions_order['pulmonary_valve_order']]['name'] = "Pulmonary Valve";
$descriptions_array[$descriptions_order['pulmonary_valve_order']]['value'] = $descriptions['pulmonary_valve_description'];
$descriptions_array[$descriptions_order['tricuspid_valve_order']]['name'] = "Tricuspid Valve";
$descriptions_array[$descriptions_order['tricuspid_valve_order']]['value'] = $descriptions['tricuspid_valve_description'];
$descriptions_array[$descriptions_order['aortic_root_and_arch_order']]['name'] = "Aortic root and arch";
$descriptions_array[$descriptions_order['aortic_root_and_arch_order']]['value'] = $descriptions['aortic_root_and_arch_description'];
$descriptions_array[$descriptions_order['pericardium_order']]['name'] = "Pericardium";
$descriptions_array[$descriptions_order['pericardium_order']]['value'] = $descriptions['pericardium_description'];
// sort by the keys and oh lord it's past 6pm
ksort($descriptions_array);
$data = [
'date' => Carbon::parse($results->created_at)->format('dS -m - Y (D)'),
'names' => $patient->last_name . ' ' . $patient->first_name,
'patient_number' => $patient->number,
'hospital_information' => $hospital_information,
'age' => Carbon::parse($patient->date_of_birth)->diff(now())->format('%y years, %m months and %d days'),
'sex' => $patient->gender == 1 ? 'Male' : 'Female',
'lad' => $measurements['LAD'] ?? "",
'ivs' => $measurements['IVS'] ?? "",
'fs' => $measurements['FS (%)'] ?? "",
'aortic' => $measurements['AO'] ?? "",
'lvidd' => $measurements['LVIDd'] ?? "",
'ef' => $measurements['EF (%)'] ?? "",
'la' => $measurements['LA'] ?? "",
'lvpwd' => $measurements['LVPWd'] ?? "",
'ea' => $measurements['E:A'] ?? "",
'rvidd' => $measurements['RVIDd'] ?? "",
'sv' => $measurements['SV'] ?? "",
'tapse' => $measurements['TAPSE'] ?? "",
'lvids' => $measurements['LVIDs'] ?? "",
'rv' => $measurements['RV'] ?? "",
'ra' => $measurements['RA'] ?? "",
'range_LAD' => $range['LAD'] ?? "",
'range_IVS' => $range['IVS'] ?? "(0.6 - 1.1 cm)",
'range_FS' => $range['FS (%)'] ?? "(26 - 55)",
'range_AO' => $range['AO'] ?? "(2.0 - 4.0 cm)",
'range_LVIDd' => $range['LVIDd'] ?? "(3.5 - 5.7 cm)",
'range_EF' => $range['EF (%)'] ?? "(55 - 80)",
'range_LA' => $range['LA'] ?? "(3.0 - 4.0 cm)",
'range_LVPWd' => $range['LVPWd'] ?? "(0.6 - 1.1 cm)",
'range_E:A' => $range['E:A'] ?? "",
'range_RVIDd' => $range['RVIDd'] ?? "",
'range_SV' => $range['SV'] ?? "",
'range_TAPSE' => $range['TAPSE'] ?? "",
'range_LVIDs' => $range['LVIDs'] ?? "(2.5 - 4.0 cm)",
'range_RV' => $range['RV'] ?? "(2.0 - 4.1 cm)",
'range_RA' => $range['RA'] ?? "",
'range_TR PG' => $range['TR PG'] ?? "",
'mitral_valve_insufficiency' => $doppler_study['Mitral Valve I'] ?? "",
'mitral_valve_stenosis' => $doppler_study['Mitral Valve S'] ?? "",
'aortic_valve_insufficiency' => $doppler_study['Aortic Valve I'] ?? "",
'aortic_valve_stenosis' => $doppler_study['Aortic Valve S'] ?? "",
'pulmonary_valve_insufficiency' => $doppler_study['Pulmonary Valve I'] ?? "",
'pulmonary_valve_stenosis' => $doppler_study['Pulmonary Valve S'] ?? "",
'tricuspid_valve_insufficiency' => $doppler_study['Tricuspid Valve I'] ?? "",
'tricuspid_valve_stenosis' => $doppler_study['Tricuspid Valve S'] ?? "",
'av_vmax' => $doppler_study['AV Vmax'] ?? "",
'av_mean' => $doppler_study['AV Vmean'] ?? "",
'mitral_ea_ratio' => $doppler_study['Mitral EA ratio'] ?? "",
'tr_pg' => $doppler_study['TR PG'] ?? "",
'rap' => $doppler_study['RAP'] ?? "",
'descriptions_array' => $descriptions_array,
'comments' => $results->comments,
'conclusion' => $results->conclusion,
'created_by' => $results->created_by,
'created_at' => $results->created_at
];
$pdf = SnappyPDF::loadView('investigations::investigations/print_cardio_echo', $data)
->setOrientation('portrait')
->setOption('margin-bottom', 7)
->setOption('margin-top', 5)
->setOption('footer-html', '<i>Printed On ' . date('Y-m-d') . '</i>');
return $pdf->inline('Cardio-Echo-Results' . date(" d-m-y h:ia") . '.pdf');
}
public function cardio_echo_template(Request $request)
{
$cardio_echo_conclusion = "";
if (isset($request->template) && $request->template != 0) {
$results = CardioEchoTemplate::find($request->template);
$measurements = unserialize($results->mode_measurements);
$doppler_study = unserialize($results->doppler_study);
$descriptions = unserialize($results->descriptions);
$range = unserialize($results->range);
$cardio_echo_conclusion = $results->conclusion;
$id = $request->template;
} else {
$measurements = 0;
$doppler_study = 0;
$descriptions = 0;
$range = 0;
$id = 0;
}
$templates = CardioEchoTemplate::pluck('name', 'id')->toArray();
$templates = [0 => '- select template-'] + $templates;
return view('investigations::investigations.cardio_echo_template', compact('measurements', 'doppler_study', 'descriptions', 'templates', 'id', 'range', 'cardio_echo_conclusion'));
}
public function save_cardio_echo_template(Request $request)
{
$mode_measurements = [
'LAD' => $request->lad_result,
'IVS' => $request->ivs_result,
'FS (%)' => $request->fs_result,
'AO' => $request->ao_result,
'LVIDd' => $request->lvidd_result,
'EF (%)' => $request->ef_result,
'LA' => $request->la_result,
'LVPWd' => $request->lvpwd_result,
'E:A' => $request->ea_result,
'RVIDd' => $request->rvidd_result,
'SV' => $request->sv_result,
'TAPSE' => $request->tapse_result,
'LVIDs' => $request->lvids_result,
'RV' => $request->rv_result,
'RA' => $request->ra_result
];
$mode_measurements = serialize($mode_measurements);
$doppler_study = [
'Mitral Valve I' => $request->mitral_valve_insufficiency,
'Mitral Valve S' => $request->mitral_valve_stenosis,
'Aortic Valve I' => $request->aortic_valve_insufficiency,
'Aortic Valve S' => $request->aortic_valve_stenosis,
'Pulmonary Valve I' => $request->pulmonary_valve_insufficiency,
'Pulmonary Valve S' => $request->pulmonary_valve_stenosis,
'Tricuspid Valve I' => $request->tricuspid_valve_insufficiency,
'Tricuspid Valve S' => $request->tricuspid_valve_stenosis,
'AV Vmax' => $request->av_vmax,
'AV Vmean' => $request->av_mean,
'Mitral EA ratio' => $request->mitral_ea_ratio,
'TR PG' => $request->tr_pg,
'RAP' => $request->rap,
];
$doppler_study = serialize($doppler_study);
$descriptions = [
'left_ventricle_description' => $request->left_ventricle_description,
'right_ventricle_description' => $request->right_ventricle_description,
'right_atrium_description' => $request->right_atrium_description,
'left_atrium_description' => $request->left_atrium_description,
'aortic_valve_description' => $request->aortic_valve_description,
'mitral_valve_description' => $request->mitral_valve_description,
'pulmonary_valve_description' => $request->pulmonary_valve_description,
'tricuspid_valve_description' => $request->tricuspid_valve_description,
'aortic_root_and_arch_description' => $request->aortic_root_and_arch_description,
'pericardium_description' => $request->pericardium_description,
];
$descriptions = serialize($descriptions);
$ranges = [
'LAD' => $request->lad_range,
'IVS' => $request->ivs_range,
'FS (%)' => $request->fs_range,
'AO' => $request->ao_range,
'LVIDd' => $request->lvidd_range,
'EF (%)' => $request->ef_range,
'LA' => $request->la_range,
'LVPWd' => $request->lvpwd_range,
'E:A' => $request->ea_range,
'RVIDd' => $request->rvidd_range,
'SV' => $request->sv_range,
'TAPSE' => $request->tapse_range,
'LVIDs' => $request->lvids_range,
'RV' => $request->rv_range,
'RA' => $request->ra_range,
'TR PG' => $request->tr_pg_range
];
$range = serialize($ranges);
$cardio = CardioEchoTemplate::find($request->id);
$cardio->mode_measurements = $mode_measurements;
$cardio->doppler_study = $doppler_study;
$cardio->descriptions = $descriptions;
$cardio->range = $range;
$cardio->conclusion = $request->cardio_echo_conclusion;
$cardio->save();
flash($cardio->name . " Echo Cardiology template has been updated")->success();
return redirect('cardio_echo_template');
}
public function fetch_cardio_echo_template($id)
{
$results = CardioEchoTemplate::find($id);
$measurements = unserialize($results->mode_measurements);
$doppler_study = unserialize($results->doppler_study);
$descriptions = unserialize($results->descriptions);
$range = unserialize($results->range);
return json_encode([
'LAD' => $measurements['LAD'],
'IVS' => $measurements['IVS'],
'FS (%)' => $measurements['FS (%)'],
'AO' => $measurements['AO'],
'LVIDd' => $measurements['LVIDd'],
'EF (%)' => $measurements['EF (%)'],
'LA' => $measurements['LA'],
'LVPWd' => $measurements['LVPWd'],
'E:A' => $measurements['E:A'],
'RVIDd' => $measurements['RVIDd'],
'SV' => $measurements['SV'],
'TAPSE' => $measurements['TAPSE'],
'LVIDs' => $measurements['LVIDs'],
'RV' => $measurements['RV'],
'RA' => $measurements['RA'],
'Mitral Valve I' => $doppler_study['Mitral Valve I'],
'Mitral Valve S' => $doppler_study['Mitral Valve S'],
'Aortic Valve I' => $doppler_study['Aortic Valve I'],
'Aortic Valve S' => $doppler_study['Aortic Valve S'],
'Pulmonary Valve I' => $doppler_study['Pulmonary Valve I'],
'Pulmonary Valve S' => $doppler_study['Pulmonary Valve S'],
'Tricuspid Valve I' => $doppler_study['Tricuspid Valve I'],
'Tricuspid Valve S' => $doppler_study['Tricuspid Valve S'],
'AV Vmax' => $doppler_study['AV Vmax'],
'AV Vmean' => $doppler_study['AV Vmean'],
'Mitral EA ratio' => $doppler_study['Mitral EA ratio'],
'TR PG' => $doppler_study['TR PG'],
'RAP' => $doppler_study['RAP'],
'left_ventricle_description' => $descriptions['left_ventricle_description'],
'right_ventricle_description' => $descriptions['right_ventricle_description'],
'right_atrium_description' => $descriptions['right_atrium_description'],
'left_atrium_description' => $descriptions['left_atrium_description'],
'aortic_valve_description' => $descriptions['aortic_valve_description'],
'mitral_valve_description' => $descriptions['mitral_valve_description'],
'pulmonary_valve_description' => $descriptions['pulmonary_valve_description'],
'tricuspid_valve_description' => $descriptions['tricuspid_valve_description'],
'aortic_root_and_arch_description' => $descriptions['aortic_root_and_arch_description'],
'pericardium_description' => $descriptions['pericardium_description'],
'conclusion' => $results->conclusion,
'range_LAD' => $range['LAD'],
'range_IVS' => $range['IVS'],
'range_FS (%)' => $range['FS (%)'],
'range_AO' => $range['AO'],
'range_LVIDd' => $range['LVIDd'],
'range_EF (%)' => $range['EF (%)'],
'range_LA' => $range['LA'],
'range_LVPWd' => $range['LVPWd'],
'range_E:A' => $range['E:A'],
'range_RVIDd' => $range['RVIDd'],
'range_SV' => $range['SV'],
'range_TAPSE' => $range['TAPSE'],
'range_LVIDs' => $range['LVIDs'],
'range_RV' => $range['RV'],
'range_RA' => $range['RA'],
'range_TR PG' => $range['TR PG'],
]);
}
public function create_cardio_echo_template(Request $request)
{
$mode_measurements = [
'LAD' => "",
'IVS' => "",
'FS (%)' => "",
'AO' => "",
'LVIDd' => "",
'EF (%)' => "",
'LA' => "",
'LVPWd' => "",
'E:A' => "",
'RVIDd' => "",
'SV' => "",
'TAPSE' => "",
'LVIDs' => "",
'RV' => "",
'RA' => ""
];
$mode_measurements = serialize($mode_measurements);
$doppler_study = [
'Mitral Valve I' => "",
'Mitral Valve S' => "",
'Aortic Valve I' => "",
'Aortic Valve S' => "",
'Pulmonary Valve I' => "",
'Pulmonary Valve S' => "",
'Tricuspid Valve I' => "",
'Tricuspid Valve S' => "",
'AV Vmax' => "",
'AV Vmean' => "",
'Mitral EA ratio' => "",
'TR PG' => "",
'RAP' => "",
];
$doppler_study = serialize($doppler_study);
$descriptions = [
'left_ventricle_description' => "",
'right_ventricle_description' => "",
'right_atrium_description' => "",
'left_atrium_description' => "",
'aortic_valve_description' => "",
'mitral_valve_description' => "",
'pulmonary_valve_description' => "",
'tricuspid_valve_description' => "",
'aortic_root_and_arch_description' => "",
'pericardium_description' => "",
];
$descriptions = serialize($descriptions);
CardioEchoTemplate::firstOrCreate([
'name' => $request->name,
'mode_measurements' => $mode_measurements,
'doppler_study' => $doppler_study,
'descriptions' => $descriptions,
'conclusion' => ''
]);
flash($request->name . " Echo Cardiology template has been created")->success();
return redirect('cardio_echo_template');
}
public function display_specialised_variables_pop_up(Request $request)
{
$id = $request->id;
$patient_id = $request->patient_id;
$specialised_results = DB::table('investigation_specialised_results')
->where('id', $id)
->get()
->first();
if (!$specialised_results) {
return 0;
}
$html_text = "<table class='table table-bordered table-striped'>";
$html_text .= "<tr>";
$html_text .= "<th style='color: black' class='text-center'> Name </th>";
$html_text .= "<th style='color: black' class='text-center'> Results </th>";
$html_text .= "<th style='color: black' class='text-center'> Reference Ranges </th>";
$html_text .= "<th style='color: black' class='text-center'> Comments </th>";
$html_text .= "</tr>";
$variable_id_array = explode(',', $specialised_results->specialised_variable_id);
$variable_value_array = explode(',', $specialised_results->value);
$variable_comment_array = explode(',', $specialised_results->comment);
for ($i = 0; $i < count($variable_id_array); $i++) {
$html_text .= "<tr>";
$html_text .= "<td>" . get_name($variable_id_array[$i], 'id', 'name', 'investigation_specialised_variables') . "</td>";
$html_text .= "<td>" . $variable_value_array[$i] . "</td>";
$html_text .= "<td>";
if (get_name($variable_id_array[$i], 'id', 'range_type', 'investigation_specialised_variables') == 1) {
$html_text .= get_dynamic_normal_range_specialized($variable_id_array[$i], get_patient_age_group($patient_id), get_name($patient_id, 'id', 'gender', 'patients'));
} else {
$html_text .= get_name($variable_id_array[$i], 'id', 'normal_ranges', 'investigation_specialised_variables');
}
$html_text .= "</td>";
$html_text .= "<td>" . $variable_comment_array[$i] . "</td>";
$html_text .= "</tr>";
}
$html_text .= "</table>";
return json_encode([
"html" => $html_text
]);
}
public function remove_investigation_with_no_result($inv_id, $order_id)
{
$is_order_deleted = false;
$ordered_investigation = DB::table('ordered_investigations')->where('id', $order_id)->first();
$investigation_results = DB::table('investigation_results')->where('order_id', $order_id)->first();
if ($ordered_investigation->payment_status == 0 && $ordered_investigation->inpatient_bill_generated == 0) {
// delete from the ordered investigations
$investigation_ids = explode(",", $ordered_investigation->investigation_id);
$urgent_ids = explode(",", $ordered_investigation->urgent_ids);
$for_inpatient = explode(",", $ordered_investigation->for_inpatient);
$comments = explode(",", $ordered_investigation->order_comments);
// check if this is a solo investigation
if (count($investigation_ids) == 1 && $investigation_ids[0] == $inv_id) {
// cancel the whole order
$ordered_investigation_delete = OrderedInvestigation::find($order_id);
if ($ordered_investigation_delete) {
$ordered_investigation_delete->delete();
$is_order_deleted = true;
}
} else {
$key = array_search($inv_id, $investigation_ids);
if ($key !== false) {
unset($investigation_ids[$key]);
unset($for_inpatient[$key]);
unset($comments[$key]);
// since urgent ids does not have same size as others handle it alone
$urgent_key = array_search($inv_id, $urgent_ids);
if ($urgent_key !== false) {
unset($urgent_ids[$urgent_key]);
}
$update = OrderedInvestigation::where('id', $order_id)
->update([
'investigation_id' => implode(",", $investigation_ids),
'urgent_ids' => implode(",", $urgent_ids),
'for_inpatient' => implode(",", $for_inpatient),
'order_comments' => implode(",", $comments)
]);
}
}
// delete from the investigation results
$investigation_id = explode(",", $investigation_results->investigation_id);
$value = explode(",", $investigation_results->value);
$per_investigation = explode(",", $investigation_results->per_investigation);
$normal_ranges = explode(",", $investigation_results->normal_ranges);
$for_inpatient = explode(",", $investigation_results->for_inpatient);
$comment = explode(",", $investigation_results->comment);
if (count($investigation_id) == 1 && $investigation_id[0] == $inv_id) {
// cancel the whole order
$investigation_results_delete = InvestigationResults::find($order_id);
if ($investigation_results_delete) {
$investigation_results_delete->delete();
}
} else {
$key = array_search($inv_id, $investigation_id);
if ($key !== false) {
unset($investigation_id[$key]);
unset($value[$key]);
unset($per_investigation[$key]);
unset($for_inpatient[$key]);
unset($comment[$key]);
unset($normal_ranges[$key]);
$update = InvestigationResults::where('order_id', $order_id)
->update([
'investigation_id' => implode(",", $investigation_id),
'value' => implode(",", $value),
'per_investigation' => implode(",", $per_investigation),
'normal_ranges' => implode(",", $normal_ranges),
'for_inpatient' => implode(",", $for_inpatient),
'comment' => implode(",", $comment)
]);
}
}
flash("Investigation has been removed")->success();
} else {
flash("This investigation order has already been paid. Please first cancel the receipt before removing an investigation")->error();
}
if ($is_order_deleted) {
return redirect('/investigations/view_lab_results/');
} else {
if ($ordered_investigation->order_type == 'Lab') {
return redirect('/investigations/view_lab_results_details/' . $order_id);
} else {
if ($investigation_results) {
return redirect('/investigations/view_patient_investigation/' . $investigation_results->id);
} else {
// just in case there is no result redirect to home
return redirect('/investigations/home');
}
}
}
}
public function edit_specialised_variables_ranking($id)
{
$specialized_variables = InvestigationSpecialisedVariable::where('investigation_id', $id)->orderBy('ranking', 'asc')->get();
return view('investigations::investigations.edit_specialised_variables_ranking', compact('specialized_variables', 'id'));
}
public function save_specialised_variables_ranking(Request $request)
{
$ids = $request->spec_id;
$rankings = $request->ranking;
$logged_in_user_id = Auth::user()->id;
for ($i = 0; $i < count($ids); $i++) {
$investigation_specialised_variable = InvestigationSpecialisedVariable::find($ids[$i]);
$investigation_specialised_variable->ranking = $rankings[$i];
$investigation_specialised_variable->updated_by = $logged_in_user_id;
$investigation_specialised_variable->save();
}
flash("Specialised variables rankings have been updated")->success();
return redirect('investigations');
}
public function reverse_receiving_investigations($order_id)
{
$ordered_investigation = OrderedInvestigation::find($order_id);
$ordered_investigation->request_received_date = null;
$ordered_investigation->specimen = null;
$ordered_investigation->specimen_status = null;
$ordered_investigation->request_received = 0;
$ordered_investigation->request_received_by = null;
if ($ordered_investigation->save()) {
flash("Investigation order has been un-received")->success();
} else {
flash("An error occured. Please try again")->success();
}
return redirect('/investigations/view_lab_results/');
}
}