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 resource.
*
* @return \Illuminate\Http\Response
*/
public function index() {
$patientCount = Patient::count();
$patients = Patient::orderBy('created_at', 'desc')->paginate(100);
$categories = PatientCategory::pluck("name", "id");
$marital_statuses = MaritalStatus::pluck("name", "id");
$patient_villages = Village::pluck("name", "id");
$patient_numbers = Patient::orderBy('number')->distinct()->pluck('number');
$first_names = [];//Patient::orderBy('first_name')->distinct()->pluck('first_name');
$last_names = [];//Patient::orderBy('last_name')->distinct()->pluck('last_name');
$villages = Village::orderBy('name')->distinct()->pluck('name');
$full_names = Patient::all(['first_name', 'last_name', 'number', 'phone'])->pluck("full_name");
return view('patients::patients.index', compact('patients', 'patientCount', 'categories', 'marital_statuses', 'patient_villages', 'patient_numbers', 'first_names', 'last_names', 'villages', 'full_names'))
->with('i', (request()->input('page', 1) - 1) * 5);
}
/**
* Show the form for creating a new resource.
*
*/
public function create() {
$occupations = Occupation::orderBy('name')->pluck('name', 'id')->toArray();
$patient_categories = PatientCategory::where('available', 1)->orderby('name')->pluck('name', 'id')->toArray();
//$districts = District::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();
$occupations = ['' => '- select -'] + $occupations;
$districts = [];// ['' => '- select -'] + $districts;
$religions = ['' => '- select -'] + $religions;
$relationships = ['' => '- select -'] + $relationships;
$dynamic_counties = [];// County::all(['id', 'name', 'district_id'])->pluck("name_with_district", "id")->prepend('- select -', '')->toArray();
$dynamic_sub_counties = [];// Subcounty::all(['id', 'name', 'county_id'])->pluck("name_with_county", "id")->prepend('- select -', '')->toArray();
$dynamic_parishes = []; // Parish::all(['id', 'name', 'subcounty_id'])->pluck("name_with_subcounty", "id")->prepend('- select -', '')->toArray();
$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'));
}
/**
* 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'
]);
// 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->language = $request->language;
$patient->lc_one = $request->lc_one;
$patient->fingerprint_template = $request->fingerprint_template ?? NULL;
$patient->created_by = Auth::user()->id;
if ($patient->save()):
$prefix = DB::table('hospital_information')->where('id', 1)->value('patient_number_abbr');
$new_id = quadLimit($patient->id);
$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
* @return \Illuminate\Http\Response
*/
public function show($id) {
$patient = Patient::withTrashed()->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('id',$id)->orderBy('created_at', 'desc')->first();
return view('patients::patients.show', compact('patient', 'districts', 'counties', 'subcounties', 'parishes', 'villages', 'occupations', 'religions', 'relationships', 'last_episode'));
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
*/
public function edit($id) {
$patient = Patient::where(['id' => $id])->first();
if (is_null($patient->date_of_birth)) {
$dob = "01/01/2020";
} else {
$dob = date_format($patient->date_of_birth, '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();
$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_categories', 'episodes', 'districts', 'marital_statuses', 'religions', 'relationships', 'countries', 'companies'));
}
/**
* 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([
'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->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;
/* ===== 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);
return redirect()->back()->withInput();
} else {
flash("There was an error")->error();
}
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id) {
$patient = Patient::find($id);
// $patient->deleted_by = auth()->user()->id;
// $patient->update();
if ($patient->delete()):
flash("Patient has been deleted.")->success();
return redirect('patients/');
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'));
}
}
public function get_counties($id) {
$code = "";
$counties = DB::table('counties')
->whereNull('deleted_at')
->where(['district_id' => $id])
->get();
foreach ($counties as $county) {
$code .= "";
}
return $code;
}
public function get_subcounties($id) {
$code = "";
$subcounties = DB::table('subcounties')
->whereNull('deleted_at')
->where(['county_id' => $id])
->get();
foreach ($subcounties as $subcounty) {
$code .= "";
}
$code .= "";
return $code;
}
public function get_parishes($id) {
$code = "";
$parishes = DB::table('parishes')
->whereNull('deleted_at')
->where(['subcounty_id' => $id])
->get();
foreach ($parishes as $parish) {
$code .= "";
}
return $code;
}
public function get_villages($id) {
$code = "";
$villages = DB::table('villages')
->whereNull('deleted_at')
->where(['parish_id' => $id])
->get();
foreach ($villages as $village) {
$code .= "";
}
return $code;
}
/**
* Display a listing of the inactive resource(s).
*
* @return \Illuminate\Http\Response
*/
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.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function activate($id) {
//dd('inn here');
$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;
}
}
/*
* get patient residences and send corresponding drop down options
*/
public function get_residence($district_id) {
//loop is going to take long execution time
$villages_array = [];
$parishes_array = [];
$subcounties_array = [];
$counties = DB::table('counties')->where(['district_id' => $district_id])->whereNull('deleted_at')->pluck("name", "id");
foreach ($counties as $county_id => $county_name) {
$subcounties = DB::table('subcounties')->where(['county_id' => $county_id])->whereNull('deleted_at')->get();
foreach ($subcounties as $subcounty) {
$subcounties_array[$subcounty->id] = $subcounty->name;
$parishes = DB::table('parishes')->where(['subcounty_id' => $subcounty->id])->whereNull('deleted_at')->get();
foreach ($parishes as $parish) {
$parishes_array[$parish->id] = $parish->name;
$villages = DB::table('villages')->where(['parish_id' => $parish->id])->whereNull('deleted_at')->get();
foreach ($villages as $village) {
$villages_array[$village->id] = $village->name;
}
}
}
}
return ['subcounties' => $subcounties_array, 'parishes' => $parishes_array, 'villages' => $villages_array];
}
public function get_residence_district($district_id) {
//loop is going to take long execution time
$villages_array = [];
$parishes_array = [];
$sub_counties_array = [];
$counties_array = [];
$residences_array = [];
$counties = DB::table('counties')->where(['district_id' => $district_id])->whereNull('deleted_at')->orderBy("name","asc")->pluck("name", "id");
foreach ($counties as $county_id => $county_name) {
$counties_array[$county_id] = $county_name;
$subcounties = DB::table('subcounties')->where(['county_id' => $county_id])->whereNull('deleted_at')->get();
foreach ($subcounties as $subcounty) {
$sub_counties_array[$subcounty->id] = $subcounty->name;
$parishes = DB::table('parishes')->where(['subcounty_id' => $subcounty->id])->whereNull('deleted_at')->get();
foreach ($parishes as $parish) {
$parishes_array[$parish->id] = $parish->name;
$villages = DB::table('villages')->where(['parish_id' => $parish->id])->whereNull('deleted_at')->get();
foreach ($villages as $village) {
$villages_array[$village->id] = $village->name;
}
}
}
}
$residences_array['counties'] = $counties_array;
$residences_array['subcounties'] = $sub_counties_array;
$residences_array['parishes'] = $parishes_array;
$residences_array['villages'] = $villages_array;
return json_encode($residences_array);
}
public function get_residence_county($county_id) {
//loop is going to take long execution time
$villages_array = [];
$parishes_array = [];
$sub_counties_array = [];
$residences_array = [];
$subcounties = DB::table('subcounties')->where(['county_id' => $county_id])->whereNull('deleted_at')->orderBy("name","asc")->get();
foreach ($subcounties as $subcounty) {
$sub_counties_array[$subcounty->id] = $subcounty->name;
$parishes = DB::table('parishes')->where(['subcounty_id' => $subcounty->id])->whereNull('deleted_at')->get();
foreach ($parishes as $parish) {
$parishes_array[$parish->id] = $parish->name;
$villages = DB::table('villages')->where(['parish_id' => $parish->id])->whereNull('deleted_at')->get();
foreach ($villages as $village) {
$villages_array[$village->id] = $village->name;
}
}
}
$residences_array['subcounties'] = $sub_counties_array;
$residences_array['parishes'] = $parishes_array;
$residences_array['villages'] = $villages_array;
return json_encode($residences_array);
}
public function get_residence_sub_county($sub_county_id) {
//loop is going to take long execution time
$villages_array = [];
$parishes_array = [];
$residences_array = [];
$parishes = DB::table('parishes')->where(['subcounty_id' => $sub_county_id])->whereNull('deleted_at')->orderBy("name","asc")->get();
foreach ($parishes as $parish) {
$parishes_array[$parish->id] = $parish->name;
$villages = DB::table('villages')->where(['parish_id' => $parish->id])->whereNull('deleted_at')->get();
foreach ($villages as $village) {
$villages_array[$village->id] = $village->name;
}
}
$residences_array['parishes'] = $parishes_array;
$residences_array['villages'] = $villages_array;
return json_encode($residences_array);
}
public function get_residence_parish($parish_id) {
//loop is going to take long execution time
$villages_array = [];
$residences_array = [];
$villages = DB::table('villages')->where(['parish_id' => $parish_id])->whereNull('deleted_at')->orderBy("name","asc")->get();
foreach ($villages as $village) {
$villages_array[$village->id] = $village->name;
}
$residences_array['villages'] = $villages_array;
return json_encode($residences_array);
}
/* cater for adding a new occupation from a modal dynamically */
public function add_new_occupation_dynamically(Request $request)
{
$occupation = new Occupation;
$occupation->name = $request->name;
$occupation->created_by = Auth::user()->id;
$occupation->updated_by = Auth::user()->id;
try {
$occupation->save();
return $occupation->id;
} catch (QueryException $e) {
$errorCode = $e->errorInfo[1];
if ($errorCode == 1062) { //error code for duplicate entry to a unique field
flash($request->name . " Occupation already exists!")->error();
return back()->withInput();
}
}
}
public function add_new_district_dynamically(Request $request)
{
$district = new District;
$district->name = $request->name;
$district->created_by = Auth::user()->id;
$district->updated_by = Auth::user()->id;
$check = District::where('name', $request->name)->pluck('name')->first();
if(is_null($check)){
try {
$district->save();
return $district->id;
} catch (QueryException $e) {
$errorCode = $e->errorInfo[1];
if ($errorCode == 1062) { //error code for duplicate entry to a unique field
flash($request->name . " District already exists!")->error();
return back()->withInput();
}
}
}else{
return 'false';
}
}
public function add_new_county_dynamically(Request $request)
{
$county = new County;
$county->name = $request->name;
$county->district_id = $request->district_id;
$county->created_by = Auth::user()->id;
$county->updated_by = Auth::user()->id;
$check = County::where('name', $request->name)->pluck('name')->first();
if(is_null($check)){
try {
$county->save();
return $county->id;
} catch (QueryException $e) {
$errorCode = $e->errorInfo[1];
if ($errorCode == 1062) { //error code for duplicate entry to a unique field
flash($request->name . " Occupation already exists!")->error();
return back()->withInput();
}
}
}else{
return 'false';
}
}
public function add_new_subcounty_dynamically(Request $request)
{
$sub_county = new Subcounty;
$sub_county->name = $request->name;
$sub_county->county_id = $request->county_id;
$sub_county->created_by = Auth::user()->id;
$sub_county->updated_by = Auth::user()->id;
$check = Subcounty::where('name', $request->name)->pluck('name')->first();
if(is_null($check)){
try {
$sub_county->save();
return $sub_county->id;
} catch (QueryException $e) {
$errorCode = $e->errorInfo[1];
if ($errorCode == 1062) { //error code for duplicate entry to a unique field
flash($request->name . " Occupation already exists!")->error();
return back()->withInput();
}
}
}else{
return 'false';
}
}
public function add_new_parish_dynamically(Request $request)
{
$parish = new Parish;
$parish->name = $request->name;
$parish->subcounty_id = $request->subcounty_id;
$parish->created_by = Auth::user()->id;
$parish->updated_by = Auth::user()->id;
$check = Parish::where('name', $request->name)->pluck('name')->first();
if(is_null($check)){
try {
$parish->save();
return $parish->id;
} catch (QueryException $e) {
$errorCode = $e->errorInfo[1];
if ($errorCode == 1062) { //error code for duplicate entry to a unique field
flash($request->name . " Occupation already exists!")->error();
return back()->withInput();
}
}
}else{
return 'false';
}
}
public function add_new_village_dynamically(Request $request)
{
$village = new Village;
$village->name = $request->name;
$village->parish_id = $request->parish_id;
$village->created_by = Auth::user()->id;
$village->updated_by = Auth::user()->id;
$check = Village::where('name', $request->name)->pluck('name')->first();
if(is_null($check)){
try {
$village->save();
return $village->id;
} catch (QueryException $e) {
$errorCode = $e->errorInfo[1];
if ($errorCode == 1062) { //error code for duplicate entry to a unique field
flash($request->name . " Occupation already exists!")->error();
return back()->withInput();
}
}
}else{
return 'false';
}
}
public function follow_up(){
$follow_ups = PatientAppointment::where('is_confirmed', 1)->get();
$calender_dates = [];
$count = 0;
foreach ($follow_ups as $follow_up){
$patient_name = get_full_name($follow_up->patient_id, 'id', 'first_name', 'last_name', 'patients');
$calender_dates[$count] = ["title" => $patient_name, "start" => $follow_up->appointment_date . "T" . $follow_up->appointment_time];
$count++;
}
$clinics = Clinic::orderBy('name')->pluck("name", "id")->toArray();
$clinics = ['0' => 'All Clinics'] + $clinics;
$users = User::orderBy('first_name')->select("id", "first_name", "last_name")->get();
$users_array = [];
$users_collection = DB::table('users')->orderBy("first_name","asc")->select("id")->get()->toArray();
foreach ($users_collection as $value){
$user = User::find($value->id);
if (!is_null($user)) {
if ($user->hasRole('Doctors') || $user->hasRole('Doctor')) {
//use this join query instead of the commented out query to cater for execution speed (N+1)
$consultation_records = DB::table('services')
->join('staff_payment_configurations','staff_payment_configurations.item_id', '=', 'services.id')
->where('services.item_type', 'Consultation')
->where('staff_payment_configurations.user_id',$value->id)
->where('staff_payment_configurations.item_category',3)
->orderBy('staff_payment_configurations.created_at','asc')
->select('services.*')
->get();
foreach ($consultation_records as $record) {
$users_consultation_fee = $record->non_insured_price;
//concatnate the service_record_id with the users id to form the key for the array
$users_array[$record->id."__".$value->id] = get_full_name($value->id, 'id', 'first_name', 'last_name', 'users')." (Consultation Fee: ".ugandan_shillings($users_consultation_fee).")";
}
}
}
}
$users_array = ['' => '- select -'] + $users_array;
$special_clinics = DB::table('clinics')->where('available', 1)->whereNull('deleted_at')->pluck("name", "id")->prepend('- select -', '');
return view('patients::patients.follow_up', compact('calender_dates', 'clinics', 'users', 'users_array', 'special_clinics'));
}
public function follow_up_fetch_patients(Request $request){
$selected_date = $request->selected_date;
if ($request->user_id != 0){
$follow_ups = PatientAppointment::where(['appointment_date' => $selected_date])->where(['incharge_id' => $request->user_id])->get();
} else {
$follow_ups = PatientAppointment::where(['appointment_date' => $selected_date])->get();
}
$code = "";
if ($follow_ups->count() > 0){
foreach ($follow_ups as $follow_up){
if ($request->clinic_id != -1){
if ($follow_up->clinic_allocation != $request->clinic_id){
// skip current loop
continue;
}
}
$code .= "
";
$code .= "| ";
$code .= get_full_name($follow_up->patient_id, 'id', 'first_name', 'last_name', 'patients') . " (" . get_name($follow_up->patient_id, 'id', 'number', 'patients') . ")";
$code .= " | ";
$code .= "";
$code .= ($follow_up->clinic_allocation == 0) ? "No clinic specified" : get_name($follow_up->clinic_allocation, 'id', 'name', 'clinics');
$code .= " | ";
$code .= "";
$code .= ($follow_up->incharge_id == 0) ? "No incharge specified" : get_full_name($follow_up->incharge_id, 'id', 'first_name', 'last_name', 'users');
$code .= " | ";
$code .= "";
$code .= $follow_up->appointment_time;
$code .= " | ";
$code .= "";
$code .= "Phone Number: " . get_name($follow_up->patient_id, 'id', 'phone', 'patients') . " Email: " . get_name($follow_up->patient_id, 'id', 'email', 'patients');
$code .= " | ";
$code .= "";
$code .= is_null($follow_up->comments) ? 'N/A' : $follow_up->comments;
$code .= " | ";
$code .= "";
if ($follow_up->appointment_fulfilled == 1){
$code .= "";
} else if ($follow_up->appointment_fulfilled == 2){
$code .= "";
} else {
$code .= "Actions";
}
$code .= " | ";
$code .= "
";
}
} else {
$code .= "No patient appointments available for this date |
";
}
// check if the code is empty for when clinics selected are not available
if ($code == ''){
$code .= "No patient appointments available for this date |
";
}
return $code;
}
public function create_appointment(){
$clinics = Clinic::orderBy('name')->pluck("name", "id")->toArray();
$clinics = ['0' => "Don't assign clinic"] + $clinics;
$users = User::orderBy('first_name')->select("id", "first_name", "last_name")->get();
return view('patients::patients.create_appointment', compact('clinics', 'users'));
}
public function save_appointment(Request $request){
$appointment = new PatientAppointment();
if (is_null($request->in_charge)){
$in_charge = 0;
} else {
$in_charge = $request->in_charge;
}
if (is_null($request->clinic_allocation)){
$clinic_allocation = 0;
} else {
$clinic_allocation = $request->clinic_allocation;
}
$appointment->patient_id = $request->patient_id;
$appointment->incharge_id = $in_charge;
$appointment->clinic_allocation = $clinic_allocation;
$appointment->episode_id = 0;
$appointment->appointment_date = Carbon::parse($request->appointment_date)->format('Y-m-d');
$appointment->appointment_time = $request->appointment_time;
$appointment->comments = $request->comments;
$appointment->created_from = "Patient Appointments";
$appointment->created_by = Auth::user()->id;
$appointment->updated_by = Auth::user()->id;
if ($appointment->save()){
flash("Patient appointment has been saved")->success();
return redirect("/patients/follow_up");
} else {
flash("An error occurred!")->error();
return back()->withInput();
}
}
public function complete_appointment($id) {
$appointment = PatientAppointment::find($id);
$patient_id = $appointment->patient_id;
// reassign the appointment_fulfilled to 1
$appointment->appointment_fulfilled = 1;
$appointment->updated_by = Auth::user()->id;
if ($appointment->save()){
/*==== create a new episode but attached to the original episode as appointment is started/activated ========*/
$episode = new PatientEpisode;
$episode->patient_id = $appointment->patient_id;
$episode->parent_episode_id = $appointment->episode_id == 0 ? null : $appointment->episode_id;//the original episode_id
$episode->created_by = auth()->user()->id;
$episode->updated_by = auth()->user()->id;
//put this patient_id into session
session()->put('patient_id', $patient_id);
try {
$episode->save();
flash("A new episode has been saved")->success();
//if the parent episode was an ANC visit then create a copy of previous anc registration and attach it to this episode
$previous_anc_visit = \Streamline\Models\AnteNatalClinicFollowup::where(['patient_id' => $episode->patient_id, 'episode_id' => $episode->parent_episode_id])->first();
if ($previous_anc_visit) {
create_anc_registration_record_from_previous_visit($patient_id, $episode->parent_episode_id, $episode->id);
//allocate to ANC clinic straight away
$anc_clinic_id = get_name('ante_natal', 'slug', 'id', 'clinics');
$episode->clinic_id = $anc_clinic_id;
$episode->update();
}
// check where the function was called from and return there
if (isset($request->is_from_finance)) {
// return to finance home
return redirect('/patient_finance/home');
} else {
// return to normal patient home
return redirect('/patient_episodes/');
}
} catch (QueryException $e) {
$errorCode = $e->errorInfo[1];
if ($errorCode == 1062) { //error code for duplicate entry to a unique field
flash("This episode already exists!")->error();
return back()->withInput();
}
}
/*================= end of creation of new episode on starting an appointment =================*/
flash("Patient follow up completed successfully")->success();
return redirect('/patient_episodes/set_patient_id/' . $patient_id);
} else {
flash("An error occurred!")->error();
return back()->withInput();
}
}
public function cancel_patient_appointment($id) {
$appointment = PatientAppointment::find($id);
// reassign the appointment_fulfilled to 2, indicating cancelled
$appointment->appointment_fulfilled = 2;
$appointment->updated_by = Auth::user()->id;
if ($appointment->save()){
return 1;
} else {
return 0;
}
}
public function reschedule_appointment($id) {
$appointment = PatientAppointment::find($id);
$clinics = Clinic::orderBy('name')->pluck("name", "id")->toArray();
$clinics = ['0' => "Don't assign clinic"] + $clinics;
$users = User::orderBy('first_name')->select("id", "first_name", "last_name")->get();
return view('patients::patients.reschedule_appointment', compact('appointment', 'clinics', 'users'));
}
public function save_rescheduled_appointment(Request $request){
$appointment = PatientAppointment::find($request->appointment_id);
if (is_null($request->in_charge)){
$in_charge = 0;
} else {
$in_charge = $request->in_charge;
}
if (is_null($request->clinic_allocation)){
$clinic_allocation = 0;
} else {
$clinic_allocation = $request->clinic_allocation;
}
$appointment->incharge_id = $in_charge;
$appointment->clinic_allocation = $clinic_allocation;
$appointment->appointment_date = Carbon::parse($request->appointment_date)->format('Y-m-d');
$appointment->appointment_time = $request->appointment_time;
$appointment->comments = $request->comments;
$appointment->updated_by = Auth::user()->id;
if ($appointment->save()){
flash("Patient appointment has been rescheduled successfully")->success();
return redirect("/patients/follow_up");
} else {
flash("An error occurred!")->error();
return back()->withInput();
}
}
public function appointment_requests() {
$appointments = PatientAppointment::where('is_confirmed', 0)
->whereNotIn('appointment_fulfilled', [2])
->where('appointment_date', '>', date('Y-m-d'))
->get();
return view('patients::patients.appointment_requests', compact('appointments'));
}
public function confirm_appointment($id) {
$appointment = PatientAppointment::find($id);
$clinics = Clinic::orderBy('name')->pluck("name", "id")->toArray();
$clinics = ['0' => "Don't assign clinic"] + $clinics;
$users = User::orderBy('first_name')->select("id", "first_name", "last_name")->get();
return view('patients::patients.confirm_appointment', compact('appointment', 'clinics', 'users'));
}
public function save_confirmed_appointment(Request $request) {
$appointment = PatientAppointment::find($request->appointment_id);
if (is_null($request->in_charge)){
$in_charge = 0;
} else {
$in_charge = $request->in_charge;
}
if (is_null($request->clinic_allocation)){
$clinic_allocation = 0;
} else {
$clinic_allocation = $request->clinic_allocation;
}
$appointment->incharge_id = $in_charge;
$appointment->clinic_allocation = $clinic_allocation;
$appointment->appointment_date = Carbon::parse($request->appointment_date)->format('Y-m-d');
$appointment->appointment_time = $request->appointment_time;
$appointment->comments = $request->comments;
$appointment->is_confirmed = 1;
$appointment->updated_by = auth()->id();
if ($appointment->save()){
if (is_sms_enabled()) {
// send sms alert to the patient
$sms = "Your appointment at " . get_name(1, 'id', 'name', 'hospital_information') .
" has been confirmed for the " . streamline_date($appointment->appointment_date) . " at " . $appointment->appointment_time;
(new SMSController)->send_appointments_alert($appointment->patient_id, $sms);
}
flash("Patient appointment has been confirmed")->success();
return redirect("/patients/appointment_requests");
} else {
flash("An error occurred!")->error();
return 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 = 'Patient Names: ' . $first_name . ' ' . $last_name . '
';
$code .= 'Patient Number: ' . $patient->number . '
';
$code .= 'Gender: ' . ($patient->gender == 1 ? "Male" : "Female"). ' Date of Birth: ' . streamline_date($patient->date_of_birth) . '
';
$code .= 'Phone Number: ' . $patient->phone . ' Next of Kin: ' . $patient->next_of_kin . ' ('.$patient->phone_of_next_of_kin. ')
';
$code .= 'Patient Category: ' . get_name($patient->category_id, 'id', 'name', 'patient_categories') . '
';
$code .= 'Village: ' . get_name($patient->village_id, 'id', 'name', 'villages') . '
';
} else {
$code = 'Patient Not Found
';
}
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) {
$errorCode = $e->errorInfo[1];
if ($errorCode == 1062) { //error code for duplicate entry to a unique field
return response()->json(['error' => $e]);
}
}
}
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) {
$errorCode = $e->errorInfo[1];
if ($errorCode == 1062) { //error code for duplicate entry to a unique field
return response()->json(['error' => $e]);
}
}
}
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) {
$errorCode = $e->errorInfo[1];
if ($errorCode == 1062) { //error code for duplicate entry to a unique field
return response()->json(['error' => $e]);
}
}
}
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 = "";
$html_text .= "";
$html_text .= "| Name | ";
$html_text .= " Gender | ";
$html_text .= " Age | ";
$html_text .= " Phone | ";
$html_text .= " Patient Category | ";
$html_text .= " | ";
$html_text .= "
";
$categories = PatientCategory::pluck("name", "id");
foreach ($patients as $patient) {
$html_text .= "";
$html_text .= "| " . $patient->first_name . " " . $patient->last_name . " (" . $patient->number . ")" . " | ";
$html_text .= "" . (($patient->gender == 1) ? "Male" : "Female") . " | ";
$html_text .= "" . get_patients_age($patient->date_of_birth) . " | ";
$html_text .= "" . $patient->phone . " | ";
$html_text .= "" . (isset($categories[$patient->category_id]) ? $categories[$patient->category_id] : "N/A") . " | ";
$html_text .= " Select | ";
$html_text .= "
";
}
$html_text .= "
";
}
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 = "";
$html_text .= "";
$html_text .= "| All values from ". get_full_name($patient->id, "id", "first_name", "last_name", "patients")." | first_name."> " . $patient->first_name . "";
$html_text .= "
";
$html_text .= "";
$html_text .= "| " . $patient->last_name . " | ";
$html_text .= "
";
$html_text .= "";
$gender = $patient->gender == 1 ? "Male" : "Female";
$html_text .= "| " . $gender . " | ";
$html_text .= "
";
$html_text .= "";
$html_text .= "| " . get_patients_age($patient->date_of_birth) . " | ";
$html_text .= "
";
$html_text .= "";
$html_text .= "| " . $patient->phone . " | ";
$html_text .= "
";
$html_text .= "";
$html_text .= "| " . get_name($patient->category_id, "id", "name", "patient_categories") . " | ";
$html_text .= "
";
$html_text .= "";
$html_text .= "| " . get_name($patient->district_id, "id", "name", "districts") . " | ";
$html_text .= "
";
$html_text .= "";
$html_text .= "| " . get_name($patient->county_id, "id", "name", "counties") . " | ";
$html_text .= "
";
$html_text .= "";
$html_text .= "| " . get_name($patient->subcounty_id, "id", "name", "subcounties") . " | ";
$html_text .= "
";
$html_text .= "";
$html_text .= "| " . get_name($patient->parish_id, "id", "name", "parishes") . " | ";
$html_text .= "
";
$html_text .= "";
$html_text .= "| " . get_name($patient->village_id, "id", "name", "villages") . " | ";
$html_text .= "
";
$html_text .= "
";
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();
}
}
$tables = ['ward_inpatient_sheet_nurse_comments','patient_accounts_deposits','patient_dispensings','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','ward_dispensing_per_charts','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','debtor_payments','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 patient_appointments_report(Request $request)
{
$clinic_id = $request->clinic_id;
$search_by = $request->search_by;
$reg_date = $request->reg_date;
$start_date = $request->start_date;
$end_date = $request->end_date;
//dd($request->all());
$clinics = Clinic::where('available', 1)->pluck('name', 'id')->prepend(['' => 'All clinics']);
$today = Carbon::now()->toDateString();
$filters = [];
$clinic_name = Clinic::where('id',$clinic_id)->pluck('name')->first();
if($search_by == 0){
array_push($filters, ['appointment_date', '<', $today]);
}elseif($search_by == 1){
// custom date
$start_date_search = Carbon::parse($reg_date)->toDateString();
array_push($filters, ['appointment_date', '=', $start_date_search]);
} elseif($search_by == 2){
// custom date range
$start_date_search = Carbon::parse($start_date)->toDateString();;
$end_date_search = Carbon::parse($end_date)->toDateString();;
array_push($filters, ['appointment_date', '>', $start_date_search]);
array_push($filters, ['appointment_date', '<', $end_date_search]);
} else{
array_push($filters, ['appointment_date', '<', $today]);
}
if($clinic_id == 0 || is_null($clinic_id)){
if ($request->appointment_outcome != 'all') {
$patient_appointments = PatientAppointment::where($filters)->where(['appointment_fulfilled' => $request->appointment_outcome])->orderBy('appointment_date', 'desc')->paginate(500);
} else {
$patient_appointments = PatientAppointment::where($filters)->orderBy('appointment_date', 'desc')->paginate(500);
}
} else {
if ($request->appointment_outcome != 'all') {
$patient_appointments = PatientAppointment::where(['clinic_allocation' => $clinic_id])->where(['appointment_fulfilled' => $request->appointment_outcome])->where($filters)->orderBy('appointment_date', 'desc')->paginate(400);
} else{
$patient_appointments = PatientAppointment::where(['clinic_allocation' => $clinic_id])->where($filters)->orderBy('appointment_date', 'desc')->paginate(400);
}
}
return view('patients::patients.appointments_report', compact('clinics', 'patient_appointments'));
}
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 .= "";
$code .= "| ";
$code .= "Name:";
$code .= " | ";
$code .= "";
$code .= insurance_flag($patient->id);
$code .= " | ";
$code .= "";
$code .= "Number:";
$code .= " | ";
$code .= "";
$code .= $patient->number;
$code .= " | ";
$code .= "
";
$code .= "";
$code .= "| ";
$code .= "Patient Category";
$code .= " | ";
$code .= "";
$code .= get_name($patient->category_id, "id", "name", "patient_categories");
$code .= " | ";
$code .= "";
$code .= "Phone Number";
$code .= " | ";
$code .= "";
$code .= $patient->phone;
$code .= " | ";
$code .= "
";
} else {
$code .= "No record in the system |
";
}
return $code;
}
public function store_appointment_comment(Request $request)
{
$patient_id = $request->patient_id;
$appointment_id = $request->set_appointment_id;
$appointment_comment = $request->appointment_comment;
$appointment = PatientAppointment::find($appointment_id);
$appointment->action_comment = $appointment_comment;
$appointment->action_comment_by = Auth::user()->id;
// reassign the appointment_fulfilled to 2, indicating cancelled
// $appointment->appointment_fulfilled = 2;
if ($appointment->save()){
return 1;
} else {
return 0;
}
}
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;
$first_name_search = $request->first_name;
$last_name_search = $request->last_name;
$village_search = $request->village;
$full_name_search = $request->full_name;
$criteria = "";
$filters = [];
$patient_numbers = DB::table('patients')->whereNull('deleted_at')->orderBy('number')->distinct()->pluck('number');
$first_names = [];//DB::table('patients')->whereNull('deleted_at')->orderBy('first_name')->distinct()->pluck('first_name');
$last_names = [];//DB::table('patients')->whereNull('deleted_at')->orderBy('last_name')->distinct()->pluck('last_name');
$villages = DB::table('villages')->whereNull('deleted_at')->orderBy('name')->distinct()->pluck('name');
$full_names = Patient::all(['first_name', 'last_name', 'number', 'phone'])->pluck("full_name");
if ($patient_number_search) {
$filters[] = ['number', 'LIKE', '%' . $patient_number_search . '%'];
$criteria .= 'Number (' . $patient_number_search . ') ';
}
if ($first_name_search) {
$filters[] = ['first_name', 'LIKE', '%' . $first_name_search . '%'];
$criteria .= 'First name (' . $first_name_search . ') ';
}
if ($last_name_search) {
$filters[] = ['last_name', 'LIKE', '%' . $last_name_search . '%'];
$criteria .= 'Last name (' . $last_name_search . ') ';
}
if ($full_name_search) {
$split_full_name_array = explode(' ', $full_name_search);
if (is_array($split_full_name_array)) {
$first_name_from_split = isset($split_full_name_array[0]) ? $split_full_name_array[0] : "";
$last_name_from_split = isset($split_full_name_array[1]) ? $split_full_name_array[1] : "";
$patient_number_from_split = isset($split_full_name_array[count($split_full_name_array)-2]) ? $split_full_name_array[count($split_full_name_array)-2] : "";
$phone_number_in_brackets_from_split = end($split_full_name_array);
$phone_number = str_replace(array('(',')'), '',$phone_number_in_brackets_from_split);
//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 . '%'];
$criteria .= 'Last 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 . ') ';
}
}
$categories = DB::table('patient_categories')->where('available', 1)->pluck("name", "id");
$marital_statuses = DB::table('marital_statuses')->pluck("name", "id");
$patient_villages = DB::table('villages')->pluck("name", "id");
if (empty($criteria)) :
$criteria = 'No results found for search';
$patients = DB::table('patients')->whereNull('deleted_at')->orderBy('id', 'desc')->paginate(200);
$resultCount = DB::table('patients')->whereNull('deleted_at')->orderBy('id', 'desc')->count();
else:
$patients = DB::table('patients')->whereNull('deleted_at')->orderBy('id', 'desc')->where($filters)->paginate(200);
$resultCount = DB::table('patients')->whereNull('deleted_at')->orderBy('id', 'desc')->where($filters)->count();
endif;
$patientCount = DB::table('patients')->whereNull('deleted_at')->count();
return view('patients::patients.index', compact('patients', 'categories', 'marital_statuses', 'patient_numbers', 'first_names', 'last_names', 'villages',
'patient_villages', 'patientCount', 'resultCount', 'criteria', 'full_names'));
}
public function quick_add_residence(Request $request) {
$district_id = $request->district_id;
$new_district_name = $request->new_district_name;
$county_id = $request->county_id;
$new_county_name = $request->new_county_name;
$subcounty_id = $request->subcounty_id;
$new_subcounty_name = $request->new_subcounty_name;
$parish_id = $request->parish_id;
$new_parish_name = $request->new_parish_name;
$village_id = 0;
$new_village_name = $request->new_village_name;
if (!isset($district_id) && isset($new_district_name)) {
$district = new District;
$district->name = $new_district_name;
$district->created_by = Auth::user()->id;
$district->updated_by = Auth::user()->id;
$district->save();
$district_id = $district->id;
}
if (!isset($county_id) && isset($new_county_name) && is_numeric($district_id)) {
$county = new County;
$county->name = $new_county_name;
$county->district_id = $district_id;
$county->created_by = Auth::user()->id;
$county->updated_by = Auth::user()->id;
$county->save();
$county_id = $county->id;
}
if (!isset($subcounty_id) && isset($new_subcounty_name) && is_numeric($county_id)) {
$sub_county = new Subcounty;
$sub_county->name = $new_subcounty_name;
$sub_county->county_id = $county_id;
$sub_county->created_by = Auth::user()->id;
$sub_county->updated_by = Auth::user()->id;
$sub_county->save();
$subcounty_id = $sub_county->id;
}
if (!isset($parish_id) && isset($new_parish_name) && is_numeric($subcounty_id)) {
$parish = new Parish;
$parish->name = $new_parish_name;
$parish->subcounty_id = $subcounty_id;
$parish->created_by = Auth::user()->id;
$parish->updated_by = Auth::user()->id;
$parish->save();
$parish_id = $parish->id;
}
if (isset($new_village_name)) {
$village = new Village;
$village->name = $new_village_name;
$village->parish_id = is_numeric($parish_id) ? $parish_id : 0;
$village->created_by = Auth::user()->id;
$village->updated_by = Auth::user()->id;
$village->save();
$village_id = $village->id;
}
return (is_numeric($village_id) ? $village_id : 0) . "," . (is_numeric($parish_id) ? $parish_id : 0) . "," . (is_numeric($subcounty_id) ? $subcounty_id : 0) . "," .
(is_numeric($county_id) ? $county_id : 0) . "," . (is_numeric($district_id) ? $district_id : 0);
}
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_card($id)
{
$patient = Patient::find($id);
$hospital_details = \Streamline\Models\HospitalInformation::first();
$data = [
'hospitalInfo' => $hospital_details,
'patient' => $patient
];
$pdf = SnappyPDF::loadView('patients::patients/patient_card', $data)
->setOrientation('portrait')
->setOption('margin-bottom', 7)
->setOption('margin-top', 5)
->setOption('footer-html', 'Stre@mline');
return $pdf->inline('Patient Card' . date(" d-m-y h:ia") . '.pdf');
}
}