middleware('auth'); } /** * Display a listing of the resource. * */ public function index() { // } /* * Display the in_patient_sheet form */ public function in_patient_sheet() { $episode_id = session()->get('episode_id'); $patient_episode_details = PatientEpisode::find($episode_id); $patient_id = $patient_episode_details->patient_id; $patient = Patient::find($patient_id); $referrals = ReferralHospital::orderBy('name')->pluck('name', 'id')->prepend('- select -', ''); // inpatient info $inpatient_info = InpatientInfo::where(['patient_id' => $patient_id, 'episode_id' => $episode_id])->orderBy('created_at', 'desc')->first(); if($inpatient_info->discharged == 1 && !Auth::user()->can('view-closed-inpatient-sheet')){ flash("Access to a discharged patient's inpatient sheet is restricted. Contact system administrator.")->error(); return redirect()->back(); } $specialities = Speciality::pluck('name', 'id')->prepend('- select -', ''); $diagnosis_categories = DiagnosisCategory::all(); $diagnoses = DB::table('diagnoses')->where('available', 1)->whereNull('deleted_at')->orderBy('name', 'asc')->pluck("name", "id")->prepend('- select -', ''); $diagnoses_all = DB::table('diagnoses')->whereNull('deleted_at')->select('id', 'prompts', 'reference_areas', 'reference_names')->get(); // for the initial procedures select $procedures = DB::table('procedures')->whereNull('deleted_at')->orderBy('name', 'asc')->pluck('name', 'id')->prepend('- select -', ''); $procedures_results = DB::table('procedures')->whereNull('deleted_at')->select('id', 'name')->get(); $options_procedures = ""; foreach ($procedures_results as $procedure_result) { $procedure_name = str_replace("'", '', $procedure_result->name); $procedure_name = str_replace("\"", '', $procedure_name); $options_procedures .= ""; } // for the initial sundries select $sundries = DB::table('sundries')->whereNull('deleted_at')->orderBy('name', 'asc')->pluck('name', 'id')->prepend('- select -', ''); $sundries_results = DB::table('sundries')->whereNull('deleted_at')->select('id', 'name')->get(); $options_sundries = ""; foreach ($sundries_results as $sundry_result) { $sundry_name = str_replace("'", '', $sundry_result->name); $sundry_name = str_replace("\"", '', $sundry_name); $options_sundries .= ""; } // for the initial drugs select $drugs = DB::table('drugs')->where('available', 1)->whereNull('deleted_at')->orderBy('name', 'asc')->pluck('name', 'id')->prepend('- select -', ''); $drugs_results = DB::table('drugs')->where('available', 1)->whereNull('deleted_at')->select('id', 'name')->get(); $options_drugs = ""; foreach ($drugs_results as $drugs_result) { $drug_name = str_replace("'", '', $drugs_result->name); $drug_name = str_replace("\"", '', $drug_name); $options_drugs .= ""; } $symptoms = DB::table('symptoms')->whereNull('deleted_at')->pluck("name", "id"); $documents = PatientDocument::where('patient_id', $patient_id)->orderBy('created_at', 'desc')->get(); $outcomes = Outcome::pluck('name', 'id'); $wards = Ward::withTrashed()->pluck('name', 'id')->prepend('- select ward-', ''); $treatment_to_take_away = Treatment::where(['patient_id' => $patient_id, 'episode_id' => $episode_id, 'tta' => 1])->get(); $ward_prescriptions = WardTreatment::where(['patient_id' => $patient_id, 'episode_id' => $episode_id])->get(); $ward_dispensed_drugs_array = WardTreatmentDispensation::where(['patient_id' => $patient_id, 'episode_id' => $episode_id])->distinct('drug_id')->pluck('drug_id')->toArray(); $triage = Triage::where(['patient_id' => $patient_id, 'episode_id' => $episode_id])->first(); $patient_appointment = PatientAppointment::where(['patient_id' => $patient_id, 'episode_id' => $episode_id])->first(); $anc_comments = AnteNatalClinicFollowup::where(['patient_id' => $patient_id, 'episode_id' => $episode_id])->select(['history_comments', 'clinic_examination_comments', 'investigation_and_management_plan_comments'])->first(); // prep the inpatient investigation arrays and counters $opd_investigations = []; $opd_investigations_position = []; $opd_investigations_date = []; $ward_investigations = []; $ward_investigations_position = []; $ward_investigations_date = []; // get all investigations ordered in this episode $ordered_investigations = OrderedInvestigation::where(['episode_id' => $episode_id])->get(); // get all results $investigation_results_order_ids = InvestigationResults::pluck('order_id', 'id')->toArray(); foreach ($ordered_investigations as $investigation) { if (isset($ward_investigations['id'])) { $ward_investigations_position[] = count($ward_investigations['id']); } else { $ward_investigations_position[] = 0; } if (isset($opd_investigations['id'])) { $opd_investigations_position[] = count($opd_investigations['id']); } else { $opd_investigations_position[] = 0; } $ward_investigations_date[] = "Ordered on " . streamline_date_time($investigation->created_at) . " by " . get_full_name($investigation->created_by, 'id', 'first_name', 'last_name', 'users'); $opd_investigations_date[] = streamline_date_time($investigation->created_at); $investigation_ids = explode(",", $investigation->investigation_id); $inpatient_status = explode(",", $investigation->for_inpatient); $eye_investigations = explode(",", $investigation->eye); // check if results are available for this investigation if (in_array($investigation->id, $investigation_results_order_ids)) { // get the key if available $key = array_search($investigation->id, $investigation_results_order_ids); // get the results object $results = InvestigationResults::find($key); // exclude obstetric u/s results if ($results->result_type != "Ultrasound_Obstetric") { $investigation_results = explode(",", $results->value); $investigation_per_valid = explode(",", $results->per_investigation); $investigation_comments = explode(",", $results->comment); if ($results->all_authenticated == 1) { for ($i = 0; $i < count($inpatient_status); $i++) { if (isset($inpatient_status[$i]) && $inpatient_status[$i] == 0) { $result = Investigation::withTrashed()->find($investigation_ids[$i]); if ($result) { $opd_investigations['id'][] = $result->id; $opd_investigations['name'][] = $result->name; $opd_investigations['type'][] = $result->type; $opd_investigations['slug'][] = $result->slug; $opd_investigations['normal_ranges'][] = $result->normal_ranges; $opd_investigations['value'][] = $investigation_results[$i] ?? ""; $opd_investigations['result_time'][] = 'On '.streamline_date_time_short($results->created_at).' by '. get_full_name($results->created_by, 'id', 'first_name', 'last_name', 'users'); $opd_investigations['comment'][] = $investigation_comments[$i] ?? ""; $opd_investigations['eye'][] = $eye_investigations[$i] ?? ''; } } else { $result = Investigation::withTrashed()->find($investigation_ids[$i]); if ($result) { $ward_investigations['id'][] = $result->id; $ward_investigations['name'][] = $result->name; $ward_investigations['type'][] = $result->type; $ward_investigations['normal_ranges'][] = $result->normal_ranges; $ward_investigations['slug'][] = $result->slug; $ward_investigations['result_time'][] = 'On '.streamline_date_time_short($results->created_at).' by '. get_full_name($results->created_by, 'id', 'first_name', 'last_name', 'users'); $ward_investigations['value'][] = $investigation_results[$i] ?? ""; $ward_investigations['comment'][] = $investigation_comments[$i] ?? ""; $ward_investigations['eye'][] = $eye_investigations[$i] ?? ''; } } } } else { for ($i = 0; $i < count($inpatient_status); $i++) { $investigation = Investigation::withTrashed()->find($investigation_ids[$i]); if (!$investigation) { continue; } if (isset($investigation_per_valid[$i]) && $investigation_per_valid[$i] == 1) { // this investigation is authenticated if (isset($inpatient_status[$i]) && $inpatient_status[$i] == 0) { $opd_investigations['id'][] = $investigation->id; $opd_investigations['name'][] = $investigation->name; $opd_investigations['type'][] = $investigation->type; $opd_investigations['slug'][] = $investigation->slug; $opd_investigations['normal_ranges'][] = $investigation->normal_ranges; $opd_investigations['value'][] = $investigation_results[$i] ?? ""; $opd_investigations['comment'][] = $investigation_comments[$i] ?? ""; $opd_investigations['eye'][] = $eye_investigations[$i] ?? ''; } else { $ward_investigations['id'][] = $investigation->id; $ward_investigations['name'][] = $investigation->name; $ward_investigations['type'][] = $investigation->type; $ward_investigations['normal_ranges'][] = $investigation->normal_ranges; $ward_investigations['slug'][] = $investigation->slug; $ward_investigations['value'][] = $investigation_results[$i] ?? ""; $ward_investigations['comment'][] = $investigation_comments[$i] ?? ""; $ward_investigations['eye'][] = $eye_investigations[$i] ?? ''; } } else { if (isset($investigation_per_valid[$i]) && $inpatient_status[$i] == 0) { $opd_investigations['id'][] = $investigation->id; $opd_investigations['name'][] = $investigation->name; $opd_investigations['type'][] = $investigation->type; $opd_investigations['slug'][] = $investigation->slug; $opd_investigations['normal_ranges'][] = $investigation->normal_ranges; $opd_investigations['value'][] = "Pending"; $opd_investigations['comment'][] = "Pending"; $opd_investigations['eye'][] = $eye_investigations[$i] ?? ''; } else { $ward_investigations['id'][] = $investigation->id; $ward_investigations['name'][] = $investigation->name; $ward_investigations['type'][] = $investigation->type; $ward_investigations['normal_ranges'][] = $investigation->normal_ranges; $ward_investigations['slug'][] = $investigation->slug; $ward_investigations['value'][] = "Pending"; $ward_investigations['comment'][] = "Pending"; $ward_investigations['eye'][] = $eye_investigations[$i] ?? ''; } } } } } } else { for ($i = 0; $i < count($inpatient_status); $i++) { if (isset($inpatient_status[$i]) && $inpatient_status[$i] == 0) { $result = Investigation::withTrashed()->find($investigation_ids[$i]); if ($result) { $opd_investigations['id'][] = $result->id; $opd_investigations['name'][] = $result->name; $opd_investigations['type'][] = $result->type; $opd_investigations['slug'][] = $result->slug; $opd_investigations['normal_ranges'][] = $result->normal_ranges; $opd_investigations['value'][] = "Pending"; $opd_investigations['comment'][] = "Pending"; $opd_investigations['eye'][] = $eye_investigations[$i] ?? ''; } } else { $result = Investigation::withTrashed()->find($investigation_ids[$i]); if ($result) { $ward_investigations['id'][] = $result->id; $ward_investigations['name'][] = $result->name; $ward_investigations['type'][] = $result->type; $ward_investigations['normal_ranges'][] = $result->normal_ranges; $ward_investigations['slug'][] = $result->slug; $ward_investigations['value'][] = "Pending"; $ward_investigations['comment'][] = "Pending"; $ward_investigations['eye'][] = $eye_investigations[$i] ?? ''; } } } } } $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(); // for initial services select $service_items = DB::table('services')->whereNull('deleted_at')->orderBy('name','asc')->pluck('name', 'id')->prepend('- select -', ''); $service_results = DB::table('services')->whereNull('deleted_at')->select('id', 'name')->get(); $options_services = ""; foreach ($service_results as $service_result) { $service_name = str_replace("'", '', $service_result->name); $service_name = str_replace("\"", '', $service_name); $service_name = str_replace("+", '', $service_name); $options_services .= ""; } $users_collection = DB::table('users')->orderBy("first_name","asc")->select("id")->get()->toArray(); $service_with_users_array = []; $users_array = []; $options_users = ""; foreach ($users_collection as $value){ $user = User::find($value->id); if (!is_null($user)) { $users_array[$user->id] = $user->first_name . " ". $user->last_name; $options_users .= ""; 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('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) { $price_list_id = is_patient_category_attached_to_price_list($patient_id); if ($price_list_id) { $users_consultation_fee = get_price_list_category_price($price_list_id, 6, $record->id); } else{ $users_consultation_fee = $record->non_insured_price; } //concatnate the service_record_id with the users_id to form the key for the array $dynamic_key = $record->id."__".$value->id; $dynamic_value = get_full_name($value->id, 'id', 'first_name', 'last_name', 'users')." (".$record->name.")"; $service_with_users_array[$dynamic_key] = $dynamic_value; //add these dynamically formed values to service_items array array_add($service_items, $dynamic_key, $dynamic_value); //add it to the services_options too i.e used when user clicks add_service btn $options_services .= ""; } } } } $service_with_users_array = ['' => '- select -'] + $service_with_users_array; $services_with_users_array = InpatientController::configured_users_with_their_services_array(); $users_array = ['' => '- select -'] + $users_array; $bed_categories = InpatientBedCategory::where('available', 1)->orderby('name','asc')->pluck('name', 'id')->prepend('- select -', ''); $options_bed_categories = ""; foreach ($bed_categories as $id => $bed_category) { $options_bed_categories .= ""; } $options_wards = ""; foreach ($wards as $id => $ward_option) { $options_wards .= ""; } $today = date("Y-m-d"); $dob = Carbon::parse($patient->date_of_birth); $age_diff_days = $dob->diffInDays(Carbon::now()); $age_diff_months = $age_diff_days / 30.436875; $difference = days_months_years($dob, $today); $days = $difference[0]; $months = $difference[1]; $years = $difference[2]; $age_group = 0; if (between($days, 0, 28) && between($months, 0, 0) && between($years, 0, 0)) { $age_group = 1; } elseif (between($days, 0, 31) && between($months, 1, 12) && between($years, 0, 0)) { $age_group = 2; } elseif (between($days, 0, 31) && between($months, 0, 12) && between($years, 1, 5)) { $age_group = 3; } elseif (between($days, 0, 31) && between($months, 0, 12) && between($years, 6, 12)) { $age_group = 4; } elseif (between($days, 0, 31) && between($months, 0, 12) && between($years, 13, 200)) { $age_group = 5; } $observations = DB::table('observations') ->whereNull('deleted_at') ->where(function($query){ $query->where('options', '') ->orWhereNull('options'); }) ->whereRaw('FIND_IN_SET(' . $age_group . ',age_group)')->pluck('name', 'id'); $options_observations = ""; foreach ($observations as $key => $value) { $options_observations .= ""; } // check saved vitals $patient_inpatient_vitals = DB::table('patient_inpatient_vitals') ->whereNull('deleted_at') ->where('inpatient_id', $inpatient_info->id) ->orderBy('id', 'desc')->get(['id', 'vitals']); $patient_vitals = []; foreach ($patient_inpatient_vitals as $vital) { $vitals_array = json_decode($vital->vitals, true); foreach ($vitals_array as $value) { $patient_vitals[$value["name"]][] = ["value" => $value["value"], "time" => $value["time"]]; } } // get ordered cancer protocols $ordered_cancer_protocols = DB::table('ordered_cancer_protocols') ->whereNull('deleted_at')->where('inpatient_id', $inpatient_info->id)->get(); $drug_with_units = $this->drugsService->pluckAvailableDrugs('unit_id'); $drug_with_forms = $this->drugsService->pluckAvailableDrugs('form_id'); $drug_forms = $this->drugFormsService->pluckAvailableDrugForms('name'); $drug_units = $this->drugUnitsService->pluckAvailableDrugUnits('name'); $drug_routes = $this->drugRoutesService->pluckAvailableDrugRoutes('name'); $factors = CancerProtocolController::$factors; if ($inpatient_info->discharged == 1) { return view('ward_management::inpatient.inpatient_sheet_history', compact('patient', 'inpatient_info', 'specialities', 'diagnoses', 'diagnoses_all', 'procedures', 'options_procedures', 'sundries', 'options_sundries', 'drugs', 'options_drugs', 'outcomes', 'wards', 'triage', 'symptoms', 'documents', 'treatment_to_take_away', 'opd_investigations', 'diagnosis_categories', 'drug_with_units', 'drug_units', 'drug_routes', 'factors', 'ward_investigations', 'referrals', 'patient_id', 'episode_id', 'ward_prescriptions', 'service_items', 'options_services','ward_dispensed_drugs_array','clinics', 'users', 'services_with_users_array', 'users_array', 'opd_investigations_position', 'ward_investigations_position', 'opd_investigations_date', 'ward_investigations_date', 'options_users', 'bed_categories', 'options_bed_categories', 'options_wards')); } else { return view('ward_management::inpatient.inpatient_sheet', compact('patient', 'inpatient_info', 'specialities', 'diagnoses', 'diagnoses_all', 'procedures', 'options_procedures', 'sundries', 'options_sundries', 'anc_comments', 'drugs', 'options_drugs', 'outcomes', 'wards', 'triage', 'symptoms', 'documents', 'treatment_to_take_away', 'opd_investigations', 'diagnosis_categories', 'patient_vitals', 'drug_units', 'drug_routes', 'factors', 'age_group', 'options_observations', 'ward_investigations', 'ward_prescriptions', 'referrals', 'patient_id', 'patient_appointment', 'episode_id', 'service_items', 'options_services','ward_dispensed_drugs_array','clinics', 'users', 'services_with_users_array', 'users_array', 'opd_investigations_position', 'ward_investigations_position', 'opd_investigations_date', 'ward_investigations_date', 'options_users', 'bed_categories', 'options_bed_categories', 'options_wards', 'ordered_cancer_protocols', 'drug_with_units', 'drug_with_forms', 'drug_forms')); } } /* submit internal ward transfers */ public function store_internal_ward_transfers(Request $request) { $ward_transfer = new InternalWardTransfer; $ward_transfer->patient_id = $request->patient_id; $ward_transfer->from_ward = $request->from_ward; $ward_transfer->to_ward = $request->to_ward; $ward_transfer->transfer_date = Carbon::createFromFormat('d/m/Y', $request->transfer_date)->toDateString(); $ward_transfer->comments = $request->transfer_comments; $ward_transfer->created_by = Auth::id(); if ($ward_transfer->save()) { //Updating the inpatient info table $inpatient_info = InpatientInfo::find($request->info_id); $inpatient_info->ward_id = $request->to_ward; $inpatient_info->transferred = 1; $inpatient_info->update(); $patient_id = $inpatient_info->patient_id; $episode_id = $inpatient_info->episode_id; // check if there is a still admitted record and close it off $still_admitted_record = WardBedStay::where(['patient_id' => $patient_id, 'episode_id' => $episode_id, 'still_here' => 1])->first(); if ($still_admitted_record) { // set the end date as today $still_admitted_record->to = Carbon::createFromFormat('d/m/Y', $request->transfer_date)->toDateString(); $still_admitted_record->still_here = 0; $still_admitted_record->save(); $bed_number = $still_admitted_record->bed_number; $bed_category = $still_admitted_record->bed_category; $current_chart_of_account = $still_admitted_record->current_chart_of_account; } else { $latest_bed_record = WardBedStay::where(['patient_id' => $patient_id, 'episode_id' => $episode_id])->orderBy('id', 'desc')->first(); $bed_number = $latest_bed_record->bed_number; $bed_category = $latest_bed_record->bed_category; $current_chart_of_account = $latest_bed_record->current_chart_of_account; } // create new record with new ward copying the still or latest record $ward_bed_stay = new WardBedStay(); $ward_bed_stay->patient_id = $patient_id; $ward_bed_stay->episode_id = $episode_id; $ward_bed_stay->ward_id = $request->to_ward; $ward_bed_stay->bed_number = $bed_number; $ward_bed_stay->bed_category = $bed_category; $ward_bed_stay->bed_ward = $request->to_ward; $ward_bed_stay->from = Carbon::createFromFormat('d/m/Y', $request->transfer_date)->toDateString(); $ward_bed_stay->to = date('Y-m-d'); $ward_bed_stay->still_here = 1; $ward_bed_stay->duration = 0; $ward_bed_stay->bed_fee_rate = 0; $ward_bed_stay->bed_fee_total = 0; $ward_bed_stay->current_chart_of_account = $current_chart_of_account; $ward_bed_stay->created_by = Auth::id(); $ward_bed_stay->save(); } return response()->json($request->all()); } /* * store from the in_patient_sheet form */ public function store(Request $request) { $patient_id = session()->get('patient_id'); $episode_id = session()->get('episode_id'); $patient_insurance_status = $request->patient_insurance_status ?? 0; // change status for the cancer protocol if (isset($request->ordered_cancer_protocol_id)) { $ordered_cancer_protocol_ids = $request->ordered_cancer_protocol_id; $ordered_cancer_protocol_status = $request->ordered_cancer_protocol_status; for ($p = 0; $p < count($ordered_cancer_protocol_ids); $p++) { $protocol = OrderedCancerProtocols::find($ordered_cancer_protocol_ids[$p]); $protocol->protocol_status = $ordered_cancer_protocol_status[$p]; $protocol->save(); } } // update the patient info $inpatient_info = InpatientInfo::find($request->info_id); $inpatient_info->primary_diagnosis = $request->primary_diagnosis; $inpatient_info->other_diagnoses = serialize($request->other_diagnosis); $inpatient_info->left_eye_diagnosis = $request->left_eye_diagnosis ? implode(',', $request->left_eye_diagnosis) : NULL; $inpatient_info->right_eye_diagnosis = $request->left_eye_diagnosis ? implode(',', $request->right_eye_diagnosis) : NULL; $inpatient_info->ward_message = $request->comments; $inpatient_info->discharge_summary = $request->discharge_summary; $inpatient_info->clinical_summary = $request->clinical_summary; $inpatient_info->referral_notes = $request->referral_notes; if ($request->comments) { $ward_inpatient_sheet_comments = new WardInpatientSheetComment; $ward_inpatient_sheet_comments->patient_id = $patient_id; $ward_inpatient_sheet_comments->episode_id = $episode_id; $ward_inpatient_sheet_comments->ward_comments = $request->comments; $ward_inpatient_sheet_comments->ward_id = $request->ward_id; $ward_inpatient_sheet_comments->created_by = Auth::id(); $ward_inpatient_sheet_comments->save(); } // save for the nurse comments if($request->nurse_comments){ $ward_inpatient_sheet_nurse_comments = new WardInpatientSheetNurseComment; $ward_inpatient_sheet_nurse_comments->patient_id = $patient_id; $ward_inpatient_sheet_nurse_comments->episode_id = $episode_id; $ward_inpatient_sheet_nurse_comments->ward_comments = $request->nurse_comments; $ward_inpatient_sheet_nurse_comments->ward_id = $request->ward_id; $ward_inpatient_sheet_nurse_comments->created_by = Auth::id(); $ward_inpatient_sheet_nurse_comments->save(); } if ($request->inpatient_history || $request->inpatient_result || $request->inpatient_vitals_and_examinations || $request->inpatient_impression || $request->inpatient_plan) { $ward_inpatient_sheet_comments = new WardInpatientDetailedNote; $ward_inpatient_sheet_comments->patient_id = $patient_id; $ward_inpatient_sheet_comments->episode_id = $episode_id; $ward_inpatient_sheet_comments->history = $request->inpatient_history; $ward_inpatient_sheet_comments->result = $request->inpatient_result; $ward_inpatient_sheet_comments->vitals = $request->inpatient_vitals_and_examinations; $ward_inpatient_sheet_comments->impression = $request->inpatient_impression; $ward_inpatient_sheet_comments->plan = $request->inpatient_plan; $ward_inpatient_sheet_comments->ward_id = $request->ward_id; $ward_inpatient_sheet_comments->created_by = Auth::id(); $ward_inpatient_sheet_comments->save(); } $inpatient_info->outcome_id = $request->outcome; $inpatient_info->updated_by = Auth::id(); $inpatient_info->tb_status_assessment = $request->tb_status_assessment; //bed categories $bed_number_array = $request->on_bed_number; $bed_category_array = $request->on_bed_bedcategory; $bed_ward_array = $request->bed_ward; $on_bed_from_array = $request->on_bed_from; $still_here_or_not = $request->upto_option; $on_bed_upto_array = $request->on_bed_upto; $bed_duration_array = $request->bed_duration; $bed_rate_array = $request->bed_rate; // if any of the currently saved are not in the previous it means they were deleted $already_stored_bed_categories = WardBedStay::where(['episode_id' => $episode_id,'patient_id' => $patient_id,'ward_id' => $request->ward_id])->get(); $previous_bed_stays = is_array($request->previous_bed_stays) ? $request->previous_bed_stays : []; foreach ($already_stored_bed_categories as $already_stored_bed_category) { if (!in_array($already_stored_bed_category->id, $previous_bed_stays)) { $already_stored_bed_category->delete(); } } if (is_array($bed_number_array)) { for ($i=0; $i < count($bed_number_array) ; $i++) { if (!empty($bed_category_array[$i]) && !empty($bed_ward_array[$i])) { $ward_bed_stay = WardBedStay::firstOrNew(['patient_id' => $patient_id, 'episode_id' => $episode_id, 'ward_id' => $request->ward_id, 'bed_category' => $bed_category_array[$i], 'bed_ward' => $bed_ward_array[$i]]); $bed_category_cost = InpatientBedCategory::find($bed_category_array[$i]); $ward_bed_stay->patient_id = $patient_id; $ward_bed_stay->episode_id = $episode_id; $ward_bed_stay->ward_id = $request->ward_id; $ward_bed_stay->bed_number = $bed_number_array[$i]; $ward_bed_stay->bed_category = $bed_category_array[$i]; $ward_bed_stay->bed_ward = $bed_ward_array[$i]; $ward_bed_stay->from = $on_bed_from_array[$i]; $ward_bed_stay->to = $on_bed_upto_array[$i]; if ($i == 0) { //the first item in array $ward_bed_stay->still_here = $still_here_or_not == "Still here" ? 1 : 0; } $ward_bed_stay->duration = $bed_duration_array[$i] ?? 0; $ward_bed_stay->bed_fee_rate = $bed_rate_array[$i] ?? 0; if ($bed_category_cost->cost_type == 2) { if (!empty($bed_duration_array[$i]) || !empty($bed_rate_array[$i])) { if ($bed_duration_array[$i] == 1) { $ward_bed_stay->bed_fee_total = $bed_category_cost->cost_first_night; } elseif (($bed_duration_array[$i] - 1) <= $bed_category_cost->to_night) { $amount = ($bed_duration_array[$i] - 1) * $bed_category_cost->cost_range; $ward_bed_stay->bed_fee_total = $bed_category_cost->cost_first_night + $amount; } else { $other_days = $bed_category_cost->to_night + 1; $range_amount = $bed_category_cost->to_night * $bed_category_cost->cost_range; $cost_after = ($bed_duration_array[$i] - $other_days) * $bed_category_cost->cost_after; $ward_bed_stay->bed_fee_total = $bed_category_cost->cost_first_night + $range_amount + $cost_after; } } else $ward_bed_stay->bed_fee_total = 0; } else $ward_bed_stay->bed_fee_total = ($bed_duration_array[$i] ?? 0) * ($bed_rate_array[$i] ?? 0); /*** add the current chart of account ***/ $default_bed_categories_income_acc = ChartOfAccount::where('slug', 'default_ward_accomodation_income')->first(); $default_bed_categories_income_acc_id = is_null($default_bed_categories_income_acc) ? null : $default_bed_categories_income_acc->id; $bed_category_income_account = get_name($bed_category_array[$i], "id", "income_account", "inpatient_bed_categories"); $bed_category_income_account = (is_null($bed_category_income_account) || $bed_category_income_account == "N/A") ? $default_bed_categories_income_acc_id : $bed_category_income_account; $ward_bed_stay->current_chart_of_account = $bed_category_income_account; /* **** */ $ward_bed_stay->created_by = Auth::id(); $ward_bed_stay->save(); } } } // check if a speciality is selected if ($request->speciality) { $inpatient_info->speciality_id = $request->speciality; } // check if any procedure is selected if (is_array($request->procedure_id) && !in_array(null, $request->procedure_id)) { $inpatient_info->procedures = serialize($request->procedure_id); } else { $inpatient_info->procedures = ''; } // procedure_done_by if (is_array($request->procedure_done_by) && !in_array(null, $request->procedure_done_by)) { $inpatient_info->procedures_done_by = serialize($request->procedure_done_by); } // procedure_hospital_fee if (is_array($request->procedure_hospital_fee) && !in_array(null, $request->procedure_hospital_fee)) { $inpatient_info->procedure_hospital_fee = serialize($request->procedure_hospital_fee); } else { $inpatient_info->procedure_hospital_fee = ''; } // procedure_staff_fee if (is_array($request->procedure_performance_fee) && !in_array(null, $request->procedure_performance_fee)) { $inpatient_info->procedure_staff_fee = serialize($request->procedure_performance_fee); } else { $inpatient_info->procedure_staff_fee = ''; } $ward_procedure_ids_array = $request->procedure_id; $ward_procedure_eye_array = $request->eye; $ward_procedure_performed_by_array = $request->procedure_done_by; $ward_procedure_hospital_fee_array = $request->procedure_hospital_fee; $ward_procedure_staff_fee_array = $request->procedure_performance_fee; $ward_procedure_dates_array = $request->procedure_date; //remove any previously stored consultations and services that are not in this new submission/save $old_already_stored_procedure_record_ids = WardProcedure::where(['episode_id' => $episode_id,'patient_id' => $patient_id,'ward_id' =>$request->ward_id])->pluck('id')->toArray(); $new_already_stored_procedure_record_ids = $request->procedure_record_id ?? []; for ($i=0; $i < count($old_already_stored_procedure_record_ids) ; $i++) { if (!in_array($old_already_stored_procedure_record_ids[$i], $new_already_stored_procedure_record_ids)) { $procedure_to_remove = WardProcedure::find($old_already_stored_procedure_record_ids[$i]); if ($procedure_to_remove) { $procedure_to_remove->delete(); } } } if (is_array($ward_procedure_ids_array)) { for ($x = 0; $x < count($ward_procedure_ids_array); $x++) { if (!is_null($ward_procedure_ids_array[$x])) { $ward_procedures_record = new WardProcedure; // get chi price if available if ($patient_insurance_status == 1) { $procedure_insurance_details = get_item_insurance_pricing($patient_id, $ward_procedure_ids_array[$x], 2, true, $request->ward_id); $ward_procedures_record->chi_price = $procedure_insurance_details[1]; } $ward_procedures_record->patient_id = $patient_id; $ward_procedures_record->episode_id = $episode_id; $ward_procedures_record->procedure_id = $ward_procedure_ids_array[$x]; $ward_procedures_record->performed_by = $ward_procedure_performed_by_array[$x]; $ward_procedures_record->hospital_fee = $ward_procedure_hospital_fee_array[$x]; $ward_procedures_record->staff_fee = $ward_procedure_staff_fee_array[$x]; $ward_procedures_record->procedure_date = is_null($ward_procedure_dates_array[$x]) ? Carbon::now() : $ward_procedure_dates_array[$x]; $ward_procedures_record->ward_id = $request->ward_id; $ward_procedures_record->eye = isset($ward_procedure_eye_array[$x])? $ward_procedure_eye_array[$x]:null; $ward_procedures_record->current_chart_of_account = get_name($ward_procedure_ids_array[$x], "id", "account_id", "procedures"); $ward_procedures_record->created_by = Auth::id(); $ward_procedures_record->save(); } } } // check if any sundry is selected if (is_array($request->sundry_id) && !in_array(null, $request->sundry_id)) { $sundry_id = $request->sundry_id; $sundry_quantity = $request->sundry_quantity; $sundries = array( "sundries" => $sundry_id, "quantity" => $sundry_quantity ); $inpatient_info->sundries = serialize($sundries); } else { $inpatient_info->sundries = ''; } $ward_sundries_ids_array = $request->sundry_id; $ward_sundries_quantities_array = $request->sundry_quantity; $ward_sundries_qty_given_so_far_array = $request->sundry_quantity_dispensed_so_far; $ward_sundries_dates_array = $request->sundry_date; if (is_array($ward_sundries_ids_array)) { for ($j = 0; $j < count($ward_sundries_ids_array); $j++) { // only save if the dispensed drug quantity is not null $sundry_details = Sundry::find($ward_sundries_ids_array[$j]); if (!is_null($ward_sundries_quantities_array[$j]) && $sundry_details) { $ward_sundry_dispensations = new WardSundryDispensation; $ward_sundry_dispensations->patient_id = $patient_id; $ward_sundry_dispensations->episode_id = $episode_id; $ward_sundry_dispensations->sundry_id = $ward_sundries_ids_array[$j]; $ward_sundry_dispensations->quantity_given = $ward_sundries_quantities_array[$j]; $ward_sundry_dispensations->dispensation_date = $ward_sundries_dates_array[$j]; $ward_sundry_dispensations->current_chart_of_account = $sundry_details->account_id; $ward_sundry_dispensations->inventory_account = $sundry_details->inventory_account; $ward_sundry_dispensations->cost_of_goods_account = $sundry_details->cost_of_goods_account; $ward_sundry_dispensations->cost_price = $sundry_details->cost_price; /* == save the selling price at point of dispensation === */ $sundry_selling_price = 0; if($patient_insurance_status == 1) { $sundry_insurance_details = get_item_insurance_pricing($patient_id, $ward_sundries_ids_array[$j], 5, true, $request->ward_id); $sundry_selling_price = $sundry_insurance_details[2]; $ward_sundry_dispensations->chi_price = $sundry_insurance_details[1]; } else { $price_list_id = is_patient_category_attached_to_price_list($patient_id); if ($price_list_id) { $sundry_selling_price = get_price_list_category_price($price_list_id, 5, $ward_sundries_ids_array[$j]); } else { $sundry_selling_price = $sundry_details->non_insured_price; } } $ward_sundry_dispensations->price = $sundry_selling_price; /* ============= */ $ward_sundry_dispensations->ward_id = $request->ward_id; $ward_sundry_dispensations->created_by = Auth::id(); $ward_sundry_dispensations->save(); reduce_ward_stock_with_consumed_quantity($ward_sundries_ids_array[$j], $ward_sundries_quantities_array[$j], 2, $request->ward_id, $patient_id, $episode_id, $ward_sundry_dispensations->id); } } } //remove any previously stored sundries that are not in this new submission/save $already_stored_ward_sundries_array = WardSundryDispensation::where(['episode_id' => $episode_id,'patient_id' => $patient_id,'ward_id' => $request->ward_id])->pluck('sundry_id')->toArray(); for ($i=0; $i < count($already_stored_ward_sundries_array) ; $i++) { $ward_sundries_ids_array = is_null($ward_sundries_ids_array) ? [] : $ward_sundries_ids_array; if (is_array($ward_sundries_ids_array) && !in_array($already_stored_ward_sundries_array[$i], $ward_sundries_ids_array)) { $sundry_to_remove = WardSundryDispensation::where(['episode_id' => $episode_id, 'patient_id' => $patient_id,'ward_id' => $request->ward_id, 'sundry_id' => $already_stored_ward_sundries_array[$i]])->first(); if ($sundry_to_remove) { $sundry_to_remove->delete(); } } } // check if any service is selected if (is_array($request->service_id) && !in_array(null, $request->service_id)) { $service_id = $request->service_id; $service_quantities = $request->service_quantity; $services = array( "services" => $service_id, "quantity" => $service_quantities ); $inpatient_info->services = serialize($services); } else { $inpatient_info->services = ''; } // services_unit_price if (is_array($request->service_unit_price) && !in_array(null, $request->service_unit_price)) { $inpatient_info->services_unit_price = serialize($request->service_unit_price); } else { $inpatient_info->services_unit_price = ''; } // service_staff_fee if (is_array($request->service_staff_fee) && !in_array(null, $request->service_staff_fee)) { $inpatient_info->services_staff_fee = serialize($request->service_staff_fee); } else { $inpatient_info->services_staff_fee = ''; } $ward_services_ids_array = $request->service_id; $ward_services_quantities_array = $request->service_quantity; $ward_services_unit_prices_array = $request->service_unit_price; $ward_services_staff_fees_array = $request->service_staff_fee; $ward_services_dates_array = $request->service_date; //remove any previously stored consultations and services that are not in this new submission/save $old_already_stored_consultation_and_services_record_ids = WardConsultationsAndService::where(['episode_id' => $episode_id,'patient_id' => $patient_id,'ward_id' =>$request->ward_id])->pluck('id')->toArray(); $new_already_stored_consultation_and_services_record_ids = $request->ward_consultations_and_services_record_id; for ($i=0; $i < count($old_already_stored_consultation_and_services_record_ids) ; $i++) { $new_already_stored_consultation_and_services_record_ids = is_null($new_already_stored_consultation_and_services_record_ids) ? [] : $new_already_stored_consultation_and_services_record_ids; if (!in_array($old_already_stored_consultation_and_services_record_ids[$i], $new_already_stored_consultation_and_services_record_ids)) { $services_to_remove = WardConsultationsAndService::find($old_already_stored_consultation_and_services_record_ids[$i]); if ($services_to_remove) { $services_to_remove->delete(); } } } //do the dew here if (is_array($ward_services_ids_array)) { for ($j = 0; $j < count($ward_services_ids_array); $j++) { // only save if the dispensed drug quantity is not null if (!is_null($ward_services_quantities_array[$j])) { $ward_services_and_consultations = new WardConsultationsAndService; $ward_services_and_consultations->patient_id = $patient_id; $ward_services_and_consultations->episode_id = $episode_id; $ward_services_and_consultations->service_id = $ward_services_ids_array[$j]; $ward_services_and_consultations->quantity_given = $ward_services_quantities_array[$j]; $ward_services_and_consultations->unit_price = $ward_services_unit_prices_array[$j]; $ward_services_and_consultations->staff_fee = $ward_services_staff_fees_array[$j]; // get chi price if available if ($patient_insurance_status == 1) { $service_insurance_details = get_item_insurance_pricing($patient_id, $ward_services_ids_array[$j], 1, true, $request->ward_id); $ward_services_and_consultations->chi_price = $service_insurance_details[1]; $ward_services_and_consultations->unit_price = $service_insurance_details[2]; } $ward_services_and_consultations->dispensation_date = is_null($ward_services_dates_array[$j]) ? Carbon::now() : $ward_services_dates_array[$j]; $ward_services_and_consultations->current_chart_of_account = get_name($ward_services_ids_array[$j], "id", "account_id", "services"); $ward_services_and_consultations->ward_id = $request->ward_id; $ward_services_and_consultations->created_by = Auth::id(); $ward_services_and_consultations->save(); } } } // check if any extras is selected if (is_array($request->extra_name) && !in_array(null, $request->extra_name)) { $extra_name = $request->extra_name; $extra_cost = $request->extra_cost; $extras = array( "name" => $extra_name, "cost" => $extra_cost ); $inpatient_info->extras = serialize($extras); } else { $inpatient_info->extras = ''; } $extra_items_array = $request->extra_name ?? []; $extra_costs_array = $request->extra_cost ?? []; $extra_dates_array = $request->extra_date ?? []; $ward_extras_income_account = ChartOfAccount::where('slug', 'ward_extras_income_account')->first(); if (is_array($extra_items_array)) { for ($k = 0; $k < count($extra_items_array); $k++) { // only save if the dispensed drug quantity is not null if (!is_null($extra_costs_array[$k])) { $ward_extra = new WardExtra; $ward_extra->patient_id = $patient_id; $ward_extra->episode_id = $episode_id; $ward_extra->extra_item = $extra_items_array[$k]; $ward_extra->extra_cost = $extra_costs_array[$k]; $ward_extra->current_chart_of_account = !is_null($ward_extras_income_account) ? $ward_extras_income_account->id : 0; $ward_extra->dispensation_date = $extra_dates_array[$k]; $ward_extra->ward_id = $request->ward_id; $ward_extra->created_by = Auth::id(); $ward_extra->save(); } } } //remove any previously stored extras that are not in this new submission/save $already_stored_extra_items_array = WardExtra::where(['episode_id' => $episode_id,'patient_id' => $patient_id,'ward_id' => $request->ward_id])->pluck('extra_item')->toArray(); for ($i=0; $i < count($already_stored_extra_items_array) ; $i++) { if (!in_array($already_stored_extra_items_array[$i], $extra_items_array)) { $extra_to_remove = WardExtra::where(['episode_id' => $episode_id, 'patient_id' => $patient_id,'ward_id' => $request->ward_id, 'extra_item' => $already_stored_extra_items_array[$i]])->first(); if ($extra_to_remove) { $extra_to_remove->delete(); } } } // check if any ward treatments are selected if (isset($request->drugs) && is_array($request->drugs) && !in_array(null, $request->drugs)) { $drug_id = $request->drugs; $days = $request->drugs_days; $treatments = array( "drugs" => $drug_id, "days" => $days ); $inpatient_info->ward_treatments = serialize($treatments); } else { $inpatient_info->ward_treatments = ''; } // check if ward dispensing has been used if (isset($request->ward_dispensed_drug_id) && isset($request->ward_quantity_dispensed)) { $dispensed_drug_ids_array = $request->ward_dispensed_drug_id; $dispensed_drug_quantities_array = $request->ward_quantity_dispensed; $dispensed_ward_treatment_ids_array = $request->ward_treatment_id; if (is_array($dispensed_drug_ids_array)) { foreach ($dispensed_drug_ids_array as $i => $drug_id) { if (!empty($dispensed_drug_quantities_array[$i])) { $ward_treatment_id = $this->dispensationService->saveDispensation((int)$patient_id, (int)$episode_id, $drug_id, (int)$dispensed_drug_quantities_array[$i], $dispensed_ward_treatment_ids_array[$i], $request->ward_id ?? 0); if ($ward_treatment_id) { //reduce the ward stock from the ward stock table reduce_ward_stock_with_consumed_quantity($drug_id, $dispensed_drug_quantities_array[$i], 1, $request->ward_id, $patient_id, $episode_id, $ward_treatment_id); } } } } } if ($request->outcome == 2) { // discharged $inpatient_info->discharged = 1; $inpatient_info->discharged_on = is_null($request->discharge_date) ? null : Carbon::createFromFormat('d/m/Y', $request->discharge_date)->toDateString(); $inpatient_info->discharged_by = Auth::id(); /* when discharged, update the bed stays table with discharge date */ $ward_bed_stay_active = WardBedStay::where(['patient_id' => $patient_id, 'episode_id' => $episode_id, 'ward_id' => $request->ward_id, 'still_here' => 1])->first(); if ($ward_bed_stay_active) { $ward_bed_stay_active->still_here = 0; $ward_bed_stay_active->to = is_null($ward_bed_stay_active->to) ? Carbon::createFromFormat('d/m/Y', $request->discharge_date)->toDateString() : $ward_bed_stay_active->to; $ward_bed_stay_active->update(); } /* end of bed stay update */ } else if ($request->outcome == 3) { // home with follow up $inpatient_info->discharged = 1; $inpatient_info->discharged_on = date('Y-m-d'); $inpatient_info->discharged_by = Auth::id(); $inpatient_info->followup_where = $request->where; $inpatient_info->followup_when = is_null($request->when) ? null : Carbon::createFromFormat('d/m/Y', $request->when)->toDateString(); // get current clinic of patient if available $episode_information = PatientEpisode::find($episode_id); // save information to the follow-up table $patient_appointment = PatientAppointment::where(['patient_id' => $patient_id, 'episode_id' => $episode_id])->first(); $appointment = $patient_appointment ? $patient_appointment : new PatientAppointment(); $appointment->patient_id = $patient_id; $appointment->incharge_id = $request->followup_in_charge; $appointment->clinic_allocation = $request->followup_clinic_allocation; $appointment->episode_id = $episode_id; $appointment->appointment_date = !is_null($request->followup_when) ? Carbon::createFromFormat('d/m/Y',$request->followup_when)->toDateString() : null; $appointment->appointment_time = $request->followup_in_time; $appointment->created_from = "Inpatient"; $appointment->created_by = Auth::id(); $appointment->updated_by = Auth::id(); $appointment->save(); } else if ($request->outcome == 4) { // referred $inpatient_info->discharged = 1; $inpatient_info->discharged_on = date('Y-m-d'); $inpatient_info->discharged_by = Auth::id(); $inpatient_info->referred_to = $request->referral_id; } else if ($request->outcome == 5) { // died $inpatient_info->died_on = $request->died_on; $inpatient_info->discharged = 1; $inpatient_info->discharged_on = date('Y-m-d'); $inpatient_info->discharged_by = Auth::id(); } else if ($request->outcome == 8) { // ran away without paying $inpatient_info->discharged = 1; $inpatient_info->discharged_on = date('Y-m-d'); $inpatient_info->discharged_by = Auth::id(); } if ($inpatient_info->update()) { if($request->outcome == 2 || $request->outcome == 3 || $request->outcome == 4){ // check if there is a discharge risk record for the patient $discharge_mortality = DB::table('discharge_mortality_risk')->where('inpatient_id', $request->info_id) ->first(); if (is_smart_discharge_enabled() && $discharge_mortality) { perform_post_discharge_actions($patient_id, $discharge_mortality->id); } } //record the update into the inpatient audit table inpatient_sheet_audit($patient_id, $episode_id, $request); switch ($request->get('submit-btn')) { case 'order_tta': // set session for the tta session()->put('tta', 1); return redirect('/prescriptions/create/'); case 'ward_prescription': session()->put('ward_id', $inpatient_info->ward_id); // set session for the ward prescription session()->put('ward_prescription', 1); return redirect('/prescriptions/create/'); case 'order_investigation': // set session for the ward investigation session()->put('ward_investigation', 1); return redirect('/investigations/investigations_review'); case 'billing': return redirect('inpatient_billing'); case 'cancer_protocol': session()->put('inpatient_info_id', $inpatient_info->id); return redirect('/cancer_protocol/order_protocol/'); case 'save': default: flash('Inpatient sheet has been saved')->success(); if (is_smart_discharge_enabled() && $request->redirect_to_pdrm_monitoring == 1) { return redirect('/triage/edit_for_post_discharge/' . $inpatient_info->episode_id); } else { return redirect('in_patient_sheet'); } } } else { flash('An error occurred. Please contact system admin')->error(); return redirect()->back(); } } public function inpatient_billing(Request $request) { if (session('print')){ $print_bill = 1; session()->forget('print'); } else { $print_bill = 0; } $patient_id = session()->get('patient_id'); $episode_id = session()->get('episode_id'); $patient = Patient::find($patient_id); $inpatient_info = InpatientInfo::where(['patient_id' => $patient_id, 'episode_id' => $episode_id])->orderBy('created_at', 'desc')->first(); $treatment_to_take_away = Treatment::where(['patient_id' => $patient_id, 'episode_id' => $episode_id, 'tta' => 1])->get(); $service_deposits = ServiceDeposit::where(['patient_id' => $patient_id, 'episode_id' => $episode_id])->get(); $patient_discount = PatientDiscount::where(['patient_category' => $patient->category_id])->select("discount", "pay_later")->first(); if (!is_null($patient_discount)) { $patient_discount->toArray(); } //get both ward and opd investigations $ordered_ward_investigations = OrderedInvestigation::where(['episode_id' => $episode_id, 'payment_status' => '0'])->get(); // get all ordered investigations paid for in in-patient $inpatient_bill_info = InpatientBill::where(['patient_id' => $patient_id, 'episode_id' => $episode_id])->first(); // set the saved opd prices here $saved_sundry_prices = []; $saved_drug_prices = []; $saved_procedures_prices = []; $saved_services_prices = []; $saved_tta_prices = []; $saved_chi_sundry_prices = []; $saved_chi_drug_prices = []; $saved_chi_procedures_prices = []; $saved_chi_services_prices = []; $saved_chi_tta_prices = []; if ($inpatient_bill_info) { $pre_sundry_ids = $inpatient_bill_info->sundries_item_ids ? explode(",", $inpatient_bill_info->sundries_item_ids) : []; $pre_sundry_prices = $inpatient_bill_info->sundries_item_prices ? explode(",", $inpatient_bill_info->sundries_item_prices) : []; $pre_sundry_chi_prices = $inpatient_bill_info->sundries_item_chi_prices ? explode(",", $inpatient_bill_info->sundries_item_chi_prices) : []; for ($i = 0; $i < count($pre_sundry_ids); $i++) { if (isset($pre_sundry_prices[$i])) { $saved_sundry_prices[$pre_sundry_ids[$i]] = $pre_sundry_prices[$i]; } if (isset($pre_sundry_chi_prices[$i])) { $saved_chi_sundry_prices[$pre_sundry_ids[$i]] = $pre_sundry_chi_prices[$i]; } } $pre_drug_ids = $inpatient_bill_info->prescription_treatment_item_ids ? explode(",", $inpatient_bill_info->prescription_treatment_item_ids) : []; $pre_drug_prices = $inpatient_bill_info->prescription_treatment_item_prices ? explode(",", $inpatient_bill_info->prescription_treatment_item_prices) : []; $pre_drug_chi_prices = $inpatient_bill_info->prescription_treatment_item_chi_prices ? explode(",", $inpatient_bill_info->prescription_treatment_item_chi_prices) : []; for ($i = 0; $i < count($pre_drug_ids); $i++) { if (isset($pre_drug_prices[$i])) { $saved_drug_prices[$pre_drug_ids[$i]] = $pre_drug_prices[$i]; } if (isset($pre_drug_chi_prices[$i])) { $saved_chi_drug_prices[$pre_drug_ids[$i]] = $pre_drug_chi_prices[$i]; } } $pre_procedure_ids = $inpatient_bill_info->procedures_item_ids ? explode(",", $inpatient_bill_info->procedures_item_ids) : []; $pre_procedure_prices = $inpatient_bill_info->procedures_item_prices ? explode(",", $inpatient_bill_info->procedures_item_prices) : []; $pre_procedure_chi_prices = $inpatient_bill_info->procedures_item_chi_prices ? explode(",", $inpatient_bill_info->procedures_item_chi_prices) : []; for ($i = 0; $i < count($pre_procedure_ids); $i++) { if (isset($pre_procedure_prices[$i])) { $saved_procedures_prices[$pre_procedure_ids[$i]] = $pre_procedure_prices[$i]; } if (isset($pre_procedure_chi_prices[$i])) { $saved_chi_procedures_prices[$pre_procedure_ids[$i]] = $pre_procedure_chi_prices[$i]; } } $pre_service_ids = $inpatient_bill_info->services_item_ids ? explode(",", $inpatient_bill_info->services_item_ids) : []; $pre_service_prices = $inpatient_bill_info->services_item_prices ? explode(",", $inpatient_bill_info->services_item_prices) : []; $pre_service_chi_prices = $inpatient_bill_info->services_item_chi_prices ? explode(",", $inpatient_bill_info->services_item_chi_prices) : []; for ($i = 0; $i < count($pre_service_ids); $i++) { if (isset($pre_service_prices[$i])) { $saved_services_prices[$pre_service_ids[$i]] = $pre_service_prices[$i]; } if (isset($pre_service_chi_prices[$i])) { $saved_chi_services_prices[$pre_service_ids[$i]] = $pre_service_chi_prices[$i]; } } $pre_tta_ids = $inpatient_bill_info->tta_item_ids ? explode(",", $inpatient_bill_info->tta_item_ids) : []; $pre_tta_prices = $inpatient_bill_info->tta_item_prices ? explode(",", $inpatient_bill_info->tta_item_prices) : []; $pre_tta_chi_prices = $inpatient_bill_info->tta_item_chi_prices ? explode(",", $inpatient_bill_info->tta_item_chi_prices) : []; for ($i = 0; $i < count($pre_tta_ids); $i++) { if (isset($pre_tta_prices[$i])) { $saved_tta_prices[$pre_tta_ids[$i]] = $pre_tta_prices[$i]; } if (isset($pre_tta_chi_prices[$i])) { $saved_chi_tta_prices[$pre_tta_ids[$i]] = $pre_tta_chi_prices[$i]; } } } // get ward dispensing details if available $ward_treatment_drug_ids_that_have_been_dispensed_array = WardTreatmentDispensation::where(['patient_id' => $patient_id, 'episode_id' => $episode_id])->whereNull('deleted_at')->distinct('drug_id')->pluck('drug_id')->toArray(); $dispensed_drug_quantity_given_array = []; for ($i = 0; $i < count($ward_treatment_drug_ids_that_have_been_dispensed_array); $i++) { $drug_ward_quantity_given = WardTreatmentDispensation::where(['patient_id' => $patient_id, 'episode_id' => $episode_id, 'drug_id' => $ward_treatment_drug_ids_that_have_been_dispensed_array[$i]])->sum('quantity_given'); $dispensed_drug_quantity_given_array[$ward_treatment_drug_ids_that_have_been_dispensed_array[$i]] = $drug_ward_quantity_given; } $price_list_categories = PriceListCategories::select('patient_category_id', 'id')->get(); if (isset($request->price_list_category_id) && $request->price_list_category_id != 0) { $price_list_set = $request->price_list_category_id; } else { $price_list_set = false; } //if the price list was changed before, continue using the price list that was set the last time /* if($inpatient_bill_info && !is_null($inpatient_bill_info->price_list)){ $price_list_set = $inpatient_bill_info->price_list; } */ // Check for anaesthesia in this episode $anaesthesia = DB::table('anaesthesias')->where('episode_id', $episode_id)->select('other_drugs_given', 'other_drugs_cost', 'other_drugs_bill')->first(); $services_with_users_array = InpatientController::configured_users_with_their_services_array(); $service_items = Services::withTrashed()->orderBy('name','asc')->pluck('name', 'id')->prepend('- select -', ''); $users_collection = DB::table('users')->orderBy("first_name","asc")->select("id")->get()->toArray(); $service_with_users_array = []; $users_array = []; $options_users = ""; foreach ($users_collection as $value){ $user = User::find($value->id); if (!is_null($user)) { $users_array[$user->id] = $user->first_name . " ". $user->last_name; $options_users .= ""; 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('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; //concatenate the service_record_id with the users_id to form the key for the array $dynamic_key = $record->id."__".$value->id; $dynamic_value = get_full_name($value->id, 'id', 'first_name', 'last_name', 'users')." (".$record->name.")"; $service_with_users_array[$dynamic_key] = $dynamic_value; //add these dynamically formed values to service_items array array_add($service_items, $dynamic_key, $dynamic_value); //add it to the services_options too i.e used when user clicks add_service btn } } } } $sundries = Sundry::where('available', 1)->orderby('name', 'asc')->pluck('name', 'id')->prepend('- select -', ''); //check for authenticated investigations $investigation_results = InvestigationResults::where(['patient_id' => $patient_id,'episode_id' => $episode_id ,'inpatient' => 1])->get(); return view('ward_management::inpatient.inpatient_billing', compact('patient', 'dispensed_drug_quantity_given_array','patient', 'inpatient_info', 'patient_id', 'saved_sundry_prices','treatment_to_take_away', 'service_deposits', 'patient_discount', 'episode_id', 'ordered_ward_investigations', 'saved_chi_tta_prices', 'price_list_categories', 'price_list_set', 'anaesthesia', 'print_bill', 'services_with_users_array', 'service_items', 'sundries', 'investigation_results', 'inpatient_bill_info', 'saved_drug_prices', 'saved_procedures_prices', 'saved_services_prices', 'saved_tta_prices', 'saved_chi_sundry_prices', 'saved_chi_drug_prices', 'saved_chi_procedures_prices', 'saved_chi_services_prices')); } public function store_inpatient_bill(Request $request) { $patient_id = session()->get('patient_id'); $episode_id = session()->get('episode_id'); $insurance_claims = []; // generate receipt number $receipt_number = $this->receiptService->createReceipt('Inpatient Bill'); // begin transaction DB::beginTransaction(); try { // store ward investigations and there dynamic prices $ward_investigations_array = $request->investigations_item_ids; $ward_investigations_amounts_array = $request->investigation_amount; $ward_investigations_insurance_amounts_array = $request->investigation_insurance_amount; $ward_investigation_order_ids = $request->investigation_order_ids; $investigations_tariff_ids = $request->investigations_tariff_ids; $investigations_benefit_ids = $request->investigations_benefit_ids; $ward_inv_pricing_ids = $request->ward_inv_pricing_ids; $orders_with_pricing = []; if (is_array($ward_investigations_array)) { for ($i=0; $i < count($ward_investigations_array) ; $i++) { $ward_inv_pricing = WardInvestigationPricing::find($ward_inv_pricing_ids[$i]); if (!$ward_inv_pricing) { $ward_inv_pricing = new WardInvestigationPricing(); $ward_inv_pricing->patient_id = $patient_id; $ward_inv_pricing->episode_id = $episode_id; $ward_inv_pricing->investigation_id = $ward_investigations_array[$i]; $ward_inv_pricing->order_id = $ward_investigation_order_ids[$i]; $ward_inv_pricing->ward_id = get_name($request->inpatient_info_id, "id", "ward_id", "inpatient_info"); $ward_inv_pricing->current_chart_of_account = get_name($ward_investigations_array[$i], "id", "account_id", "investigations"); $ward_inv_pricing->created_by = Auth::id(); } $ward_inv_pricing->price = $ward_investigations_amounts_array[$i]; $ward_inv_pricing->chi_price = $ward_investigations_insurance_amounts_array[$i]; $ward_inv_pricing->save(); $orders_with_pricing[$ward_investigation_order_ids[$i]][] = $ward_inv_pricing->id; // check if benefit is valid and save item if ($investigations_benefit_ids[$i] != 0) { $insurance_claims[3]["benefit_ids"][] = $investigations_benefit_ids[$i]; $insurance_claims[3]["item_ids"][] = $ward_investigations_array[$i]; $insurance_claims[3]["item_quantities"][] = 1; $insurance_claims[3]["tariff_ids"][] = $investigations_tariff_ids[$i]; $insurance_claims[3]["tariff_amounts"][] = $ward_investigations_insurance_amounts_array[$i]; $insurance_claims[3]["co_payment_amounts"][] = $ward_investigations_amounts_array[$i]; $insurance_claims[3]["item_cash_amounts"][] = $ward_investigations_insurance_amounts_array[$i] + $ward_investigations_amounts_array[$i]; } } } // ward treatments $ward_treatments_ids = $request->prescription_treatment_item_ids ?? []; $ward_treatment_amounts = $request->prescription_treatment_item_prices ?? []; $ward_treatment_insurance = $request->drug_unit_insurance_amount ?? []; $ward_treatment_tariff_ids = $request->prescription_treatment_tariff_ids ?? []; $ward_treatment_benefit_ids = $request->prescription_treatment_benefit_ids ?? []; $ward_treatment_quantities = $request->ward_drug_quantity ?? []; $ward_treatment_subtotal = $request->drug_subtotal ?? []; $ward_treatment_subtotal_insurance = $request->drug_insurance_amount ?? []; for ($i=0; $i < count($ward_treatments_ids); $i++) { $ward_treatment = WardTreatmentDispensation::where(['patient_id' => $patient_id, 'episode_id' => $episode_id, 'drug_id' => $ward_treatments_ids[$i]])->first(); if ($ward_treatment) { $ward_treatment->price = $ward_treatment_amounts[$i] ?? 0; $ward_treatment->chi_price = $ward_treatment_insurance[$i] ?? 0; $ward_treatment->update(); // check if benefit is valid and save item if ($ward_treatment_benefit_ids[$i] != 0) { $insurance_claims[4]["benefit_ids"][] = $ward_treatment_benefit_ids[$i]; $insurance_claims[4]["item_ids"][] = $ward_treatments_ids[$i]; $insurance_claims[4]["item_quantities"][] = (int)$ward_treatment_quantities[$i]; $insurance_claims[4]["tariff_ids"][] = $ward_treatment_tariff_ids[$i]; $insurance_claims[4]["tariff_amounts"][] = $ward_treatment_subtotal_insurance[$i]; $insurance_claims[4]["co_payment_amounts"][] = $ward_treatment_subtotal[$i]; $insurance_claims[4]["item_cash_amounts"][] = $ward_treatment_subtotal_insurance[$i] + $ward_treatment_subtotal[$i]; } } } // ward services $ward_service_ids = $request->services_item_ids ?? []; $ward_service_amounts = $request->services_item_prices ?? []; $ward_service_insurance = $request->service_insurance_unit ?? []; $ward_service_benefit_ids = $request->service_benefit_ids ?? []; $ward_service_tariff_ids = $request->service_tariff_ids ?? []; $ward_service_quantity = $request->service_quantity ?? []; $ward_service_total_cost = $request->service_total_cost ?? []; $ward_service_total_insurance = $request->service_insurance_amount ?? []; for ($i=0; $i < count($ward_service_ids); $i++) { $ward_service = WardConsultationsAndService::where(['patient_id' => $patient_id, 'episode_id' => $episode_id, 'service_id' => $ward_service_ids[$i]])->first(); if ($ward_service) { $ward_service->unit_price = $ward_service_amounts[$i] ?? 0; $ward_service->chi_price = $ward_service_insurance[$i] ?? 0; $ward_service->update(); // check if benefit is valid and save item if ($ward_service_benefit_ids[$i] != 0) { $insurance_claims[1]["benefit_ids"][] = $ward_service_benefit_ids[$i]; $insurance_claims[1]["item_ids"][] = $ward_service_ids[$i]; $insurance_claims[1]["item_quantities"][] = $ward_service_quantity[$i]; $insurance_claims[1]["tariff_ids"][] = $ward_service_tariff_ids[$i]; $insurance_claims[1]["tariff_amounts"][] = $ward_service_total_insurance[$i]; $insurance_claims[1]["co_payment_amounts"][] = $ward_service_total_cost[$i]; $insurance_claims[1]["item_cash_amounts"][] = $ward_service_total_insurance[$i] + $ward_service_total_cost[$i]; } } } // ward sundries $ward_sundry_ids = $request->sundries_item_ids ?? []; $ward_sundry_amounts = $request->sundries_item_prices ?? []; $ward_sundry_insurance = $request->sundry_unit_insurance_amount ?? []; $ward_sundry_tariff_ids = $request->sundries_tariff_ids ?? []; $ward_sundry_benefit_ids = $request->sundries_benefit_ids ?? []; $ward_sundry_quantity = $request->sundry_quantity_given ?? []; $ward_sundry_subtotal = $request->sundry_subtotal ?? []; $ward_sundry_subtotal_insurance = $request->sundry_insurance_amount ?? []; for ($i=0; $i < count($ward_sundry_ids); $i++) { $ward_sundry = WardSundryDispensation::where(['patient_id' => $patient_id, 'episode_id' => $episode_id, 'sundry_id' => $ward_sundry_ids[$i]])->first(); if ($ward_sundry) { $ward_sundry->price = $ward_sundry_amounts[$i] ?? 0; $ward_sundry->chi_price = $ward_sundry_insurance[$i] ?? 0; $ward_sundry->update(); // check if benefit is valid and save item if ($ward_sundry_benefit_ids[$i] != 0) { $insurance_claims[5]["benefit_ids"][] = $ward_sundry_benefit_ids[$i]; $insurance_claims[5]["item_ids"][] = $ward_sundry_ids[$i]; $insurance_claims[5]["item_quantities"][] = $ward_sundry_quantity[$i]; $insurance_claims[5]["tariff_ids"][] = $ward_sundry_tariff_ids[$i]; $insurance_claims[5]["tariff_amounts"][] = $ward_sundry_subtotal_insurance[$i]; $insurance_claims[5]["co_payment_amounts"][] = $ward_sundry_subtotal[$i]; $insurance_claims[5]["item_cash_amounts"][] = $ward_sundry_subtotal_insurance[$i] + $ward_sundry_subtotal[$i]; } } } // ward procedures $ward_procedure_ids = $request->procedures_item_ids ?? []; $ward_procedure_amounts = $request->ipd_procedure_amount ?? []; $ward_procedure_insurance = $request->ipd_procedure_insurance_amount ?? []; $ward_procedure_benefit_ids = $request->ipd_procedure_benefit_ids ?? []; $ward_procedure_tariff_ids = $request->ipd_procedure_tariff_ids ?? []; $ward_procedure_order_ids = $request->ipd_procedure_order_ids ?? []; for ($i=0; $i < count($ward_procedure_ids); $i++) { $ward_procedure = WardProcedure::where('id', $ward_procedure_order_ids[$i])->first(); if ($ward_procedure) { $ward_procedure->hospital_fee = $ward_procedure_amounts[$i] ?? 0; $ward_procedure->chi_price = $ward_procedure_insurance[$i] ?? 0; $ward_procedure->update(); // check if benefit is valid and save item if ($ward_procedure_benefit_ids[$i] != 0) { $insurance_claims[2]["benefit_ids"][] = $ward_procedure_benefit_ids[$i]; $insurance_claims[2]["item_ids"][] = $ward_procedure_ids[$i]; $insurance_claims[2]["item_quantities"][] = 1; $insurance_claims[2]["tariff_ids"][] = $ward_procedure_tariff_ids[$i]; $insurance_claims[2]["tariff_amounts"][] = $ward_procedure_insurance[$i]; $insurance_claims[2]["co_payment_amounts"][] = $ward_procedure_amounts[$i]; $insurance_claims[2]["item_cash_amounts"][] = $ward_procedure_insurance[$i] + $ward_procedure_amounts[$i]; } } } // make claims for items if insured if ($request->patient_insurance_status == 1) { $opd_treatment_item = $request->opd_treatment_item ?? []; $opd_treatment_tariff = $request->opd_treatment_tariff ?? []; $opd_treatment_benefit = $request->opd_treatment_benefit ?? []; $opd_treatment_quantity = $request->opd_treatment_quantity ?? []; $opd_treatment_subtotal = $request->opd_treatment_subtotal ?? []; $opd_treatment_insurance_amount = $request->opd_treatment_insurance_amount ?? []; for ($i=0; $i < count($opd_treatment_item); $i++) { if ($opd_treatment_benefit[$i] != 0) { $insurance_claims[4]["benefit_ids"][] = $opd_treatment_benefit[$i]; $insurance_claims[4]["item_ids"][] = $opd_treatment_item[$i]; $insurance_claims[4]["item_quantities"][] = (int)$opd_treatment_quantity[$i]; $insurance_claims[4]["tariff_ids"][] = $opd_treatment_tariff[$i]; $insurance_claims[4]["tariff_amounts"][] = $opd_treatment_insurance_amount[$i]; $insurance_claims[4]["co_payment_amounts"][] = $opd_treatment_subtotal[$i]; $insurance_claims[4]["item_cash_amounts"][] = $opd_treatment_insurance_amount[$i] + $opd_treatment_subtotal[$i]; } } $tta_drugs_array = $request->tta_drugs_array ?? []; $tta_tariff_ids = $request->tta_tariff_ids ?? []; $tta_benefit_ids = $request->tta_benefit_ids ?? []; $tta_quantity = $request->tta_quantity ?? []; $tta_amount = $request->tta_amount ?? []; $tta_insurance_amount = $request->tta_insurance_amount ?? []; for ($i=0; $i < count($tta_drugs_array); $i++) { if ($tta_benefit_ids[$i] != 0) { $insurance_claims[4]["benefit_ids"][] = $tta_benefit_ids[$i]; $insurance_claims[4]["item_ids"][] = $tta_drugs_array[$i]; $insurance_claims[4]["item_quantities"][] = (int)$tta_quantity[$i]; $insurance_claims[4]["tariff_ids"][] = $tta_tariff_ids[$i]; $insurance_claims[4]["tariff_amounts"][] = $tta_amount[$i]; $insurance_claims[4]["co_payment_amounts"][] = $tta_insurance_amount[$i]; $insurance_claims[4]["item_cash_amounts"][] = $tta_amount[$i] + $tta_insurance_amount[$i]; } } $opd_service_id = $request->opd_service_id ?? []; $opd_service_benefit_ids = $request->opd_service_benefit_ids ?? []; $opd_service_tariff_ids = $request->opd_service_tariff_ids ?? []; $opd_service_quantity = $request->opd_service_quantity ?? []; $opd_service_amount = $request->opd_service_amount ?? []; $opd_service_insurance_amount = $request->opd_service_insurance_amount ?? []; for ($i=0; $i < count($opd_service_id); $i++) { if ($opd_service_benefit_ids[$i] != 0) { $insurance_claims[1]["benefit_ids"][] = $opd_service_benefit_ids[$i]; $insurance_claims[1]["item_ids"][] = $opd_service_id[$i]; $insurance_claims[1]["item_quantities"][] = $opd_service_quantity[$i]; $insurance_claims[1]["tariff_ids"][] = $opd_service_tariff_ids[$i]; $insurance_claims[1]["tariff_amounts"][] = $opd_service_insurance_amount[$i]; $insurance_claims[1]["co_payment_amounts"][] = $opd_service_amount[$i]; $insurance_claims[1]["item_cash_amounts"][] = $opd_service_insurance_amount[$i] + $opd_service_amount[$i]; } } $opd_sundries_ids = $request->opd_sundries_ids ?? []; $opd_sundries_benefit_ids = $request->opd_sundries_benefit_ids ?? []; $opd_sundries_tariff_ids = $request->opd_sundries_tariff_ids ?? []; $opd_sundry_quantity = $request->opd_sundry_quantity ?? []; $opd_sundry_subtotal = $request->opd_sundry_subtotal ?? []; $opd_sundry_insurance_amount = $request->opd_sundry_insurance_amount ?? []; for ($i=0; $i < count($opd_sundries_ids); $i++) { if ($opd_sundries_benefit_ids[$i] != 0) { $insurance_claims[5]["benefit_ids"][] = $opd_sundries_benefit_ids[$i]; $insurance_claims[5]["item_ids"][] = $opd_sundries_ids[$i]; $insurance_claims[5]["item_quantities"][] = $opd_sundry_quantity[$i]; $insurance_claims[5]["tariff_ids"][] = $opd_sundries_tariff_ids[$i]; $insurance_claims[5]["tariff_amounts"][] = $opd_sundry_subtotal[$i]; $insurance_claims[5]["co_payment_amounts"][] = $opd_sundry_insurance_amount[$i]; $insurance_claims[5]["item_cash_amounts"][] = $opd_sundry_subtotal[$i] + $opd_sundry_insurance_amount[$i]; } } $opd_procedure_ids = $request->opd_procedure_ids ?? []; $opd_procedure_benefit_ids = $request->opd_procedure_benefit_ids ?? []; $opd_procedure_tariff_ids = $request->opd_procedure_tariff_ids ?? []; $opd_procedure_amount = $request->opd_procedure_amount ?? []; $opd_procedure_insurance_amount = $request->opd_procedure_insurance_amount ?? []; for ($i=0; $i < count($opd_procedure_ids); $i++) { if ($opd_procedure_benefit_ids[$i] != 0) { $insurance_claims[2]["benefit_ids"][] = $opd_procedure_benefit_ids[$i]; $insurance_claims[2]["item_ids"][] = $opd_procedure_ids[$i]; $insurance_claims[2]["item_quantities"][] = 1; $insurance_claims[2]["tariff_ids"][] = $opd_procedure_tariff_ids[$i]; $insurance_claims[2]["tariff_amounts"][] = $opd_procedure_insurance_amount[$i]; $insurance_claims[2]["co_payment_amounts"][] = $opd_procedure_amount[$i]; $insurance_claims[2]["item_cash_amounts"][] = $opd_procedure_insurance_amount[$i] + $opd_procedure_amount[$i]; } } $ward_bed_stays = WardBedStay::where(['patient_id' => $patient_id, 'episode_id' => $episode_id])->whereNotIn('chi_bed_rate_id', [0])->get(); foreach ($ward_bed_stays as $stay) { $rate_info = DB::table('insurance_inpatient_accommodation_rates')->where('id', $stay->chi_bed_rate_id)->first(); if($rate_info) { $insurance_claims[6]["benefit_ids"][] = $rate_info->benefit_id; $insurance_claims[6]["item_ids"][] = $rate_info->id; $insurance_claims[6]["item_quantities"][] = $stay->duration; $insurance_claims[6]["tariff_ids"][] = 0; $insurance_claims[6]["tariff_amounts"][] = $stay->chi_bed_fee_total; $insurance_claims[6]["co_payment_amounts"][] = $stay->bed_fee_total; $insurance_claims[6]["item_cash_amounts"][] = $stay->chi_bed_fee_total + $stay->bed_fee_total; } } } // check if any investigations are available if ($request->investigation_ids) { $inpatient_info = InpatientInfo::find($request->inpatient_info_id); $inpatient_info->investigation_ids = $request->investigation_ids; $inpatient_info->update(); $order_ids_array = $request->investigation_order_ids; // update the ordered_investigation table to show it has been paid for ($i = 0; $i < count($order_ids_array); $i++) { OrderedInvestigation::where(['id' => $order_ids_array[$i]]) ->update([ 'inpatient_bill_generated' => 1, 'ward_pricing_id' => implode(",", $orders_with_pricing[$order_ids_array[$i]]) ]); remove_insurance_claim_by_order($order_ids_array[$i], 3); } } /* start unpaid opd items black magic */ if ($request->opd_treatment_cost) { $opd_ordered_treatments = []; for ($i=0; $i < count($request->opd_treatment_id) ; $i++) { $drug_details = DB::table('drugs')->find($request->opd_treatment_item[$i]); $opd_ordered_treatments[$request->opd_treatment_id[$i]]['amount_paid'][] = $request->opd_treatment_subtotal[$i]; $opd_ordered_treatments[$request->opd_treatment_id[$i]]['current_chart_of_account'][] = $drug_details->account_id; $opd_ordered_treatments[$request->opd_treatment_id[$i]]['unit_selling_prices'][] = $request->opd_treatment_amount[$i]; $opd_ordered_treatments[$request->opd_treatment_id[$i]]['unit_cost_price'][] = $drug_details->cost_price; $opd_ordered_treatments[$request->opd_treatment_id[$i]]['cost_of_goods_account'][] = $drug_details->cost_of_goods_account; $opd_ordered_treatments[$request->opd_treatment_id[$i]]['inventory_account'][] = $drug_details->inventory_account; $opd_ordered_treatments[$request->opd_treatment_id[$i]]['bill_generated'] = $request->opd_inpatient_bill_generated[$i]; } foreach ($opd_ordered_treatments as $key => $opd_ordered_treatment) { if ($opd_ordered_treatment['bill_generated'] == 0) { Treatment::where(['id' => $key])->update([ 'inpatient_bill_generated' => 1, 'balance' => implode(",", $opd_ordered_treatment['amount_paid']), 'current_chart_of_account' => implode(",", $opd_ordered_treatment['current_chart_of_account']), 'unit_selling_prices' => implode(",", $opd_ordered_treatment['unit_selling_prices']), 'cost_of_goods_account' => implode(",", $opd_ordered_treatment['cost_of_goods_account']), 'unit_cost_price' => implode(",", $opd_ordered_treatment['unit_cost_price']), 'inventory_account' => implode(",", $opd_ordered_treatment['inventory_account']), 'amount_paid' => implode(",", array_fill(0, count($opd_ordered_treatment['amount_paid']), 0)), ]); } else { Treatment::where(['id' => $key])->update([ 'unit_selling_prices' => implode(",", $opd_ordered_treatment['unit_selling_prices']) ]); } remove_insurance_claim_by_order($key, 4); } } if ($request->tta_treatment_id) { $tta_treatments = []; for ($i=0; $i < count($request->tta_treatment_id) ; $i++) { $drug_details = DB::table('drugs')->find($request->tta_drugs_array[$i]); $tta_treatments[$request->tta_treatment_id[$i]]['amount_paid'][] = $request->tta_amount[$i]; $tta_treatments[$request->tta_treatment_id[$i]]['current_chart_of_account'][] = $drug_details->account_id; $tta_treatments[$request->tta_treatment_id[$i]]['unit_selling_prices'][] = $request->tta_unit_cost[$i]; $tta_treatments[$request->tta_treatment_id[$i]]['unit_cost_price'][] = $drug_details->cost_price; $tta_treatments[$request->tta_treatment_id[$i]]['cost_of_goods_account'][] = $drug_details->cost_of_goods_account; $tta_treatments[$request->tta_treatment_id[$i]]['inventory_account'][] = $drug_details->inventory_account; $tta_treatments[$request->tta_treatment_id[$i]]['bill_generated'] = $request->tta_inpatient_bill_generated[$i]; } foreach ($tta_treatments as $key => $tta_treatment) { if ($tta_treatment['bill_generated'] == 0) { Treatment::where(['id' => $key])->update([ 'inpatient_bill_generated' => 1, 'balance' => implode(",", $tta_treatment['amount_paid']), 'current_chart_of_account' => implode(",", $tta_treatment['current_chart_of_account']), 'unit_selling_prices' => implode(",", $tta_treatment['unit_selling_prices']), 'cost_of_goods_account' => implode(",", $tta_treatment['cost_of_goods_account']), 'unit_cost_price' => implode(",", $tta_treatment['unit_cost_price']), 'inventory_account' => implode(",", $tta_treatment['inventory_account']), 'amount_paid' => implode(",", array_fill(0, count($tta_treatment['amount_paid']), 0)), ]); } else { Treatment::where(['id' => $key])->update([ 'unit_selling_prices' => implode(",", $tta_treatment['unit_selling_prices']) ]); } remove_insurance_claim_by_order($key, 4); } } if ($request->opd_sundries_cost) { $sundry_order_ids_array = explode(",", $request->opd_sundry_order_ids); for ($i=0; $i < count($sundry_order_ids_array) ; $i++) { OrderedSundry::where(['id' => $sundry_order_ids_array[$i]])->update(['inpatient_bill_generated' => 1]); remove_insurance_claim_by_order($sundry_order_ids_array[$i], 5); } $arr_opd_sundries_ids = $request->opd_sundries_ids; $arr_opd_sundry_insurance_unit = $request->opd_sundry_insurance_unit; $arr_opd_sundry_quantity = $request->opd_sundry_quantity; $arr_opd_sundry_subtotal = $request->opd_sundry_subtotal; for ($i=0; $i < count($arr_opd_sundries_ids) ; $i++) { $sundry_details = Sundry::find($arr_opd_sundries_ids[$i]); $ward_sundry_dispensations = new WardSundryDispensation; $ward_sundry_dispensations->patient_id = $patient_id; $ward_sundry_dispensations->episode_id = $episode_id; $ward_sundry_dispensations->sundry_id = $arr_opd_sundries_ids[$i]; $ward_sundry_dispensations->quantity_given = $arr_opd_sundry_quantity[$i]; $ward_sundry_dispensations->dispensation_date = Carbon::now(); $ward_sundry_dispensations->current_chart_of_account = $sundry_details->account_id; $ward_sundry_dispensations->inventory_account = $sundry_details->inventory_account; $ward_sundry_dispensations->cost_of_goods_account = $sundry_details->cost_of_goods_account; $ward_sundry_dispensations->cost_price = $sundry_details->cost_price; $ward_sundry_dispensations->chi_price = $arr_opd_sundry_insurance_unit[$i]; $ward_sundry_dispensations->price = $arr_opd_sundry_subtotal[$i]; $ward_sundry_dispensations->ward_id = get_name($request->inpatient_info_id, "id", "ward_id", "inpatient_info"); $ward_sundry_dispensations->created_by = Auth::id(); $ward_sundry_dispensations->save(); } } if ($request->opd_services_cost) { $services_order_ids_array = $request->opd_service_order_id; for ($i=0; $i < count($services_order_ids_array) ; $i++) { OrderedService::where(['id' => $services_order_ids_array[$i]])->update(['inpatient_bill_generated' => 1]); remove_insurance_claim_by_order($services_order_ids_array[$i], 1); } $arr_opd_service_id = $request->opd_service_id; $arr_opd_service_unit_cost = $request->opd_service_unit_cost; $arr_opd_service_insurance_unit = $request->opd_service_insurance_unit; $arr_opd_service_quantity = $request->opd_service_quantity; for ($i=0; $i < count($arr_opd_service_id) ; $i++) { $ward_services_and_consultations = new WardConsultationsAndService; $ward_services_and_consultations->patient_id = $patient_id; $ward_services_and_consultations->episode_id = $episode_id; $ward_services_and_consultations->service_id = $arr_opd_service_id[$i]; $ward_services_and_consultations->quantity_given = $arr_opd_service_quantity[$i]; $ward_services_and_consultations->unit_price = $arr_opd_service_unit_cost[$i]; $ward_services_and_consultations->staff_fee = 0; $ward_services_and_consultations->chi_price = $arr_opd_service_insurance_unit[$i]; $ward_services_and_consultations->dispensation_date = Carbon::now(); $ward_services_and_consultations->current_chart_of_account = get_name($arr_opd_service_id[$i], "id", "account_id", "services"); $ward_services_and_consultations->ward_id = get_name($request->inpatient_info_id, "id", "ward_id", "inpatient_info"); $ward_services_and_consultations->created_by = Auth::id(); $ward_services_and_consultations->save(); } } if ($request->opd_procedures_cost) { $procedure_order_ids_array = explode(",", $request->opd_procedure_order_ids); for ($i=0; $i < count($procedure_order_ids_array) ; $i++) { OrderedProcedure::where(['id' => $procedure_order_ids_array[$i]])->update(['inpatient_bill_generated' => 1]); remove_insurance_claim_by_order($procedure_order_ids_array[$i], 2); } $arr_opd_procedure_ids = $request->opd_procedure_ids; $arr_opd_procedure_insurance_amount = $request->opd_procedure_insurance_amount; $arr_opd_procedure_amount = $request->opd_procedure_amount; for ($x=0; $x < count($arr_opd_procedure_ids) ; $x++) { $ward_procedures_record = new WardProcedure; $ward_procedures_record->patient_id = $patient_id; $ward_procedures_record->episode_id = $episode_id; $ward_procedures_record->procedure_id = $arr_opd_procedure_ids[$x]; $ward_procedures_record->hospital_fee = $arr_opd_procedure_amount[$x]; $ward_procedures_record->staff_fee = 0; $ward_procedures_record->chi_price = $arr_opd_procedure_insurance_amount[$x]; $ward_procedures_record->procedure_date = Carbon::now(); $ward_procedures_record->ward_id = get_name($request->inpatient_info_id, "id", "ward_id", "inpatient_info"); $ward_procedures_record->eye = null; $ward_procedures_record->current_chart_of_account = get_name($arr_opd_procedure_ids[$x], "id", "account_id", "procedures"); $ward_procedures_record->created_by = Auth::id(); $ward_procedures_record->save(); } } $inpatient_bill = InpatientBill::where(['patient_id'=>$patient_id, 'episode_id'=>$episode_id])->first(); if (is_null($inpatient_bill)) { // create new record $inpatient_bill = new InpatientBill; $inpatient_bill->patient_id = $patient_id; $inpatient_bill->episode_id = $episode_id; $inpatient_bill->created_by = Auth::id(); } else { $inpatient_bill->updated_by = Auth::id(); } //determine whether to update the prices in the ward table or not to allow retrospective billing if (!is_null($request->billing_price_list)) { $this->update_ward_consumption_prices_with_price_list($patient_id, $episode_id, $request->billing_price_list); } $inpatient_bill->price_list = $request->billing_price_list; $inpatient_bill->duration = $request->duration; $inpatient_bill->receipt_number = $receipt_number; $inpatient_bill->inpatient_info_id = $request->inpatient_info_id; $inpatient_bill->treatment_cost = ($request->treatment_cost ?? 0) + ($request->opd_treatment_cost ?? 0); $inpatient_bill->sundries_cost = ($request->sundries_cost ?? 0) + ($request->opd_sundries_cost ?? 0); $inpatient_bill->services_cost = ($request->services_cost ?? 0) + ($request->opd_services_cost ?? 0); $inpatient_bill->procedures_cost = ($request->procedures_cost ?? 0) + ($request->opd_procedures_cost ?? 0); $inpatient_bill->extras_cost = $request->extras_cost; $inpatient_bill->tta_cost = $request->tta_cost; $inpatient_bill->investigation_cost = $request->investigation_cost ?? 0; $inpatient_bill->insurance_hospital_stay_cost = $request->insurance_admission_cost ?? 0; $inpatient_bill->hospital_stay_cost = $request->ward_bed_admission_cost ?? 0; $inpatient_bill->insurance_investigation_cost = $request->insurance_investigation_cost ?? 0; $inpatient_bill->insurance_treatment_cost = ($request->insurance_treatment_cost ?? 0) + ($request->insurance_opd_treatment ?? 0); $inpatient_bill->insurance_sundries_cost = ($request->insurance_sundries_cost ?? 0) + ($request->insurance_opd_sundries_cost ?? 0); $inpatient_bill->insurance_services_cost = ($request->insurance_services_cost ?? 0) + ($request->insurance_opd_services_cost ?? 0); $inpatient_bill->insurance_procedures_cost = ($request->insurance_procedures_cost ?? 0) + ($request->insurance_opd_procedures_cost ?? 0); $inpatient_bill->insurance_tta_cost = $request->insurance_tta_cost; $inpatient_bill->amount_to_pay = $request->amount_owed; $inpatient_bill->original_bill = $request->original_amount_owed; $inpatient_bill->amount_paid = $request->deposits_made; $inpatient_bill->invoices_amount = $request->invoices_amount + $request->ward_discount_total; // save items and prices for OPD items since IPD have their own tables 'cept for investigations $inpatient_bill->investigations_item_prices = is_null($request->investigation_amount) ? null : implode(",",$request->investigation_amount); $inpatient_bill->sundries_item_prices = is_null($request->opd_sundry_amount) ? null : implode(",",$request->opd_sundry_amount); $inpatient_bill->prescription_treatment_item_prices = is_null($request->opd_treatment_amount) ? null : implode(",",$request->opd_treatment_amount); $inpatient_bill->pf_treatment_item_prices = is_null($request->pf_treatment_item_prices) ? null : implode(",",$request->pf_treatment_item_prices); $inpatient_bill->procedures_item_prices = is_null($request->opd_procedure_amount) ? null : implode(",",$request->opd_procedure_amount); $inpatient_bill->services_item_prices = is_null($request->opd_service_unit_cost) ? null : implode(",",$request->opd_service_unit_cost); $inpatient_bill->tta_item_prices = is_null($request->tta_unit_cost) ? null : implode(",",$request->tta_unit_cost); $inpatient_bill->investigations_item_chi_prices = is_null($request->investigation_insurance_amount) ? null : implode(",",$request->investigation_insurance_amount); $inpatient_bill->sundries_item_chi_prices = is_null($request->opd_sundry_insurance_unit) ? null : implode(",",$request->opd_sundry_insurance_unit); $inpatient_bill->prescription_treatment_item_chi_prices = is_null($request->opd_treatment_insurance_unit_amount) ? null : implode(",",$request->opd_treatment_insurance_unit_amount); $inpatient_bill->procedures_item_chi_prices = is_null($request->opd_procedure_insurance_amount) ? null : implode(",",$request->opd_procedure_insurance_amount); $inpatient_bill->services_item_chi_prices = is_null($request->opd_service_insurance_unit) ? null : implode(",",$request->opd_service_insurance_unit); $inpatient_bill->tta_item_chi_prices = is_null($request->tta_insurance_unit) ? null : implode(",",$request->tta_insurance_unit); $inpatient_bill->investigations_item_ids = is_null($request->investigations_item_ids) ? null : implode(",",$request->investigations_item_ids); $inpatient_bill->sundries_item_ids = is_null($request->opd_sundries_ids) ? null : implode(",",$request->opd_sundries_ids); $inpatient_bill->prescription_treatment_item_ids = is_null($request->opd_treatment_item) ? null : implode(",",$request->opd_treatment_item); $inpatient_bill->pf_treatment_item_ids = is_null($request->pf_treatment_item_ids) ? null : implode(",",$request->pf_treatment_item_ids); $inpatient_bill->procedures_item_ids = is_null($request->opd_procedure_ids) ? null : implode(",",$request->opd_procedure_ids); $inpatient_bill->services_item_ids = is_null($request->opd_service_id) ? null : implode(",",$request->opd_service_id); $inpatient_bill->tta_item_ids = is_null($request->tta_drugs_array) ? null : implode(",",$request->tta_drugs_array); $saved_bill_savers_array = is_null($inpatient_bill->bill_saved_by) ? [] : explode(",", $inpatient_bill->bill_saved_by); $saved_bill_savers_array[] = Auth::id(); $inpatient_bill->bill_saved_by = implode(",", $saved_bill_savers_array); $bill_saved_at_array = is_null($inpatient_bill->bill_saved_at) ? [] : explode(",", $inpatient_bill->bill_saved_at); $bill_saved_at_array[] = Carbon::now(); $inpatient_bill->bill_saved_at = implode(",", $bill_saved_at_array); $inpatient_bill->save(); flash("Inpatient billing details have been saved successfully")->success(); // generate the insurance claims if ($request->patient_insurance_status == 1) { create_inpatient_claims($insurance_claims, $patient_id, $episode_id, $inpatient_bill->id); } // handle closing the inpatient bill if ($request->get('submit-btn') == 'save_close_bill') { $inpatient_bill->bill_closed = 1; $inpatient_bill->bill_closed_by = Auth::id(); $inpatient_bill->bill_closed_at = Carbon::now(); $claim_ids_with_errors = DB::table('insurance_claims')->where('order_id', $inpatient_bill->id) ->where('inpatient_outpatient', 1) ->whereNull('insurance_claims.deleted_at') ->where(function($query) { $query->where('insurance_claims.is_authorisation_required', 1) ->orWhereRaw('FIND_IN_SET(1,insurance_claims.is_item_authorisation_required)') ->orWhere('insurance_claims.plan_validity_error', 1) ->orWhereRaw('FIND_IN_SET(1,insurance_claims.benefit_waiting_period_error)') ->orWhereRaw('FIND_IN_SET(1,insurance_claims.plan_limit_error)') ->orWhereRaw('FIND_IN_SET(1,insurance_claims.benefit_limit_error)') ->orWhereRaw('FIND_IN_SET(1,insurance_claims.item_limit_error)'); })->pluck('id')->toArray(); if (count($claim_ids_with_errors) > 0) { flash("Please make sure to adjudicate all claims before receiving payment")->error(); } // finish adjudicating the claims InsuranceClaim::where('order_id', $inpatient_bill->id) ->whereNotIn('id', $claim_ids_with_errors) ->where('inpatient_outpatient', 1)->update(['claim_status' => 2]); // for those with errors, flag them InsuranceClaim::where('order_id', $inpatient_bill->id) ->whereIn('id', $claim_ids_with_errors) ->where('inpatient_outpatient', 1)->update(['adjudication_required' => 1]); $inpatient_bill->save(); flash("Inpatient bill has been closed successfully")->success(); } // all good so we can commit DB::commit(); } catch (\Exception | \Error $exception) { DB::rollback(); DB::table('system_errors')->insert([ 'error_message' => $exception->getMessage(), 'error_trace' => $exception->getTraceAsString(), 'logged_in_user' => Auth::id() ]); flash("An error occurred. Please try again or contact Stre@mline Support")->error(); return back()->withInput(); } if ($request->get('submit-btn') == 'print') { return redirect()->back()->with('print', 'true'); } elseif($request->get('submit-btn') == 'pay_bill'){ return redirect('patient_finance/make_inpatient_deposit'); } elseif($request->get('submit-btn') == 'authorize_bill'){ $saved_bill_authorizers_array = is_null($inpatient_bill->bill_authorized_by) ? [] : explode(",", $inpatient_bill->bill_authorized_by); $saved_bill_authorizers_array[] = Auth::id(); $inpatient_bill->bill_authorized_by = implode(",", $saved_bill_authorizers_array); $bill_authorized_at_at_array = is_null($inpatient_bill->bill_authorized_at) ? [] : explode(",", $inpatient_bill->bill_authorized_at); $bill_authorized_at_at_array[] = Carbon::now(); $inpatient_bill->bill_authorized_at = implode(",", $bill_authorized_at_at_array); flash("Inpatient bill has been authorized")->success(); $inpatient_bill->update(); return redirect()->back(); } else { return redirect()->back(); } } public function edit_inpatient_sheet() { $episode_id = session()->get('episode_id'); $patient_id = session()->get('patient_id'); // check if bill exists and is not closed $inpatient_bill = InpatientBill::where(['patient_id'=>$patient_id, 'episode_id'=>$episode_id])->first(); if ($inpatient_bill && $inpatient_bill->bill_closed == 1) { flash("Inpatient information cannot be modified while inpatient bill is closed")->error(); } else { $inpatient_info = InpatientInfo::where(['patient_id' => $patient_id, 'episode_id' => $episode_id])->orderBy('created_at', 'desc')->first(); $inpatient_info->discharged = 0; $inpatient_info->save(); } return redirect('in_patient_sheet'); } /* inpatient bill print */ public function in_patient_bill_print($patient_id, $episode_id, $price_list_set) { $patient = Patient::find($patient_id); $hospitalInfo = DB::table('hospital_information')->find(1); $unserialized_price_list_set = unserialize($price_list_set); $price_list_set = $unserialized_price_list_set['price_list_set']; $inpatient_info = InpatientInfo::where(['patient_id' => $patient_id, 'episode_id' => $episode_id])->orderBy('created_at', 'desc')->first(); $treatment_to_take_away = Treatment::where(['patient_id' => $patient_id, 'episode_id' => $episode_id, 'tta' => 1])->get(); $service_deposits = ServiceDeposit::where(['patient_id' => $patient_id, 'episode_id' => $episode_id])->get(); $patient_discount = PatientDiscount::where(['patient_category' => $patient->category_id])->select("discount", "pay_later")->first(); if (!is_null($patient_discount)) { $patient_discount->toArray(); } // get ward dispensing details if available $ward_treatment_drug_ids_that_have_been_dispensed_array = WardTreatmentDispensation::where(['patient_id' => $patient_id, 'episode_id' => $episode_id])->distinct('drug_id')->pluck('drug_id')->toArray(); $dispensed_drug_quantity_given_array = []; for ($i = 0; $i < count($ward_treatment_drug_ids_that_have_been_dispensed_array); $i++) { $drug_ward_quantity_given = WardTreatmentDispensation::where(['patient_id' => $patient_id, 'episode_id' => $episode_id, 'drug_id' => $ward_treatment_drug_ids_that_have_been_dispensed_array[$i]])->sum('quantity_given'); $dispensed_drug_quantity_given_array[$ward_treatment_drug_ids_that_have_been_dispensed_array[$i]] = $drug_ward_quantity_given; } $price_list_categories = PriceListCategories::select('patient_category_id', 'id')->get(); // Check for anaesthesia in this episode $anaesthesia = DB::table('anaesthesias')->where('episode_id', $episode_id)->select('other_drugs_given', 'other_drugs_cost')->first(); $ordered_ward_investigations = OrderedInvestigation::where(['episode_id' => $episode_id, 'payment_status' => '0'])->get(); /*=======necessary for staff payments configuration========*/ $service_items = Services::withTrashed()->orderBy('name','asc')->pluck('name', 'id')->prepend('- select -', ''); $services_with_users_array = InpatientController::configured_users_with_their_services_array(); $sundries = Sundry::where('available', 1)->orderby('name', 'asc')->pluck('name', 'id')->prepend('- select -', ''); $users_collection = DB::table('users')->orderBy("first_name","asc")->select("id")->get()->toArray(); $service_with_users_array = []; $users_array = []; $options_users = ""; foreach ($users_collection as $value){ $user = User::find($value->id); if (!is_null($user)) { $users_array[$user->id] = $user->first_name . " ". $user->last_name; $options_users .= ""; 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('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 $dynamic_key = $record->id."__".$value->id; $dynamic_value = get_full_name($value->id, 'id', 'first_name', 'last_name', 'users')." (".$record->name.")"; $service_with_users_array[$dynamic_key] = $dynamic_value; //add these dynamically formed values to service_items array array_add($service_items, $dynamic_key, $dynamic_value); //add it to the services_options too i.e used when user clicks add_service btn } } } } /*===================*/ //check for authenticated investigations $investigation_results = InvestigationResults::where(['patient_id' => $patient_id,'episode_id' => $episode_id ,'inpatient' => 1])->get(); $debt_plan_payments = DebtPlan::where(['patient_id' => $patient_id, 'episode_id' => $episode_id, 'tag_id' => 10])->get(); $data = [ 'patient' => $patient, 'price_list_set' => $price_list_set, 'dispensed_drug_quantity_given_array' => $dispensed_drug_quantity_given_array, 'inpatient_info' => $inpatient_info, 'patient_id' => $patient_id, 'treatment_to_take_away' => $treatment_to_take_away, 'service_deposits' => $service_deposits, 'patient_discount' => $patient_discount, 'episode_id' => $episode_id, 'price_list_categories' => $price_list_categories, 'hospitalInfo' => $hospitalInfo, 'anaesthesia' => $anaesthesia, 'service_items' => $service_items, 'sundries' => $sundries, 'services_with_users_array' => $services_with_users_array, 'ordered_ward_investigations' => $ordered_ward_investigations, 'investigation_results' => $investigation_results, 'debt_plan_payments' => $debt_plan_payments ]; $pdf = SnappyPDF::loadView('ward_management::inpatient/inpatient_billing_print', $data) ->setOrientation('portrait') ->setOption('margin-bottom', 7) ->setOption('margin-top', 5) ->setOption('footer-html', 'Stre@mline'); return $pdf->inline('Inpatient Bill' . date(" d-m-y h:ia") . '.pdf'); } public function check_for_open_admissions($patient_id) { $inpatient_info = InpatientInfo::where('patient_id', $patient_id) ->where('discharged', 0) ->get(); return count($inpatient_info); } public function discharge_patient_past_admissions($patient_id) { $inpatient_info = InpatientInfo::where('patient_id', $patient_id) ->where('discharged', 0) ->get(['id']); foreach ($inpatient_info as $record) { // discharge the patient DB::table('inpatient_info') ->where('id', $record->id) ->update(["discharged" => 1, "outcome_id" => 2, "discharged_on" => date('Y-m-d'), "discharged_by" => Auth::user()->id]); } } public static function configured_users_with_their_services_array(): array { $users = User::orderBy("first_name","asc")->get(); $service_with_users_array = []; foreach ($users as $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('staff_payment_configurations.user_id',$user->id) ->where('staff_payment_configurations.item_category',3) ->select('services.non_insured_price', 'services.id', 'services.name') ->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 $dynamic_key = $record->id."__".$user->id; $dynamic_value = $user->first_name . ' ' . $user->last_name ." (".$record->name." Fee: ".ugandan_shillings($users_consultation_fee).")"; $service_with_users_array[$dynamic_key] = $dynamic_value; } } } return $service_with_users_array; } public function get_procedure_hospital_fees($procedure_id, $patient_id) { return get_procedure_hospital_fees_func($procedure_id, $patient_id); } public function get_inpatient_services_fees(Request $request) { $service_id = $request->service_id; $patient_id = $request->patient_id; $patient_insurance_status = $request->patient_insurance_status; $ward_id = $request->ward_id ?? 0; $price_list_id = is_patient_category_attached_to_price_list($patient_id); $services_with_users_array = InpatientController::configured_users_with_their_services_array(); $staff_id = 0; if(array_key_exists($service_id, $services_with_users_array)){ $services_user_key = explode("__", $service_id); $cleaned_service_id = $services_user_key[0]; $staff_id = $services_user_key[1]; } else { $cleaned_service_id = $service_id; } if(is_numeric($patient_insurance_status) && $patient_insurance_status == 1 && $patient_id != 0 && is_numeric($patient_id)) { $services_cost = get_item_insurance_co_payment($patient_id, $cleaned_service_id, 1, true, $ward_id); } else { if ($price_list_id) { $services_cost = get_price_list_category_price($price_list_id, 6, $cleaned_service_id); } else { $services_cost = get_name($cleaned_service_id, "id", "non_insured_price", "services"); } } if($staff_id != 0){ $services_price_and_staff_fee_array = [$services_cost, service_fee_configured_to_staff($staff_id,$cleaned_service_id,$price_list_id)]; } else{ $services_price_and_staff_fee_array = [$services_cost, 0]; } return $services_price_and_staff_fee_array; } public function inpatient_sundries_print($patient_id, $episode_id) { $patient = Patient::find($patient_id); $hospitalInfo = DB::table('hospital_information')->find(1); $inpatient_info = InpatientInfo::where(['patient_id' => $patient_id, 'episode_id' => $episode_id])->orderBy('created_at', 'desc')->first(); // allergies header $categories = DB::table('patient_categories')->where('available', 1)->pluck("name", "id"); $known_patient_allergies = Allergy::where('patient_id', $patient_id)->orderBy('created_at', 'desc')->take(2)->get(); $known_patient_alerts = Alert::where('patient_id', $patient_id)->orderBy('created_at', 'desc')->take(2)->get(); $drug_categories = DB::table('drug_categories')->orderBy('name', 'asc')->get(); $drug_categories_array = DrugCategory::pluck('name', 'id'); $sundries = Sundry::where('available', 1)->orderby('name', 'asc')->pluck('name', 'id')->prepend('- select -', ''); $price_list_set = false; $price_list_categories = PriceListCategories::select('patient_category_id', 'id')->get(); $patient_discount = PatientDiscount::where(['patient_category' => $patient->category_id])->select("discount", "pay_later")->first(); if (!is_null($patient_discount)) { $patient_discount->toArray(); } $data = [ 'patient' => $patient, 'patient_id' => $patient_id, 'episode_id' => $episode_id, 'price_list_set' => $price_list_set, 'categories' => $categories, 'known_patient_alerts' => $known_patient_allergies, 'drug_categories' => $drug_categories, 'drug_categories_array' => $drug_categories_array, 'inpatient_info' => $inpatient_info, 'price_list_categories' => $price_list_categories, 'patient_discount' => $patient_discount, 'hospitalInfo' => $hospitalInfo, 'sundries' => $sundries, ]; $pdf = SnappyPDF::loadView('ward_management::inpatient/inpatient_sundries_print', $data) ->setOrientation('portrait') ->setOption('margin-bottom', 7) ->setOption('margin-top', 5) ->setOption('footer-html', 'Stre@mline'); return $pdf->inline('Inpatient Sundries' . date(" d-m-y h:ia") . '.pdf'); } public function inpatient_treatment_print($patient_id, $episode_id) { $patient = Patient::find($patient_id); $hospitalInfo = DB::table('hospital_information')->find(1); $inpatient_info = InpatientInfo::where(['patient_id' => $patient_id, 'episode_id' => $episode_id])->orderBy('created_at', 'desc')->first(); // allergies header $categories = DB::table('patient_categories')->where('available', 1)->pluck("name", "id"); $known_patient_allergies = Allergy::where('patient_id', $patient_id)->orderBy('created_at', 'desc')->take(2)->get(); $known_patient_alerts = Alert::where('patient_id', $patient_id)->orderBy('created_at', 'desc')->take(2)->get(); $drug_categories = DB::table('drug_categories')->orderBy('name', 'asc')->get(); $drug_categories_array = DrugCategory::pluck('name', 'id'); $price_list_set = false; $price_list_categories = PriceListCategories::select('patient_category_id', 'id')->get(); $patient_discount = PatientDiscount::where(['patient_category' => $patient->category_id])->select("discount", "pay_later")->first(); if (!is_null($patient_discount)) { $patient_discount->toArray(); } $data = [ 'patient' => $patient, 'patient_id' => $patient_id, 'episode_id' => $episode_id, 'price_list_set' => $price_list_set, 'categories' => $categories, 'known_patient_alerts' => $known_patient_allergies, 'drug_categories' => $drug_categories, 'drug_categories_array' => $drug_categories_array, 'inpatient_info' => $inpatient_info, 'price_list_categories' => $price_list_categories, 'patient_discount' => $patient_discount, 'hospitalInfo' => $hospitalInfo, ]; $pdf = SnappyPDF::loadView('ward_management::inpatient/inpatient_treatment_print', $data) ->setOrientation('portrait') ->setOption('margin-bottom', 7) ->setOption('margin-top', 5) ->setOption('footer-html', 'Stre@mline'); return $pdf->inline('Inpatient Sundries' . date(" d-m-y h:ia") . '.pdf'); } public function inpatient_extras_print($patient_id, $episode_id) { $patient = Patient::find($patient_id); $hospitalInfo = DB::table('hospital_information')->find(1); $inpatient_info = InpatientInfo::where(['patient_id' => $patient_id, 'episode_id' => $episode_id])->orderBy('created_at', 'desc')->first(); // allergies header $categories = DB::table('patient_categories')->where('available', 1)->pluck("name", "id"); $known_patient_allergies = Allergy::where('patient_id', $patient_id)->orderBy('created_at', 'desc')->take(2)->get(); $known_patient_alerts = Alert::where('patient_id', $patient_id)->orderBy('created_at', 'desc')->take(2)->get(); $drug_categories = DB::table('drug_categories')->orderBy('name', 'asc')->get(); $drug_categories_array = DrugCategory::pluck('name', 'id'); $price_list_set = false; $price_list_categories = PriceListCategories::select('patient_category_id', 'id')->get(); $patient_discount = PatientDiscount::where(['patient_category' => $patient->category_id])->select("discount", "pay_later")->first(); if (!is_null($patient_discount)) { $patient_discount->toArray(); } $data = [ 'patient' => $patient, 'patient_id' => $patient_id, 'episode_id' => $episode_id, 'price_list_set' => $price_list_set, 'categories' => $categories, 'known_patient_alerts' => $known_patient_allergies, 'drug_categories' => $drug_categories, 'drug_categories_array' => $drug_categories_array, 'inpatient_info' => $inpatient_info, 'price_list_categories' => $price_list_categories, 'patient_discount' => $patient_discount, 'hospitalInfo' => $hospitalInfo, ]; $pdf = SnappyPDF::loadView('ward_management::inpatient/inpatient_extras_print', $data) ->setOrientation('portrait') ->setOption('margin-bottom', 7) ->setOption('margin-top', 5) ->setOption('footer-html', 'Stre@mline'); return $pdf->inline('Inpatient Extras' . date(" d-m-y h:ia") . '.pdf'); } public function inpatient_consultation_and_services_print($patient_id, $episode_id) { $patient = Patient::find($patient_id); $hospitalInfo = DB::table('hospital_information')->find(1); $inpatient_info = InpatientInfo::where(['patient_id' => $patient_id, 'episode_id' => $episode_id])->orderBy('created_at', 'desc')->first(); // allergies header $categories = DB::table('patient_categories')->where('available', 1)->pluck("name", "id"); $known_patient_allergies = Allergy::where('patient_id', $patient_id)->orderBy('created_at', 'desc')->take(2)->get(); $known_patient_alerts = Alert::where('patient_id', $patient_id)->orderBy('created_at', 'desc')->take(2)->get(); $drug_categories = DB::table('drug_categories')->orderBy('name', 'asc')->get(); $drug_categories_array = DrugCategory::pluck('name', 'id'); $price_list_set = false; $price_list_categories = PriceListCategories::select('patient_category_id', 'id')->get(); $patient_discount = PatientDiscount::where(['patient_category' => $patient->category_id])->select("discount", "pay_later")->first(); if (!is_null($patient_discount)) { $patient_discount->toArray(); } $services_with_users_array = InpatientController::configured_users_with_their_services_array(); $service_items = Services::withTrashed()->orderBy('name','asc')->pluck('name', 'id')->prepend('- select -', ''); $users_collection = DB::table('users')->orderBy("first_name","asc")->select("id")->get()->toArray(); $service_with_users_array = []; $users_array = []; $options_users = ""; foreach ($users_collection as $value){ $user = User::find($value->id); if (!is_null($user)) { $users_array[$user->id] = $user->first_name . " ". $user->last_name; 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('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) { $price_list_id = is_patient_category_attached_to_price_list($patient_id); if ($price_list_id) { $users_consultation_fee = get_price_list_category_price($price_list_id, 6, $record->id); } else{ $users_consultation_fee = $record->non_insured_price; } //concatnate the service_record_id with the users_id to form the key for the array $dynamic_key = $record->id."__".$value->id; $dynamic_value = get_full_name($value->id, 'id', 'first_name', 'last_name', 'users')." (".$record->name." Fee: ".ugandan_shillings($users_consultation_fee).")"; $service_with_users_array[$dynamic_key] = $dynamic_value; //add these dynamically formed values to service_items array array_add($service_items, $dynamic_key, $dynamic_value); } } } } $data = [ 'patient' => $patient, 'patient_id' => $patient_id, 'episode_id' => $episode_id, 'price_list_set' => $price_list_set, 'categories' => $categories, 'known_patient_alerts' => $known_patient_allergies, 'drug_categories' => $drug_categories, 'drug_categories_array' => $drug_categories_array, 'inpatient_info' => $inpatient_info, 'price_list_categories' => $price_list_categories, 'patient_discount' => $patient_discount, 'hospitalInfo' => $hospitalInfo, 'services_with_users_array' => $services_with_users_array, 'service_items' => $service_items ]; $pdf = SnappyPDF::loadView('ward_management::inpatient/inpatient_consultation_and_services_print', $data) ->setOrientation('portrait') ->setOption('margin-bottom', 7) ->setOption('margin-top', 5) ->setOption('footer-html', 'Stre@mline'); return $pdf->inline('Inpatient Consultation and Services' . date(" d-m-y h:ia") . '.pdf'); } public function inpatient_procedures_print($patient_id, $episode_id) { $patient = Patient::find($patient_id); $hospitalInfo = DB::table('hospital_information')->find(1); $inpatient_info = InpatientInfo::where(['patient_id' => $patient_id, 'episode_id' => $episode_id])->orderBy('created_at', 'desc')->first(); // allergies header $categories = DB::table('patient_categories')->where('available', 1)->pluck("name", "id"); $known_patient_allergies = Allergy::where('patient_id', $patient_id)->orderBy('created_at', 'desc')->take(2)->get(); $known_patient_alerts = Alert::where('patient_id', $patient_id)->orderBy('created_at', 'desc')->take(2)->get(); $drug_categories = DB::table('drug_categories')->orderBy('name', 'asc')->get(); $drug_categories_array = DrugCategory::pluck('name', 'id'); $price_list_set = false; $price_list_categories = PriceListCategories::select('patient_category_id', 'id')->get(); $patient_discount = PatientDiscount::where(['patient_category' => $patient->category_id])->select("discount", "pay_later")->first(); if (!is_null($patient_discount)) { $patient_discount->toArray(); } $data = [ 'patient' => $patient, 'patient_id' => $patient_id, 'episode_id' => $episode_id, 'price_list_set' => $price_list_set, 'categories' => $categories, 'known_patient_alerts' => $known_patient_allergies, 'drug_categories' => $drug_categories, 'drug_categories_array' => $drug_categories_array, 'inpatient_info' => $inpatient_info, 'price_list_categories' => $price_list_categories, 'patient_discount' => $patient_discount, 'hospitalInfo' => $hospitalInfo, ]; $pdf = SnappyPDF::loadView('ward_management::inpatient/inpatient_procedures_print', $data) ->setOrientation('portrait') ->setOption('margin-bottom', 7) ->setOption('margin-top', 5) ->setOption('footer-html', 'Stre@mline'); return $pdf->inline('Inpatient Procedures' . date(" d-m-y h:ia") . '.pdf'); } public function inpatient_investigations_print($patient_id, $episode_id) { $patient = Patient::find($patient_id); $hospitalInfo = DB::table('hospital_information')->find(1); $inpatient_info = InpatientInfo::where(['patient_id' => $patient_id, 'episode_id' => $episode_id])->orderBy('created_at', 'desc')->first(); // allergies header $categories = DB::table('patient_categories')->where('available', 1)->pluck("name", "id"); $known_patient_allergies = Allergy::where('patient_id', $patient_id)->orderBy('created_at', 'desc')->take(2)->get(); $known_patient_alerts = Alert::where('patient_id', $patient_id)->orderBy('created_at', 'desc')->take(2)->get(); $drug_categories = DB::table('drug_categories')->orderBy('name', 'asc')->get(); $drug_categories_array = DrugCategory::pluck('name', 'id'); $price_list_set = false; $price_list_categories = PriceListCategories::select('patient_category_id', 'id')->get(); $patient_discount = PatientDiscount::where(['patient_category' => $patient->category_id])->select("discount", "pay_later")->first(); if (!is_null($patient_discount)) { $patient_discount->toArray(); } $data = [ 'patient' => $patient, 'patient_id' => $patient_id, 'episode_id' => $episode_id, 'price_list_set' => $price_list_set, 'categories' => $categories, 'known_patient_alerts' => $known_patient_allergies, 'drug_categories' => $drug_categories, 'drug_categories_array' => $drug_categories_array, 'inpatient_info' => $inpatient_info, 'price_list_categories' => $price_list_categories, 'patient_discount' => $patient_discount, 'hospitalInfo' => $hospitalInfo, ]; $pdf = SnappyPDF::loadView('ward_management::inpatient/inpatient_invs_print', $data) ->setOrientation('portrait') ->setOption('margin-bottom', 7) ->setOption('margin-top', 5) ->setOption('footer-html', 'Stre@mline'); return $pdf->inline('Inpatient Investigations' . date(" d-m-y h:ia") . '.pdf'); } public function inpatient_notes_print($patient_id, $episode_id) { $patient = Patient::find($patient_id); $hospitalInfo = DB::table('hospital_information')->find(1); $inpatient_info = InpatientInfo::where(['patient_id' => $patient_id, 'episode_id' => $episode_id])->orderBy('created_at', 'desc')->first(); $patient_discount = PatientDiscount::where(['patient_category' => $patient->category_id])->select("discount", "pay_later")->first(); if (!is_null($patient_discount)) { $patient_discount->toArray(); } $data = [ 'patient' => $patient, 'patient_id' => $patient_id, 'episode_id' => $episode_id, 'inpatient_info' => $inpatient_info, 'patient_discount' => $patient_discount, 'hospitalInfo' => $hospitalInfo, ]; $pdf = SnappyPDF::loadView('ward_management::inpatient/inpatient_notes_print', $data) ->setOrientation('portrait') ->setOption('margin-bottom', 7) ->setOption('margin-top', 5) ->setOption('footer-html', 'Stre@mline'); return $pdf->inline('Inpatient Notes' . date(" d-m-y h:ia") . '.pdf'); } public function get_ward_bed_rate(Request $request) { $bed_category_id = $request->bed_category_id; $patient_id = $request->patient_id; $patient_insurance_status = $request->patient_insurance_status; $inpatient_bed_category = InpatientBedCategory::withTrashed()->find($bed_category_id); if ($inpatient_bed_category) { if($patient_insurance_status == 1) { return get_insurance_bed_rate($patient_id, $bed_category_id); } else { return ($inpatient_bed_category->cost_type == 1) ? $inpatient_bed_category->cost_per_night : $inpatient_bed_category->cost_first_night; } } return 0; } public function discharge_summary_print() { $patient_id = session()->get('patient_id'); $episode_id = session()->get('episode_id'); if(is_eye_module_enabled() && is_patient_in_eye_clinic($episode_id)) { $main_exam = EyeClinicMainExam::where(['patient_id' => $patient_id, 'episode_id' => $episode_id])->first(); $base_exam = EyeClinicBaseExamRefraction::where(['patient_id' => $patient_id, 'episode_id' => $episode_id])->first(); $slit_lamp_test_areas = SlitLampTestArea::all(); $slit_lamp_test_area_values = SlitLampTestAreaValue::pluck('name', 'id')->toArray(); $slit_lamp_test_area_ids = SlitLampTestAreaValue::pluck('id')->toArray(); } else { $main_exam = false; $base_exam = false; $slit_lamp_test_areas = []; $slit_lamp_test_area_values = []; $slit_lamp_test_area_ids = []; } $patient = Patient::find($patient_id); $hospitalInfo = DB::table('hospital_information')->find(1); $inpatient_info = InpatientInfo::where(['patient_id' => $patient_id, 'episode_id' => $episode_id])->orderBy('created_at', 'desc')->first(); $cons_comments = Consultation::where(['patient_id' => $patient_id, 'episode_id' => $episode_id])->select(['comments', 'history_comments', 'clinic_examination_comments', 'investigation_and_management_plan_comments'])->first(); $treatment_to_take_away = Treatment::where(['patient_id' => $patient_id, 'episode_id' => $episode_id, 'tta' => 1])->get(); $service_deposits = ServiceDeposit::where(['patient_id' => $patient_id, 'episode_id' => $episode_id])->get(); $patient_discount = PatientDiscount::where(['patient_category' => $patient->category_id])->select("discount", "pay_later")->first(); if (!is_null($patient_discount)) { $patient_discount->toArray(); } // get ward dispensing details if available $ward_treatment_drug_ids_that_have_been_dispensed_array = WardTreatmentDispensation::where(['patient_id' => $patient_id, 'episode_id' => $episode_id])->distinct('drug_id')->pluck('drug_id')->toArray(); $dispensed_drug_quantity_given_array = []; for ($i = 0; $i < count($ward_treatment_drug_ids_that_have_been_dispensed_array); $i++) { $drug_ward_quantity_given = WardTreatmentDispensation::where(['patient_id' => $patient_id, 'episode_id' => $episode_id, 'drug_id' => $ward_treatment_drug_ids_that_have_been_dispensed_array[$i]])->sum('quantity_given'); $dispensed_drug_quantity_given_array[$ward_treatment_drug_ids_that_have_been_dispensed_array[$i]] = $drug_ward_quantity_given; } $price_list_categories = PriceListCategories::select('patient_category_id', 'id')->get(); // Check for anaesthesia in this episode $anaesthesia = DB::table('anaesthesias')->where('episode_id', $episode_id)->select('other_drugs_given', 'other_drugs_cost')->first(); $price_list_set = false; /*=======necessary for staff payments configuration========*/ $service_items = Services::withTrashed()->orderBy('name','asc')->pluck('name', 'id')->prepend('- select -', ''); $services_with_users_array = InpatientController::configured_users_with_their_services_array(); $sundries = Sundry::where('available', 1)->orderby('name', 'asc')->pluck('name', 'id')->prepend('- select -', ''); $users_collection = DB::table('users')->orderBy("first_name","asc")->select("id")->get()->toArray(); $service_with_users_array = []; $users_array = []; $options_users = ""; foreach ($users_collection as $value){ $user = User::find($value->id); if (!is_null($user)) { $users_array[$user->id] = $user->first_name . " ". $user->last_name; $options_users .= ""; 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('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 $dynamic_key = $record->id."__".$value->id; $dynamic_value = get_full_name($value->id, 'id', 'first_name', 'last_name', 'users')." (".$record->name.")"; $service_with_users_array[$dynamic_key] = $dynamic_value; //add these dynamically formed values to service_items array array_add($service_items, $dynamic_key, $dynamic_value); //add it to the services_options too i.e used when user clicks add_service btn } } } } /*===================*/ /* ====== start work on investigations */ // prep the inpatient investigation arrays and counters $opd_investigations = []; $opd_investigations_position = []; $opd_investigations_date = []; $ward_investigations = []; $ward_investigations_position = []; $ward_investigations_date = []; // get all investigations ordered in this episode $ordered_investigations = OrderedInvestigation::where(['episode_id' => $episode_id])->get(); // get all results $investigation_results_order_ids = InvestigationResults::pluck('order_id', 'id')->toArray(); foreach ($ordered_investigations as $investigation) { if (isset($ward_investigations['id'])) { $ward_investigations_position[] = count($ward_investigations['id']); } else { $ward_investigations_position[] = 0; } if (isset($opd_investigations['id'])) { $opd_investigations_position[] = count($opd_investigations['id']); } else { $opd_investigations_position[] = 0; } $ward_investigations_date[] = "Ordered on " . streamline_date_time($investigation->created_at) . " by " . get_full_name($investigation->created_by, 'id', 'first_name', 'last_name', 'users'); $opd_investigations_date[] = streamline_date_time($investigation->created_at); $investigation_ids = explode(",", $investigation->investigation_id); $inpatient_status = explode(",", $investigation->for_inpatient); // check if results are available for this investigation if (in_array($investigation->id, $investigation_results_order_ids)) { // get the key if available $key = array_search($investigation->id, $investigation_results_order_ids); // get the results object $results = InvestigationResults::find($key); // exclude obstetric u/s results if ($results->result_type != "Ultrasound_Obstetric") { $investigation_results = explode(",", $results->value); $investigation_per_valid = explode(",", $results->per_investigation); $investigation_comments = explode(",", $results->comment); if ($results->all_authenticated == 1) { for ($i = 0; $i < count($inpatient_status); $i++) { if (isset($inpatient_status[$i]) && $inpatient_status[$i] == 0) { $result = Investigation::withTrashed()->find($investigation_ids[$i]); if ($result) { $opd_investigations['id'][] = $result->id; $opd_investigations['name'][] = $result->name; $opd_investigations['type'][] = $result->type; $opd_investigations['slug'][] = $result->slug; $opd_investigations['value'][] = $investigation_results[$i] ?? ""; $opd_investigations['comment'][] = $investigation_comments[$i] ?? ""; } } else { $result = Investigation::withTrashed()->find($investigation_ids[$i]); if ($result) { $ward_investigations['id'][] = $result->id; $ward_investigations['name'][] = $result->name; $ward_investigations['type'][] = $result->type; $ward_investigations['slug'][] = $result->slug; $ward_investigations['value'][] = $investigation_results[$i] ?? ""; $ward_investigations['comment'][] = $investigation_comments[$i] ?? ""; } } } } else { for ($i = 0; $i < count($inpatient_status); $i++) { $investigation = Investigation::withTrashed()->find($investigation_ids[$i]); if (!$investigation) { continue; } if (isset($investigation_per_valid[$i]) && $investigation_per_valid[$i] == 1) { // this investigation is authenticated if (isset($inpatient_status[$i]) && $inpatient_status[$i] == 0) { $opd_investigations['id'][] = $investigation->id; $opd_investigations['name'][] = $investigation->name; $opd_investigations['type'][] = $investigation->type; $opd_investigations['slug'][] = $investigation->slug; $opd_investigations['value'][] = $investigation_results[$i] ?? ""; $opd_investigations['comment'][] = $investigation_comments[$i] ?? ""; } else { $ward_investigations['id'][] = $investigation->id; $ward_investigations['name'][] = $investigation->name; $ward_investigations['type'][] = $investigation->type; $ward_investigations['slug'][] = $investigation->slug; $ward_investigations['value'][] = $investigation_results[$i] ?? ""; $ward_investigations['comment'][] = $investigation_comments[$i] ?? ""; } } else { if (isset($investigation_per_valid[$i]) && $inpatient_status[$i] == 0) { $opd_investigations['id'][] = $investigation->id; $opd_investigations['name'][] = $investigation->name; $opd_investigations['type'][] = $investigation->type; $opd_investigations['slug'][] = $investigation->slug; $opd_investigations['value'][] = "Pending"; $opd_investigations['comment'][] = "Pending"; } else { $ward_investigations['id'][] = $investigation->id; $ward_investigations['name'][] = $investigation->name; $ward_investigations['type'][] = $investigation->type; $ward_investigations['slug'][] = $investigation->slug; $ward_investigations['value'][] = "Pending"; $ward_investigations['comment'][] = "Pending"; } } } } } } else { for ($i = 0; $i < count($inpatient_status); $i++) { if (isset($inpatient_status[$i]) && $inpatient_status[$i] == 0) { $result = Investigation::withTrashed()->find($investigation_ids[$i]); if ($result) { $opd_investigations['id'][] = $result->id; $opd_investigations['name'][] = $result->name; $opd_investigations['type'][] = $result->type; $opd_investigations['slug'][] = $result->slug; $opd_investigations['value'][] = "Pending"; $opd_investigations['comment'][] = "Pending"; } } else { $result = Investigation::withTrashed()->find($investigation_ids[$i]); if ($result) { $ward_investigations['id'][] = $result->id; $ward_investigations['name'][] = $result->name; $ward_investigations['type'][] = $result->type; $ward_investigations['slug'][] = $result->slug; $ward_investigations['value'][] = "Pending"; $ward_investigations['comment'][] = "Pending"; } } } } } /* ====== end work on investigations */ $data = [ 'patient' => $patient, 'price_list_set' => $price_list_set, 'dispensed_drug_quantity_given_array' => $dispensed_drug_quantity_given_array, 'inpatient_info' => $inpatient_info, 'patient_id' => $patient_id, 'treatment_to_take_away' => $treatment_to_take_away, 'service_deposits' => $service_deposits, 'patient_discount' => $patient_discount, 'episode_id' => $episode_id, 'price_list_categories' => $price_list_categories, 'hospitalInfo' => $hospitalInfo, 'anaesthesia' => $anaesthesia, 'service_items' => $service_items, 'sundries' => $sundries, 'cons_comments'=>$cons_comments, 'services_with_users_array' => $services_with_users_array, 'ward_investigations' => $ward_investigations, 'opd_investigations' => $opd_investigations, 'opd_investigations_position' => $opd_investigations_position, 'ward_investigations_position' => $ward_investigations_position, 'opd_investigations_date' => $opd_investigations_date, 'ward_investigations_date' => $ward_investigations_date, 'base_exam' => $base_exam, 'main_exam' => $main_exam, 'slit_lamp_test_areas' => $slit_lamp_test_areas, 'slit_lamp_test_area_values' => $slit_lamp_test_area_values, 'slit_lamp_test_area_ids' => $slit_lamp_test_area_ids ]; $pdf = SnappyPDF::loadView('ward_management::inpatient/discharge_summary_print', $data) ->setOrientation('portrait') ->setOption('margin-bottom', 7) ->setOption('margin-top', 5) ->setOption('footer-html', 'Stre@mline'); return $pdf->inline('Discharge Summary' . date("y-m-d h:ia") . '.pdf'); } public function receive_inpatient_payment(Request $request) { session()->put('patient_id', $request->patient_id); session()->put('episode_id', $request->episode_id); return redirect('patient_finance/make_inpatient_deposit'); } public function cancel_ward_prescription($ward_prescription_id) { $ward_prescription = WardTreatment::find($ward_prescription_id); if ($ward_prescription->delete()) { flash('Ward prescription has been cancelled')->success(); return redirect('in_patient_sheet'); } flash('System could not cancel prescription')->error(); return redirect()->back(); } public function inpatient_bill_summary_print($patient_id, $episode_id, $price_list_set) { $patient = Patient::find($patient_id); $hospitalInfo = DB::table('hospital_information')->find(1); $unserialized_price_list_set = unserialize($price_list_set); $price_list_set = $unserialized_price_list_set['price_list_set']; $inpatient_info = InpatientInfo::where(['patient_id' => $patient_id, 'episode_id' => $episode_id])->orderBy('created_at', 'desc')->first(); $treatment_to_take_away = Treatment::where(['patient_id' => $patient_id, 'episode_id' => $episode_id, 'tta' => 1])->get(); $service_deposits = ServiceDeposit::where(['patient_id' => $patient_id, 'episode_id' => $episode_id])->get(); $patient_discount = PatientDiscount::where(['patient_category' => $patient->category_id])->select("discount", "pay_later")->first(); if (!is_null($patient_discount)) { $patient_discount->toArray(); } // get ward dispensing details if available $ward_treatment_drug_ids_that_have_been_dispensed_array = WardTreatmentDispensation::where(['patient_id' => $patient_id, 'episode_id' => $episode_id])->distinct('drug_id')->pluck('drug_id')->toArray(); $dispensed_drug_quantity_given_array = []; for ($i = 0; $i < count($ward_treatment_drug_ids_that_have_been_dispensed_array); $i++) { $drug_ward_quantity_given = WardTreatmentDispensation::where(['patient_id' => $patient_id, 'episode_id' => $episode_id, 'drug_id' => $ward_treatment_drug_ids_that_have_been_dispensed_array[$i]])->sum('quantity_given'); $dispensed_drug_quantity_given_array[$ward_treatment_drug_ids_that_have_been_dispensed_array[$i]] = $drug_ward_quantity_given; } $price_list_categories = PriceListCategories::select('patient_category_id', 'id')->get(); // Check for anaesthesia in this episode $anaesthesia = DB::table('anaesthesias')->where('episode_id', $episode_id)->select('other_drugs_given', 'other_drugs_cost')->first(); $ordered_ward_investigations = OrderedInvestigation::where(['episode_id' => $episode_id, 'payment_status' => '0'])->get(); /*=======necessary for staff payments configuration========*/ $service_items = Services::withTrashed()->orderBy('name','asc')->pluck('name', 'id')->prepend('- select -', ''); $services_with_users_array = InpatientController::configured_users_with_their_services_array(); $sundries = Sundry::where('available', 1)->orderby('name', 'asc')->pluck('name', 'id')->prepend('- select -', ''); $users_collection = DB::table('users')->orderBy("first_name","asc")->select("id")->get()->toArray(); $service_with_users_array = []; $users_array = []; $options_users = ""; foreach ($users_collection as $value){ $user = User::find($value->id); if (!is_null($user)) { $users_array[$user->id] = $user->first_name . " ". $user->last_name; $options_users .= ""; 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('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 $dynamic_key = $record->id."__".$value->id; $dynamic_value = get_full_name($value->id, 'id', 'first_name', 'last_name', 'users')." (".$record->name.")"; $service_with_users_array[$dynamic_key] = $dynamic_value; //add these dynamically formed values to service_items array array_add($service_items, $dynamic_key, $dynamic_value); //add it to the services_options too i.e used when user clicks add_service btn } } } } /*===================*/ //check for authenticated investigations $investigation_results = InvestigationResults::where(['patient_id' => $patient_id,'episode_id' => $episode_id ,'inpatient' => 1])->get(); $debt_plan_payments = DebtPlan::where(['patient_id' => $patient_id, 'episode_id' => $episode_id, 'tag_id' => 10])->get(); $data = [ 'patient' => $patient, 'price_list_set' => $price_list_set, 'dispensed_drug_quantity_given_array' => $dispensed_drug_quantity_given_array, 'inpatient_info' => $inpatient_info, 'patient_id' => $patient_id, 'treatment_to_take_away' => $treatment_to_take_away, 'service_deposits' => $service_deposits, 'patient_discount' => $patient_discount, 'episode_id' => $episode_id, 'price_list_categories' => $price_list_categories, 'hospitalInfo' => $hospitalInfo, 'anaesthesia' => $anaesthesia, 'service_items' => $service_items, 'sundries' => $sundries, 'services_with_users_array' => $services_with_users_array, 'ordered_ward_investigations' => $ordered_ward_investigations, 'investigation_results' => $investigation_results, 'debt_plan_payments' => $debt_plan_payments ]; $pdf = SnappyPDF::loadView('ward_management::inpatient/inpatient_bill_summary_print', $data) ->setOrientation('portrait') ->setOption('margin-bottom', 7) ->setOption('margin-top', 5) ->setOption('footer-html', 'Stre@mline'); return $pdf->inline('Inpatient Bill' . date(" d-m-y h:ia") . '.pdf'); } public function referral_notes_print() { $patient_id = session()->get('patient_id'); $episode_id = session()->get('episode_id'); $patient = Patient::find($patient_id); $hospitalInfo = DB::table('hospital_information')->find(1); $inpatient_info = InpatientInfo::where(['patient_id' => $patient_id, 'episode_id' => $episode_id])->orderBy('created_at', 'desc')->first(); $treatment_to_take_away = Treatment::where(['patient_id' => $patient_id, 'episode_id' => $episode_id, 'tta' => 1])->get(); $service_deposits = ServiceDeposit::where(['patient_id' => $patient_id, 'episode_id' => $episode_id])->get(); $patient_discount = PatientDiscount::where(['patient_category' => $patient->category_id])->select("discount", "pay_later")->first(); if (!is_null($patient_discount)) { $patient_discount->toArray(); } // get ward dispensing details if available $ward_treatment_drug_ids_that_have_been_dispensed_array = WardTreatmentDispensation::where(['patient_id' => $patient_id, 'episode_id' => $episode_id])->distinct('drug_id')->pluck('drug_id')->toArray(); $dispensed_drug_quantity_given_array = []; for ($i = 0; $i < count($ward_treatment_drug_ids_that_have_been_dispensed_array); $i++) { $drug_ward_quantity_given = WardTreatmentDispensation::where(['patient_id' => $patient_id, 'episode_id' => $episode_id, 'drug_id' => $ward_treatment_drug_ids_that_have_been_dispensed_array[$i]])->sum('quantity_given'); $dispensed_drug_quantity_given_array[$ward_treatment_drug_ids_that_have_been_dispensed_array[$i]] = $drug_ward_quantity_given; } $price_list_categories = PriceListCategories::select('patient_category_id', 'id')->get(); // Check for anaesthesia in this episode $anaesthesia = DB::table('anaesthesias')->where('episode_id', $episode_id)->select('other_drugs_given', 'other_drugs_cost')->first(); $price_list_set = false; /*=======necessary for staff payments configuration========*/ $service_items = Services::withTrashed()->orderBy('name','asc')->pluck('name', 'id')->prepend('- select -', ''); $services_with_users_array = InpatientController::configured_users_with_their_services_array(); $sundries = Sundry::where('available', 1)->orderby('name', 'asc')->pluck('name', 'id')->prepend('- select -', ''); $users_collection = DB::table('users')->orderBy("first_name","asc")->select("id")->get()->toArray(); $service_with_users_array = []; $users_array = []; $options_users = ""; foreach ($users_collection as $value){ $user = User::find($value->id); if (!is_null($user)) { $users_array[$user->id] = $user->first_name . " ". $user->last_name; $options_users .= ""; 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('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 $dynamic_key = $record->id."__".$value->id; $dynamic_value = get_full_name($value->id, 'id', 'first_name', 'last_name', 'users')." (".$record->name.")"; $service_with_users_array[$dynamic_key] = $dynamic_value; //add these dynamically formed values to service_items array array_add($service_items, $dynamic_key, $dynamic_value); //add it to the services_options too i.e used when user clicks add_service btn } } } } /*===================*/ /* ====== start work on investigations */ // prep the inpatient investigation arrays and counters $opd_investigations = []; $opd_investigations_position = []; $opd_investigations_date = []; $ward_investigations = []; $ward_investigations_position = []; $ward_investigations_date = []; // get all investigations ordered in this episode $ordered_investigations = OrderedInvestigation::where(['episode_id' => $episode_id])->get(); // get all results $investigation_results_order_ids = InvestigationResults::pluck('order_id', 'id')->toArray(); foreach ($ordered_investigations as $investigation) { if (isset($ward_investigations['id'])) { $ward_investigations_position[] = count($ward_investigations['id']); } else { $ward_investigations_position[] = 0; } if (isset($opd_investigations['id'])) { $opd_investigations_position[] = count($opd_investigations['id']); } else { $opd_investigations_position[] = 0; } $ward_investigations_date[] = "Ordered on " . streamline_date_time($investigation->created_at) . " by " . get_full_name($investigation->created_by, 'id', 'first_name', 'last_name', 'users'); $opd_investigations_date[] = streamline_date_time($investigation->created_at); $investigation_ids = explode(",", $investigation->investigation_id); $inpatient_status = explode(",", $investigation->for_inpatient); // check if results are available for this investigation if (in_array($investigation->id, $investigation_results_order_ids)) { // get the key if available $key = array_search($investigation->id, $investigation_results_order_ids); // get the results object $results = InvestigationResults::find($key); // exclude obstetric u/s results if ($results->result_type != "Ultrasound_Obstetric") { $investigation_results = explode(",", $results->value); $investigation_per_valid = explode(",", $results->per_investigation); $investigation_comments = explode(",", $results->comment); if ($results->all_authenticated == 1) { for ($i = 0; $i < count($inpatient_status); $i++) { if (isset($inpatient_status[$i]) && $inpatient_status[$i] == 0) { $result = Investigation::withTrashed()->find($investigation_ids[$i]); if ($result) { $opd_investigations['id'][] = $result->id; $opd_investigations['name'][] = $result->name; $opd_investigations['type'][] = $result->type; $opd_investigations['slug'][] = $result->slug; $opd_investigations['value'][] = $investigation_results[$i]; $opd_investigations['comment'][] = $investigation_comments[$i]; } } else { $result = Investigation::withTrashed()->find($investigation_ids[$i]); if ($result) { $ward_investigations['id'][] = $result->id; $ward_investigations['name'][] = $result->name; $ward_investigations['type'][] = $result->type; $ward_investigations['slug'][] = $result->slug; $ward_investigations['value'][] = $investigation_results[$i] ?? ""; $ward_investigations['comment'][] = $investigation_comments[$i]?? ""; } } } } else { for ($i = 0; $i < count($inpatient_status); $i++) { $investigation = Investigation::withTrashed()->find($investigation_ids[$i]); if (!$investigation) { continue; } if (isset($investigation_per_valid[$i]) && $investigation_per_valid[$i] == 1) { // this investigation is authenticated if (isset($inpatient_status[$i]) && $inpatient_status[$i] == 0) { $opd_investigations['id'][] = $investigation->id; $opd_investigations['name'][] = $investigation->name; $opd_investigations['type'][] = $investigation->type; $opd_investigations['slug'][] = $investigation->slug; $opd_investigations['value'][] = $investigation_results[$i]; $opd_investigations['comment'][] = $investigation_comments[$i]; } else { $ward_investigations['id'][] = $investigation->id; $ward_investigations['name'][] = $investigation->name; $ward_investigations['type'][] = $investigation->type; $ward_investigations['slug'][] = $investigation->slug; $ward_investigations['value'][] = $investigation_results[$i]; $ward_investigations['comment'][] = $investigation_comments[$i]; } } else { if (isset($investigation_per_valid[$i]) && $inpatient_status[$i] == 0) { $opd_investigations['id'][] = $investigation->id; $opd_investigations['name'][] = $investigation->name; $opd_investigations['type'][] = $investigation->type; $opd_investigations['slug'][] = $investigation->slug; $opd_investigations['value'][] = "Pending"; $opd_investigations['comment'][] = "Pending"; } else { $ward_investigations['id'][] = $investigation->id; $ward_investigations['name'][] = $investigation->name; $ward_investigations['type'][] = $investigation->type; $ward_investigations['slug'][] = $investigation->slug; $ward_investigations['value'][] = "Pending"; $ward_investigations['comment'][] = "Pending"; } } } } } } else { for ($i = 0; $i < count($inpatient_status); $i++) { if (isset($inpatient_status[$i]) && $inpatient_status[$i] == 0) { $result = Investigation::withTrashed()->find($investigation_ids[$i]); if ($result) { $opd_investigations['id'][] = $result->id; $opd_investigations['name'][] = $result->name; $opd_investigations['type'][] = $result->type; $opd_investigations['slug'][] = $result->slug; $opd_investigations['value'][] = "Pending"; $opd_investigations['comment'][] = "Pending"; } } else { $result = Investigation::withTrashed()->find($investigation_ids[$i]); if ($result) { $ward_investigations['id'][] = $result->id; $ward_investigations['name'][] = $result->name; $ward_investigations['type'][] = $result->type; $ward_investigations['slug'][] = $result->slug; $ward_investigations['value'][] = "Pending"; $ward_investigations['comment'][] = "Pending"; } } } } } /* ====== end work on investigations */ $data = [ 'patient' => $patient, 'price_list_set' => $price_list_set, 'dispensed_drug_quantity_given_array' => $dispensed_drug_quantity_given_array, 'inpatient_info' => $inpatient_info, 'patient_id' => $patient_id, 'treatment_to_take_away' => $treatment_to_take_away, 'service_deposits' => $service_deposits, 'patient_discount' => $patient_discount, 'episode_id' => $episode_id, 'price_list_categories' => $price_list_categories, 'hospitalInfo' => $hospitalInfo, 'anaesthesia' => $anaesthesia, 'service_items' => $service_items, 'sundries' => $sundries, 'services_with_users_array' => $services_with_users_array, 'ward_investigations' => $ward_investigations, 'opd_investigations' => $opd_investigations, 'opd_investigations_position' => $opd_investigations_position, 'ward_investigations_position' => $ward_investigations_position, 'opd_investigations_date' => $opd_investigations_date, 'ward_investigations_date' => $ward_investigations_date ]; // return view('ward_management::inpatient/referral_notes_print', $data); $pdf = SnappyPDF::loadView('ward_management::inpatient/referral_notes_print', $data) ->setOrientation('portrait') ->setOption('margin-bottom', 7) ->setOption('margin-top', 5) ->setOption('footer-html', 'Stre@mline'); return $pdf->inline('Referral Notes' . date("y-m-d h:ia") . '.pdf'); } public function inpatient_attendant_pass(Request $request) { $episode_id = session()->get('episode_id'); $patient_id = session()->get('patient_id'); $total_deposits_paid = 0; $inpatient_info = InpatientInfo::where(['patient_id' => $patient_id,'episode_id' => $episode_id])->orderBy('created_at','desc')->first(); $inpatient_bill = InpatientBill::where(['patient_id' => $patient_id,'episode_id' => $episode_id])->orderBy('created_at','desc')->first(); $inpatient_deposits = ServiceDeposit::where(['patient_id'=>$patient_id,'episode_id'=>$episode_id])->get(); foreach($inpatient_deposits as $service_deposit): $item_ids_array = explode(",", $service_deposit->items_ids); $item_amounts_array = explode(",", $service_deposit->items_amounts); if(($service_deposit->service_type == "Inpatient_Deposit") && ($service_deposit->patient_id == $patient_id) && ($service_deposit->episode_id == $episode_id)): $total_deposits_paid += $service_deposit->patient_amount_paid; $latest_payment_date = $service_deposit->created_at; $latest_deposit_id = $service_deposit->id; endif; endforeach; $number_of_days = 1; if ($total_deposits_paid > 0) { $number_of_days = 5; } $patient = Patient::find($patient_id); return view('ward_management::inpatient.inpatient_attendant_pass',compact('patient', 'inpatient_info', 'inpatient_deposits', 'inpatient_bill','number_of_days')); } public function store_inpatient_attendant_pass(Request $request) { $episode_id = session()->get('episode_id'); $patient_id = session()->get('patient_id'); $latest_deposit_id = null; $total_deposits_paid = 0; $expiration_number_of_days = $request->expiry_days; $inpatient_info = InpatientInfo::where(['patient_id' => $patient_id,'episode_id' => $episode_id])->orderBy('created_at','desc')->first(); $service_deposits = ServiceDeposit::where(['patient_id'=>$patient_id,'episode_id'=>$episode_id])->get(); foreach($service_deposits as $service_deposit): $item_ids_array = explode(",", $service_deposit->items_ids); $item_amounts_array = explode(",", $service_deposit->items_amounts); if(($service_deposit->service_type == "Inpatient_Deposit") && ($service_deposit->patient_id == $patient_id) && ($service_deposit->episode_id == $episode_id)): $total_deposits_paid += $service_deposit->patient_amount_paid; $latest_payment_date = $service_deposit->created_at; $latest_deposit_id = $service_deposit->id; endif; endforeach; $inpatient_attendant_pass = InpatientAttendantPass::where(['services_deposit_id' => $latest_deposit_id, 'inpatient_info_id' => $inpatient_info->id])->first(); if (is_null($inpatient_attendant_pass)) { $inpatient_attendant_pass = new InpatientAttendantPass; $inpatient_attendant_pass->patient_id = $patient_id; $inpatient_attendant_pass->episode_id = $episode_id; $inpatient_attendant_pass->inpatient_info_id = $inpatient_info->id; $inpatient_attendant_pass->services_deposit_id = $latest_deposit_id; $inpatient_attendant_pass->expiry_date = Carbon::now()->addDays($expiration_number_of_days); $inpatient_attendant_pass->created_by = Auth::id(); $inpatient_attendant_pass->save(); } $inpatient_attendant_pass_id = $inpatient_attendant_pass->id; session()->put(['number_of_days' => $expiration_number_of_days]); session()->put(['inpatient_attendant_pass_id' => $inpatient_attendant_pass_id]); return redirect('print_inpatient_attendant_pass'); } public function print_inpatient_attendant_pass(Request $request) { $episode_id = session()->get('episode_id'); $patient_id = session()->get('patient_id'); $number_of_days = session()->get('number_of_days'); $inpatient_attendant_pass_id = session()->get('inpatient_attendant_pass_id'); $hospital_information = HospitalInformation::first(); $patient = Patient::find($patient_id); $inpatient_info = InpatientInfo::where(['patient_id' => $patient_id,'episode_id' => $episode_id])->orderBy('created_at','desc')->first(); $total_deposits_paid = 0; $attendant_pass_information = InpatientAttendantPass::find($inpatient_attendant_pass_id); return view('ward_management::inpatient.inpatient_attendant_pass_print',compact('hospital_information', 'patient', 'attendant_pass_information', 'number_of_days', 'inpatient_info')); } public function delete_doctor_notes($id) { $ward_doctor_notes = WardInpatientSheetComment::find($id); $ward_doctor_notes->delete(); flash('Ward doctor notes have been deleted')->success(); return redirect('in_patient_sheet'); } public function delete_nurse_notes($id) { $ward_nurse_notes = WardInpatientSheetNurseComment::find($id); $ward_nurse_notes->delete(); flash('Ward nurse notes have been deleted')->success(); return redirect('in_patient_sheet'); } public function re_calculate_inpatient_bill(Request $request) { $patient_id = session()->get('patient_id'); $episode_id = session()->get('episode_id'); $patient_insurance_status = (patient_insurance_status($patient_id) == 1); $ward_id = get_name($episode_id, 'episode_id', 'ward_id', 'inpatient_info'); $ward_id = is_integer($ward_id) ? $ward_id : 0; $inpatient_bill = InpatientBill::where(['patient_id'=>$patient_id, 'episode_id'=>$episode_id])->first(); if (!$inpatient_bill) { flash('No bill has been generated for this inpatient record')->error(); return redirect()->back()->withInput(); } $price_list_id = is_patient_category_attached_to_price_list($patient_id); //ward treatments $ward_treatments = WardTreatmentDispensation::where(['patient_id' => $patient_id, 'episode_id' => $episode_id])->get(); foreach ($ward_treatments as $ward_treatment) { $drugs_details = Drug::find($ward_treatment->drug_id); $drug_chi_price = 0; $ward_treatment->cost_price = $drugs_details->cost_price; $ward_treatment->inventory_account = $drugs_details->inventory_account; $ward_treatment->cost_of_goods_account = $drugs_details->cost_of_goods_account; if($patient_insurance_status){ $item_pricing_details = get_item_insurance_pricing($patient_id, $ward_treatment->drug_id, 4, true, $ward_id); $drug_selling_price = $item_pricing_details[2]; $drug_chi_price = $item_pricing_details[1]; } else { if ($price_list_id) { $drug_selling_price = get_price_list_category_price($price_list_id, 3, $ward_treatment->drug_id); } else { $drug_selling_price = $drugs_details->non_insured_price; } } $ward_treatment->price = $drug_selling_price; $ward_treatment->chi_price = $drug_chi_price; $ward_treatment->update(); } //ward investigations $ward_investigations = WardInvestigationPricing::where(['patient_id' => $patient_id,'episode_id' => $episode_id])->get(); foreach ($ward_investigations as $ward_inv_pricing) { $investigation_chi_amount = 0; if($patient_insurance_status){ $item_pricing_details = get_item_insurance_pricing($patient_id, $ward_inv_pricing->investigation_id, 3, true, $ward_id); $investigation_amount = $item_pricing_details[2]; $investigation_chi_amount = $item_pricing_details[1]; } else { if ($price_list_id) { $investigation_amount = get_price_list_category_price($price_list_id, 2, $ward_inv_pricing->investigation_id); } else { $investigation_amount = get_name($ward_inv_pricing->investigation_id, "id", "non_insured_price", "investigations"); } } $ward_inv_pricing->price = $investigation_amount; $ward_inv_pricing->chi_price = $investigation_chi_amount; $ward_inv_pricing->current_chart_of_account = get_name($ward_inv_pricing->investigation_id, "id", "account_id", "investigations"); $ward_inv_pricing->update(); } // ward services $ward_services = WardConsultationsAndService::where(['patient_id' => $patient_id,'episode_id' => $episode_id])->get(); foreach ($ward_services as $ward_serv) { $service_chi_amount = 0; if($patient_insurance_status){ $item_pricing_details = get_item_insurance_pricing($patient_id, $ward_serv->service_id, 1, true, $ward_id); $service_amount = $item_pricing_details[2]; $service_chi_amount = $item_pricing_details[1]; } else { if ($price_list_id) { $service_amount = get_price_list_category_price($price_list_id, 6, $ward_serv->service_id); } else { $service_amount = get_name($ward_serv->service_id, "id", "non_insured_price", "services"); } } $ward_serv->unit_price = $service_amount; $ward_serv->chi_price = $service_chi_amount; $ward_serv->current_chart_of_account = get_name($ward_serv->service_id, "id", "account_id", "services"); $ward_serv->update(); } //ward sundries $ward_sundries = WardSundryDispensation::where(['patient_id' => $patient_id,'episode_id' => $episode_id])->get(); foreach ($ward_sundries as $ward_sundry) { $sundry_details = Sundry::find($ward_sundry->sundry_id); $sundry_chi_price = 0; $ward_sundry->current_chart_of_account = $sundry_details->account_id; $ward_sundry->inventory_account = $sundry_details->inventory_account; $ward_sundry->cost_of_goods_account = $sundry_details->cost_of_goods_account; $ward_sundry->cost_price = $sundry_details->cost_price; if($patient_insurance_status){ $item_pricing_details = get_item_insurance_pricing($patient_id, $ward_sundry->sundry_id, 5, true, $ward_id); $sundry_selling_price = $item_pricing_details[2]; $sundry_chi_price = $item_pricing_details[1]; } else { if ($price_list_id) { $sundry_selling_price = get_price_list_category_price($price_list_id, 5, $ward_sundry->sundry_id); } else { $sundry_selling_price = $sundry_details->non_insured_price; } } $ward_sundry->price = $sundry_selling_price; $ward_sundry->chi_price = $sundry_chi_price; $ward_sundry->update(); } //ward procedures $ward_procedures = WardProcedure::where(['patient_id' => $patient_id,'episode_id' => $episode_id])->get(); foreach ($ward_procedures as $ward_procedure) { $procedure_details = Procedure::find($ward_procedure->procedure_id); $procedure_chi_price = 0; $ward_procedure->current_chart_of_account = $procedure_details->account_id; if($patient_insurance_status){ $item_pricing_details = get_item_insurance_pricing($patient_id, $ward_procedure->procedure_id, 2, true, $ward_id); $procedure_selling_price = $item_pricing_details[2]; $procedure_chi_price = $item_pricing_details[1]; } else { if ($price_list_id) { $procedure_selling_price = get_price_list_category_price($price_list_id, 4, $ward_procedure->procedure_id); } else { $procedure_selling_price = $procedure_details->non_insured_price; } } $ward_procedure->hospital_fee = $procedure_selling_price; $ward_procedure->chi_price = $procedure_chi_price; $ward_procedure->update(); } // opd procedures $opd_unpaid_procedures = OrderedProcedure::where(['patient_id' => $patient_id, 'episode_id' => $episode_id,'payment_status' => 0])->get(); $saved_procedures_prices = []; $saved_chi_procedures_prices = []; foreach ($opd_unpaid_procedures as $opd_unpaid_procedure) { $procedure_ids = explode(",", $opd_unpaid_procedure->procedure_id); for ($i = 0; $i < count($procedure_ids) ; $i++) { if($patient_insurance_status){ $item_insurance_details = get_item_insurance_pricing($patient_id, $procedure_ids[$i], 2, true, $ward_id); $opd_procedure_amount = $item_insurance_details[2]; $opd_procedure_insurance_amount = $item_insurance_details[1]; } else { if ($price_list_id) { $opd_procedure_amount = get_price_list_category_price($price_list_id, 4, $procedure_ids[$i]); } else { $opd_procedure_amount = get_name($procedure_ids[$i], "id", "non_insured_price", "procedures"); } $opd_procedure_insurance_amount = 0; } $saved_procedures_prices[] = $opd_procedure_amount; $saved_chi_procedures_prices[] = $opd_procedure_insurance_amount; } } //opd treatments $opd_unpaid_treatments = Treatment::where(['patient_id' => $patient_id, 'episode_id' => $episode_id,'payment_status' => 0, 'tta' => 0])->get(); $saved_drug_prices = []; $saved_chi_drug_prices = []; foreach ($opd_unpaid_treatments as $opd_treatment) { $unit_selling_prices_array = []; $opd_drug_ids = explode(",", $opd_treatment->drugs); for ($i=0; $i < count($opd_drug_ids) ; $i++) { if($patient_insurance_status){ $item_insurance_details = get_item_insurance_pricing($patient_id, $opd_drug_ids[$i], 4, true, $ward_id); $treatment_amount = $item_insurance_details[2]; $opd_treatment_insurance_amount = $item_insurance_details[1]; } else { if ($price_list_id) { $treatment_amount = get_price_list_category_price($price_list_id, 3, $opd_drug_ids[$i]); } else { $treatment_amount = get_name($opd_drug_ids[$i], "id", "non_insured_price", "drugs"); } $opd_treatment_insurance_amount = 0; } $unit_selling_prices_array[] = $treatment_amount; $saved_drug_prices[] = $treatment_amount; $saved_chi_drug_prices[] = $opd_treatment_insurance_amount; } $opd_treatment->unit_selling_prices = implode(",", $unit_selling_prices_array); $opd_treatment->save(); } //opd sundries $opd_unpaid_sundries = OrderedSundry::where(['patient_id' => $patient_id, 'episode_id' => $episode_id,'payment_status' => 0])->get(); $saved_sundry_prices = []; $saved_chi_sundry_prices = []; foreach ($opd_unpaid_sundries as $opd_sundry_order) { $opd_sundry_ids_array = explode(",", $opd_sundry_order->sundries_id); $unit_selling_prices_array = []; for ($i=0; $i < count($opd_sundry_ids_array) ; $i++) { if($patient_insurance_status){ $item_insurance_details = get_item_insurance_pricing($patient_id, $opd_sundry_ids_array[$i], 5, true, $ward_id); $opd_sundry_amount = $item_insurance_details[2]; $opd_sundry_insurance_amount = $item_insurance_details[1]; } else { if ($price_list_id) { $opd_sundry_amount = get_price_list_category_price($price_list_id, 5, $opd_sundry_ids_array[$i]); } else { $opd_sundry_amount = get_name($opd_sundry_ids_array[$i], "id", "non_insured_price", "sundries"); } $opd_sundry_insurance_amount = 0; } $unit_selling_prices_array[] = $opd_sundry_amount; $saved_sundry_prices[] = $opd_sundry_amount; $saved_chi_sundry_prices[] = $opd_sundry_insurance_amount; } $opd_sundry_order->sundries_id = implode(",", $opd_sundry_ids_array); $opd_sundry_order->sundries_amount = implode(",", $unit_selling_prices_array); $opd_sundry_order->update(); } //opd services $opd_unpaid_services = OrderedService::where(['patient_id' => $patient_id, 'episode_id' => $episode_id,'payment_status' => 0])->get(); $saved_services_prices = []; $saved_chi_services_prices = []; foreach($opd_unpaid_services as $opd_used_service){ $service_ids_array = explode(",", $opd_used_service->service_id); $services_amounts_array = []; $price_list_id = is_patient_category_attached_to_price_list($patient_id); for ($i=0; $i < count($service_ids_array) ; $i++) { if($patient_insurance_status){ $item_insurance_details = get_item_insurance_pricing($patient_id, $service_ids_array[$i], 1, true, $ward_id); $service_cost = $item_insurance_details[2]; $opd_service_insurance = $item_insurance_details[1]; } else { if ($price_list_id) { $service_cost = get_price_list_category_price($price_list_id, 6, $service_ids_array[$i]); } else{ $service_cost = get_name($service_ids_array[$i], "id", "non_insured_price", "services"); } $opd_service_insurance = 0; } $services_amounts_array[] = $service_cost; $saved_services_prices[] = $service_cost; $saved_chi_services_prices[] = $opd_service_insurance; } $opd_used_service->service_amount = implode(",", $services_amounts_array); $opd_used_service->save(); } $treatment_to_take_away = Treatment::where(['patient_id' => $patient_id, 'episode_id' => $episode_id, 'tta' => 1])->get(); $saved_tta_prices = []; $saved_chi_tta_prices = []; foreach($treatment_to_take_away as $treatment) { $unit_selling_prices_array = []; $opd_drug_ids = explode(",", $treatment->drugs); for ($i=0; $i < count($opd_drug_ids) ; $i++) { if($patient_insurance_status){ $item_insurance_details = get_item_insurance_pricing($patient_id, $opd_drug_ids[$i], 4, true, $ward_id); $treatment_amount = $item_insurance_details[2]; $opd_treatment_insurance_amount = $item_insurance_details[1]; } else { if ($price_list_id) { $treatment_amount = get_price_list_category_price($price_list_id, 3, $opd_drug_ids[$i]); } else { $treatment_amount = get_name($opd_drug_ids[$i], "id", "non_insured_price", "drugs"); } $opd_treatment_insurance_amount = 0; } $unit_selling_prices_array[] = $treatment_amount; $saved_tta_prices[] = $treatment_amount; $saved_chi_tta_prices[] = $opd_treatment_insurance_amount; } $treatment->unit_selling_prices = implode(",", $unit_selling_prices_array); $treatment->save(); } // save items and prices for OPD items since IPD have their own tables 'cept for investigations $inpatient_bill->sundries_item_prices = implode(",", $saved_sundry_prices); $inpatient_bill->prescription_treatment_item_prices = implode(",", $saved_drug_prices); $inpatient_bill->procedures_item_prices = implode(",", $saved_procedures_prices); $inpatient_bill->services_item_prices = implode(",", $saved_services_prices); $inpatient_bill->tta_item_prices = implode(",", $saved_tta_prices); $inpatient_bill->sundries_item_chi_prices = implode(",", $saved_chi_sundry_prices); $inpatient_bill->prescription_treatment_item_chi_prices = implode(",", $saved_chi_drug_prices); $inpatient_bill->procedures_item_chi_prices = implode(",", $saved_chi_procedures_prices); $inpatient_bill->services_item_chi_prices = implode(",", $saved_chi_services_prices); $inpatient_bill->tta_item_chi_prices = implode(",", $saved_chi_tta_prices); $inpatient_bill->save(); flash('Inpatient bill has been re-calculated using the current price list of the patient')->info(); return redirect('inpatient_billing'); } public function update_ward_consumption_prices_with_price_list($patient_id, $episode_id, $price_list_id) { //1.ward treatments $ward_treatment_dispensations = WardTreatmentDispensation::where(['episode_id' => $episode_id, 'patient_id' => $patient_id])->get(); if (count($ward_treatment_dispensations) > 0) { foreach ($ward_treatment_dispensations as $ward_treatment) { $ward_treatment->price = get_price_list_category_price($price_list_id, 3, $ward_treatment->drug_id); $ward_treatment->update(); } } //2.ward sundries $ward_sundry_dispensations = WardSundryDispensation::where(['episode_id' => $episode_id, 'patient_id' => $patient_id])->get(); if (count($ward_sundry_dispensations) > 0) { foreach ($ward_sundry_dispensations as $ward_sundry) { $ward_sundry->price = get_price_list_category_price($price_list_id, 5, $ward_sundry->sundry_id); $ward_sundry->update(); } } //3.ward services $ward_consultations_and_services = WardConsultationsAndService::where(['episode_id' => $episode_id, 'patient_id' => $patient_id])->get(); if (count($ward_consultations_and_services) > 0) { foreach ($ward_consultations_and_services as $ward_service) { if (is_numeric($ward_service->service_id)) { //make sure it is numeric to cater for staff configured services $ward_service->unit_price = get_price_list_category_price($price_list_id, 6, $ward_service->service_id); $ward_service->update(); } } } //4.ward procedures $ward_procedures = WardProcedure::where(['episode_id' => $episode_id, 'patient_id' => $patient_id])->get(); if (count($ward_procedures) > 0) { foreach ($ward_procedures as $ward_procedure) { $ward_procedure->hospital_fee = get_price_list_category_price($price_list_id, 4, $ward_procedure->procedure_id); $ward_procedure->update(); } } //update the inpatient record for procedures $inpatient_info = InpatientInfo::where(['episode_id' => $episode_id, 'patient_id' => $patient_id])->first(); $inpatient_procedures = @unserialize($inpatient_info->procedures); $inpatient_procedures_hospital_fees = @unserialize($inpatient_info->procedure_hospital_fee); $procedures_array = $hospital_fees_array = []; if(is_array($inpatient_procedures)){ for ($i = 0; $i < count($inpatient_procedures); $i++){ $procedures_array[] = $inpatient_procedures[$i]; $hospital_fees_array[] = get_price_list_category_price($price_list_id, 4, $inpatient_procedures[$i]); } } $inpatient_info->procedures = serialize($procedures_array); $inpatient_info->procedure_hospital_fee = serialize($hospital_fees_array); $inpatient_info->update(); //5.ward investigations $ward_investigations = WardInvestigationPricing::where(['episode_id' => $episode_id, 'patient_id' => $patient_id])->get(); if (count($ward_investigations) > 0) { foreach ($ward_investigations as $ward_inv) { $ward_inv->price = get_price_list_category_price($price_list_id, 2, $ward_inv->investigation_id); $ward_inv->update(); } } } public function delete_inpatient_detailed_notes($id) { $ward_doctor_notes = WardInpatientDetailedNote::find($id); $ward_doctor_notes->delete(); flash('Notes have been deleted')->success(); return redirect('in_patient_sheet'); } public function update_inpatient_notes(Request $request) { //pick id from ajax post request :: id $inpatient_notes_id = $request->id; // Validate the incoming request data $request->validate([ 'history' => 'nullable|string', 'vitals' => 'nullable|string', 'result' => 'nullable|string', 'impression' => 'nullable|string', 'plan' => 'nullable|string', ]); try { $ward_doctor_notes = WardInpatientDetailedNote::findOrFail($inpatient_notes_id); $ward_doctor_notes->history = $request->history; $ward_doctor_notes->result = $request->result; $ward_doctor_notes->vitals = $request->vitals; $ward_doctor_notes->impression = $request->impression; $ward_doctor_notes->plan = $request->plan; $ward_doctor_notes->save(); // Return a JSON response indicating success return response()->json(['success' => true, 'message' => 'Inpatient notes updated successfully.']); } catch (\Exception $e) { \Log::error("Error updating inpatient notes: " . $e->getMessage()); return response()->json([ 'success' => false, 'message' => 'An error occurred while updating notes.', 'error' => $e->getMessage() // Include error message for debugging ], 500); } } public function update_doctor_ward_notes(Request $request){ $doctor_inpatient_notes_id = $request->id; // Validate the incoming request data $request->validate([ 'ward_comments' => 'nullable|string', ]); try { $doctor_ward_notes = WardInpatientSheetComment::findOrFail($doctor_inpatient_notes_id); $doctor_ward_notes->ward_comments = $request->ward_comments; $doctor_ward_notes->save(); // Return a JSON response indicating success return response()->json([ 'success' => true, 'message' => 'Doctor Ward inpatient notes updated successfully.' ]); } catch (\Exception $e) { \Log::error("Error updating inpatient notes: " . $e->getMessage()); return response()->json([ 'success' => false, 'message' => 'An error occurred while updating notes.', 'error' => $e->getMessage() ], 500); } } public function update_nurse_ward_notes(Request $request){ $nurse_inpatient_notes_id = $request->id; // Validate the incoming request data $request->validate([ 'ward_comments' => 'nullable|string', ]); try { $doctor_ward_notes = WardInpatientSheetNurseComment::findOrFail($nurse_inpatient_notes_id); $doctor_ward_notes->ward_comments = $request->ward_comments; $doctor_ward_notes->save(); // Return a JSON response indicating success return response()->json([ 'success' => true, 'message' => 'Nurse Ward inpatient notes updated successfully.' ]); } catch (\Exception $e) { \Log::error("Error updating inpatient notes: " . $e->getMessage()); return response()->json([ 'success' => false, 'message' => 'An error occurred while updating notes.', 'error' => $e->getMessage() ], 500); } } public function inpatient_detailed_notes_print() { $patient_id = session()->get('patient_id'); $episode_id = session()->get('episode_id'); $patient = Patient::find($patient_id); $hospitalInfo = DB::table('hospital_information')->find(1); $inpatient_info = InpatientInfo::where(['patient_id' => $patient_id, 'episode_id' => $episode_id])->orderBy('created_at', 'desc')->first(); $patient_discount = PatientDiscount::where(['patient_category' => $patient->category_id])->select("discount", "pay_later")->first(); if (!is_null($patient_discount)) { $patient_discount->toArray(); } $data = [ 'patient' => $patient, 'patient_id' => $patient_id, 'episode_id' => $episode_id, 'inpatient_info' => $inpatient_info, 'patient_discount' => $patient_discount, 'hospitalInfo' => $hospitalInfo, ]; $pdf = SnappyPDF::loadView('ward_management::inpatient/inpatient_detailed_notes_print', $data) ->setOrientation('portrait') ->setOption('margin-bottom', 7) ->setOption('margin-top', 5) ->setOption('footer-html', 'Stre@mline'); return $pdf->inline('Inpatient Notes' . date(" d-m-y h:ia") . '.pdf'); } public function save_patient_vitals(Request $request) { $vitals_observations = $request->vitals_observations; $vitals_value = $request->vitals_value; $vitals_datetime = $request->vitals_datetime; $patient_id = $request->patient_id; $episode_id = $request->episode_id; $inpatient_id = $request->inpatient_id; $observations = DB::table('observations') ->whereNull('deleted_at') ->pluck('name', 'id'); $vitals = []; for ($i = 0; $i < count($vitals_observations); $i++) { $exploded_date = explode("-", $vitals_datetime[$i]); if (!(empty($vitals_observations[$i]) || empty($vitals_value[$i]) || empty($vitals_datetime[$i])) && strtotime($vitals_datetime[$i]) && isset($observations[$vitals_observations[$i]]) && ((int)$exploded_date[0] <= (int)date('Y'))) { $vitals[] = [ "name" => $observations[$vitals_observations[$i]], "value" => $vitals_value[$i], "time" => $vitals_datetime[$i] ]; } } if (count($vitals) === 0) { return 0; } $inpatient_vitals = new PatientInpatientVitals(); $inpatient_vitals->patient_id = $patient_id; $inpatient_vitals->episode_id = $episode_id; $inpatient_vitals->inpatient_id = $inpatient_id; $inpatient_vitals->vitals = json_encode($vitals); $inpatient_vitals->created_by = Auth::id(); try { $inpatient_vitals->save(); return 1; } catch (QueryException $exception) { return 0; } } public function open_inpatient_bill($id) { $inpatient_bill = InpatientBill::find($id); // TODO check if the insurance has been changed before opening try { $inpatient_bill->bill_closed = 0; $inpatient_bill->bill_closed_by = NULL; $inpatient_bill->bill_closed_at = NULL; $inpatient_bill->updated_by = Auth::id(); $inpatient_bill->save(); $claim = InsuranceClaim::where('order_id', $id) ->where('inpatient_outpatient', 1)->update(['claim_status' => 1]); } catch (\ErrorException $e) { flash("An error occurred, please try again")->error(); } return redirect('inpatient_billing'); } public function stop_ward_drug(Request $request){ $ward_prescription_id = $request->ward_prescription_id; $drug_id = $request->drug_id; $ward_treatment = WardTreatment::find($ward_prescription_id); $stopped_drugs_array = is_null($ward_treatment->stopped_drugs) ? [] : explode(",", $ward_treatment->stopped_drugs); if (!in_array($drug_id, $stopped_drugs_array)) { $stopped_drugs_array[] = $drug_id; $stopped_drugs_string = implode(",", $stopped_drugs_array); $ward_treatment->stopped_drugs = $stopped_drugs_string; $ward_treatment->update(); return 1; } return 0; } public function resume_ward_drug(Request $request){ $ward_prescription_id = $request->ward_prescription_id; $drug_id = $request->drug_id; $ward_treatment = WardTreatment::find($ward_prescription_id); $stopped_drugs_array = is_null($ward_treatment->stopped_drugs) ? [] : explode(",", $ward_treatment->stopped_drugs); if (in_array($drug_id, $stopped_drugs_array)) { //get array of stopped drugs and find index of this drug, remove drug from array then implode $key = array_search($drug_id, $stopped_drugs_array); unset($stopped_drugs_array[$key]); $updated_drugs_string = implode(",", $stopped_drugs_array); $ward_treatment->stopped_drugs = $updated_drugs_string; $ward_treatment->update(); return 1; } return 0; } }