Files

1580 lines
72 KiB
PHP
Executable File

<?php
namespace Modules\Patients\Http\Controllers;
use Illuminate\Contracts\View\View;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Streamline\Models\Country;
use Streamline\Models\District;
use Streamline\Models\FamilyRelationship;
use Streamline\Models\HospitalInformation;
use Streamline\Models\MaritalStatus;
use Streamline\Models\Patient;
use Streamline\Models\Occupation;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;
use Streamline\Models\PatientCategory;
use Streamline\Models\PatientEpisode;
use Streamline\Models\PatientRegistrationField;
use Streamline\Models\Religion;
use Streamline\Models\Village;
use Streamline\Models\Company;
use Illuminate\Support\Facades\Http;
use Barryvdh\Snappy\Facades\SnappyPdf;
use Illuminate\Database\QueryException;
use Barryvdh\DomPDF\Facade\Pdf as DomPDF;
use Streamline\Services\PatientCardsService;
use Illuminate\Pagination\LengthAwarePaginator;
class PatientController extends Controller
{
function __construct(protected PatientCardsService $patientCardsService)
{
$this->middleware('auth');
$this->middleware('permission:patient-list', ['only' => ['index', 'select']]);
$this->middleware('permission:patient-detail', ['only' => ['show']]);
$this->middleware('permission:patient-create', ['only' => ['create', 'store']]);
$this->middleware('permission:patient-edit', ['only' => ['edit', 'update']]);
$this->middleware('permission:patient-delete', ['only' => ['destroy']]);
}
/**
* Display a listing of the resources
*/
public function index(): View
{
$patients = DB::table('patients')->whereNull('deleted_at')
->orderBy('created_at', 'desc')->paginate(100);
$categories = DB::table('patient_categories')->pluck("name", "id");
$villages = DB::table('villages')->pluck("name", "id")->toArray();
$previous_ids = DB::table('patients')->whereNull('deleted_at')
->distinct()->pluck('previous_id');
$patient_numbers = DB::table('patients')->whereNull('deleted_at')
->pluck('number');
$full_names = DB::table('patients')->whereNull('deleted_at')
->select(DB::raw('CONCAT(first_name, " ", last_name, " - ", number, " - (", phone, ")") AS full_name'))
->pluck("full_name");
return view('patients::patients.index', compact('patients', 'categories', 'patient_numbers', 'villages', 'previous_ids', 'full_names'))
->with('i', (request()->input('page', 1) - 1) * 5);
}
/**
* Show the form for creating a new resource.
*
*/
public function create(): View
{
$occupations = Occupation::orderBy('name')->pluck('name', 'id')->toArray();
$patient_categories = PatientCategory::where('available', 1)->orderby('name')->pluck('name', 'id')->toArray();
$marital_statuses = MaritalStatus::pluck('name', 'id')->toArray();
$religions = Religion::orderBy('name')->pluck('name', 'id')->toArray();
$relationships = FamilyRelationship::orderBy('name')->pluck('name', 'id')->toArray();
$patient_registration_fields = PatientRegistrationField::orderBy('name', 'asc')->get();
$occupations = ['' => '- select -'] + $occupations;
$districts = [];
$religions = ['' => '- select -'] + $religions;
$relationships = ['' => '- select -'] + $relationships;
$dynamic_counties = [];
$dynamic_sub_counties = [];
$dynamic_parishes = [];
$countries = DB::table('countries')->pluck('name', 'id')->prepend('- Select country of origin - ', '');
$companies = Company::orderBy('name')->pluck("name", "id")->toArray();
$companies = ['' => '- select -'] + $companies;
return view('patients::patients.create', compact('occupations', 'patient_categories', 'districts', 'marital_statuses', 'religions', 'relationships', 'dynamic_counties', 'dynamic_sub_counties', 'dynamic_parishes', 'countries', 'companies', 'patient_registration_fields'));
}
/**
* Store a newly created resource in storage.
*
*/
public function store(Request $request)
{
request()->validate([
'first_name' => 'required',
'last_name' => 'required',
'gender' => 'required',
'date_of_birth' => 'required_without:age_in_years',
'age_in_years' => 'required_without:date_of_birth',
/*'national_id' => 'max:15|unique:patients',*/
'patient_category' => 'required'
]);
$other_patients_info_array = [
'non_ugandan_foreigner_or_refugee' => $request->input('non_ugandan_foreigner_or_refugee'),
'non_ugandan_national_id_no' => $request->input('non_ugandan_national_id_no'),
];
// check if a patient's national_id is in the system already..
$patient_exists = Patient::where('national_id', $request->national_id)->pluck('national_id')->first();
if (is_null($patient_exists)) {
$patient = new Patient;
$patient->first_name = $request->first_name;
$patient->last_name = $request->last_name;
$calculated_date_of_birth = null;
if (is_null($request->date_of_birth)) {
$age_in_years = $request->age_in_years;
$calculated_dob = \Carbon\Carbon::now()->subYears($age_in_years);
$calculated_date_of_birth = $calculated_dob->toDateString();
$patient->date_of_birth = $calculated_date_of_birth;
} else {
$patient->date_of_birth = Carbon::createFromFormat('d/m/Y', $request->date_of_birth)->toDateString();
}
$patient->marital_status = $request->marital_status;
$patient->occupation_id = $request->occupation;
$patient->religion_id = $request->religion;
$patient->category_id = $request->patient_category;
$patient->company_id = $request->company;
$patient->citizenship = $request->citizenship;
$patient->country_id = $request->country_id;
$residence_array = explode(",", $request->residence);
$patient->district_id = $residence_array[4] ?? 0;
$patient->county_id = $residence_array[3] ?? 0;
$patient->subcounty_id = $residence_array[2] ?? 0;
$patient->parish_id = $residence_array[1] ?? 0;
$patient->village_id = $residence_array[0] ?? 0;
$patient->address_details = $request->residence;
$patient->gender = $request->gender;
$patient->next_of_kin = $request->next_of_kin;
$patient->next_of_kin_relationship = $request->next_of_kin_relationship;
$patient->phone_of_next_of_kin = removeSpaces($request->next_of_kin_phone);
$patient->phone = removeSpaces($request->phone);
$patient->alternative_phone = removeSpaces($request->alternative_phone);
$patient->national_id = $request->national_id;
$patient->phone_owner = $request->phone_owner; // problem
$patient->hospital_contact = $request->hospital_contact;
$patient->other_patients_info = !empty($other_patients_info_array) ? json_encode($other_patients_info_array) : '' ;
$patient->language = $request->language;
$patient->lc_one = $request->lc_one;
$patient->fingerprint_template = $request->fingerprint_template ?? NULL;
$patient->created_by = Auth::user()->id;
if (!empty($request->registration_field_values)) {
for ($i = 0; $i < count($request->registration_field_values); $i++) $registration_fields[$request->registration_field_names[$i]] = $request->registration_field_values[$i];
$patient->registration_fields = json_encode($registration_fields);
}
//year prefix
$currentYear = Carbon::now()->year;
$current_year_last_two_digits = substr($currentYear,-2);
$year_prefix = HospitalInformation::where('id', 1)->value('patient_number_year_prefix');
if ($patient->save()) :
$prefix = DB::table('hospital_information')->where('id', 1)->value('patient_number_abbr');
$new_id = quadLimit($patient->id);
if($year_prefix == 1){
$patient_number = $prefix . "-" . $current_year_last_two_digits . "-" . $new_id;
}
else{
$patient_number = $prefix . "-" . $new_id;
}
DB::table('patients')->where('id', $new_id)->update(['number' => $patient_number]); // Updating the patient number
flash('Patient with patient number ' . $patient_number . ' has been successfully registered')->success();
return redirect('/patient_episodes/set_patient_id/' . $patient->id);
else :
flash("There was an error")->error();
return redirect()->back()->withInput();
endif;
} else {
flash("Patient With This National ID Number is already Registered")->error();
return redirect()->back()->withInput();
}
}
/**
* Display the specified resource.
*
* @param int $id
*/
public function show($id): View
{
$patient = Patient::withTrashed()->find($id);
$last_episode = PatientEpisode::where('id', $id)->orderBy('created_at', 'desc')->first();
$country = null;
if($patient){
$country = Country::find($patient->country_id);
}
return view('patients::patients.show', compact('patient', 'last_episode','country'));
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
*/
public function edit($id): View
{
$patient = Patient::where(['id' => $id])->first();
if (is_null($patient->date_of_birth)) {
$dob = "01/01/2020";
} else {
$dob = Carbon::parse($patient->date_of_birth)->format('d/m/Y');
}
$episodes = PatientEpisode::distinct('patient_id')->pluck('patient_id')->toArray();
$occupations = Occupation::orderBy('name')->pluck('name', 'id')->toArray();
$patient_categories = PatientCategory::where('available', 1)->orderby('name')->pluck('name', 'id')->toArray();
$districts = DB::table('districts')->whereNull('deleted_at')->orderBy('name')->pluck('name', 'id')->toArray();
$religions = Religion::orderBy('name')->pluck('name', 'id')->toArray();
$relationships = FamilyRelationship::orderBy('name')->pluck('name', 'id')->toArray();
$patient_registration_fields = PatientRegistrationField::orderBy('name', 'asc')->get();
$occupations = ['' => '- select -'] + $occupations;
$districts = ['' => '- select -'] + $districts;
$religions = ['' => '- select -'] + $religions;
$relationships = ['' => '- select -'] + $relationships;
$marital_statuses = DB::table('marital_statuses')->whereNull('deleted_at')->pluck('name', 'id');
$countries = DB::table('countries')->whereNull('deleted_at')->pluck('name', 'id')->prepend('- Select country of origin - ', '');
$companies = Company::orderBy('name')->pluck("name", "id")->toArray();
$companies = ['' => '- select -'] + $companies;
return view('patients::patients.edit', compact('patient', 'occupations', 'dob', 'patient_registration_fields', 'patient_categories', 'episodes', 'districts', 'marital_statuses', 'religions', 'relationships', 'countries', 'companies'));
}
/**
* Update the specified resource in storage.
*/
public function update(Request $request, $id): RedirectResponse
{
$other_patients_info_array = [
'non_ugandan_foreigner_or_refugee' => $request->input('non_ugandan_foreigner_or_refugee'),
'non_ugandan_national_id_no' => $request->input('non_ugandan_national_id_no'),
];
request()->validate(
[
'first_name' => 'required',
'last_name' => 'required',
'date_of_birth' => 'required_without:age_in_years',
'age_in_years' => 'required_without:date_of_birth',
//'national_id' => 'max:15',
'patient_category' => 'required'
],
[
'first_name.required' => 'Please enter first name'
]
);
$patient = Patient::find($id);
$patient->first_name = $request->first_name;
$patient->last_name = $request->last_name;
$calculated_date_of_birth = null;
if (is_null($request->date_of_birth)) {
$age_in_years = $request->age_in_years;
$calculated_dob = \Carbon\Carbon::now()->subYears($age_in_years);
$calculated_date_of_birth = $calculated_dob->toDateString();
$patient->date_of_birth = $calculated_date_of_birth;
} else {
$patient->date_of_birth = Carbon::createFromFormat('d/m/Y', $request->date_of_birth)->toDateString();
}
$patient->marital_status = $request->marital_status;
$patient->occupation_id = $request->occupation;
$patient->religion_id = $request->religion;
$patient->category_id = $request->patient_category;
$patient->company_id = $request->company;
$patient->citizenship = $request->citizenship;
$patient->country_id = $request->country_id;
/*=========*/
// split the residence values
$residence_array = explode(",", $request->residence);
$patient->district_id = isset($residence_array[4]) ? $residence_array[4] : 0;
$patient->county_id = isset($residence_array[3]) ? $residence_array[3] : 0;
$patient->subcounty_id = isset($residence_array[2]) ? $residence_array[2] : 0;
$patient->parish_id = isset($residence_array[1]) ? $residence_array[1] : 0;
$patient->village_id = isset($residence_array[0]) ? $residence_array[0] : 0;
//for now put the residences string into address_details but ask douglas what it was meant for
$patient->address_details = $request->residence;
$patient->gender = $request->gender;
$patient->next_of_kin = $request->next_of_kin;
$patient->next_of_kin_relationship = $request->next_of_kin_relationship;
$patient->phone_of_next_of_kin = removeSpaces($request->next_of_kin_phone);
$patient->phone = removeSpaces($request->phone);
$patient->alternative_phone = removeSpaces($request->alternative_phone);
$patient->national_id = $request->national_id;
$patient->phone_owner = $request->phone_owner;
$patient->hospital_contact = $request->hospital_contact;
$patient->other_patients_info = !empty($other_patients_info_array) ? json_encode($other_patients_info_array) : '' ;
$patient->language = $request->language;
$patient->lc_one = $request->lc_one;
$patient->is_test_patient = $request->is_test_patient ?? 0;
if ($request->fingerprint_template) {
$patient->fingerprint_template = $request->fingerprint_template;
}
$patient->updated_by = Auth::user()->id;
if (!empty($request->registration_field_values)) {
for ($i = 0; $i < count($request->registration_field_values); $i++) $registration_fields[$request->registration_field_names[$i]] = $request->registration_field_values[$i];
$patient->registration_fields = json_encode($registration_fields);
}
/* ===== check if it was previously a main_dependant and patient category has changed then handle */
$main_patient_to_dependants = null;
$does_previous_patient_category_have_threshold = does_patient_category_have_threshold($patient->category_id);
$does_new_patient_category_have_threshold = does_patient_category_have_threshold($request->patient_category);
$patient_is_a_dependant_of = patient_is_a_dependant_of($patient->id);
if ($does_previous_patient_category_have_threshold == true || !is_null($patient_is_a_dependant_of)) {
//the patient is on a patient dependants category if we go inside this "if" statement
if ($patient_is_a_dependant_of == $patient->id) {
//the patient is a main patient for dependants when we enter this "if" statement
$main_patient_to_dependants = \Streamline\Models\CategoryPatientDependant::where('main_patient_id', $patient->id)->first();
}
}
/* ======== end of patient dependants hullabaloo =========== */
if ($patient->update()) {
if ($main_patient_to_dependants && $does_new_patient_category_have_threshold == false) {
//what happens to their existing invoices though ??
$main_patient_to_dependants->delete();
}
if ($main_patient_to_dependants && $does_new_patient_category_have_threshold == true) {
$main_patient_to_dependants->patient_category_id = $request->patient_category;
$main_patient_to_dependants->update();
}
flash("Patient " . $request->first_name . " " . $request->last_name . " has been updated")->success();
return redirect('patients/' . $patient->id);
} else {
flash("There was an error")->error();
return redirect()->back()->withInput();
}
}
/**
* Remove the specified resource from storage.
*/
public function destroy($id)
{
$patient = Patient::find($id);
if ($patient->delete()) :
flash("Patient has been deleted.")->success();
return redirect('patients/');
else :
return redirect()->back()->withInput();
endif;
}
/**
* Search/select a resource in storage.
*/
public function select(Request $request)
{
$patient_number = $request->number;
$first_name = $request->first_name;
$last_name = $request->last_name;
$national_id = $request->national_id;
$phone_number = $request->phone_number;
$subcounty = $request->subcounty_id;
$parish = $request->parish;
$village = $request->village;
$insurance_group = $request->insurance_group;
$patient_category = $request->patient_category;
$filters = array();
$subcounty_ids = array();
$parish_ids = array();
$village_ids = array();
$insurance_group_ids = array();
$patient_category_ids = array();
$patients = array();
$criteria = '';
$searched = false;
if (!empty($request->date_of_birth)) {
$searched = TRUE;
$birth_day = Carbon::createFromFormat('d/m/Y', $request->date_of_birth)->format('Y-m-d');
if (!empty($birth_day)) {
array_push($filters, ['date_of_birth', '=', $birth_day]);
$criteria .= 'Born (' . $request->date_of_birth . ') ';
}
}
if (!empty($patient_number)) {
$searched = TRUE;
array_push($filters, ['number', 'LIKE', '%' . $patient_number . '%']);
$criteria .= 'Number (' . $patient_number . ') ';
}
if (!empty($first_name)) {
$searched = TRUE;
array_push($filters, ['first_name', 'LIKE', '%' . $first_name . '%']);
$criteria .= 'First name (' . $first_name . ') ';
}
if (!empty($last_name)) {
$searched = TRUE;
array_push($filters, ['last_name', 'LIKE', '%' . $last_name . '%']);
$criteria .= 'Last name (' . $last_name . ') ';
}
if (!empty($national_id)) {
$searched = TRUE;
array_push($filters, ['national_id', 'LIKE', '%' . $national_id . '%']);
$criteria .= 'National ID (' . $national_id . ') ';
}
if (!empty($phone_number)) {
$searched = TRUE;
array_push($filters, ['phone', 'LIKE', '%' . $phone_number . '%']);
$criteria .= 'Phone Number (' . $phone_number . ') ';
}
if (!empty($subcounty)) {
$searched = TRUE;
$subcounty_ids = DB::table('subcounties')->where('name', 'LIKE', '%' . $subcounty . '%')->pluck('id');
$criteria .= 'Subcounty (' . $subcounty . ') ';
}
if (!empty($parish)) {
$searched = TRUE;
$parish_ids = DB::table('parishes')->where('name', 'LIKE', '%' . $parish . '%')->pluck('id');
$criteria .= 'Parish (' . $parish . ') ';
}
if (!empty($village)) {
$searched = TRUE;
$village_ids = DB::table('villages')->where('name', 'LIKE', '%' . $village . '%')->pluck('id');
$criteria .= 'Village (' . $village . ') ';
}
if (!empty($insurance_group)) {
$searched = TRUE;
$insurance_group_ids = DB::table('insurance_groups')->where('name', 'LIKE', '%' . $insurance_group . '%')->pluck('id');
$criteria .= 'Insurance group (' . $insurance_group . ') ';
}
if (!empty($patient_category)) {
$searched = TRUE;
$patient_category_ids = DB::table('patient_categories')->where('name', 'LIKE', '%' . $patient_category . '%')->pluck('id');
$criteria .= 'Category (' . $patient_category . ') ';
}
if (!empty($filters)) {
$searched = TRUE;
if (!empty($subcounty_ids) || !empty($parish_ids) || !empty($village_ids) || !empty($insurance_group_ids) || !empty($patient_category_ids)) {
$patients = Patient::orderBy('first_name', 'asc')
->where($filters)
->whereIn('subcounty_id', $subcounty_ids)
->orWhereIn('parish_id', $parish_ids)
->orWhereIn('village_id', $village_ids)
->orWhereIn('insurance_group', $insurance_group_ids)
->orWhereIn('category_id', $patient_category_ids)
->paginate(200);
} else {
$patients = Patient::orderBy('first_name', 'asc')->where($filters)->paginate(200);
}
} elseif (!empty($subcounty_ids) || !empty($parish_ids) || !empty($village_ids) || !empty($insurance_group_ids) || !empty($patient_category_ids)) {
$patients = Patient::orderBy('first_name', 'asc')
->whereIn('subcounty_id', $subcounty_ids)
->orWhereIn('parish_id', $parish_ids)
->orWhereIn('village_id', $village_ids)
->orWhereIn('insurance_group', $insurance_group_ids)
->orWhereIn('category_id', $patient_category_ids)
->paginate(200);
}
$categories = DB::table('patient_categories')
->pluck("name", "id");
$marital_statuses = DB::table('marital_statuses')
->pluck("name", "id");
$occupations = DB::table('occupations')
->pluck('name', 'id');
$patient_numbers = DB::table('patients')
->orderBy('number')
->distinct()
->pluck('number');
$first_names = DB::table('patients')
->orderBy('first_name')
->distinct()
->pluck('first_name');
$last_names = DB::table('patients')
->orderBy('last_name')
->distinct()
->pluck('last_name');
$national_ids = DB::table('patients')
->orderBy('national_id')
->distinct()
->pluck('national_id');
$insurance_groups = DB::table('insurance_groups')
->orderBy('name')
->distinct()
->pluck('name');
$patient_categories = DB::table('patient_categories')
->orderBy('name')
->distinct()
->pluck('name');
$subcounties = DB::table('subcounties')
->orderBy('name')
->distinct()
->pluck('name');
$parishes = DB::table('parishes')
->orderBy('name')
->distinct()
->pluck('name');
$villages = DB::table('villages')
->orderBy('name')
->distinct()
->pluck('name');
if (count($patients) || $searched == TRUE) {
$categories = DB::table('patient_categories')->where('available', 1)->pluck("name", "id")->toArray();
$marital_statuses = DB::table('marital_statuses')->pluck("name", "id")->toArray();
$occupations = DB::table('occupations')->pluck('name', 'id')->toArray();
return view('patients::patients.selected', ['patient_count' => count($patients), 'criteria' => $criteria], compact('patients', 'categories', 'marital_statuses', 'occupations'));
} else {
return view('patients::patients.select', compact('subcounty_ids', 'categories', 'marital_statuses', 'occupations', 'patient_numbers', 'first_names', 'last_names', 'national_ids', 'insurance_groups', 'patient_categories', 'subcounties', 'parishes', 'villages'));
}
}
/**
* Display a listing of the inactive resource(s).
*/
public function inactive()
{
$patientCount = Patient::get()->count();
$patients = Patient::onlyTrashed()->orderBy('id', 'desc')->paginate(20);
$categories = PatientCategory::pluck("name", "id");
$marital_statuses = MaritalStatus::pluck("name", "id");
if (is_null($patients)) {
flash()->error("There is no inactive patient");
return redirect('/patients/');
} else {
return view('patients::patients.inactive', ['PatientCount' => $patientCount], compact('patients', 'categories', "marital_statuses"));
}
}
/**
* Activate the specified resource in storage.
*/
public function activate($id)
{
$patients = Patient::withTrashed()->where('id', $id)->get();
if (!is_null($patients)) {
$patient = $patients->first();
if ($patient->restore()) :
flash("Patient has been activated.")->success();
return redirect('/patients/inactive');
endif;
}
return redirect()->back()->withInput();
}
public function update_patient_info($id)
{
$patient = Patient::find($id);
if ($patient) {
$first_name = title_case($patient->first_name);
$last_name = title_case($patient->last_name);
$code = '<p><b>Patient Names:</b> ' . $first_name . ' ' . $last_name . '</p>';
$code .= '<p><b>Patient Number:</b> ' . $patient->number . '</p>';
$code .= '<p><b>Gender:</b> ' . ($patient->gender == 1 ? "Male" : "Female") . ' &nbsp;&nbsp;&nbsp;<b>Date of Birth:</b> ' . streamline_date($patient->date_of_birth) . '</p>';
$code .= '<p><b>Phone Number:</b> ' . $patient->phone . ' &nbsp;&nbsp;&nbsp;<b>Next of Kin:</b> ' . $patient->next_of_kin . ' (' . $patient->phone_of_next_of_kin . ')</p>';
$code .= '<p><b>Patient Category:</b> ' . get_name($patient->category_id, 'id', 'name', 'patient_categories') . '</p>';
$code .= '<p><b>Village:</b> ' . get_name($patient->village_id, 'id', 'name', 'villages') . '</p>';
} else {
$code = '<h3 style="color: red"><b>Patient Not Found</b></h3>';
}
return $code;
}
public function search_residences(Request $request)
{
$data = [];
$counter = 0;
if ($request->has('q')) {
$search = $request->q;
$districts = DB::table('districts')->whereNull('deleted_at')->where('name', 'LIKE', "%$search%")->get();
$counties = DB::table('counties')->whereNull('deleted_at')->where('name', 'LIKE', "%$search%")->get();
$subcounties = DB::table('subcounties')->whereNull('deleted_at')->where('name', 'LIKE', "%$search%")->get();
$parish = DB::table('parishes')->whereNull('deleted_at')->where('name', 'LIKE', "%$search%")->get();
$village = DB::table('villages')->whereNull('deleted_at')->where('name', 'LIKE', "%$search%")->get();
$districts_arr = DB::table('districts')->whereNull('deleted_at')->pluck('name', 'id')->toArray();
$counties_arr = DB::table('counties')->whereNull('deleted_at')->pluck('name', 'id')->toArray();
$subcounties_arr = DB::table('subcounties')->whereNull('deleted_at')->pluck('name', 'id')->toArray();
$parish_arr = DB::table('parishes')->whereNull('deleted_at')->pluck('name', 'id')->toArray();
$counties_rel_arr = DB::table('counties')->whereNull('deleted_at')->pluck('district_id', 'id')->toArray();
$subcounties_rel_arr = DB::table('subcounties')->whereNull('deleted_at')->pluck('county_id', 'id')->toArray();
$parish_rel_arr = DB::table('parishes')->whereNull('deleted_at')->pluck('subcounty_id', 'id')->toArray();
if (count($village) > 0) {
// village with name found
foreach ($village as $value) {
$parish_id = $value->parish_id;
$parish_name = $parish_arr[$parish_id] ?? '';
$subcounty_id = $parish_rel_arr[$parish_id] ?? 0;
$subcounty_name = $subcounties_arr[$subcounty_id] ?? '';
$county_id = $subcounties_rel_arr[$subcounty_id] ?? 0;
$county_name = $counties_arr[$county_id] ?? '';
$district_id = $counties_rel_arr[$county_id] ?? 0;
$district_name = $districts_arr[$district_id] ?? '';
$data[$counter]['ids'] = $value->id . "," . $parish_id . "," . $subcounty_id . "," . $county_id . "," . $district_id;
$data[$counter]['text'] = "Village: " . $value->name . " Parish: " . $parish_name . " Subcounty: " . $subcounty_name . " County: " . $county_name . " District: " . $district_name;
$counter++;
}
}
if (count($parish) > 0) {
// parish with name found
foreach ($parish as $value) {
$parish_name = $parish_arr[$value->id] ?? '';
$subcounty_id = $parish_rel_arr[$value->id] ?? 0;
$subcounty_name = $subcounties_arr[$subcounty_id] ?? '';
$county_id = $subcounties_rel_arr[$subcounty_id] ?? 0;
$county_name = $counties_arr[$county_id] ?? '';
$district_id = $counties_rel_arr[$county_id] ?? 0;
$district_name = $districts_arr[$district_id] ?? '';
$data[$counter]['ids'] = 0 . "," . $value->id . "," . $subcounty_id . "," . $county_id . "," . $district_id;
$data[$counter]['text'] = "Parish: " . $parish_name . " Subcounty: " . $subcounty_name . " County: " . $county_name . " District: " . $district_name;
$counter++;
}
}
if (count($subcounties) > 0) {
// subcounties with name found
foreach ($subcounties as $value) {
$subcounty_name = $subcounties_arr[$value->id] ?? '';
$county_id = $subcounties_rel_arr[$value->id] ?? 0;
$county_name = $counties_arr[$county_id] ?? '';
$district_id = $counties_rel_arr[$county_id] ?? 0;
$district_name = $districts_arr[$district_id] ?? '';
$data[$counter]['ids'] = 0 . "," . 0 . "," . $value->id . "," . $county_id . "," . $district_id;
$data[$counter]['text'] = "Subcounty: " . $subcounty_name . " County: " . $county_name . " District: " . $district_name;
$counter++;
}
}
if (count($counties) > 0) {
// counties with name found
foreach ($counties as $value) {
$county_name = $counties_arr[$value->id] ?? '';
$district_id = $counties_rel_arr[$value->id] ?? 0;
$district_name = $districts_arr[$district_id] ?? '';
$data[$counter]['ids'] = 0 . "," . 0 . "," . 0 . "," . $value->id . "," . $district_id;
$data[$counter]['text'] = "County: " . $county_name . " District: " . $district_name;
$counter++;
}
}
if (count($districts) > 0) {
// districts with name found
foreach ($districts as $value) {
// auto generate the rest of the variables
$district_name = $districts_arr[$value->id] ?? '';
$data[$counter]['ids'] = 0 . "," . 0 . "," . 0 . "," . 0 . "," . $value->id;
$data[$counter]['text'] = "District: " . $district_name;
$counter++;
}
}
}
return response()->json($data);
}
public function add_company(Request $request)
{
$company = new Company;
$company->name = $request->company_name;
$company->contact = $request->company_contact;
$company->slug = $request->company_identifier;
$company->created_by = auth()->user()->id;
try {
$company->save();
return $company->id;
} catch (QueryException $e) {
flash("An error occurred")->error();
return back()->withInput();
}
}
// add new country
public function add_country(Request $request)
{
// $country = new Country;
// $country->name = $request->name;
// $country->created_by = auth()->user()->id;
// try {
// $country->save();
// return $country->id;
// } catch (QueryException $e) {
// $errorCode = $e->errorInfo[1];
// if ($errorCode == 1062) {
// return response()->json(['error' => $e]);
// }
// }
// Check if the country already exists
$existingCountry = Country::where('name', $request->name)->first();
if ($existingCountry) {
return response()->json(['error' => 'Country already exists'], 409);
}
// Create a new Country instance
$country = new Country;
$country->name = $request->name;
$country->created_by = auth()->user()->id;
try {
// Save the country and return the ID
$country->save();
return $country->id;
} catch (QueryException $e) {
return response()->json(['error' => 'Database error occurred'], 500);
}
}
public function quick_add_district_residence(Request $request)
{
$district = new District;
$district->name = $request->new_residence_district_name;
$district->created_by = auth()->user()->id;
try {
$district->save();
return $district->id;
} catch (QueryException $e) {
flash("An error occurred")->error();
return back()->withInput();
}
}
public function quick_add_village_residence(Request $request)
{
$district_id = $request->residence_district_name;
$village = new Village;
$village->name = $request->new_residence_village_name;
$village->parish_id = 0; //$request->parish_id;
$village->created_by = auth()->user()->id;
try {
$village->save();
return $village->id;
} catch (QueryException $e) {
flash("An error occurred")->error();
return back()->withInput();
}
}
public function check_duplicate_patients(Request $request)
{
$result_count = 0;
$html_text = 0;
$patients = [];
if (isset($request->first_name) && isset($request->last_name)) {
$patients_one = DB::table('patients')
->where('first_name', 'LIKE', "%$request->first_name%")
->where('last_name', 'LIKE', "%$request->last_name%")
->get(["id", "first_name", "last_name", "number", "gender", "date_of_birth", "phone", "category_id"]);
$patients_two = DB::table('patients')
->where('first_name', 'LIKE', "%$request->last_name%")
->where('last_name', 'LIKE', "%$request->first_name%")
->get(["id", "first_name", "last_name", "number", "gender", "date_of_birth", "phone", "category_id"]);
$patients = $patients_one->merge($patients_two);
$result_count += count($patients);
}
if (isset($request->phone)) {
$patients_phone = DB::table('patients')
->where('phone', removeSpaces($request->phone))
->get(["id", "first_name", "last_name", "number", "gender", "date_of_birth", "phone", "category_id"]);
if (count($patients) > 0) {
$patients = $patients->merge($patients_phone);
} else {
$patients = $patients_phone;
}
$result_count += count($patients_phone);
}
if ($result_count > 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'> Gender </th>";
$html_text .= "<th style='color: black' class='text-center'> Age </th>";
$html_text .= "<th style='color: black' class='text-center'> Phone </th>";
$html_text .= "<th style='color: black' class='text-center'> Patient Category </th>";
$html_text .= "<th></th>";
$html_text .= "</tr>";
$categories = PatientCategory::pluck("name", "id");
foreach ($patients as $patient) {
$html_text .= "<tr>";
$html_text .= "<td>" . $patient->first_name . " " . $patient->last_name . " (" . $patient->number . ")" . "</td>";
$html_text .= "<td>" . (($patient->gender == 1) ? "Male" : "Female") . "</td>";
$html_text .= "<td>" . get_patients_age($patient->date_of_birth) . "</td>";
$html_text .= "<td>" . $patient->phone . "</td>";
$html_text .= "<td>" . (isset($categories[$patient->category_id]) ? $categories[$patient->category_id] : "N/A") . "</td>";
$html_text .= "<td><a href='/patient_episodes/set_patient_id/" . $patient->id . "' class='btn btn-rounded btn-primary btn-sm'><i class='fa fa-hand-pointer-o'></i> <strong>Select</strong></a></td>";
$html_text .= "</tr>";
}
$html_text .= "</table>";
}
return json_encode([
"results_count" => $result_count,
"html" => $html_text
]);
}
public function search_patient_by_name_number(Request $request)
{
$data = [];
if ($request->has('q')) {
$search = $request->q;
$data = DB::table('patients')->select("id", "first_name", "last_name", "number", "phone")
->where('last_name', 'LIKE', "%$search%")
->orWhere('first_name', 'LIKE', "%$search%")
->orWhere('number', 'LIKE', "%$search%")
->get();
}
return response()->json($data);
}
public function possible_duplicate_patients($id)
{
$possible_duplicate_patients = possible_patient_record_duplicates($id);
$original_patient = Patient::find($id);
$districts = DB::table('districts')->pluck('name', 'id');
$counties = DB::table('counties')->pluck('name', 'id');
$subcounties = DB::table('subcounties')->pluck('name', 'id');
$parishes = DB::table('parishes')->pluck('name', 'id');
$villages = DB::table('villages')->pluck('name', 'id');
$occupations = DB::table('occupations')->pluck('name', 'id');
$religions = DB::table('religions')->pluck('name', 'id');
$relationships = DB::table('family_relations')->pluck('name', 'id');
$last_episode = PatientEpisode::where('patient_id', $id)->orderBy('created_at', 'desc')->first();
return view('patients::patients.compare_patient_records', compact('original_patient', 'possible_duplicate_patients', 'districts', 'counties', 'subcounties', 'parishes', 'villages', 'occupations', 'religions', 'relationships', 'last_episode'));
}
public function display_original_and_duplicate_patients(Request $request)
{
$patient_id = $request->patient_id;
$patient = Patient::find($patient_id);
$html_text = "<table class='table table-bordered table-striped'>";
$html_text .= "<tr>";
$html_text .= "<td><input type='checkbox' name='all_duplicate_fields' id='all_duplicate_fields'> All values from " . get_full_name($patient->id, "id", "first_name", "last_name", "patients") . "</td><input name='duplicate_id' type='hidden' value='" . $patient->id . "'";
$html_text .= "</tr>";
$html_text .= "<tr>";
$html_text .= "<td><input type='radio' class='duplicate_radio' name='first_name' value=" . $patient->first_name . "> " . $patient->first_name . "</td>";
$html_text .= "</tr>";
$html_text .= "<tr>";
$html_text .= "<td><input type='radio' class='duplicate_radio' name='last_name' value=" . $patient->last_name . "> " . $patient->last_name . "</td>";
$html_text .= "</tr>";
$html_text .= "<tr>";
$gender = $patient->gender == 1 ? "Male" : "Female";
$html_text .= "<td><input type='radio' class='duplicate_radio' name='gender' value=" . $patient->gender . "> " . $gender . "</td>";
$html_text .= "</tr>";
$html_text .= "<tr>";
$html_text .= "<td><input type='radio' class='duplicate_radio' name='dob' value=" . $patient->date_of_birth . "> " . get_patients_age($patient->date_of_birth) . "</td>";
$html_text .= "</tr>";
$html_text .= "<tr>";
$html_text .= "<td><input type='radio' class='duplicate_radio' name='phone' value=" . $patient->phone . "> " . $patient->phone . "</td>";
$html_text .= "</tr>";
$html_text .= "<tr>";
$html_text .= "<td><input type='radio' class='duplicate_radio' name='category_id' value=" . $patient->category_id . "> " . get_name($patient->category_id, "id", "name", "patient_categories") . "</td>";
$html_text .= "</tr>";
$html_text .= "<tr>";
$html_text .= "<td><input type='radio' class='duplicate_radio' name='district_id' value=" . $patient->district_id . "> " . get_name($patient->district_id, "id", "name", "districts") . "</td>";
$html_text .= "</tr>";
$html_text .= "<tr>";
$html_text .= "<td><input type='radio' class='duplicate_radio' name='county_id' value=" . $patient->county_id . "> " . get_name($patient->county_id, "id", "name", "counties") . "</td>";
$html_text .= "</tr>";
$html_text .= "<tr>";
$html_text .= "<td><input type='radio' class='duplicate_radio' name='subcounty_id' value=" . $patient->subcounty_id . "> " . get_name($patient->subcounty_id, "id", "name", "subcounties") . "</td>";
$html_text .= "</tr>";
$html_text .= "<tr>";
$html_text .= "<td><input type='radio' class='duplicate_radio' name='parish_id' value=" . $patient->parish_id . "> " . get_name($patient->parish_id, "id", "name", "parishes") . "</td>";
$html_text .= "</tr>";
$html_text .= "<tr>";
$html_text .= "<td><input type='radio' class='duplicate_radio' name='village_id' value=" . $patient->village_id . "> " . get_name($patient->village_id, "id", "name", "villages") . "</td>";
$html_text .= "</tr>";
$html_text .= "</table>";
return json_encode([
"html" => $html_text
]);
}
public function merge_records(Request $request)
{
$patient_id_one = (int)$request->original_id;
$patient_id_two = (int)$request->duplicate_id;
//1.get the original and dupe patient ids
//2.the the original record with all selected fields to keep
//3.loop through the medical and finance tables updating the patient id.
//4.delete the duplicate
$patient_ids_array = [$patient_id_one, $patient_id_two];
$patient_id = min($patient_ids_array);
$patient_id_to_delete = max($patient_ids_array);
$patient = Patient::find($patient_id);
$patient->first_name = $request->first_name;
$patient->last_name = $request->last_name;
$patient->date_of_birth = $request->dob;
$patient->gender = $request->gender;
$patient->phone = removeSpaces($request->phone);
$patient->category_id = $request->category_id;
$patient->district_id = $request->district_id;
$patient->county_id = $request->county_id;
$patient->subcounty_id = $request->subcounty_id;
$patient->parish_id = $request->parish_id;
$patient->village_id = $request->village_id;
$patient->updated_by = Auth::user()->id;
if ($patient->update()) {
$delete_patient_record = Patient::find($patient_id_to_delete);
$delete_patient_record->delete();
//loop thru episodes
$patient_episodes = PatientEpisode::where('patient_id', $patient_id_to_delete)->get();
if (count($patient_episodes) > 0) {
foreach ($patient_episodes as $episode) {
$episode->patient_id = $patient_id;
$episode->update();
}
}
//loop through triage
$patient_triage = \Streamline\Models\Triage::where('patient_id', $patient_id_to_delete)->get();
if (count($patient_triage) > 0) {
foreach ($patient_triage as $triage) {
$triage->patient_id = $patient_id;
$triage->update();
}
}
//loop thru consultations
$patient_consultations = \Streamline\Models\Consultation::where('patient_id', $patient_id_to_delete)->get();
if (count($patient_consultations) > 0) {
foreach ($patient_consultations as $consultation) {
$consultation->patient_id = $patient_id;
$consultation->update();
}
}
//loop thru treatment
$patient_treatments = \Streamline\Models\Treatment::where('patient_id', $patient_id_to_delete)->get();
if (count($patient_treatments) > 0) {
foreach ($patient_treatments as $treatment) {
$treatment->patient_id = $patient_id;
$treatment->update();
}
}
//loop thru ordered invs
$patient_ordered_invs = \Streamline\Models\OrderedInvestigation::where('patient_id', $patient_id_to_delete)->get();
if (count($patient_ordered_invs) > 0) {
foreach ($patient_ordered_invs as $ordered_invs) {
$ordered_invs->patient_id = $patient_id;
$ordered_invs->update();
}
}
//loop thru investigation results
$investigation_results = \Streamline\Models\InvestigationResults::where('patient_id', $patient_id_to_delete)->get();
if (count($investigation_results) > 0) {
foreach ($investigation_results as $inv_results) {
$inv_results->patient_id = $patient_id;
$inv_results->update();
}
}
//loop thru ordered procedures
$patient_ordered_procedures = \Streamline\Models\OrderedProcedure::where('patient_id', $patient_id_to_delete)->get();
if (count($patient_ordered_procedures) > 0) {
foreach ($patient_ordered_procedures as $ordered_procedures) {
$ordered_procedures->patient_id = $patient_id;
$ordered_procedures->update();
}
}
//loop thru ordered sundries
$patient_ordered_sundries = \Streamline\Models\OrderedSundry::where('patient_id', $patient_id_to_delete)->get();
if (count($patient_ordered_sundries) > 0) {
foreach ($patient_ordered_sundries as $ordered_sundry) {
$ordered_sundry->patient_id = $patient_id;
$ordered_sundry->update();
}
}
//loop through ordered services
$patient_ordered_services = \Streamline\Models\OrderedService::where('patient_id', $patient_id_to_delete)->get();
if (count($patient_ordered_services) > 0) {
foreach ($patient_ordered_services as $ordered_services) {
$ordered_services->patient_id = $patient_id;
$ordered_services->update();
}
}
//loop through inpatient info
$inpatient_info_records = \Streamline\Models\InpatientInfo::where('patient_id', $patient_id_to_delete)->get();
if (count($inpatient_info_records) > 0) {
foreach ($inpatient_info_records as $inpatient_info) {
$inpatient_info->patient_id = $patient_id;
$inpatient_info->update();
}
}
//loop though inpatient bills
$inpatient_bills = \Streamline\Models\InpatientBill::where('patient_id', $patient_id_to_delete)->get();
if (count($inpatient_bills) > 0) {
foreach ($inpatient_bills as $inpatient_bill) {
$inpatient_bill->patient_id = $patient_id;
$inpatient_bill->update();
}
}
//loop though ward bed stays
$ward_bed_stay = \Streamline\Models\WardBedStay::where('patient_id', $patient_id_to_delete)->get();
if (count($ward_bed_stay) > 0) {
foreach ($ward_bed_stay as $bed_stay) {
$bed_stay->patient_id = $patient_id;
$bed_stay->update();
}
}
//loop though ward consultation and service
$ward_consultations_and_services = \Streamline\Models\WardConsultationsAndService::where('patient_id', $patient_id_to_delete)->get();
if (count($ward_consultations_and_services) > 0) {
foreach ($ward_consultations_and_services as $ward_consultation) {
$ward_consultation->patient_id = $patient_id;
$ward_consultation->update();
}
}
//loop though ward extras
$ward_extras = \Streamline\Models\WardExtra::where('patient_id', $patient_id_to_delete)->get();
if (count($ward_extras) > 0) {
foreach ($ward_extras as $ward_extra) {
$ward_extra->patient_id = $patient_id;
$ward_extra->update();
}
}
//loop though ward comments
$ward_comments = \Streamline\Models\WardInpatientSheetComment::where('patient_id', $patient_id_to_delete)->get();
if (count($ward_comments) > 0) {
foreach ($ward_comments as $ward_comment) {
$ward_comment->patient_id = $patient_id;
$ward_comment->update();
}
}
//loop though ward investigation pricing
$ward_investigation_pricing = \Streamline\Models\WardInvestigationPricing::where('patient_id', $patient_id_to_delete)->get();
foreach ($ward_investigation_pricing as $ward_inv_pricing) {
$ward_inv_pricing->patient_id = $patient_id;
$ward_inv_pricing->update();
}
//loop though ward procedures
$ward_procedures = \Streamline\Models\WardProcedure::where('patient_id', $patient_id_to_delete)->get();
foreach ($ward_procedures as $ward_procedure) {
$ward_procedure->patient_id = $patient_id;
$ward_procedure->update();
}
//loop though ward sundries
$ward_sundries = \Streamline\Models\WardSundryDispensation::where('patient_id', $patient_id_to_delete)->get();
foreach ($ward_sundries as $ward_sundry) {
$ward_sundry->patient_id = $patient_id;
$ward_sundry->update();
}
//loop though ward treatment
$ward_treatments = \Streamline\Models\WardTreatment::where('patient_id', $patient_id_to_delete)->get();
foreach ($ward_treatments as $ward_treatment) {
$ward_treatment->patient_id = $patient_id;
$ward_treatment->update();
}
$ward_treatment_dispensations = \Streamline\Models\WardTreatmentDispensation::where('patient_id', $patient_id_to_delete)->get();
foreach ($ward_treatment_dispensations as $ward_treatment_dispensation) {
$ward_treatment_dispensation->patient_id = $patient_id;
$ward_treatment_dispensation->update();
}
//loop through investigation deposits
$investigation_deposits = \Streamline\Models\InvestigationDeposit::where('patient_id', $patient_id_to_delete)->get();
foreach ($investigation_deposits as $inv_deposit) {
$inv_deposit->patient_id = $patient_id;
$inv_deposit->update();
}
//loop through treatment deposits
$treatment_deposits = \Streamline\Models\TreatmentDeposits::where('patient_id', $patient_id_to_delete)->get();
foreach ($treatment_deposits as $treatment_deposit) {
$treatment_deposit->patient_id = $patient_id;
$treatment_deposit->update();
}
//loop through service deposits
$service_deposits = \Streamline\Models\ServiceDeposit::where('patient_id', $patient_id_to_delete)->get();
foreach ($service_deposits as $service_deposit) {
$service_deposit->patient_id = $patient_id;
$service_deposit->update();
}
//loop through procedure deposits
$procedure_deposits = \Streamline\Models\ProcedureDeposit::where('patient_id', $patient_id_to_delete)->get();
foreach ($procedure_deposits as $procedure_deposit) {
$procedure_deposit->patient_id = $patient_id;
$procedure_deposit->update();
}
//loop through sundries deposits
$sundry_deposits = \Streamline\Models\SundryDeposit::where('patient_id', $patient_id_to_delete)->get();
foreach ($sundry_deposits as $sundry_deposit) {
$sundry_deposit->patient_id = $patient_id;
$sundry_deposit->update();
}
//loop through patient category invoice
$patient_category_invoices = \Streamline\Models\PatientCategoryInvoice::where('patient_id', $patient_id_to_delete)->get();
if (count($patient_category_invoices) > 0) {
foreach ($patient_category_invoices as $patient_category_invoice) {
$patient_category_invoice->patient_id = $patient_id;
$patient_category_invoice->update();
}
}
//loop through patient dependants incase they were category dependant
$does_patient_to_delete_category_have_threshold = does_patient_category_have_threshold(get_name($patient_id_to_delete, 'id', 'category_id', 'patients'));
$patient_is_a_dependant_of = patient_is_a_dependant_of($patient_id);
if ($does_patient_to_delete_category_have_threshold == true || !is_null($patient_is_a_dependant_of)) {
//the patient is on a patient dependants category if we go inside this "if" statement
$previous_main_dependant_to_delete = \Streamline\Models\CategoryPatientDependant::where('main_patient_id', $patient_id_to_delete)->first();
if ($previous_main_dependant_to_delete) {
$previous_main_dependant_to_delete->main_patient_id = $patient_id;
$previous_main_dependant_to_delete->update();
}
$record_where_duplicate_patient_is_dependant = \Streamline\Models\CategoryPatientDependant::whereRaw('FIND_IN_SET(' . $patient_id_to_delete . ',dependant_patient_ids)')->first();
if ($record_where_duplicate_patient_is_dependant) {
$array_with_new_patient_id = [];
$array_where_patient_to_delete_is_dependant = explode(",", $record_where_duplicate_patient_is_dependant->dependant_patient_ids);
for ($i = 0; $i < count($array_where_patient_to_delete_is_dependant); $i++) {
$member = $array_where_patient_to_delete_is_dependant[$i];
if ($array_where_patient_to_delete_is_dependant[$i] == $patient_id_to_delete) {
$member = $patient_id;
}
$array_with_new_patient_id[] = $member;
}
$record_where_duplicate_patient_is_dependant->dependant_patient_ids = implode(",", $array_with_new_patient_id);
$record_where_duplicate_patient_is_dependant->update();
}
$main_dependants_consumptions = \Streamline\Models\DependantsConsumption::where('main_patient_id', $patient_id_to_delete)->get();
if (count($main_dependants_consumptions)) {
foreach ($main_dependants_consumptions as $main_patient_consumption) {
$main_patient_consumption->main_patient_id = $patient_id;
$main_patient_consumption->update();
}
}
$dependants_consumptions = \Streamline\Models\DependantsConsumption::where('dependant_patient_id', $patient_id_to_delete)->get();
if (count($dependants_consumptions)) {
foreach ($dependants_consumptions as $consumption) {
$consumption->dependant_patient_id = $patient_id;
$consumption->update();
}
}
}
//loop through discounts
$discounts = \Streamline\Models\Discount::where('patient_id', $patient_id_to_delete)->get();
if (count($discounts) > 0) {
foreach ($discounts as $discount_record) {
$discount_record->patient_id = $patient_id;
$discount_record->update();
}
}
// TODO Refactor this merge to be in a separate controller and remove repeated table throughs by using one-to-many relationships https://stackoverflow.com/questions/77837354/implementing-one-to-many-relationship-in-laravel-eloquent/77837508
$tables = ['ward_inpatient_sheet_nurse_comments', 'patient_accounts_deposits', 'patient_dispensings', 'patient_accounts_refunds', 'prescription_errors', 'patient_messages_from_app', 'ward_investigation_pricings', 'patient_clinic_transfers', 'clinic_transfers', 'staff_performed_services', 'ward_inpatient_detailed_notes', 'patient_documents', 'patient_one_off_discounts', 'triage_nutrition', 'triage_news', 'surgeries', 'sundries_deposits', 'smart_triage', 'payrolls', 'patient_refunds', 'patient_account_consumptions', 'patient_appointments', 'phone_followup_patients', 'point_of_sale_records', 'cancelled_patient_opd_dispensations', 'procedure_deposits', 'cancel_patient_transactions', 'central_billing_deposits', 'chronic_patients', 'chi_deposits', 'debtors', 'debt_plan', 'family_account_consumptions', 'inpatient_attendant_passes', 'inpatient_ward_discounts', 'internal_ward_transfers', 'inpatient_sheet_audits', 'maternity_delivery_records', 'maternity_inpatients', 'mental_health_consultation', 'ordered_investigations', 'ordered_procedures'];
foreach ($tables as $table) {
$episodes = DB::table($table)->where('patient_id', $patient_id_to_delete)->get();
foreach ($episodes as $episode) DB::table($table)->where('id', $episode->id)->update(['patient_id' => $patient_id]);
}
$incoming_ward_charts = DB::table('incoming_ward_charts')->whereRaw('FIND_IN_SET(' . $patient_id_to_delete . ', patient_ids)')->get();
foreach ($incoming_ward_charts as $incoming_ward_chart) {
$episode_ids = explode(',', $incoming_ward_chart->patient_ids);
foreach ($episode_ids as $key => $episode_id) if ($episode_id == $patient_id_to_delete) $episode_ids[$key] = $patient_id;
DB::table('incoming_ward_charts')->where('id', $incoming_ward_chart->id)->update(['patient_ids' => implode(',', $episode_ids)]);
}
$category_patient_dependants = DB::table('category_patient_dependants')->whereRaw('FIND_IN_SET(' . $patient_id_to_delete . ', dependant_patient_ids)')->get();
foreach ($category_patient_dependants as $category_patient_dependant) {
$episode_ids = explode(',', $category_patient_dependant->dependant_patient_ids);
foreach ($episode_ids as $key => $episode_id) if ($episode_id == $patient_id_to_delete) $episode_ids[$key] = $patient_id;
DB::table('category_patient_dependants')->where('id', $category_patient_dependant->id)->update(['dependant_patient_ids' => implode(',', $episode_ids)]);
}
$main_patient_ids = DB::table('category_patient_dependants')->where('main_patient_id', $patient_id_to_delete)->get();
foreach ($main_patient_ids as $main_patient_id) DB::table('category_patient_dependants')->where('id', $main_patient_id->id)->update(['main_patient_id' => $patient_id]);
$family_members_ids = DB::table('family_accounts')->whereRaw('FIND_IN_SET(' . $patient_id_to_delete . ', family_members_ids)')->get();
foreach ($family_members_ids as $family_members_id) {
$episode_ids = explode(',', $family_members_id->family_members_ids);
foreach ($episode_ids as $key => $episode_id) if ($episode_id == $patient_id_to_delete) $episode_ids[$key] = $patient_id;
DB::table('family_accounts')->where('id', $family_members_id->id)->update(['family_members_ids' => implode(',', $episode_ids)]);
}
$family_head_ids = DB::table('family_accounts')->where('family_head_id', $patient_id_to_delete)->get();
foreach ($family_head_ids as $family_head_id) DB::table('family_accounts')->where('id', $family_head_id->id)->update(['family_head_id' => $patient_id]);
// update the session ids with the remaining one
session()->put('patient_id', $patient_id);
flash("Records have been merged")->success();
return redirect('/possible_duplicate_patients/' . $patient_id);
}
flash("Oops. Merge has failed. Contact your system admin")->error();
return redirect()->back()->withInput();
}
public function view_dna_patient_demographic(Request $request)
{
$patient_id = $request->patient_id;
$patient = Patient::withTrashed()->find($patient_id);
$code = "";
$x = 1;
if ($patient) {
$code .= "<tr>";
$code .= "<th><b>";
$code .= "Name:";
$code .= "</b></th>";
$code .= "<td>";
$code .= insurance_flag($patient->id);
$code .= "</td>";
$code .= "<th><b>";
$code .= "Number:";
$code .= "</b></th>";
$code .= "<td>";
$code .= $patient->number;
$code .= "</td>";
$code .= "</tr>";
$code .= "<tr>";
$code .= "<th><b>";
$code .= "Patient Category";
$code .= "</b></th>";
$code .= "<td>";
$code .= get_name($patient->category_id, "id", "name", "patient_categories");
$code .= "</td>";
$code .= "<th><b>";
$code .= "Phone Number";
$code .= "</b></th>";
$code .= "<td>";
$code .= $patient->phone;
$code .= "</td>";
$code .= "</tr>";
} else {
$code .= "<tr><td colspan='8'><h4>No record in the system</h4></td></tr>";
}
return $code;
}
public function delete_patient_with_reason(Request $request)
{
$patient = Patient::findOrFail($request->patient_id);
$patient->deleted_by = auth()->user()->id;
$patient->update();
$patient_deactivation_reasons = new \Streamline\Models\PatientDeactivationReason;
$patient_deactivation_reasons->patient_id = $request->patient_id;
$patient_deactivation_reasons->reason = $request->patient_deactivation_reasons;
$patient_deactivation_reasons->save();
if ($patient_deactivation_reasons->save() && $patient->delete()) {
flash("Patient has been deleted.")->success();
return 1;
} else {
return 0;
}
}
public function search(Request $request)
{
$patient_number_search = $request->number;
$village_search = $request->village;
$previous_id_search = $request->previous_id;
$full_name_search = $request->full_name;
$criteria = "";
$filters = [];
if ($patient_number_search) {
$filters[] = ['number', 'LIKE', '%' . $patient_number_search . '%'];
$criteria .= 'Number (' . $patient_number_search . ') ';
}
if ($previous_id_search) {
$filters[] = ['previous_id', 'LIKE', '%' . $previous_id_search . '%'];
$criteria .= 'Previous Number (' . $previous_id_search . ') ';
}
if ($full_name_search) {
$split_full_name_array = explode(' ', $full_name_search);
if (is_array($split_full_name_array)) {
$first_name_from_split = $split_full_name_array[0] ?? "";
$last_name_from_split = $split_full_name_array[1] ?? "";
$patient_number_from_split = count($split_full_name_array) > 2 ? array_slice($split_full_name_array, -3)[0] : '';
//just only use the patient number from the full name submitted
if ($patient_number_from_split != "") {
$filters[] = ['number', 'LIKE', '%' . $patient_number_from_split . '%'];
$criteria .= 'Number (' . $patient_number_from_split . ') ';
} else {
$filters[] = ['first_name', 'LIKE', '%' . $first_name_from_split . '%'];
$filters[] = ['last_name', 'LIKE', '%' . $last_name_from_split . '%'];
$criteria .= 'Name (' . $full_name_search . ') ';
}
} else {
//just only use the patient number from the full name submitted
$filters[] = ['first_name', 'LIKE', '%' . $full_name_search . '%'];
$criteria .= 'Name (' . $full_name_search . ') ';
}
}
if ($village_search) {
$village_id = DB::table('villages')->where(['name' => $village_search])->pluck('id')->first();
if (!empty($village_id)) {
$filters[] = ['village_id', 'LIKE', '%' . $village_id . '%'];
$criteria .= 'Village (' . $village_search . ') ';
}
}
if (empty($criteria)) :
$criteria = 'No results found for search';
$patients = DB::table('patients')->whereNull('deleted_at')
->orderBy('created_at', 'desc')->paginate(100);
else :
$patients = DB::table('patients')->whereNull('deleted_at')->where($filters)
->orderBy('created_at', 'desc')->paginate(100);
endif;
$categories = DB::table('patient_categories')->pluck("name", "id");
$villages = DB::table('villages')->pluck("name", "id")->toArray();
$previous_ids = DB::table('patients')->whereNull('deleted_at')
->distinct()->pluck('previous_id');
$patient_numbers = DB::table('patients')->whereNull('deleted_at')
->pluck('number');
$full_names = DB::table('patients')->whereNull('deleted_at')
->select(DB::raw('CONCAT(first_name, " ", last_name, " - ", number, " - (", phone, ")") AS full_name'))
->pluck("full_name");
return view('patients::patients.index', compact('patients', 'categories', 'patient_numbers', 'villages', 'previous_ids', 'full_names', 'criteria'))
->with('i', (request()->input('page', 1) - 1) * 5);
}
public function get_fingerprint($id)
{
$patient = DB::table('patients')->where('id', $id)->first();
if ($patient && $patient->fingerprint_template) {
return $patient->fingerprint_template;
} else {
return "0";
}
}
public function fetch_fingerprint_from_scanner()
{
$response = Http::get('http://localhost:13124/cams/fp-scanner/capture?sendimage=1&apikey=' . get_fingerprint_key());
$scanner_response = json_decode($response, true);
$template = $scanner_response["ApiRequestInfo"]["OperationData"]["Signature"][0]["Template"];
$pngImage = $scanner_response["ApiRequestInfo"]["OperationData"]["Signature"][0]["Image"];
$error_code = $scanner_response["ScannerError"]["errorCode"];
$error_message = $scanner_response["ScannerError"]["errorString"];
return json_encode([
"template" => $template,
"image" => $pngImage,
"error_code" => $error_code,
"error_message" => $error_message,
]);
}
public function compare_fingerprint_from_scanner(Request $request)
{
$fingerprint_template = $request->fingerprint_template;
$saved_fingerprint_template = $request->saved_fingerprint_template;
$response = Http::get('http://localhost:13124/cams/fp-scanner/compare?apikey=' . get_fingerprint_key() . '&tmpl1=' . $fingerprint_template . '&tmpl2=' . $saved_fingerprint_template);
$scanner_response = json_decode($response, true);
$score = $scanner_response["ApiRequestInfo"]["OperationData"]["Score"];
$error_code = $scanner_response["ScannerError"]["errorCode"];
$error_message = $scanner_response["ScannerError"]["errorString"];
return json_encode([
"score" => $score,
"error_code" => $error_code,
"error_message" => $error_message,
]);
}
public function patient_cards(Request $request){
$patients = $this->patientCardsService->getPatientCardsToday($request);
if ($patients->isEmpty()) {
$patients = new LengthAwarePaginator([], 0, 200);
} else {
$patients = $patients->toQuery()->paginate(200);
}
return view('patients::patients/patient_cards_list', compact('patients'));
}
public function search_patient_cards_to_print(Request $request){
$patients_data = $this->patientCardsService->searchPatientCardsToPrint($request);
$searched_data_string = $patients_data['searched_data_string'];
$patients = $patients_data['patients'];
if ($patients->isEmpty()) {
$patients = new LengthAwarePaginator([], 0, 200);
} else {
$patients = $patients->toQuery()->paginate(200);
}
return view('patients::patients/searched_patient_cards', compact('patients','searched_data_string'));
}
public function patient_card($id)
{
$patient = Patient::find($id);
$hospital_details = HospitalInformation::first();
$data = [
'hospitalInfo' => $hospital_details,
'patient' => $patient
];
//dompdf
$pdf_card = new DomPDF();
$html = view('patients::patients/patient_card',compact('data'))->render();
$pdf_card = DomPDF::loadHtml($html);
$pdf_card->setPaper('A4', 'potrait');
$options = [
'isPhpEnabled' => true,
'isHtml5ParserEnabled' => true,
// Add more options
];
DomPDF::setOptions($options);
return $pdf_card->stream('Patient Card.pdf');
}
public function print_patients_cards(Request $request){
$patient_cards = $this->patientCardsService->printPatientCardsList($request);
$hospital_details = HospitalInformation::first();
$pdf_cards = new DomPDF();
$html = view('patients::patients/print_patients_cards',compact('patient_cards','hospital_details'))->render();
$pdf_cards = DomPDF::loadHtml($html);
$pdf_cards->setPaper('A4', 'potrait');
$options = [
'isPhpEnabled' => true,
'isHtml5ParserEnabled' => true,
// Add more options
];
DomPDF::setOptions($options);
return $pdf_cards->stream('Patient Cards.pdf', array('Attachment' => false));
}
}