middleware('auth'); $this->middleware('permission:finance-reports-activate'); } public function index() { return view('finance_reports::finance_reports.index'); } public function pointOfSale(Request $request): View { $treatments = []; $sundries = []; $counter = 0; $staff_members = User::get(); $display = dateLabelSetter($request); $end = Carbon::parse($request->end_date)->endOfDay()->toDateTimeString(); $start = Carbon::parse($request->start_date)->startOfDay()->toDateTimeString(); $pos_episodes = PatientEpisode::where('paid_over', 'pos')->get()->pluck('id'); if ($request->staff_member == "ALL STAFF") { switch ($request->dates) { case 'today': foreach ($pos_episodes as $episode) { $sundries[$counter] = SundryDeposit::where('episode_id', $episode)->whereDate('created_at', Carbon::today()->toDateTimeString())->get()->toArray(); $treatments[$counter] = TreatmentDeposits::where('episode_id', $episode)->whereDate('created_at', Carbon::today()->toDateTimeString())->get()->toArray(); ++$counter; } break; case 'yesterday': foreach ($pos_episodes as $episode) { $sundries[$counter] = SundryDeposit::where('episode_id', $episode)->whereDate('created_at', Carbon::yesterday()->toDateTimeString())->get()->toArray(); $treatments[$counter] = TreatmentDeposits::where('episode_id', $episode)->whereDate('created_at', Carbon::yesterday()->toDateTimeString())->get()->toArray(); ++$counter; } break; case 'custom_date': foreach ($pos_episodes as $episode) { $sundries[$counter] = SundryDeposit::where('episode_id', $episode)->whereDate('created_at', Carbon::parse($start)->toDateTimeString())->get()->toArray(); $treatments[$counter] = TreatmentDeposits::where('episode_id', $episode)->whereDate('created_at', Carbon::parse($start)->toDateTimeString())->get()->toArray(); ++$counter; } break; case 'custom_date_range': foreach ($pos_episodes as $episode) { $sundries[$counter] = SundryDeposit::where('episode_id', $episode)->whereBetween('created_at', [$start, $end])->get()->toArray(); $treatments[$counter] = TreatmentDeposits::where('episode_id', $episode)->whereBetween('created_at', [$start, $end])->get()->toArray(); ++$counter; } break; } } else { switch ($request->dates) { case 'today': foreach ($pos_episodes as $episode) { $sundries[$episode] = SundryDeposit::where('episode_id', $episode)->where('created_by', $request->staff_member)->whereDate('created_at', Carbon::today()->toDateTimeString())->get()->toArray(); $treatments[$episode] = TreatmentDeposits::where('episode_id', $episode)->where('created_by', $request->staff_member)->whereDate('created_at', Carbon::today()->toDateTimeString())->get()->toArray(); ++$counter; } break; case 'yesterday': foreach ($pos_episodes as $episode) { $sundries[$counter] = SundryDeposit::where('episode_id', $episode)->where('created_by', $request->staff_member)->whereDate('created_at', Carbon::yesterday()->toDateTimeString())->get()->toArray(); $treatments[$counter] = TreatmentDeposits::where('episode_id', $episode)->where('created_by', $request->staff_member)->whereDate('created_at', Carbon::yesterday()->toDateTimeString())->get()->toArray(); ++$counter; } break; case 'custom_date': foreach ($pos_episodes as $episode) { $sundries[$counter] = SundryDeposit::where('episode_id', $episode)->where('created_by', $request->staff_member)->whereDate('created_at', Carbon::parse($start)->toDateTimeString())->get()->toArray(); $treatments[$counter] = TreatmentDeposits::where('episode_id', $episode)->where('created_by', $request->staff_member)->whereDate('created_at', Carbon::parse($start)->toDateTimeString())->get()->toArray(); ++$counter; } break; case 'custom_date_range': foreach ($pos_episodes as $episode) { $sundries[$counter] = SundryDeposit::where('episode_id', $episode)->where('created_by', $request->staff_member)->whereBetween('created_at', [$start, $end])->get()->toArray(); $treatments[$counter] = TreatmentDeposits::where('episode_id', $episode)->where('created_by', $request->staff_member)->whereBetween('created_at', [$start, $end])->get()->toArray(); ++$counter; } break; } } return view('finance_reports::finance_reports.point_of_sale', compact('staff_members', 'pos_episodes', 'request', 'display', 'treatments', 'sundries')); } public function incomeCashReport(Request $request): View { if ($request->dates == "yesterday") { $start = Carbon::yesterday()->startOfDay(); $end = Carbon::yesterday()->endOfDay(); } elseif ($request->dates == "custom_date") { $start = Carbon::parse($request->start_date)->startOfDay(); $end = Carbon::parse($request->start_date)->endOfDay(); } elseif ($request->dates == "custom_date_range") { $start = Carbon::parse($request->start_date)->startOfDay(); $end = Carbon::parse($request->end_date)->endOfDay(); } else { // includes $request->dates == 'today' $start = Carbon::today()->startOfDay(); $end = Carbon::today()->endOfDay(); } $result = $this->incomeCashService->getSumServiceDeposit('service_deposits', $request); $consult_sum = $result[3]; $co_payments = $result[4]; $service_sum = $result[5]; $inpatient_deposit_sum = $result[7]; $staff_members = $this->userService->pluckUserFullName(); $staff_members = [0 => 'All Staff'] + $staff_members; $investigations = $this->incomeCashService->getSumByTableColumn('investigation_deposits', 'patient_amount_paid', $request); $drugs = $this->incomeCashService->getSumByTableColumn('treatment_deposits', 'patient_amount_paid', $request); $procedures = $this->incomeCashService->getSumByTableColumn('procedure_deposits', 'patient_amount_paid', $request); $sundries = $this->incomeCashService->getSumByTableColumn('sundries_deposits', 'patient_amount_paid', $request); $optics = $this->incomeCashService->getSumByTableColumn('eye_glasses_deposits', 'patient_amount_paid', $request); $inpatient_bill_payments = $this->incomeCashService->getSumByTableColumn('inpatient_bills', 'amount_paid', $request); // unreceived income within a given time frame... $unreceived_services = $this->incomeCashService->getUnReceivedSumServiceDeposit('service_deposits', $request); $unreceived_investigations = $this->incomeCashService->getUnReceivedSumByTableColumn('investigation_deposits', 'patient_amount_paid', $request); $unreceived_drugs = $this->incomeCashService->getUnReceivedSumByTableColumn('treatment_deposits', 'patient_amount_paid', $request); $unreceived_procedures = $this->incomeCashService->getUnReceivedSumByTableColumn('procedure_deposits', 'patient_amount_paid', $request); $unreceived_sundries = $this->incomeCashService->getUnReceivedSumByTableColumn('sundries_deposits', 'patient_amount_paid', $request); $unreceived_optics = $this->incomeCashService->getUnReceivedSumByTableColumn('eye_glasses_deposits', 'patient_amount_paid', $request); $invoice_payments = $this->invoicesService->getInvoicePayments($request); $donor_invoice_payments = $this->invoicesService->getDonorInvoicePayments($start, $end, $request->staff_member); // get the debtor payments $debtor_payments = $this->debtorsService->getDebtPaymentsSum($request); $debt_plan_payments = $this->debtPlanService->getDebtPlanPaymentsSum($request); $other_incomes = 0; $display = dateLabelSetter($request); $family_accounts_consumption = $this->familyAccountsService->getFamilyAccountsConsumptionAmounts($request->staff_member, $start, $end); $family_accounts_consumption_amount = array_sum($family_accounts_consumption); $family_accounts_consumption_unreceived_amount = $family_accounts_consumption[1]; $family_accounts_deposits = $this->familyAccountsService->getFamilyAccountsDepositAmounts($request->staff_member, $start, $end); $family_accounts_deposits_amount = array_sum($family_accounts_deposits); $unreceived_family_accounts_deposits_amount = $family_accounts_deposits[1]; $patient_accounts_consumption = $this->patientAccountsService->getPatientAccountsConsumptionAmounts($request->staff_member, $start, $end); $patient_accounts_consumption_amount = array_sum($patient_accounts_consumption); $patient_accounts_consumption_unreceived_amount = $patient_accounts_consumption[1]; $patient_accounts_deposits = $this->patientAccountsService->getPatientAccountsDepositAmounts($request->staff_member, $start, $end); $patient_accounts_deposits_amount = array_sum($patient_accounts_deposits); $unreceived_patient_accounts_deposits_amount = $patient_accounts_deposits[1]; $direct_bank_deposits_amount = get_direct_bank_deposits_amount($request); $unreceived_direct_bank_deposits_amount = get_unreceived_direct_bank_deposits_amount($request); return view('finance_reports::finance_reports.incomeCashReport', compact('staff_members', 'consult_sum', 'service_sum', 'debtor_payments', 'donor_invoice_payments', 'sundries', 'procedures', 'investigations', 'other_incomes', 'drugs', 'co_payments', 'display', 'request', 'inpatient_deposit_sum', 'inpatient_bill_payments', 'unreceived_drugs', 'invoice_payments', 'debt_plan_payments', 'unreceived_investigations', 'unreceived_sundries', 'unreceived_procedures', 'unreceived_services', 'family_accounts_consumption_amount', 'optics', 'unreceived_optics', 'family_accounts_deposits_amount', 'unreceived_family_accounts_deposits_amount', 'family_accounts_consumption_unreceived_amount', 'patient_accounts_consumption_amount', 'patient_accounts_consumption_unreceived_amount', 'patient_accounts_deposits_amount', 'unreceived_patient_accounts_deposits_amount', 'direct_bank_deposits_amount', 'unreceived_direct_bank_deposits_amount')); } public function incomeDetailedReport(Request $request): View { $test_patients = findTestOrDemoPatients(); $result = $hospital_invoice_payments = $sorted_investigations = []; $patient_category_payments = $donor_invoice_payments = $debt_plan_payments = $debtor_payments = []; if ($request->date_type == "yesterday") { $end = Carbon::yesterday()->endOfDay(); $start = Carbon::yesterday()->startOfDay(); } else if ($request->date_type == "custom_date") { $dates = explode("/", $request->dates); $end = Carbon::parse($dates[0])->endOfDay(); $start = Carbon::parse($dates[0])->startOfDay(); } else if ($request->date_type == "custom_date_range") { $dates = explode("/", $request->dates); $end = Carbon::parse($dates[1])->endOfDay(); $start = Carbon::parse($dates[0])->startOfDay(); } else { $end = Carbon::today()->endOfDay(); $start = Carbon::today()->startOfDay(); } $filters = []; $staff_members = $this->userService->pluckUserFullName(); if ($request->user_id != 0) { $filters[] = ['created_by', '=', $request->user_id]; } if ($request->comparator == "consultations") { $result = DB::table('service_deposits') ->whereNotIn('patient_id', $test_patients) ->where('service_type', 'Consultation') ->whereBetween('created_at', [$start, $end]) ->where($filters) ->get() ->toArray(); } if ($request->comparator == "other_services") { $result = DB::table('service_deposits') ->whereNotIn('patient_id', $test_patients) ->where($filters) ->whereIn('service_type', ['Services', 'Other Services', 'Service']) ->whereBetween('created_at', [$start, $end]) ->get() ->toArray(); } if ($request->comparator == "investigations") { $sorted_investigations = $this->incomeCashService->getInvestigationDepositsByCategory($filters, $start, $end); } if ($request->comparator == "drugs") { $result = DB::table('treatment_deposits') ->whereNotIn('patient_id', $test_patients) ->where($filters) ->whereBetween('created_at', [$start, $end]) ->get() ->toArray(); } if ($request->comparator == "co_payments") { $result = DB::table('service_deposits') ->whereNotIn('patient_id', $test_patients) ->where('service_type', 'Co_Payment') ->where($filters) ->whereBetween('created_at', [$start, $end]) ->get() ->toArray(); } if ($request->comparator == "inpatient_deposits") { $result = DB::table('service_deposits') ->whereNotIn('patient_id', $test_patients) ->where('service_type', 'Inpatient_Deposit') ->where($filters) ->whereBetween('created_at', [$start, $end]) ->get() ->toArray(); return view('finance_reports::finance_reports.detail.inpatient_deposits', compact('result', 'request')); } if ($request->comparator == "procedures") { $result = DB::table('procedure_deposits') ->whereNotIn('patient_id', $test_patients) ->where($filters) ->whereBetween('created_at', [$start, $end]) ->get() ->toArray(); } if ($request->comparator == "sundries") { $result = DB::table('sundries_deposits') ->whereNotIn('patient_id', $test_patients) ->where($filters) ->whereBetween('created_at', [$start, $end]) ->get() ->toArray(); } if ($request->comparator == "optics") { $result = DB::table('eye_glasses_deposits') ->whereNotIn('patient_id', $test_patients) ->where($filters) ->whereBetween('created_at', [$start, $end]) ->get() ->toArray(); } if ($request->comparator == "paid_patient_debts") { $debtor_payments = $this->debtorsService->getDebtPaymentsRecords($start, $end, $filters); $debt_plan_payments = $this->debtPlanService->getDebtPlanPaymentsRecords($request); } if ($request->comparator == "paid_invoices") { $patient_category_payments = DB::table('invoice_payment_records') ->whereBetween('created_at', [$start, $end]) ->where($filters) ->get() ->toArray(); $donor_invoice_payments = DB::table('donor_invoice_payments') ->whereBetween('created_at', [$start, $end]) ->where($filters) ->get() ->toArray(); $hospital_invoice_payments = DB::table('hospital_invoice_payments') ->whereBetween('created_at', [$start, $end]) ->where($filters) ->get() ->toArray(); } $display = dateLabelSetter($request); return view('finance_reports::finance_reports.incomeDetailedReport', compact('result', 'request', 'donor_invoice_payments', 'patient_category_payments', 'debtor_payments', 'debt_plan_payments', 'staff_members', 'display', 'hospital_invoice_payments', 'sorted_investigations')); } public function receivedCash(Request $request) { $staff_members = DB::table('users')->get()->toArray(); $result = receivedCashFilter($request); $display = dateLabelSetter($request); $banks = DB::table('chart_of_accounts')->whereNotIn('slug', ['undeposited_funds', 'daily_cash_collections'])->where('type', 4)->whereNull('deleted_at')->get(); $expense_accounts = ChartOfAccount::where('type', 2)->pluck('name', 'id')->prepend('-select-', '')->toArray(); return view('finance_reports::finance_reports.receivedCash', compact('staff_members', 'request', 'result', 'display', 'banks', 'expense_accounts')); } public function cashier_income_detail($id) { $service_deposits = ServiceDeposit::where('received', $id)->get(); $sundry_deposits = SundryDeposit::where('received', $id)->get(); $treatment_deposits = TreatmentDeposits::where('received', $id)->get(); $procedure_deposits = ProcedureDeposit::where('received', $id)->get(); $investigation_deposits = InvestigationDeposit::where('received', $id)->get(); $debt_plan_payments = DebtPlanPaymentStaff::where('received_id', $id)->get(); $donor_invoice_payments = DonorInvoicePayment::where('received', $id)->get(); $patient_category_invoice_payments = InvoicePaymentRecord::where('received_id', $id)->groupBy('invoice_number')->get(); $other_incomes = []; return view('finance_reports::finance_reports.detail.received_cash', compact( 'service_deposits', 'sundry_deposits', 'treatment_deposits', 'procedure_deposits', 'investigation_deposits', 'debt_plan_payments', 'donor_invoice_payments', 'patient_category_invoice_payments', 'other_incomes' )); } public function discountsReport(Request $request) { $end = Carbon::parse($request->end_date)->endOfDay()->toDateTimeString(); $start = Carbon::parse($request->start_date)->startOfDay()->toDateTimeString(); $patient_categories = DB::table('patient_categories')->get()->toArray(); if ($request->patient_category == "ALL") { $discounts = DB::table('discounts')->whereBetween('created_at', [$start, $end])->get() ->toArray(); } else { $discounts = DB::table('discounts')->whereBetween('created_at', [$start, $end])->where('patient_category', $request->patient_category) ->get() ->toArray(); } $display = dateLabelSetter($request); return view('finance_reports::finance_reports.discountsReport', compact('patient_categories', 'discounts', 'display', 'request')); } public function donorDiscountsReport(Request $request) { $start = Carbon::parse($request->start_date)->startOfDay()->toDateTimeString(); $end = Carbon::parse($request->end_date)->endOfDay()->toDateTimeString(); $donors = DB::table('donors')->get()->toArray(); if ($request->donor == "ALL") { $discounts = DB::table('donor_discount_details')->whereBetween('created_at', [$start, $end]) ->groupBy('patient_category') ->get() ->toArray(); } else { $discounts = DB::table('donor_discount_details')->whereBetween('created_at', [$start, $end]) ->where('donor_id', $request->donor) ->groupBy('patient_category') ->get() ->toArray(); } $display = dateLabelSetter($request); return view('finance_reports::finance_reports.donorDiscountsReport', compact('donors', 'discounts', 'display', 'request')); } public function hospitalDiscountsReport(Request $request) { $start = Carbon::parse($request->start_date)->startOfDay()->toDateTimeString(); $end = Carbon::parse($request->end_date)->endOfDay()->toDateTimeString(); $result = DB::table('donor_discount_details')->whereBetween('created_at', [$start, $end])->get()->toArray(); //->where('hospital_to_pay', '>', 0) $display = dateLabelSetter($request); return view('finance_reports::finance_reports.hospitalDiscountsReport', compact('result', 'request', 'display')); } public function discrepancies(Request $request) { $filters = []; $users = User::pluck('id')->toArray(); if (isset($request->staff_member) && $request->staff_member != "ALL STAFF") { $filters[] = ['brought_by', '=', $request->staff_member]; } if (isset($request->start_date) && isset($request->end_date)) { $start = Carbon::parse($request->start_date)->startOfDay()->toDateTimeString(); $end = Carbon::parse($request->end_date)->endOfDay()->toDateTimeString(); $display = streamline_date($start) . ' to ' . streamline_date($end); } else { $start = Carbon::today()->startOfDay()->toDateTimeString(); $end = Carbon::today()->endOfDay()->toDateTimeString(); $display = "Today"; } $filters[] = ['balance', '!=', 0]; $discrepancies = DB::table('cashier_income') ->whereBetween('created_at', [$start, $end]) ->where($filters) ->whereNull('deleted_at') ->get() ->toArray(); return view('finance_reports::finance_reports.discrepancyReport', compact('users', 'display', 'discrepancies')); } public function receiveCashierPayments(Request $request) { $received_by = Auth::id(); $total = $request->total; $tracker = "Money Received From "; return view('finance_reports::finance_reports.receiveCashierPayments', compact( 'request', 'received_by', 'total', 'tracker', 'request' )); } public function processCashierReceipt(Request $request) { $validator = Validator::make($request->all(), [ 'amount_received' => 'required', ]); if ($validator->fails()) { $string = ""; foreach ($validator->errors()->getMessages() as $item) { $string .= "{$item[0]}
"; } flash($string)->error(); return back()->withErrors($validator)->withInput(); } else { $track_receipt = new TrackReceipt; $track_receipt->reason = $request->reason; $track_receipt->created_by = Auth::id(); $track_receipt->save(); $receipt_number = sprintf("%04u", $track_receipt->id); $most_recent_undeposited_funds_banking_record = get_latest_banking_record_based_on_transaction_date(get_name("undeposited_funds", "slug", "id", "chart_of_accounts"), Carbon::today()); $cashier_income = new CashierIncome; $cashier_income->cashier_id = $request->received_from_id; $cashier_income->brought_by = $request->received_by_id; $cashier_income->expected_amount = $request->expected_amount; $cashier_income->reason = $request->reason; $cashier_income->amount = $request->amount_received; $cashier_income->balance = $balance = ($request->expected_amount - $request->amount_received); $cashier_income->receipt_number = $receipt_number; $cashier_income->previous_balance = ($most_recent_undeposited_funds_banking_record) ? (int)$most_recent_undeposited_funds_banking_record->account_balance : 0; $cashier_income->date_string = getDateStringBasedOnDateSearchType($request); if ($cashier_income->save()) { flash("Cashier Receipt Created Successfully.")->success(); } else { flash("Cashier Receipt Not Created.")->error(); } $balance_after_addition = ($most_recent_undeposited_funds_banking_record) ? ((int)$most_recent_undeposited_funds_banking_record->account_balance + (int)$request->amount_received) : (int)$request->amount_received; capture_bank_record('DEPOSIT', Carbon::today()->toDateString(), 10, 'sales and payments', $balance_after_addition, $request->amount_received, 0, 'deposit to un-deposited funds.', $receipt_number); // subtract the money from the cash collection record_cash_debits_to_daily_collection_account($request->amount_received, $receipt_number, "Cashiers Collection"); $latest_cashier_income = CashierIncome::latest()->first(); $service_points = explode(',', $request->service_points); $filters = date_query_builder_using_date_time($request->start_date, $request->end_date, 'created_at', $request->dates); $created_by_filter = ['created_by', '=', $request->received_from_id]; ($request->received_from_id == "ALL STAFF") ? $filters : array_push($filters, $created_by_filter); for ($i = 0; $i < count($service_points); $i++) { switch ($service_points[$i]) { case 'services': ServiceDeposit::where($filters)->whereNull('received')->update(['received' => $latest_cashier_income->id]); break; case 'drugs': TreatmentDeposits::where($filters)->whereNull('received')->update(['received' => $latest_cashier_income->id]); break; case 'procedures': ProcedureDeposit::where($filters)->whereNull('received')->update(['received' => $latest_cashier_income->id]); break; case 'investigations': InvestigationDeposit::where($filters)->whereNull('received')->update(['received' => $latest_cashier_income->id]); break; case 'sundries': SundryDeposit::where($filters)->whereNull('received')->update(['received' => $latest_cashier_income->id]); break; case 'optics': EyeGlassesDeposits::where($filters)->whereNull('received')->update(['received' => $latest_cashier_income->id]); break; case 'premiums': SingleGroupPremium::where($filters)->whereNull('received')->update(['received' => $latest_cashier_income->id]); /* InsurancePremiums::where($filters)->whereNull('received')->update(['received' => $latest_cashier_income->id]); Note: Winfred says we remove these */ break; case 'debt_plan': $payments = DebtPlanPaymentStaff::where($filters)->get(); foreach ($payments as $payment) { DebtPlanPaymentStaff::where('id', $payment->id)->update([ 'received_id' => $latest_cashier_income->id, 'received_amount' => $payment->amount_paid ]); } break; case 'debtors': $payments = DebtorPayment::where($filters)->get(); foreach ($payments as $payment) { DebtorPayment::where('id', $payment->id)->update([ 'received_id' => $latest_cashier_income->id, 'received_amount' => $payment->amount_paid ]); } break; case 'family_account_deposits': FamilyAccountDeposit::where($filters)->whereNull('received')->update(['received' => $latest_cashier_income->id]); break; case 'family_account_consumptions': FamilyAccountConsumption::where($filters)->whereNull('received')->update(['received' => $latest_cashier_income->id]); break; case 'patient_account_deposits': PatientAccountsDeposit::where($filters)->whereNull('received')->update(['received' => $latest_cashier_income->id]); break; case 'patient_account_consumptions': PatientAccountConsumption::where($filters)->whereNull('received')->update(['received' => $latest_cashier_income->id]); break; case 'direct_bank_deposits': //OtherIncome::where($filters)->whereNull('received')->update(['received' => $latest_cashier_income->id]); $other_income_table = OtherIncome::where($filters)->whereNull('received')->get(); if (count($other_income_table) > 0) { foreach ($other_income_table as $other_income_record) { if (str_contains($other_income_record->deposit_memo, 'Journal (')) { //in this if, it is a journal so first check if it's a receivable account and skip it $journal_number = getStringBetweenCharacters($other_income_record->deposit_memo,"(",")"); $journal = Journal::withTrashed()->find($journal_number); if($journal){ $account_types_to_exclude = [8]; // 8 - receivables $journaled_account_ids_array = explode(",", $journal->account_ids); $journaled_account_types = []; for ($i=0; $i < count($journaled_account_ids_array) ; $i++) { $journaled_account_types[] = get_name($journaled_account_ids_array[$i], "id", "type", "chart_of_accounts"); } $journaled_and_not_receivable = array_intersect($journaled_account_types, $account_types_to_exclude); if (empty($journaled_and_not_receivable)) { //if the journaled account types are cash, then go ahead and it to the result $other_income_record->received = $latest_cashier_income->id; $other_income_record->save(); } } } else { $other_income_record->received = $latest_cashier_income->id; $other_income_record->save(); } } } break; } } return redirect()->route('finance_reports.print_cashier_receipt'); } } public function print_cashier_receipt() { $cashier_income = CashierIncome::latest()->first(); $hospital_information = HospitalInformation::first(); return view('finance_reports::finance_reports.receipts.cashierReceipt', compact('hospital_information', 'cashier_income')); } public function reconcile_cashier_income_records(Request $request) { $all_ids = []; $ids = CashierIncome::whereNull('banked')->pluck('id')->toArray(); $received_record_ids = []; $today = Carbon::today()->toDateString(); $yesterday = Carbon::yesterday()->toDateString(); $end = Carbon::parse($request->end_date)->endOfDay()->toDateTimeString(); $start = Carbon::parse($request->start_date)->startOfDay()->toDateTimeString(); $tables = [ 'service_deposits', 'investigation_deposits', 'treatment_deposits', 'procedure_deposits', 'sundries_deposits', 'invoice_payments', 'debtor_payments', 'debt_plan_payment_staffs', 'eye_glasses_deposits' ]; foreach ($tables as $table) { switch ($request->dates) { case 'today': $received_record_ids[] = DB::table($table)->whereDate('created_at', $today)->groupBy('received') ->pluck('received')->toArray(); break; case 'yesterday': $received_record_ids[] = DB::table($table)->whereDate('created_at', $yesterday)->groupBy('received') ->pluck('received')->toArray(); break; case 'custom_date': $received_record_ids[] = DB::table($table)->whereDate('created_at', $start)->get()->groupBy('received') ->pluck('received')->toArray(); break; case 'custom_date_range': $received_record_ids[] = DB::table($table)->whereBetween('created_at', [$start, $end])->groupBy('received') ->pluck('received')->toArray(); break; } } for ($i = 0; $i < count($received_record_ids); $i++) { $all_ids = array_merge($all_ids, $received_record_ids[$i]); }; foreach ($ids as $id) { if (!in_array($id, $all_ids)) { CashierIncome::find($id)->delete(); } } flash('reconciliation successfully')->success(); return back(); } public function delete_cashier_income($id) { $track_receipt = new TrackReceipt; $track_receipt->reason = "deduction from undeposited funds."; $track_receipt->created_by = Auth::id(); $track_receipt->save(); $receipt_number = sprintf("%04u", $track_receipt->id); $received_cash = CashierIncome::where('id', $id)->first(); $latest_undeposited_funds_bank_record = get_latest_banking_record_based_on_transaction_date(get_name("undeposited_funds", "slug", "id", "chart_of_accounts"), Carbon::now()); capture_bank_record( 'PAYMENT', Carbon::today()->toDateString(), 10, 'Deduction', (int)$latest_undeposited_funds_bank_record->account_balance - $received_cash->amount, 0, $received_cash->amount, 'deletion of received undeposited money', $receipt_number ); record_cash_credits_to_daily_collection_account($received_cash->amount, $receipt_number, 'Cancel Received Cash Collection'); ServiceDeposit::where('received', $received_cash->id)->update(['received' => null]); ProcedureDeposit::where('received', $received_cash->id)->update(['received' => null]); SundryDeposit::where('received', $received_cash->id)->update(['received' => null]); TreatmentDeposits::where('received', $received_cash->id)->update(['received' => null]); InvestigationDeposit::where('received', $received_cash->id)->update(['received' => null]); FamilyAccountDeposit::where('received', $received_cash->id)->update(['received' => null]); FamilyAccountConsumption::where('received', $received_cash->id)->update(['received' => null]); PatientCategoryInvoice::where('received', $received_cash->id)->update(['received' => null]); $this->debtPlanService->reverseCashReceived($received_cash->id); $this->debtorsService->reverseCashReceived($received_cash->id); $this->invoicesService->reverseCashReceived($received_cash->id); // update the other incomes if was a direct bank deposit $other_income_record = OtherIncome::where('received', $received_cash->id)->update(['received' => null]); if ($received_cash->delete()) : flash("Received Cash has been deducted from undeposited funds.")->success(); endif; return redirect()->route('finance_reports.received_cash'); } public function receiveDonorDiscountPayment(Request $request) { return view('finance_reports::finance_reports.donorDiscountPayment', 'request'); } /*======================Company and Financial Reports=============================*/ public function trial_balance(Request $request) { $income_accounts = $cost_of_sales_accounts = $expense_accounts = array(); $non_current_assets = $current_assets = $other_current_assets = array(); $current_liabilities = $non_current_liabilities = $other_current_liabilities = array(); $equities = array(); if (empty($request->all())) { $request->request->add(['dates' => 'custom_date']); $today = $date = Carbon::today()->toDateString(); $request->request->add(['start_date' => $today]); } $non_current_assets = getNonCurrentAssetsByAccount($request); $current_assets = getCurrentAssetsByAccountBalanceSheet($request); $other_current_assets = getOtherCurrentAssetsByAccountBalanceSheet($request); $non_current_liabilities = getNonCurrentLiabilitiesByAccountBalanceSheet($request); $current_liabilities = getCurrentLiabilitiesByAccountBalanceSheet($request); $other_current_liabilities = getOtherCurrentLiabilitiesByAccountBalanceSheet($request); $equities = getEquitiesByAccount($request); /*========== enter this creed ==============*/ switch ($request->dates) { case 'yesterday': $start_of_fiscal_year = get_fiscal_year_start_from_hospital_information(Carbon::yesterday()); $end_date = Carbon::yesterday()->toDateString(); break; case 'custom_date': $start_of_fiscal_year = get_fiscal_year_start_from_hospital_information(Carbon::parse($request->start_date)); $end_date = Carbon::parse($request->start_date)->startOfDay()->toDateTimeString(); break; case 'today': default: $start_of_fiscal_year = get_fiscal_year_start_from_hospital_information(Carbon::today()); $end_date = Carbon::today()->toDateString(); break; } $request->request->add(['dates' => 'custom_date_range']); $request->request->add(['start_date' => $start_of_fiscal_year]); $request->request->add(['end_date' => $end_date]); /*============== leave this creed after becoming a better man =================*/ if (!empty($request->all())) { $revenue = getRevenueSumByAccount($request); $income_accounts = $revenue[0]; $cost_of_sales_accounts = $revenue[1]; $expense_accounts = getExpensesByAccount($request); } $display = "Trial Balance as of " . streamline_date($end_date); return view('finance_reports::finance_reports.trial_balance', compact('other_current_liabilities', 'current_liabilities', 'non_current_liabilities', 'other_current_assets', 'current_assets', 'non_current_assets', 'income_accounts', 'cost_of_sales_accounts', 'expense_accounts', 'equities', 'display', 'request')); } public function profit_or_loss_statement(Request $request): View { /*========== enter this creed ==============*/ if ($request->dates == "yesterday") { $start_of_fiscal_year = Carbon::yesterday(); $end_date = Carbon::yesterday()->toDateString(); } elseif ($request->dates == "custom_date") { $start_of_fiscal_year = Carbon::parse($request->start_date); $end_date = Carbon::parse($request->start_date)->startOfDay()->toDateTimeString(); } elseif ($request->dates == "custom_date_range") { $start_of_fiscal_year = Carbon::parse($request->start_date); $end_date = Carbon::parse($request->end_date)->startOfDay()->toDateTimeString(); } else { $start_of_fiscal_year = Carbon::today(); $end_date = Carbon::today()->toDateString(); } $request->request->add(['dates' => 'custom_date_range']); $request->request->add(['start_date' => $start_of_fiscal_year]); $request->request->add(['end_date' => $end_date]); /*============== leave this creed after becoming a better man =================*/ $revenue = getRevenueSumByAccount($request); $income_accounts = $revenue[0]; $cost_of_sales_accounts = $revenue[1]; $expense_accounts = getExpensesByAccount($request); $display = dateLabelSetter($request); $income_account_names = $i_cash_per_account = $i_accrued_per_account = []; $cog_account_names = $c_cash_per_account = $c_accrued_per_account = []; $expense_account_names = $e_cash_per_account = $e_accrued_per_account = []; $c = $e = $i = $accrual_income_total = $cash_income_total = $expenses_accrual_total = $expenses_cash_total = 0; foreach ($income_accounts as $account) { $income_account_names[$i] = get_name($account['id'], 'id', 'name', 'chart_of_accounts'); $i_accrued_per_account[$i] = $account['accrual'] ?? 0; $i_cash_per_account[$i] = $account['cash']; $cash_income_total += $account['cash']; $accrual_income_total += $account['accrual']; $i++; } foreach ($expense_accounts as $account) { $expense_account_names[$e] = get_name($account['id'], 'id', 'name', 'chart_of_accounts'); $e_accrued_per_account[$e] = $account['accrual'] ?? 0; $e_cash_per_account[$e] = $account['cash']; $expenses_cash_total += $account['cash']; $expenses_accrual_total += $account['accrual']; $e++; } foreach ($cost_of_sales_accounts as $account) { $cog_account_names[$c] = get_name($account['id'], 'id', 'name', 'chart_of_accounts'); $c_accrued_per_account[$c] = $account['accrual'] ?? 0; $c_cash_per_account[$c] = $account['cash']; $c++; } $c_gross_profit = $cash_income_total - $expenses_cash_total; $c_gross_profit_chart = profit_v_loss_multi_color_graph( 'GROSS_CASH_PROFIT', 'bar', ['incomes', 'expenses'], [$c_gross_profit, $expenses_cash_total] ); $a_gross_profit = $accrual_income_total - $expenses_accrual_total; $a_gross_profit_chart = profit_v_loss_multi_color_graph( 'GROSS_ACCRUED_PROFIT', 'bar', ['incomes', 'expenses'], [$a_gross_profit, $expenses_accrual_total] ); if (count($income_accounts) != 1) { $income_cash_chart = plot_graph('INCOMES_CASH', 'bar', $income_account_names, $i_cash_per_account, 'green'); } else { $data = dataForIncomeAccrualGraph($request); $income_cash_chart = plot_graph('INCOMES_CASH', 'line', $data['dates'], $data['amounts'], 'green'); } if (count($income_accounts) != 1) { $income_accrual_chart = plot_graph('INCOMES_ACCRUAL', 'bar', $income_account_names, $i_accrued_per_account, 'green'); } else { $data = dataForIncomeCashGraph($request); $income_accrual_chart = plot_graph('INCOMES_ACCRUAL', 'line', $data['dates'], $data['amounts'], 'green'); } if (count($cost_of_sales_accounts) != 1) { $cog_chart = plot_graph('COG', 'bar', $cog_account_names, $c_cash_per_account, 'orange'); } else { $data = dataForCogGraph($request); $cog_chart = plot_graph('COG', 'line', $data['dates'], $data['amounts'], 'orange'); } if (count($expense_accounts) != 1) { $expense_accrual_chart = plot_graph('EXPENSES_ACCRUAL', 'bar', $expense_account_names, $e_accrued_per_account, 'red'); } else { $data = dataForExpenseGraph($request); $expense_accrual_chart = plot_graph('EXPENSES_ACCRUAL', 'line', $data['dates'], $data['amounts'], 'red'); } if (count($expense_accounts) != 1) { $expense_cash_chart = plot_graph('EXPENSES_CASH', 'bar', $expense_account_names, $e_cash_per_account, 'red'); } else { $data = dataForExpenseGraph($request); $expense_cash_chart = plot_graph('EXPENSES_CASH', 'line', $data['dates'], $data['amounts'], 'red'); } return view('finance_reports::finance_reports.profit_or_loss_statement', compact('income_accounts', 'expense_accounts', 'cost_of_sales_accounts', 'request', 'display', 'income_cash_chart', 'income_accrual_chart', 'expense_accrual_chart', 'expense_cash_chart', 'cog_chart', 'c_gross_profit_chart', 'a_gross_profit_chart')); } public function income_detail($data): View { $data = explode(',', $data); $search_type = $data[0]; $accounting_basis = $data[6]; $start = $data[1]; $end = $data[2]; $tag_id = $data[5]; $chart_of_account = $data[4]; $title = get_name($data[4], 'id', 'name', 'chart_of_accounts'); $incomes = $receivables = $ward_incomes = $other_incomes = []; $today = Carbon::today()->toDateString(); $yesterday = Carbon::yesterday()->toDateString(); $end = Carbon::parse($end)->endOfDay()->toDateTimeString(); $start = Carbon::parse($start)->startOfDay()->toDateTimeString(); $sales_tables = [ 'service_deposits', 'investigation_deposits', 'treatment_deposits', 'procedure_deposits', 'sundries_deposits', 'eye_glasses_deposits' ]; $ward_item_tables = [ 'ward_extras', 'ward_procedures', 'ward_bed_stays', 'ward_consultations_and_services', 'ward_investigation_pricings', 'ward_sundry_dispensations', 'ward_treatment_dispensations' ]; foreach ($sales_tables as $table) { switch ($search_type) { case 'today': $incomes[$table] = DB::table($table)->whereNull('deleted_at')->whereDate('created_at', $today)->get()->toArray(); break; case 'yesterday': $incomes[$table] = DB::table($table)->whereNull('deleted_at')->whereDate('created_at', $yesterday)->get()->toArray(); break; case 'custom_date': $incomes[$table] = DB::table($table)->whereNull('deleted_at')->whereDate('created_at', $start)->get()->toArray(); break; case 'custom_date_range': $incomes[$table] = DB::table($table)->whereNull('deleted_at')->whereBetween('created_at', [$start, $end])->get()->toArray(); break; } } switch ($search_type) { case 'today': $other_incomes = DB::table('other_incomes')->whereDate('deposit_date', '=', $today)->where('income_account', $chart_of_account) ->whereNull('deleted_at')->get()->toArray(); break; case 'yesterday': $other_incomes = DB::table('other_incomes')->whereNull('deleted_at')->whereDate('deposit_date', $yesterday)->where('income_account', $chart_of_account) ->get()->toArray(); break; case 'custom_date': $other_incomes = DB::table('other_incomes')->whereNull('deleted_at')->whereDate('deposit_date', $start)->where('income_account', $chart_of_account) ->get()->toArray(); break; case 'custom_date_range': $other_incomes = DB::table('other_incomes')->where('income_account', $chart_of_account)->whereNull('deleted_at')->whereBetween('deposit_date', [$start, $end]) ->get()->toArray(); break; } foreach ($ward_item_tables as $table) { if ($accounting_basis == 'accrual') { switch ($search_type) { case 'today': $ward_item_amounts[$table] = DB::table($table)->whereDate('created_at', $today)->where('current_chart_of_account', $chart_of_account) ->whereNull('deleted_at')->get()->toArray(); break; case 'yesterday': $ward_item_amounts[$table] = DB::table($table)->whereNull('deleted_at')->whereDate('created_at', $yesterday)->where('current_chart_of_account', $chart_of_account) ->get()->toArray(); break; case 'custom_date': $ward_item_amounts[$table] = DB::table($table)->whereNull('deleted_at')->whereDate('created_at', $start)->where('current_chart_of_account', $chart_of_account) ->get()->toArray(); break; case 'custom_date_range': $ward_item_amounts[$table] = DB::table($table)->whereNull('deleted_at')->whereBetween('created_at', [$start, $end])->where('current_chart_of_account', $chart_of_account) ->get()->toArray(); break; } } else { switch ($search_type) { case 'today': $ward_item_amounts[$table] = DB::table($table)->whereDate('payment_date', $today)->where('current_chart_of_account', $chart_of_account) ->whereNull('deleted_at')->get()->toArray(); break; case 'yesterday': $ward_item_amounts[$table] = DB::table($table)->whereNull('deleted_at')->whereDate('payment_date', $yesterday)->where('current_chart_of_account', $chart_of_account) ->get()->toArray(); break; case 'custom_date': $ward_item_amounts[$table] = DB::table($table)->whereNull('deleted_at')->whereDate('payment_date', $start)->where('current_chart_of_account', $chart_of_account) ->get()->toArray(); break; case 'custom_date_range': $ward_item_amounts[$table] = DB::table($table)->whereNull('deleted_at')->whereBetween('payment_date', [$start, $end])->where('current_chart_of_account', $chart_of_account) ->get()->toArray(); break; } } } if (!empty($ward_item_amounts)) { if ($ward_item_amounts['ward_procedures']) { foreach ($ward_item_amounts['ward_procedures'] as $item) { if ($item->current_chart_of_account == $chart_of_account) { $ward_incomes['ward_procedures'][] = $item; } } } if ($ward_item_amounts['ward_bed_stays']) { foreach ($ward_item_amounts['ward_bed_stays'] as $item) { if ($item->current_chart_of_account == $chart_of_account) { $ward_incomes['ward_bed_stays'][] = $item; } } } if ($ward_item_amounts['ward_consultations_and_services']) { foreach ($ward_item_amounts['ward_consultations_and_services'] as $item) { if ($item->current_chart_of_account == $chart_of_account) { $ward_incomes['ward_consultations_and_services'][] = $item; } } } if ($ward_item_amounts['ward_investigation_pricings']) { foreach ($ward_item_amounts['ward_investigation_pricings'] as $item) { if ($item->current_chart_of_account == $chart_of_account) { $ward_incomes['ward_investigation_pricings'][] = $item; } } } if ($ward_item_amounts['ward_sundry_dispensations']) { foreach ($ward_item_amounts['ward_sundry_dispensations'] as $item) { if ($item->current_chart_of_account == $chart_of_account) { $ward_incomes['ward_sundry_dispensations'][] = $item; } } } if ($ward_item_amounts['ward_treatment_dispensations']) { foreach ($ward_item_amounts['ward_treatment_dispensations'] as $item) { if ($item->current_chart_of_account == $chart_of_account) { $ward_incomes['ward_treatment_dispensations'][] = $item; } } } if ($ward_item_amounts['ward_extras']) { foreach ($ward_item_amounts['ward_extras'] as $item) { if ($item->current_chart_of_account == $chart_of_account) { $ward_incomes['ward_extras'][] = $item; } } } } if (count($incomes['service_deposits']) > 0) { foreach ($incomes['service_deposits'] as $payment) : $item_id_array = explode(',', $payment->items_ids); $item_account_array = explode(',', $payment->current_chart_of_accounts); $item_amounts_array = explode(',', $payment->items_amounts); $item_amount_paid_array = explode(',', $payment->item_amount_paid); $item_balance_remaining_array = explode(',', $payment->item_balance_remaining); for ($x = 0; $x < count($item_id_array); $x++) : if (isset($item_account_array[$x])) { if ($chart_of_account == $item_account_array[$x]) { $incomes['new_service_deposits'][] = [ 'item_id' => $item_id_array[$x], 'item_amount' => $item_amounts_array[$x], 'item_account' => $chart_of_account, 'item_amount_paid' => $item_amount_paid_array[$x], 'balance' => $item_balance_remaining_array[$x], 'created_by' => $payment->created_by, 'patient_id' => $payment->patient_id, 'created_at' => $payment->created_at, 'receipt_number' => $payment->receipt_number ]; } } endfor; endforeach; } if (count($incomes['investigation_deposits']) > 0) { foreach ($incomes['investigation_deposits'] as $payment) : $item_id_array = explode(',', $payment->investigation_items); $item_account_array = explode(',', $payment->current_chart_of_accounts); $investigation_amounts_array = explode(',', $payment->investigation_amounts); $item_amount_paid_array = explode(',', $payment->item_amount_paid); $item_balance_remaining_array = explode(',', $payment->item_balance_remaining); for ($x = 0; $x < count($item_id_array); $x++) : if (isset($item_account_array[$x])) { if ($chart_of_account == $item_account_array[$x]) { $incomes['new_investigation_deposits'][] = [ 'item_id' => $item_id_array[$x], 'item_amount' => $investigation_amounts_array[$x], 'item_account' => $chart_of_account, 'item_amount_paid' => $item_amount_paid_array[$x], 'balance' => $item_balance_remaining_array[$x], 'created_by' => $payment->created_by, 'patient_id' => $payment->patient_id, 'created_at' => $payment->created_at, 'receipt_number' => $payment->receipt_number ]; } } endfor; endforeach; } if (count($incomes['sundries_deposits']) > 0) { foreach ($incomes['sundries_deposits'] as $payment) : $item_id_array = explode(',', $payment->sundry_items); $item_account_array = explode(',', $payment->current_chart_of_accounts); $investigation_amounts_array = explode(',', $payment->sundry_subtotals); $item_amount_paid_array = explode(',', $payment->item_amount_paid); $item_balance_remaining_array = explode(',', $payment->item_balance_remaining); for ($x = 0; $x < count($item_id_array); $x++) : if (isset($item_account_array[$x])) { if ($chart_of_account == $item_account_array[$x]) { $incomes['new_sundries_deposits'][] = [ 'item_id' => $item_id_array[$x], 'item_amount' => $investigation_amounts_array[$x], 'item_account' => $chart_of_account, 'item_amount_paid' => $item_amount_paid_array[$x], 'balance' => $item_balance_remaining_array[$x], 'created_by' => $payment->created_by, 'patient_id' => $payment->patient_id, 'created_at' => $payment->created_at, 'receipt_number' => $payment->receipt_number ]; } } endfor; endforeach; } if (count($incomes['procedure_deposits']) > 0) { foreach ($incomes['procedure_deposits'] as $payment) : $item_id_array = explode(',', $payment->procedure_items); $item_account_array = explode(',', $payment->current_chart_of_accounts); $investigation_amounts_array = explode(',', $payment->procedure_amounts); $item_amount_paid_array = explode(',', $payment->item_amount_paid); $item_balance_remaining_array = explode(',', $payment->item_balance_remaining); for ($x = 0; $x < count($item_id_array); $x++) : if (isset($item_account_array[$x])) { if ($chart_of_account == $item_account_array[$x]) { $incomes['new_procedure_deposits'][] = [ 'item_id' => $item_id_array[$x], 'item_amount' => $investigation_amounts_array[$x], 'item_account' => $chart_of_account, 'item_amount_paid' => $item_amount_paid_array[$x], 'balance' => $item_balance_remaining_array[$x], 'created_by' => $payment->created_by, 'patient_id' => $payment->patient_id, 'created_at' => $payment->created_at, 'receipt_number' => $payment->receipt_number ]; } } endfor; endforeach; } if (count($incomes['treatment_deposits']) > 0) { foreach ($incomes['treatment_deposits'] as $payment) : $item_id_array = explode(',', $payment->treatment_items); $item_account_array = explode(',', $payment->current_chart_of_accounts); $investigation_amounts_array = explode(',', $payment->treatment_subtotals); $item_amount_paid_array = explode(',', $payment->item_amount_paid); $item_balance_remaining_array = explode(',', $payment->item_balance_remaining); for ($x = 0; $x < count($item_id_array); $x++) : if (isset($item_account_array[$x])) { if ($chart_of_account == $item_account_array[$x]) { $incomes['new_treatment_deposits'][] = [ 'item_id' => $item_id_array[$x], 'item_amount' => $investigation_amounts_array[$x], 'item_account' => $chart_of_account, 'item_amount_paid' => $item_amount_paid_array[$x], 'balance' => $item_balance_remaining_array[$x], 'created_by' => $payment->created_by, 'patient_id' => $payment->patient_id, 'created_at' => $payment->created_at, 'receipt_number' => $payment->receipt_number ]; } } endfor; endforeach; } if (count($incomes['eye_glasses_deposits']) > 0) { foreach ($incomes['eye_glasses_deposits'] as $payment) { $item_id_array = explode(',', $payment->items); $item_account_array = explode(',', $payment->current_chart_of_accounts); $items_amounts_array = explode(',', $payment->subtotals); $item_amount_paid_array = explode(',', $payment->item_amount_paid); $item_balance_remaining_array = explode(',', $payment->item_balance_remaining); for ($x = 0; $x < count($item_id_array); $x++) { if (isset($item_account_array[$x]) && $chart_of_account == $item_account_array[$x]) { $incomes['new_eye_glasses_deposits'][] = [ 'item_id' => $item_id_array[$x], 'item_amount' => $items_amounts_array[$x], 'item_account' => $chart_of_account, 'item_amount_paid' => $item_amount_paid_array[$x] ?? $items_amounts_array[$x], 'balance' => $item_balance_remaining_array[$x] ?? 0, 'created_by' => $payment->created_by, 'patient_id' => $payment->patient_id, 'created_at' => $payment->created_at, 'receipt_number' => $payment->receipt_number ]; } } } } $receivables['debtors'] = DB::table('debtor_payments')->join('debtors', 'debtors.id', '=', 'debtor_payments.debt_id') ->where('debtors.income_account', $chart_of_account) ->whereNull('debtor_payments.deleted_at')->whereBetween('debtor_payments.date_paid', [$start, $end]) ->get(['debtor_payments.amount_paid', 'debtor_payments.date_paid', 'debtors.balance_remaining', 'debtors.patient_id', 'debtor_payments.created_by', 'debtor_payments.created_at', 'debtor_payments.receipt_number']); $receivables['debt_plan'] = DB::table('debt_plan_payment_staffs') ->leftJoin('debt_plan', 'debt_plan.id', '=', 'debt_plan_payment_staffs.debt_plan_id') ->where('debt_plan.income_account', $chart_of_account) ->whereNull('debt_plan_payment_staffs.deleted_at') ->whereBetween('debt_plan_payment_staffs.date_paid', [$start, $end]) ->get(['debt_plan.patient_id', 'debt_plan.staff_guarantor', 'debt_plan.balance_remaining', 'debt_plan_payment_staffs.created_by', 'debt_plan_payment_staffs.created_at', 'debt_plan_payment_staffs.amount_paid', 'debt_plan_payment_staffs.comment', 'debt_plan.staff_guarantor_to_pay']); if ($accounting_basis == 'accrual') { $invoice_filters = [ ['transaction_date', '>=', $start], ['transaction_date', '<=', $end], ]; } else { $invoice_filters = [ ['payment_date', '>=', $start], ['payment_date', '<=', $end], ]; } $receivables['patient_category_invoices'] = DB::table('patient_category_invoices') ->whereRaw('FIND_IN_SET(' . $chart_of_account . ',income_account)') ->whereNull('deleted_at') ->where($invoice_filters) ->get(['amount_paid_off', 'patient_amount', 'receipt_number', 'created_by', 'payment_date', 'transaction_date']); if ($accounting_basis === 'accrual') { $opd_treatments = DB::table('treatments')->whereNull('deleted_at') ->where('inpatient_bill_generated', 1) ->whereRaw('FIND_IN_SET(' . $chart_of_account . ',current_chart_of_account)') ->whereBetween('created_at', [$start, $end]) ->get(); } else { $opd_treatments = DB::table('treatments')->whereNull('deleted_at') ->where('inpatient_bill_generated', 1) ->whereRaw('FIND_IN_SET(' . $chart_of_account . ',current_chart_of_account)') ->whereBetween('payment_date', [$start, $end]) ->get(); } return view('finance_reports::finance_reports.accounts.incomes', compact( 'title', 'accounting_basis', 'tag_id', 'incomes', 'table', 'receivables', 'chart_of_account', 'ward_incomes', 'other_incomes', 'opd_treatments' )); } public function cost_of_sales_detail($data) { $data = explode(',', $data); $search_type = $data[0]; $_start = $data[1]; $_end = $data[2]; $tables = ['treatment_deposits', 'sundries_deposits']; $ward_item_tables = ['ward_treatment_dispensations', 'ward_sundry_dispensations']; $title = get_name($data[4], 'id', 'name', 'chart_of_accounts'); $chart_of_account = $data[4]; $result = $ward_incomes = []; $accounting_basis = $data[6] ?? 'accrual'; $today = Carbon::today()->toDateString(); $yesterday = Carbon::yesterday()->toDateString(); $end = Carbon::parse($_end)->endOfDay()->toDateTimeString(); $start = Carbon::parse($_start)->startOfDay()->toDateTimeString(); foreach ($tables as $table) { switch ($search_type) { case 'today': $result[$table] = DB::table($table)->whereDate('created_at', $today)->where('cost_of_goods_account', $chart_of_account)->get(); break; case 'yesterday': $result[$table] = DB::table($table)->whereDate('created_at', $yesterday)->where('cost_of_goods_account', $chart_of_account)->get(); break; case 'custom_date': $result[$table] = DB::table($table)->whereDate('created_at', $start)->where('cost_of_goods_account', $chart_of_account)->get(); break; case 'custom_date_range': $result[$table] = DB::table($table)->whereBetween('created_at', [$start, $end])->where('cost_of_goods_account', $chart_of_account)->get(); break; } } foreach ($ward_item_tables as $table) { switch ($search_type) { case 'today': $ward_incomes[$table] = DB::table($table)->whereDate('created_at', $today)->where('cost_of_goods_account', $chart_of_account) ->whereNull('deleted_at')->get()->toArray(); break; case 'yesterday': $ward_incomes[$table] = DB::table($table)->whereNull('deleted_at')->whereDate('created_at', $yesterday)->where('cost_of_goods_account', $chart_of_account) ->get()->toArray(); break; case 'custom_date': $ward_incomes[$table] = DB::table($table)->whereNull('deleted_at')->whereDate('created_at', $start)->where('cost_of_goods_account', $chart_of_account) ->get()->toArray(); break; case 'custom_date_range': $ward_incomes[$table] = DB::table($table)->whereNull('deleted_at')->where('cost_of_goods_account', $chart_of_account)->whereBetween('created_at', [$start, $end]) ->get()->toArray(); break; } } $drugs = DB::table('drugs')->where('available', 1)->pluck('name', 'id'); $sundries = DB::table('sundries')->where('available', 1)->pluck('name', 'id'); $patient_category_invoices = DB::table('patient_category_invoices')->whereRaw('FIND_IN_SET(' . $chart_of_account . ',cost_of_goods_account)')->whereNull('deleted_at')->whereBetween('transaction_date', [$start, $end]) ->get(['amount_paid_off', 'balance_remaining', 'patient_amount', 'income_account', 'receipt_number', 'items_amounts', 'tag_id', 'cost_price', 'items_quantity', 'created_by', 'patient_id', 'patient_category', 'cost_of_goods_account','created_at','items_ids']); return view('finance_reports::finance_reports.accounts.cost_of_sales', compact('ward_incomes', 'patient_category_invoices', 'result', 'table', 'title', 'search_type', 'start', 'end', 'chart_of_account', 'accounting_basis', 'drugs', 'sundries')); } public function expense_detail($_data) { $data = explode(',', $_data); $search_type = $data[0]; $_start = $data[1]; $_end = $data[2]; $table = $data[3]; $title = get_name($data[4], 'id', 'name', 'chart_of_accounts'); $chart_of_account = $data[4]; $payments = $bills = $_bills = $discounts = []; $one_off_discounts = $ward_discounts = []; $today = Carbon::today(); $yesterday = Carbon::yesterday(); $end = Carbon::parse($_end)->endOfDay(); $start = Carbon::parse($_start)->startOfDay(); $tracked_patient_categories = PatientDiscount::whereNotNull('tracking_expense_account')->where('tracking_expense_account', $chart_of_account)->pluck('patient_category')->toArray(); if ($chart_of_account == '14') { return redirect()->route('finance_reports.liability_detail', $_data); } $chart_of_account_slug = get_name($chart_of_account, "id", "slug", "chart_of_accounts"); if ($chart_of_account_slug == "professional_fees") { return redirect()->route('finance_reports.professional_fees_detail', $_data); } if ($chart_of_account_slug == "ward_discounts") { switch ($search_type) { case 'today': $ward_discounts = DB::table('inpatient_ward_discounts')->whereNull('deleted_at')->whereDate('created_at', $today)->get()->toArray(); break; case 'yesterday': $ward_discounts = DB::table('inpatient_ward_discounts')->whereNull('deleted_at')->whereDate('created_at', $yesterday)->get()->toArray(); break; case 'custom_date': $ward_discounts = DB::table('inpatient_ward_discounts')->whereNull('deleted_at')->whereDate('created_at', $start)->get()->toArray(); break; case 'custom_date_range': $ward_discounts = DB::table('inpatient_ward_discounts')->whereNull('deleted_at')->whereBetween('created_at', [$start, $end])->get()->toArray(); break; } } if ($chart_of_account_slug == "one_off_discounts") { switch ($search_type) { case 'today': $one_off_discounts = DB::table('patient_one_off_discounts')->whereDate('created_at', $today)->get()->toArray(); break; case 'yesterday': $one_off_discounts = DB::table('patient_one_off_discounts')->whereDate('created_at', $yesterday)->get()->toArray(); break; case 'custom_date': $one_off_discounts = DB::table('patient_one_off_discounts')->whereDate('created_at', $start)->get()->toArray(); break; case 'custom_date_range': $one_off_discounts = DB::table('patient_one_off_discounts')->whereBetween('created_at', [$start, $end])->get()->toArray(); break; } } switch ($search_type) { case 'today': $_bills = DB::table('hospital_bills')->whereNull('deleted_at')->whereDate('bill_date', $today->toDateString())->get()->toArray(); $discounts = DB::table('discounts')->whereNull('deleted_at')->whereIn('patient_category', $tracked_patient_categories)->whereDate('created_at', $today)->get()->toArray(); $payments = DB::table('payments')->whereNull('deleted_at')->whereDate('expense_date', $today)->where('expense_account', $chart_of_account)->groupBy('transaction_id')->selectRaw('*, sum(amount) as sum')->get()->toArray(); break; case 'yesterday': $_bills = DB::table('hospital_bills')->whereNull('deleted_at')->whereDate('bill_date', $yesterday->toDateString())->get()->toArray(); $discounts = DB::table('discounts')->whereNull('deleted_at')->whereIn('patient_category', $tracked_patient_categories)->whereDate('created_at', $yesterday)->get()->toArray(); $payments = DB::table($table)->whereNull('deleted_at')->whereDate('expense_date', $yesterday)->where('expense_account', $chart_of_account)->groupBy('transaction_id')->selectRaw('*, sum(amount) as sum')->get()->toArray(); break; case 'custom_date': $_bills = DB::table('hospital_bills')->whereNull('deleted_at')->whereDate('bill_date', $start->toDateString())->get()->toArray(); $discounts = DB::table('discounts')->whereNull('deleted_at')->whereDate('created_at', $start)->get()->toArray(); $payments = DB::table($table)->whereNull('deleted_at')->whereDate('expense_date', $start)->where('expense_account', $chart_of_account)->groupBy('transaction_id')->selectRaw('*, sum(amount) as sum')->get()->toArray(); break; case 'custom_date_range': $_bills = DB::table('hospital_bills')->whereNull('deleted_at')->whereBetween('bill_date', [$start->toDateString(), $end->toDateString()])->get()->toArray(); $discounts = DB::table('discounts')->whereNull('deleted_at')->whereIn('patient_category', $tracked_patient_categories)->whereBetween('created_at', [$start, $end])->get()->toArray(); $payments = DB::table('payments')->whereNull('deleted_at')->whereBetween('expense_date', [$start, $end])->where('expense_account', $chart_of_account)->groupBy('transaction_id')->selectRaw('*, sum(amount) as sum')->get()->toArray(); break; } if (count($_bills) > 0) { foreach ($_bills as $bill) : $item_id_array = explode(',', $bill->item_ids); $item_account_array = explode(',', $bill->item_accounts); $item_amounts_array = explode(',', $bill->item_subtotals); $item_quantites_array = explode(',', $bill->item_quantities); $item_amount_paid_array = explode(',', $bill->item_amount_paid); $item_balance_remaining_array = explode(',', $bill->item_balance_remaining); for ($x = 0; $x < count($item_id_array); $x++) : if (isset($item_account_array[$x]) && ($chart_of_account == $item_account_array[$x])) { $bills[] = [ 'bill_id' => $bill->id, 'bill_type' => $bill->bill_type, 'item' => $item_id_array[$x], 'item_amount' => $item_amounts_array[$x], 'item_quantity' => $item_quantites_array[$x], 'item_account' => $chart_of_account, 'item_amount_paid' => !is_null($bill->item_amount_paid) ? $item_amount_paid_array[$x] : 0, 'item_balance_remaining' => !is_null($bill->item_amount_paid) ? $item_balance_remaining_array[$x] : $item_amounts_array[$x], 'created_by' => $bill->created_by, 'created_at' => $bill->created_at, 'vendor' => $bill->vendor, 'bill_number' => $bill->bill_number, 'bill_date' => $bill->bill_date, 'bill_due_date' => $bill->bill_due_date, 'bill_memo' => $bill->bill_memo, ]; } endfor; endforeach; } return view('finance_reports::finance_reports.accounts.expenses', compact('payments', 'table', 'title', 'search_type', 'start', 'end', 'chart_of_account', 'bills', 'discounts', 'one_off_discounts', 'ward_discounts')); } public function print_profit_or_loss_statement(Request $request) { $income_accounts = unserialize($request->income_accounts); $expense_accounts = unserialize($request->expense_accounts); $cost_of_sales_accounts = unserialize($request->cost_of_sales_accounts); $display = $request->display; $switch_to_cash_print = $request->switch_to_cash_print; $data = [ 'income_accounts' => $income_accounts, 'expense_accounts' => $expense_accounts, 'cost_of_sales_accounts' => $cost_of_sales_accounts, 'display' => $display, 'switch_to_cash_print' => $switch_to_cash_print, ]; $pdf = SnappyPDF::loadView("finance_reports::finance_reports/print_profit_or_loss_statement", $data) ->setOrientation('portrait') ->setOption('margin-bottom', 7) ->setOption('margin-top', 5) ->setOption('footer-html', '© ' . date('Y') . ' Stre@mline'); return $pdf->inline('Profit and Loss Statement' . date(" d-m-y h:ia") . '.pdf'); } public function balance_sheet(Request $request) { // liabilities $non_current_liabilities = getNonCurrentLiabilitiesByAccountBalanceSheet($request); $current_liabilities = getCurrentLiabilitiesByAccountBalanceSheet($request); $other_current_liabilities = getOtherCurrentLiabilitiesByAccountBalanceSheet($request); // assets $non_current_assets = getNonCurrentAssetsByAccount($request); $current_assets = getCurrentAssetsByAccountBalanceSheet($request); $other_current_assets = getOtherCurrentAssetsByAccountBalanceSheet($request); $individual_accounts_receivables = getIndividualAccountsReceivablesBalanceSheet($request); // equity $equities = getEquitiesByAccount($request); /*========== enter this creed ==============*/ switch ($request->dates) { case 'yesterday': $start_of_fiscal_year = get_fiscal_year_start_from_hospital_information(Carbon::yesterday()); $end_date = Carbon::yesterday()->toDateString(); break; case 'custom_date': $start_of_fiscal_year = get_fiscal_year_start_from_hospital_information(Carbon::parse($request->start_date)); $end_date = Carbon::parse($request->start_date)->startOfDay()->toDateTimeString(); break; case 'today': default: $start_of_fiscal_year = get_fiscal_year_start_from_hospital_information(Carbon::today()); $end_date = Carbon::today()->toDateString(); break; } $request->request->add(['dates' => 'custom_date_range']); $request->request->add(['start_date' => $start_of_fiscal_year]); $request->request->add(['end_date' => $end_date]); $display = "As of " . streamline_date($end_date); /*============== leave this creed after becoming a better man =================*/ /* ===== start of net income ======= */ $net_income = getNetIncome($request); $accrual_net_income = $net_income['accrual_net_income']; /* ============== */ //retained earnings::::::::: VERY IMPORTANT: let this variable be the last variable in this function coz it plays with the $request to load previous net incomes $retained_earnings = getRetainedEarnings($request, $start_of_fiscal_year); //loop through equities and find retained earnings account using slug and add this figure $new_equities_array = []; foreach ($equities as $equity) { $equity_details = ChartOfAccount::withTrashed()->find($equity['id']); if ($equity_details && $equity_details->slug == "retained_earnings") { $new_amount = $equity["amount"] + $retained_earnings; } else{ $new_amount = $equity["amount"]; } $new_equities_array[] = ["id" => $equity["id"], "amount" => $new_amount, "data" => $equity["data"]]; } $equities = $new_equities_array; //overide the original equities return view('finance_reports::finance_reports.balance_sheet', compact('request', 'display', 'non_current_assets', 'current_assets', 'retained_earnings', 'other_current_assets', 'non_current_liabilities', 'current_liabilities', 'other_current_liabilities', 'equities', 'accrual_net_income', 'individual_accounts_receivables')); } public function print_balance_sheet(Request $request) { $non_current_assets = unserialize($request->non_current_assets); $current_assets = unserialize($request->current_assets); $other_current_assets = unserialize($request->other_current_assets); $non_current_liabilities = unserialize($request->non_current_liabilities); $current_liabilities = unserialize($request->current_liabilities); $other_current_liabilities = unserialize($request->other_current_liabilities); $display = $request->display; $equities = unserialize($request->equities); $data = [ 'non_current_assets' => $non_current_assets, 'current_assets' => $current_assets, 'other_current_assets' => $other_current_assets, 'non_current_liabilities' => $non_current_liabilities, 'current_liabilities' => $current_liabilities, 'other_current_liabilities' => $other_current_liabilities, 'equities' => $equities, 'display' => $display, ]; $pdf = SnappyPDF::loadView("finance_reports::finance_reports/print_balance_sheet", $data) ->setOrientation('portrait') ->setOption('margin-bottom', 7) ->setOption('margin-top', 5) ->setOption('footer-html', '© ' . date('Y') . ' Stre@mline'); return $pdf->inline('Balance Sheet' . date(" d-m-y h:ia") . '.pdf'); } public function fixed_asset_detail($data) { $data = explode(',', $data); $chart_of_account = $data[4]; $title = get_name($chart_of_account, 'id', 'name', 'chart_of_accounts'); $filters = []; if ($data[0] == "custom_date") { $filters[] = ['acquisition_date', '<=', $data[1]]; } elseif ($data[0] == "custom_date_range") { $filters[] = ['acquisition_date', '>', Carbon::parse($data[2])->subDay()->toDateString()]; $filters[] = ['acquisition_date', '<', Carbon::parse($data[1])->addDay()->toDateString()]; } $result = DB::table('fixed_assets') ->whereNull('deleted_at') ->where('fixed_asset_account_id', $chart_of_account)->where($filters)->get(); return view('finance_reports::finance_reports.accounts.fixed_assets', compact('result', 'chart_of_account', 'title')); } public function current_asset_detail($data) { $data = explode(',', $data); $result = $undeposited_funds_banking_records = []; $table = $data[3]; $search_type = $data[0]; $chart_of_account = $data[4]; $today = Carbon::today()->endOfDay()->toDateTimeString(); $yesterday = Carbon::yesterday()->endOfDay()->toDateTimeString(); $end = Carbon::parse($data[2])->endOfDay()->toDateTimeString(); $start = Carbon::parse($data[1])->startOfDay()->toDateTimeString(); $accounts_receivables_tables = ['patient_category_invoices', 'debtors', 'debt_plan']; $title = get_name($chart_of_account, 'id', 'name', 'chart_of_accounts'); if ($table == 'cashier_income') { switch ($search_type) { case 'today': $result = Banking::where('bank', 10)->whereDate('created_at', '<=', $today)->whereNull('deleted_at')->get(); break; case 'yesterday': $result = Banking::where('bank', 10)->whereDate('created_at', '<=', $yesterday)->whereNull('deleted_at')->get(); break; case 'custom_date': $result = Banking::where('bank', 10)->whereDate('created_at', '<=', $start)->whereNull('deleted_at')->get(); break; case 'custom_date_range': $result = Banking::where('bank', 10)->whereBetween('created_at', [$start, $end])->whereNull('deleted_at')->get(); break; } foreach ($result as $key => $row) : $total = 0; for ($i = 0; $i <= $key; $i++) : $total = $total + $result[$i]->credit - $result[$i]->debit; endfor; $undeposited_funds_banking_records[] = [ 'trans_id' => $row->trans_id, 'trans_date' => $row->trans_date, 'trans_type' => $row->trans_type, 'memo' => $row->memo, 'debit' => $row->debit, 'credit' => $row->credit, 'account_balance' => $total, 'created_by' => $row->created_by, ]; endforeach; return view('finance_reports::finance_reports.accounts.undeposited_funds', compact('undeposited_funds_banking_records', 'chart_of_account', 'title', 'table') ); } else if ($table == 'banking') { switch ($search_type) { case 'today': $result = Banking::whereNull('deleted_at')->whereDate('trans_date', '<=', $today)->where('bank', $chart_of_account)->get(); break; case 'yesterday': $result = Banking::whereNull('deleted_at')->whereDate('trans_date', '<=', $yesterday)->where('bank', $chart_of_account)->get(); break; case 'custom_date': $result = Banking::whereNull('deleted_at')->whereDate('trans_date', '<=', $start)->where('bank', $chart_of_account)->get(); break; case 'custom_date_range': $result = Banking::whereNull('deleted_at')->whereBetween('trans_date', [$start, $end])->where('bank', $chart_of_account)->get(); break; } return view('finance_reports::finance_reports.accounts.banking', compact('result', 'chart_of_account', 'title', 'table')); } elseif ($table == 'stock_watcher') { $date_of_interest = $end; /* $result['drugs'] = DB::table('drugs')->whereNull('deleted_at')->whereDate('created_at', '<=', $today) ->where('inventory_account', $chart_of_account)->get(['id', 'cost_price', 'pharmacy_stock', 'inventory_account', 'store_stock', 'insurance_coverage', 'brand_name', 'name']); $result['sundries'] = DB::table('sundries')->whereNull('deleted_at')->whereDate('created_at', '<=', $today) ->where('inventory_account', $chart_of_account)->get(['id', 'cost_price', 'pharmacy_stock', 'inventory_account', 'store_stock', 'name']); */ $drugs = DB::table('drugs')->whereNull('deleted_at') ->where('inventory_account', $chart_of_account)->get(['id', 'name', 'insurance_coverage', 'cost_price', 'pharmacy_stock', 'inventory_account', 'store_stock']); $sundries = DB::table('sundries')->whereNull('deleted_at') ->where('inventory_account', $chart_of_account)->get(['id', 'name', 'insurance', 'cost_price', 'pharmacy_stock', 'inventory_account', 'store_stock']); $inventory_items = [ ["item_type" => 1, "data" => $drugs], ["item_type" => 2, "data" => $sundries] ]; foreach ($inventory_items as $inventory_item) { foreach ($inventory_item['data'] as $inventory_item_data) { $stock_watcher_record = DB::table('batch_stock_watcher')->where('item_type', $inventory_item['item_type']) ->where('item_id', $inventory_item_data->id)->first(); $cost_price = $pharmacy_stock = $store_stock = $ward_stock = 0; if ($stock_watcher_record) { $details_arr = json_decode($stock_watcher_record->details, true); if (!isset($details_arr[$date_of_interest])) { // just get the dates into their own array $dates_array = array_keys($details_arr); // search for the closest date to ours of interest and set that as our reference $closest_date = get_closest_element_in_array($dates_array, $date_of_interest); if ($closest_date < $date_of_interest) { // we should only get dates less than that of interest since if it is greater calculations will be wrong $details = $details_arr[$closest_date]; } else { $details = ["buying_price" => 0, "pharmacy_stock" => 0, "store_stock" => 0, "ward_stock" => 0]; } } else { $details = $details_arr[$date_of_interest]; } $stock_value = ($details["buying_price"] * ($details["pharmacy_stock"] + $details["store_stock"] + ($details["ward_stock"] ?? 0))); $cost_price = $details["buying_price"]; $pharmacy_stock = $details["pharmacy_stock"]; $store_stock = $details["store_stock"]; $ward_stock = $details["ward_stock"]; } else { // just bring up the previous since having no stock watcher record means it has never changed switch ($inventory_item['item_type']) { case 1: case 2: $stock_value = ($inventory_item_data->cost_price * ($inventory_item_data->pharmacy_stock + $inventory_item_data->store_stock)); break; $cost_price = $inventory_item_data->cost_price; $pharmacy_stock = $inventory_item_data->pharmacy_stock; $store_stock = $inventory_item_data->store_stock; $ward_stock = 0; } } if($inventory_item['item_type'] == 1){ $result["drugs"][$inventory_item_data->id] = (object)["name" => $inventory_item_data->name, "insurance_coverage" => $inventory_item_data->insurance_coverage, "cost_price" => $cost_price, "pharmacy_stock" => $pharmacy_stock, "store_stock" => $store_stock, "ward_stock" => $ward_stock]; } elseif ($inventory_item['item_type'] == 2) { $result["sundries"][$inventory_item_data->id] = (object)["name" => $inventory_item_data->name, "cost_price" => $cost_price, "pharmacy_stock" => $pharmacy_stock, "store_stock" => $store_stock, "ward_stock" => $ward_stock]; } } } return view('finance_reports::finance_reports.accounts.inventory', compact('result', 'chart_of_account', 'title', 'table')); } elseif ($table == 'accounts_receivables') { foreach ($accounts_receivables_tables as $table) { switch ($search_type) { case 'today': $result[$table] = DB::table($table)->whereDate('created_at', '<=', $today)->whereNull('deleted_at') ->whereNull('balance_remaining')->orWhere('balance_remaining', '>', 0)->get(); break; case 'yesterday': $result[$table] = DB::table($table)->whereDate('created_at', '<=', $yesterday)->whereNull('deleted_at') ->whereNull('balance_remaining')->orWhere('balance_remaining', '>', 0)->get(); break; case 'custom_date': $result[$table] = DB::table($table)->whereDate('created_at', '<=', $start)->whereNull('deleted_at') ->whereNull('balance_remaining')->orWhere('balance_remaining', '>', 0)->get(); break; case 'custom_date_range': $result[$table] = DB::table($table)->whereBetween('created_at', [$start, $end])->whereNull('deleted_at') ->whereNull('balance_remaining')->orWhere('balance_remaining', '>', 0)->get(); break; } } $result['inpatient_bills'] = DB::table('inpatient_bills') ->whereBetween('updated_at', [$start, $end]) ->get(['amount_to_pay', 'updated_at', 'patient_id', 'updated_by', 'original_bill', 'amount_paid']); return view('finance_reports::finance_reports.accounts.accounts_receivables', compact('result', 'chart_of_account', 'title', 'table')); } elseif ($table == 'incomes') { $tag_id = $data[5]; (isset($data[6])) ? $accounting_basis = $data[6] : $accounting_basis = 'cash'; $incomes = $receivables = []; $sales_tables = ['service_deposits', 'investigation_deposits', 'treatment_deposits', 'procedure_deposits', 'sundries_deposits']; foreach ($sales_tables as $table) { switch ($search_type) { case 'today': $incomes[$table] = DB::table($table)->whereNull('deleted_at')->whereDate('created_at', '<=', $today)->where('current_chart_of_accounts', $chart_of_account)->get(); break; case 'yesterday': $incomes[$table] = DB::table($table)->whereNull('deleted_at')->whereDate('created_at', '<=', $yesterday)->where('current_chart_of_accounts', $chart_of_account)->get(); break; case 'custom_date': $incomes[$table] = DB::table($table)->whereNull('deleted_at')->whereDate('created_at', '<=', $start)->where('current_chart_of_accounts', $chart_of_account)->get(); break; case 'custom_date_range': $incomes[$table] = DB::table($table)->whereNull('deleted_at')->whereBetween('created_at', [$start, $end])->where('current_chart_of_accounts', $chart_of_account)->get(); break; } } return view('finance_reports::finance_reports.accounts.incomes', compact('title', 'accounting_basis', 'tag_id', 'incomes', 'receivables', 'chart_of_account')); } } public function other_current_asset_detail($data) { $data = explode(',', $data); $result = []; $table = $data[3]; $search_type = $data[0]; $chart_of_account = $data[4]; $today = Carbon::today()->toDateString(); $yesterday = Carbon::yesterday()->toDateString(); $end = Carbon::parse($data[2])->endOfDay()->toDateTimeString(); $start = Carbon::parse($data[1])->startOfDay()->toDateTimeString(); if ($table == 'chart_of_accounts') { $title = get_name($chart_of_account, 'id', 'name', 'chart_of_accounts'); switch ($search_type) { case 'today': $result = ChartOfAccount::whereDate('created_at', '<=', $today)->where('id', $chart_of_account)->get(); break; case 'yesterday': $result = ChartOfAccount::whereDate('created_at', '<=', $yesterday)->where('id', $chart_of_account)->get(); break; case 'custom_date': $result = ChartOfAccount::whereDate('created_at', '<=', $start)->where('id', $chart_of_account)->get(); break; case 'custom_date_range': $result = ChartOfAccount::whereBetween('created_at', [$start, $end])->where('id', $chart_of_account)->get(); break; } return view('finance_reports::finance_reports.accounts.other_current_assets', compact('result', 'chart_of_account', 'title', 'table')); } } public function liability_detail($data) { $data = explode(',', $data); $table = $data[3]; $search_type = $data[0]; $chart_of_account = $data[4]; $today = Carbon::today()->toDateString(); $yesterday = Carbon::yesterday()->toDateString(); $end = Carbon::parse($data[2])->endOfDay()->toDateTimeString(); $start = Carbon::parse($data[1])->startOfDay()->toDateTimeString(); $title = get_name($chart_of_account, 'id', 'name', 'chart_of_accounts'); (isset($data[6])) ? $accounting_basis = $data[6] : $accounting_basis = 'cash'; $result = $result_bills = []; if ($table == "hospital_bills") { switch ($search_type) { case 'today': //$result = DB::table($table)->whereNull('deleted_at')->whereDate('created_at', '<=', $today)->where('payable_account', 'LIKE', $chart_of_account)->get(); $result = DB::table($table)->whereNull('deleted_at')->whereDate('bill_date', '<=', $today)->whereRaw('FIND_IN_SET(' . $chart_of_account . ',payable_account)')->get(); break; case 'yesterday': $result = DB::table($table)->whereNull('deleted_at')->whereDate('bill_date', '<=', $yesterday)->whereRaw('FIND_IN_SET(' . $chart_of_account . ',payable_account)')->get(); break; case 'custom_date': $result = DB::table($table)->whereNull('deleted_at')->whereDate('bill_date', '<=', $start)->whereRaw('FIND_IN_SET(' . $chart_of_account . ',payable_account)')->get(); break; case 'custom_date_range': $result = DB::table($table)->whereNull('deleted_at')->whereBetween('bill_date', [$start, $end])->whereRaw('FIND_IN_SET(' . $chart_of_account . ',payable_account)')->get(); break; } } else if ($table == "journals") { $probable_duplicate_records = []; switch ($search_type) { case 'today': $result_bills = DB::table("hospital_bills")->whereNull('deleted_at')->whereDate('created_at', '<=', $today)->where('payable_account', 'LIKE', $chart_of_account)->get(); foreach ($result_bills as $bill) { $bill_number = $bill->bill_number; if (strpos($bill_number, 'Journal') !== false) { $bill_number_trim1 = trim($bill_number, "Journal ("); $bill_number_trim2 = trim($bill_number_trim1, ")"); $journal_number = (int)$bill_number_trim2; $probable_duplicate_records[] = $journal_number; } } $result = DB::table($table)->whereNull('deleted_at')->whereDate('journal_date', '<=', $today)->whereNotIn('journal_number', $probable_duplicate_records)->get(); break; case 'yesterday': $result_bills = DB::table("hospital_bills")->whereNull('deleted_at')->whereDate('created_at', '<=', $yesterday)->where('payable_account', 'LIKE', $chart_of_account)->get(); foreach ($result_bills as $bill) { $bill_number = $bill->bill_number; if (strpos($bill_number, 'Journal') !== false) { $bill_number_trim1 = trim($bill_number, "Journal ("); $bill_number_trim2 = trim($bill_number_trim1, ")"); $journal_number = (int)$bill_number_trim2; $probable_duplicate_records[] = $journal_number; } } $result = DB::table($table)->whereNull('deleted_at')->whereDate('journal_date', '<=', $yesterday)->whereNotIn('journal_number', $probable_duplicate_records)->get(); break; case 'custom_date': $result_bills = DB::table("hospital_bills")->whereNull('deleted_at')->whereDate('created_at', '<=', $start)->where('payable_account', 'LIKE', $chart_of_account)->get(); foreach ($result_bills as $bill) { $bill_number = $bill->bill_number; if (strpos($bill_number, 'Journal') !== false) { $bill_number_trim1 = trim($bill_number, "Journal ("); $bill_number_trim2 = trim($bill_number_trim1, ")"); $journal_number = (int)$bill_number_trim2; $probable_duplicate_records[] = $journal_number; } } $result = DB::table($table)->whereNull('deleted_at')->whereDate('journal_date', $start)->whereNotIn('journal_number', $probable_duplicate_records)->get(); break; case 'custom_date_range': $result_bills = DB::table("hospital_bills")->whereNull('deleted_at')->whereBetween('created_at', [$start, $end])->where('payable_account', 'LIKE', $chart_of_account)->get(); foreach ($result_bills as $bill) { $bill_number = $bill->bill_number; if (strpos($bill_number, 'Journal') !== false) { $bill_number_trim1 = trim($bill_number, "Journal ("); $bill_number_trim2 = trim($bill_number_trim1, ")"); $journal_number = (int)$bill_number_trim2; $probable_duplicate_records[] = $journal_number; } } $result = DB::table($table)->whereNull('deleted_at')->whereBetween('journal_date', [$start, $end])->whereNotIn('journal_number', $probable_duplicate_records)->get(); break; } } else if ($table == "patient_accounts_deposits") { switch ($search_type) { case 'today': $result["patient_accounts_deposits"] = DB::table('patient_accounts_deposits')->whereNull('deleted_at')->whereDate('deposit_date', '<=', $today)->get(); $result["patient_account_consumptions"] = DB::table('patient_account_consumptions')->whereNull('deleted_at')->whereDate('created_at', '<=', Carbon::parse($today)->endOfDay())->get(); $result["patient_accounts_refunds"] = DB::table('patient_accounts_refunds')->whereNull('deleted_at')->whereDate('refund_date', '<=', $today)->get(); break; case 'yesterday': $result["patient_accounts_deposits"] = DB::table('patient_accounts_deposits')->whereNull('deleted_at')->whereDate('deposit_date', '<=', $yesterday)->get(); $result["patient_account_consumptions"] = DB::table('patient_account_consumptions')->whereNull('deleted_at')->whereDate('created_at', '<=', Carbon::parse($yesterday)->endOfDay())->get(); $result["patient_accounts_refunds"] = DB::table('patient_accounts_refunds')->whereNull('deleted_at')->whereDate('refund_date', '<=', $yesterday)->get(); break; case 'custom_date': $result["patient_accounts_deposits"] = DB::table('patient_accounts_deposits')->whereNull('deleted_at')->whereDate('deposit_date', '<=', $start)->get(); $result["patient_account_consumptions"] = DB::table('patient_account_consumptions')->whereNull('deleted_at')->whereDate('created_at', '<=', Carbon::parse($start)->endOfDay())->get(); $result["patient_accounts_refunds"] = DB::table('patient_accounts_refunds')->whereNull('deleted_at')->whereDate('refund_date', '<=', $start)->get(); break; case 'custom_date_range': $result["patient_accounts_deposits"] = DB::table('patient_accounts_deposits')->whereNull('deleted_at')->whereBetween('deposit_date', [$start, $end])->get(); $result["patient_account_consumptions"] = DB::table('patient_account_consumptions')->whereNull('deleted_at')->whereBetween('created_at', [Carbon::parse($start)->startOfDay(), Carbon::parse($end)->endOfDay()])->get(); $result["patient_accounts_refunds"] = DB::table('patient_accounts_refunds')->whereNull('deleted_at')->whereBetween('refund_date', [$start, $end])->get(); break; } } else { switch ($search_type) { case 'today': $result = DB::table($table)->whereNull('deleted_at')->whereDate('created_at', '<=', $today)->get(); break; case 'yesterday': $result = DB::table($table)->whereNull('deleted_at')->whereDate('created_at', '<=', $yesterday)->get(); break; case 'custom_date': $result = DB::table($table)->whereNull('deleted_at')->whereDate('created_at', '<=', $start)->get(); break; case 'custom_date_range': $result = DB::table($table)->whereNull('deleted_at')->whereBetween('created_at', [$start, $end])->get(); break; } } return view('finance_reports::finance_reports.accounts.liabilities', compact('result', 'result_bills', 'chart_of_account', 'title', 'table', 'accounting_basis')); } public function equity_detail(Request $request, $data) { $data = explode(',', $data); $table = $data[3]; $chart_of_account = $data[4]; $chart_of_account_detail = ChartOfAccount::withTrashed()->find($chart_of_account); $title = $chart_of_account_detail ? $chart_of_account_detail->name : ""; $slug = $chart_of_account_detail ? $chart_of_account_detail->slug : ""; if ($slug == "retained_earnings") { return redirect('finance_reports/profit_or_loss_statement'); } $result_equities = []; if ($table == 'banking') { $result = $opening_balance_record = []; switch ($data[0]) { case 'today': $_today = Carbon::today(); $opening_balance_record = get_latest_opening_balance_record($chart_of_account, $_today); break; case 'yesterday': $_yesterday = Carbon::yesterday(); $opening_balance_record = get_latest_opening_balance_record($chart_of_account, $_yesterday); break; case 'custom_date': $start_date = $data[1]; $start = Carbon::parse($start_date)->startOfDay()->toDateTimeString(); $opening_balance_record = get_latest_opening_balance_record($chart_of_account, $start); break; case 'custom_date_range': $end_date = $data[2]; $end = Carbon::parse($end_date)->endOfDay()->toDateTimeString(); $opening_balance_record = get_latest_opening_balance_record($chart_of_account, $end); break; } $result['name'] = $title; $result['amount'] = (!is_null($opening_balance_record) && !empty($opening_balance_record)) ? $opening_balance_record->account_balance : 0; $result['created_by'] = get_name($chart_of_account, 'id', 'created_by', 'chart_of_accounts'); $result['created_at'] = get_name($chart_of_account, 'id', 'created_at', 'chart_of_accounts'); $result_equities = DB::table('equities')->where('account_id', $chart_of_account)->get(); } elseif ($table == 'opening_inventory') { $result = $drugs_data = $sundries_data = []; $total_inventory_opening_balance = 0; $drugs = Drug::get(); $sundries = Sundry::get(); switch ($data[0]) { case 'today': $_today = Carbon::today(); $drugs = DB::table('drugs')->whereNotNull('opening_stock')->whereDate('opening_stock_date', '<=', $_today)->get(); $sundries = DB::table('sundries')->whereNotNull('opening_stock')->whereDate('opening_stock_date', '<=', $_today)->get(); break; case 'yesterday': $_yesterday = Carbon::yesterday(); $drugs = DB::table('drugs')->whereNotNull('opening_stock')->whereDate('opening_stock_date', '<=', $_yesterday)->get(); $sundries = DB::table('sundries')->whereNotNull('opening_stock')->whereDate('opening_stock_date', '<=', $_yesterday)->get(); break; case 'custom_date': $start_date = $data[1]; $start = Carbon::parse($start_date)->startOfDay()->toDateTimeString(); $drugs = DB::table('drugs')->whereNotNull('opening_stock')->whereDate('opening_stock_date', '<=', $start)->get(); $sundries = DB::table('sundries')->whereNotNull('opening_stock')->whereDate('opening_stock_date', '<=', $start)->get(); break; case 'custom_date_range': $start_date = $data[1]; $end_date = $data[2]; $drugs = DB::table('drugs')->whereNotNull('opening_stock')->whereDate('opening_stock_date', '<=', $end_date)->get(); $sundries = DB::table('sundries')->whereNotNull('opening_stock')->whereDate('opening_stock_date', '<=', $end_date)->get(); break; } $result['drugs'] = []; foreach ($drugs as $drug) { $drugs_data['name'] = $drug->name; if ($drug->opening_cost_price == 0 && !is_null($drug->opening_stock)) { $drugs_data['amount'] = get_first_cost_of_good($drug->id, 1) * $drug->opening_stock; } else { $drugs_data['amount'] = (!is_null($drug->opening_stock) && !empty($drug->opening_stock)) ? ($drug->opening_cost_price * $drug->opening_stock) : 0; } $drugs_data['created_by'] = $drug->created_by; $drugs_data['updated_at'] = $drug->updated_at; array_push($result['drugs'], $drugs_data); } $result['sundries'] = []; foreach ($sundries as $sundry) { $sundries_data['name'] = $sundry->name; if ($sundry->opening_cost_price == 0 && !is_null($sundry->opening_stock)) { $sundries_data['amount'] = get_first_cost_of_good($sundry->id, 2) * $sundry->opening_stock; } else { $sundries_data['amount'] = (!is_null($sundry->opening_stock) && !empty($sundry->opening_stock)) ? ($sundry->opening_cost_price * $sundry->opening_stock) : 0; } $sundries_data['created_by'] = $sundry->created_by; $sundries_data['updated_at'] = $sundry->updated_at; array_push($result['sundries'], $sundries_data); } } else { $result = DB::table($table)->where('account_id', $chart_of_account)->get(); } $request->request->add(['start_date' => $data[1]]); $request->request->add(['end_date' => $data[2]]); $retained_earnings = getRetainedEarnings($request, $data[1]); $banks = ChartOfAccount::where('type', 4)->orderBy('name', 'asc')->get(); return view('finance_reports::finance_reports.accounts.equities', compact('result', 'chart_of_account', 'title', 'table', 'banks', 'data', 'result_equities')); } public function cash_flow_statement(Request $request) { $hospital_information = HospitalInformation::first(); $operating_activities = $this->operating_activities($request); $working_capital = $this->working_capital($request); $investing_activities = getAssetTransactions($request); $financing_activities = $this->financing_activities($request); $peroid_start_cash = $this->peroid_start_cash($request); return view('finance_reports::finance_reports.cash_flow_statement', compact('hospital_information', 'operating_activities', 'working_capital', 'investing_activities', 'financing_activities', 'peroid_start_cash')); } public function print_cash_flow_statement(Request $request) { $operating_activities = $this->operating_activities($request); $working_capital = $this->working_capital($request); $investing_activities = getAssetTransactions($request); $financing_activities = $this->financing_activities($request); $peroid_start_cash = $this->peroid_start_cash($request); $data = [ "operating_activities" => $operating_activities, "working_capital" => $working_capital, "investing_activities" => $investing_activities, "financing_activities" => $financing_activities, "peroid_start_cash" => $peroid_start_cash ]; $pdf = SnappyPDF::loadView("finance_reports::finance_reports/print_cash_flow_statement", $data) ->setOrientation('portrait') ->setOption('margin-bottom', 7) ->setOption('margin-top', 5) ->setOption('footer-html', '© ' . date('Y') . ' Stre@mline'); return $pdf->inline('Cash Flow Statement - ' . date("d-m-y h:ia") . '.pdf'); } /*===================RECEIPTS======================*/ public function debtPlanPaymentReceipt(Request $request, $new_receipt_number) { $patient = Patient::where(['id' => $request->patient_id])->first(); $hospital_information = HospitalInformation::first(); $compact_values = compact('hospital_information', 'request', 'new_receipt_number', 'patient'); return view('finance_reports::finance_reports.receipts.debt_plan_payment', $compact_values); } public function patientDiscountReceipt(Request $request) { $total_amount_pay = 0; $patient_to_pay = 0; $service_payment = false; // central billing has an insurance expenditure tag of "11" if (!($request->reason == "11")) { $reason = $request->reason; } else { $reason = get_name($request->reason, 'id', 'name', 'finance_point_tags'); } if ($reason == "Consultation" || $reason == "Services" || $reason == "Other Services" || $reason == "Co_Payment") { // get payment details for the services $service_payment = ServiceDeposit::where(['receipt_number' => $request->receipt_number])->first(); $patient_to_pay = $service_payment->patient_amount_paid; $service_prices_array = explode(",", $service_payment->items_amounts); $service_ids_array = explode(",", $service_payment->items_ids); $total_amount_pay = 0; foreach ($service_prices_array as $price) { $total_amount_pay += is_numeric($price) ? $price : 0; } $receipt_date = $service_payment->created_at; // receipt number $receipt_number = $service_payment->receipt_number; } else if ($reason == "Investigations") { // get payment details for the services $service_payment = InvestigationDeposit::where(['receipt_number' => $request->receipt_number])->first(); $patient_to_pay = $service_payment->patient_amount_paid; $service_prices_array = explode(",", $service_payment->investigation_amounts); $service_ids_array = explode(",", $service_payment->investigation_items); $total_amount_pay = 0; foreach ($service_prices_array as $price) { $total_amount_pay += $price; } $receipt_date = $service_payment->created_at; // receipt number $receipt_number = $service_payment->receipt_number; } else if ($reason == "Procedures") { // get payment details for the services $service_payment = ProcedureDeposit::where(['receipt_number' => $request->receipt_number])->first(); $patient_to_pay = $service_payment->patient_amount_paid; $service_prices_array = explode(",", $service_payment->procedure_amounts); $service_ids_array = explode(",", $service_payment->procedure_items); $total_amount_pay = 0; foreach ($service_prices_array as $price) { $total_amount_pay += is_numeric($price) ? $price : 0; } $receipt_date = $service_payment->created_at; // receipt number $receipt_number = $service_payment->receipt_number; } else if ($reason == "Sundries") { // get payment details for the services $service_payment = SundryDeposit::where(['receipt_number' => $request->receipt_number])->first(); $patient_to_pay = $service_payment->patient_amount_paid; $service_prices_array = explode(",", $service_payment->sundry_amount); $service_ids_array = explode(",", $service_payment->sundry_items); $total_amount_pay = 0; foreach ($service_prices_array as $price) { $total_amount_pay += is_numeric($price) ? $price : 0; } $receipt_date = $service_payment->created_at; // receipt number $receipt_number = $service_payment->receipt_number; } else if ($reason == "Treatment") { // get payment details for the services $service_payment = TreatmentDeposits::where(['receipt_number' => $request->receipt_number])->first(); $patient_to_pay = $service_payment->patient_amount_paid; $service_prices_array = explode(",", $service_payment->treatment_items); $service_ids_array = explode(",", $service_payment->treatment_subtotals); $total_amount_pay = 0; foreach ($service_prices_array as $price) { $total_amount_pay += is_numeric($price) ? $price : 0; } $receipt_date = $service_payment->created_at; // receipt number $receipt_number = $service_payment->receipt_number; } else if ($reason == "Central Billing") { // get payment details for the services $service_payment = CentralBillingDeposits::where(['receipt_number' => $request->receipt_number])->get()->toArray(); } else if ($reason == "Dependant-Consultation" || $reason == "Dependant-Procedures" || $reason == "Dependant-Investigations" || $reason == "Dependant-Treatment" || $reason == "Dependant-Sundries") { // dependant consumptions $reason = substr($reason, 10); //now remove the substring "Dependant-" $service_payment = DependantsConsumption::where(['episode_id' => $request->episode_id, 'dependant_patient_id' => $request->patient_id, 'reason' => $reason, 'receipt_number' => $request->receipt_number])->first(); $service_prices_array = explode(",", $service_payment->items_prices); $service_ids_array = explode(",", $service_payment->items_ids); $total_amount_pay = $service_payment->amount_consumed; $patient_to_pay = $service_payment->unpaid_balance; $receipt_date = $service_payment->created_at; // receipt number $receipt_number = $service_payment->receipt_number; $service_payment->patient_id = $request->patient_id; } // details to be used for receipt $hospital_information = HospitalInformation::first(); $discounts_applied = $total_amount_pay - $patient_to_pay; if ($reason != "Central Billing") { $patient = Patient::find($request->patient_id); } $compact_values = compact( 'hospital_information', 'receipt_date', 'receipt_number', 'discounts_applied', 'patient', 'service_prices_array', 'service_ids_array', 'total_amount_pay', 'patient_to_pay', 'reason', 'service_payment' ); return view('finance_reports::finance_reports.receipts.patient_discount', $compact_values); } public function servicesReceiptReprint($id) { // get payment details for the services $service_payment = ServiceDeposit::where(['id' => $id])->first(); $patient_to_pay = $service_payment->patient_amount_paid; $service_prices_array = explode(",", $service_payment->items_amounts); $service_ids_array = explode(",", $service_payment->items_ids); $total_amount_pay = 0; foreach ($service_prices_array as $price) { $total_amount_pay += $price; } $receipt_date = $service_payment->created_at; // receipt number $receipt_number = $service_payment->receipt_number; // details to be used for receipt $hospital_information = HospitalInformation::first(); $discounts_applied = $total_amount_pay - $patient_to_pay; $patient = Patient::find($service_payment->patient_id); $compact_values = compact( 'hospital_information', 'receipt_date', 'receipt_number', 'discounts_applied', 'patient', 'service_prices_array', 'service_ids_array', 'total_amount_pay', 'patient_to_pay' ); return view('finance_reports::finance_reports.receipts.services_reprint', $compact_values); } public function inpatient_deposit_receipt_reprint($id) { $deposit = ServiceDeposit::where('id', $id)->first(); $hospital_information = HospitalInformation::first(); return view('finance_reports::finance_reports.receipts.inpatient_deposits', compact('hospital_information', 'deposit')); } public function proceduresReceiptReprint($id) { // get payment details for the services $service_payment = ProcedureDeposit::where(['id' => $id])->first(); $patient_to_pay = $service_payment->patient_amount_paid; $service_prices_array = explode(",", $service_payment->procedure_amounts); $service_ids_array = explode(",", $service_payment->procedure_items); $total_amount_pay = 0; // foreach ($service_prices_array as $price){ // $total_amount_pay += $price; // } $receipt_date = $service_payment->created_at; // receipt number $receipt_number = $service_payment->receipt_number; // details to be used for receipt $hospital_information = HospitalInformation::first(); $discounts_applied = $total_amount_pay - $patient_to_pay; $patient = Patient::find($service_payment->patient_id); $compact_values = compact( 'hospital_information', 'receipt_date', 'receipt_number', 'discounts_applied', 'patient', 'service_prices_array', 'service_ids_array', 'total_amount_pay', 'patient_to_pay' ); return view('finance_reports::finance_reports.receipts.procedures_reprint', $compact_values); } public function treatmentReceiptReprint($id) { // get payment details for the services $service_payment = TreatmentDeposits::where(['id' => $id])->first(); $patient_to_pay = $service_payment->patient_amount_paid; $service_prices_array = explode(",", $service_payment->treatment_subtotals); $service_ids_array = explode(",", $service_payment->treatment_items); $total_amount_pay = 0; foreach ($service_prices_array as $price) { $total_amount_pay += $price; } $receipt_date = $service_payment->created_at; // receipt number $receipt_number = $service_payment->receipt_number; // details to be used for receipt $hospital_information = HospitalInformation::first(); $discounts_applied = $total_amount_pay - $patient_to_pay; $patient = Patient::find($service_payment->patient_id); $compact_values = compact( 'hospital_information', 'receipt_date', 'receipt_number', 'discounts_applied', 'patient', 'service_prices_array', 'service_ids_array', 'total_amount_pay', 'patient_to_pay' ); return view('finance_reports::finance_reports.receipts.treatment_reprint', $compact_values); } public function sundriesReceiptReprint($id) { // get payment details for the services $service_payment = SundryDeposit::where(['id' => $id])->first(); $patient_to_pay = $service_payment->patient_amount_paid; $service_prices_array = explode(",", $service_payment->sundry_amounts); $service_ids_array = explode(",", $service_payment->sundry_items); $total_amount_pay = 0; $receipt_date = $service_payment->created_at; // receipt number $receipt_number = $service_payment->receipt_number; // details to be used for receipt $hospital_information = HospitalInformation::first(); $discounts_applied = $total_amount_pay - $patient_to_pay; $patient = Patient::find($service_payment->patient_id); $compact_values = compact( 'hospital_information', 'receipt_date', 'receipt_number', 'discounts_applied', 'patient', 'service_prices_array', 'service_ids_array', 'total_amount_pay', 'patient_to_pay' ); return view('finance_reports::finance_reports.receipts.sundries_reprint', $compact_values); } public function investigationsReceiptReprint($id) { // get payment details for the services $service_payment = InvestigationDeposit::where(['id' => $id])->first(); $patient_to_pay = $service_payment->patient_amount_paid; $service_prices_array = explode(",", $service_payment->investigation_amounts); $service_ids_array = explode(",", $service_payment->investigation_items); $total_amount_pay = 0; foreach ($service_prices_array as $price) { $total_amount_pay += $price; } $receipt_date = $service_payment->created_at; // receipt number $receipt_number = $service_payment->receipt_number; // details to be used for receipt $hospital_information = HospitalInformation::first(); $discounts_applied = $total_amount_pay - $patient_to_pay; $patient = Patient::find($service_payment->patient_id); $compact_values = compact( 'hospital_information', 'receipt_date', 'receipt_number', 'discounts_applied', 'patient', 'service_prices_array', 'service_ids_array', 'total_amount_pay', 'patient_to_pay' ); return view('finance_reports::finance_reports.receipts.investigations_reprint', $compact_values); } public function PremiumsReceiptReprint($id) { $insurance_deposit = InsuranceSubscription::where(['id' => $id])->first(); $insurance_amount = $insurance_deposit->amount; $insurance_start_date = $insurance_deposit->start_date; $insurance_end_date = $insurance_deposit->end_date; $insurance_payment_date = $insurance_deposit->payment_date; $insurance_family_amount = $insurance_deposit->family_amount; $receipt_date = $insurance_deposit->created_at; $receipt_number = $insurance_deposit->receipt_number; $hospital_information = HospitalInformation::first(); $insurance_group = InsuranceGroup::find($insurance_deposit->group_id); $compact_values = compact( 'hospital_information', 'receipt_date', 'receipt_number', 'insurance_group', 'insurance_amount', 'insurance_start_date', 'insurance_end_date', 'insurance_payment_date', 'insurance_family_amount' ); return view('finance_reports::finance_reports.receipts.premiums_reprint', $compact_values); } public function patient_payment_receipt($id) { $payment = InvoicePayment::where('id', $id)->first(); $hospital_information = HospitalInformation::first(); return view('finance_reports::finance_reports.receipts.patient_invoice_reprint', compact('hospital_information', 'payment')); } public function donor_payment_receipt($id) { $payment = DonorInvoicePayment::where('id', $id)->first(); $hospital_information = HospitalInformation::first(); return view('finance_reports::finance_reports.receipts.donor_invoice_reprint', compact('hospital_information', 'payment')); } public function debt_plan_payment($id) { $payment = DebtPlanPaymentStaff::where(['id' => $id])->first(); $hospital_information = HospitalInformation::first(); $compact_values = compact('hospital_information', 'payment'); return view('finance_reports::finance_reports.receipts.debt_plan_payment_detail', $compact_values); } public function patient_refunds_report(Request $request) { if ($request->start_date) { $start_date = $request->start_date; $end_date = $request->end_date; } else { $start_date = date('Y-m-d h:i:s'); $end_date = date('Y-m-d h:i:s'); } $start_date = Carbon::parse($start_date)->startOfDay()->toDateTimeString(); $end_date = Carbon::parse($end_date)->endOfDay()->toDateTimeString(); $criteria = 'Between (' . streamline_date($start_date) . ') And (' . streamline_date($end_date) . ')'; if ($request->refunded_by != 0) { $criteria .= ' User: ' . get_full_name($request->refunded_by, 'id', 'first_name', 'last_name', 'users'); $refunds = PatientRefunds::whereBetween('refund_date', [DATE($start_date), DATE($end_date)])->where('created_by', $request->refunded_by)->get(); } else { $criteria .= ' All Users'; $refunds = PatientRefunds::whereBetween('refund_date', [DATE($start_date), DATE($end_date)])->get(); } $users = User::select('id')->get(); return view('finance_reports::finance_reports.patient_refunds_report', compact('refunds', 'criteria', 'users')); } public function ward_discounts_report(Request $request) { $wards = Ward::pluck('name', 'id')->toArray(); $wards = ['' => '- select -'] + $wards; $wards = [0 => 'All Wards'] + $wards; if (isset($request->start_date) && isset($request->end_date)) { $start_date = Carbon::parse($request->start_date)->startOfDay()->toDateTimeString(); $end_date = Carbon::parse($request->end_date)->endOfDay()->toDateTimeString(); } else { $start_date = Carbon::now()->startOfDay()->toDateTimeString(); $end_date = Carbon::now()->endOfDay()->toDateTimeString(); } if (!empty($request->ward)) { $discounts = InpatientWardDiscounts::where('ward_id', $request->ward) ->whereBetween('created_at', [$start_date, $end_date])->get(); } else { $discounts = InpatientWardDiscounts::whereBetween('created_at', [$start_date, $end_date])->get(); } return view('finance_reports::finance_reports.ward_discounts_report', compact('wards', 'start_date', 'end_date', 'discounts')); } public function one_off_discounts_report(Request $request) { if ($request->start_date) { $start_date = $request->start_date; $end_date = $request->end_date; } else { $start_date = date('Y-m-d h:i:s'); $end_date = date('Y-m-d h:i:s'); } $start_date = Carbon::parse($start_date)->startOfDay(); $end_date = Carbon::parse($end_date)->endOfDay(); $criteria = 'Between (' . streamline_date($start_date) . ') And (' . streamline_date($end_date) . ')'; $discounts = DB::table('patient_one_off_discounts') ->whereBetween('created_at', [$start_date, $end_date]) ->get(); $tags = DB::table('finance_point_tags')->pluck('name', 'id'); return view('finance_reports::finance_reports.one_off_discounts_report', compact('criteria', 'discounts', 'tags')); } public function professional_fees_detail($data) { $data = explode(',', $data); $result = []; $table = $data[3]; $search_type = $data[0]; $chart_of_account = $data[4]; $today = Carbon::today()->toDateString(); $yesterday = Carbon::yesterday()->toDateString(); $end = Carbon::parse($data[2])->endOfDay()->toDateTimeString(); $start = Carbon::parse($data[1])->startOfDay()->toDateTimeString(); $title = get_name($chart_of_account, 'id', 'name', 'chart_of_accounts'); switch ($search_type) { case 'today': $ward_procedure_staff_fees = DB::table('ward_procedures')->whereNull('deleted_at')->whereDate('created_at', $today)->where('expense_chart_of_account', $chart_of_account) ->get()->toArray(); break; case 'yesterday': $ward_procedure_staff_fees = DB::table('ward_procedures')->whereNull('deleted_at')->whereDate('created_at', $yesterday)->where('expense_chart_of_account', $chart_of_account) ->get()->toArray(); break; case 'custom_date': $ward_procedure_staff_fees = DB::table('ward_procedures')->whereNull('deleted_at')->whereDate('created_at', $start)->where('expense_chart_of_account', $chart_of_account) ->get()->toArray(); break; case 'custom_date_range': $ward_procedure_staff_fees = DB::table('ward_procedures')->whereNull('deleted_at')->where('expense_chart_of_account', $chart_of_account)->whereBetween('created_at', [$start, $end]) ->get()->toArray(); } return view('finance_reports::finance_reports.accounts.proffesional_fees', compact('table', 'title', 'search_type', 'start', 'end', 'chart_of_account', 'ward_procedure_staff_fees') ); } public function undo_banking($cashier_income_id) { $record = CashierIncome::where('id', $cashier_income_id)->first(); if ($record->banked) { $deposit_id_array = explode(",", $record->banked); foreach ($deposit_id_array as $deposit_id) { $bank_record = Banking::where('id', $deposit_id)->first(); $new_memo = $bank_record->memo . " (Deleted by " . get_name(Auth::id(), 'id', 'username', 'users') . ")"; $bank_record->memo = $new_memo; $bank_record->update(); if ($bank_record->delete()) : flash("Bank Record has been deleted.")->success(); /* ******* try getting previous record using this instead of the one commented out code above ******* */ $orderByCreatedAtIfTransDateIsTheSame = "created_at ASC"; $orderByIdIfTransDateIsTheSame = "id ASC"; $previous_bank_record = Banking::where('bank', $bank_record->bank) ->whereNull('deleted_at') ->where('trans_date', '<', $bank_record->trans_date) ->orderBy('trans_date', 'asc') ->orderByRaw($orderByCreatedAtIfTransDateIsTheSame) ->orderByRaw($orderByIdIfTransDateIsTheSame) ->first(); /* ************************************************************** */ if ($previous_bank_record) { update_banking_record_balances(Carbon::parse($previous_bank_record->trans_date)->toDateString(), $bank_record->bank, $previous_bank_record->id, $previous_bank_record->account_balance); } else { //there exists no previous record i.e what we deleted is the first bank record so let bal = $balance_to_use_for_updating = 0;//$bank_record->account_balance; update_banking_record_balances(Carbon::parse($bank_record->trans_date)->toDateString(), $bank_record->bank, $deposit_id, $balance_to_use_for_updating); } flash("Payment has been deleted successfully from Bank: " . get_name($bank_record->bank, 'id', 'name', 'chart_of_accounts'))->success(); //NOTE: check if the undo is from direct bank deposit, transfer the money back to undeposited fund /* $this_transactions_records = Banking::where('trans_id',$bank_record->trans_id)->pluck('other_accounts')->toArray(); */ $transaction_id_string = $bank_record->trans_id; //how banking table stores it using sprintf() $transaction_id_int = (int)$transaction_id_string; //how other_incomes table stores it $other_income_record = OtherIncome::where('trans_id', $transaction_id_int)->first(); if ($other_income_record) { // add the deposit amount to undeposited funds account. $cash_account_balance_record_on_deposit_date = get_latest_banking_record_based_on_transaction_date(get_name("undeposited_funds", "slug", "id", "chart_of_accounts"), $other_income_record->deposit_date); $cash_account_balance_on_deposit_date = is_null($cash_account_balance_record_on_deposit_date) ? 0 : (int)$cash_account_balance_record_on_deposit_date->account_balance; $undeposited_funds_balance_after_addition = ($cash_account_balance_on_deposit_date + $other_income_record->deposit_amount); $last_insert_id_to_account = capture_bank_record( 'TRANSFER', $other_income_record->deposit_date, get_name("undeposited_funds", "slug", "id", "chart_of_accounts"), $bank_record->bank, $undeposited_funds_balance_after_addition, $other_income_record->deposit_amount, 0, "undone banking from direct bank deposit", $transaction_id_string ); update_banking_record_balances($other_income_record->deposit_date, 10, $last_insert_id_to_account, $undeposited_funds_balance_after_addition); } endif; } $record->banked = null; $record->update(); return 'success'; } else { return 'fail'; } } public function undo_payment($payment_id) { return delete_hospital_bill_payment($payment_id); } public function accounts_payable_aging_summary() { $suppliers = Supplier::get(); $hospital_information = HospitalInformation::first(); $bills_query = "SELECT * FROM hospital_bills WHERE deleted_at IS NULL AND (balance IS NULL OR balance > 0) ORDER BY vendor ASC"; $bills = DB::select($bills_query); $data = $this->get_payable_aging_report_data($bills); return view('finance_reports::finance_reports.accounts.accounts_payable_aging_summary', compact('bills', 'hospital_information', 'suppliers', 'data')); } public function accounts_payable_aging_detail(Request $request) { $suppliers = Supplier::get(); $hospital_information = HospitalInformation::first(); $vendor_id = $request->vendor; if ($vendor_id == '0' || $vendor_id == null) { $bills_query = "SELECT * FROM hospital_bills WHERE deleted_at IS NULL AND (balance IS NULL OR balance > 0) ORDER BY vendor ASC"; $bills = DB::select($bills_query); } else { $bills_query = "SELECT * FROM hospital_bills WHERE deleted_at IS NULL AND vendor = {$vendor_id} AND (balance IS NULL OR balance > 0) ORDER BY id ASC"; if ($vendor_id == 0) { $bills_query = "SELECT * FROM hospital_bills WHERE deleted_at IS NULL AND vendor IS NULL AND (balance IS NULL OR balance > 0) ORDER BY id ASC"; } $bills = DB::select($bills_query); } $data = $this->get_payable_aging_report_data($bills); return view('finance_reports::finance_reports.accounts.accounts_payable_aging_detail', compact('bills', 'hospital_information', 'suppliers', 'data', 'vendor_id')); } public function get_payable_aging_report_data($bills) { $data = []; $today = Carbon::now()->toDateString(); $today_minus_thirty = Carbon::now()->subDays(30)->toDateString(); $today_minus_sixty = Carbon::now()->subDays(60)->toDateString(); $today_minus_ninety = Carbon::now()->subDays(90)->toDateString(); foreach ($bills as $bill) { $balance = is_null($bill->balance) ? (int)$bill->total_amount : (int)$bill->balance; if ($bill->bill_date == $today) { if (isset($data[$bill->vendor]['current'])) { $data[$bill->vendor]['current'] += $balance; } else { $data[$bill->vendor]['current'] = $balance; $data[$bill->vendor]['current_bills'] = []; } array_push($data[$bill->vendor]['current_bills'], ["id" => $bill->id, "bill_number" => $bill->bill_number, "bill_memo" => $bill->bill_memo, "bill_date" => $bill->bill_date, "bill_due_date" => $bill->bill_due_date, "balance" => $balance, "category" => "current"]); } elseif ($bill->bill_date < $today && $bill->bill_date >= $today_minus_thirty) { if (isset($data[$bill->vendor]['one_to_thirty'])) { $data[$bill->vendor]['one_to_thirty'] += $balance; } else { $data[$bill->vendor]['one_to_thirty'] = $balance; $data[$bill->vendor]['one_to_thirty_bills'] = []; } array_push($data[$bill->vendor]['one_to_thirty_bills'], ["id" => $bill->id, "bill_number" => $bill->bill_number, "bill_memo" => $bill->bill_memo, "bill_date" => $bill->bill_date, "bill_due_date" => $bill->bill_due_date, "balance" => $balance, "category" => "one_to_thirty"]); } elseif ($bill->bill_date < $today_minus_thirty && $bill->bill_date >= $today_minus_sixty) { if (isset($data[$bill->vendor]['thirty_one_to_sixty'])) { $data[$bill->vendor]['thirty_one_to_sixty'] += $balance; } else { $data[$bill->vendor]['thirty_one_to_sixty'] = $balance; $data[$bill->vendor]['thirty_one_to_sixty_bills'] = []; } array_push($data[$bill->vendor]['thirty_one_to_sixty_bills'], ["id" => $bill->id, "bill_number" => $bill->bill_number, "bill_memo" => $bill->bill_memo, "bill_date" => $bill->bill_date, "bill_due_date" => $bill->bill_due_date, "balance" => $balance, "category" => "thirty_one_to_sixty"]); } elseif ($bill->bill_date < $today_minus_sixty && $bill->bill_date >= $today_minus_ninety) { if (isset($data[$bill->vendor]['sixty_one_to_ninety'])) { $data[$bill->vendor]['sixty_one_to_ninety'] += $balance; } else { $data[$bill->vendor]['sixty_one_to_ninety'] = $balance; $data[$bill->vendor]['sixty_one_to_ninety_bills'] = []; } array_push($data[$bill->vendor]['sixty_one_to_ninety_bills'], ["id" => $bill->id, "bill_number" => $bill->bill_number, "bill_memo" => $bill->bill_memo, "bill_date" => $bill->bill_date, "bill_due_date" => $bill->bill_due_date, "balance" => $balance, "category" => "sixty_one_to_ninety"]); } elseif ($bill->bill_date < $today_minus_ninety) { if (isset($data[$bill->vendor]['ninety_one_and_over'])) { $data[$bill->vendor]['ninety_one_and_over'] += $balance; } else { $data[$bill->vendor]['ninety_one_and_over'] = $balance; $data[$bill->vendor]['ninety_one_and_over_bills'] = []; } array_push($data[$bill->vendor]['ninety_one_and_over_bills'], ["id" => $bill->id, "bill_number" => $bill->bill_number, "bill_memo" => $bill->bill_memo, "bill_date" => $bill->bill_date, "bill_due_date" => $bill->bill_due_date, "balance" => $balance, "category" => "ninety_one_and_over"]); } } return $data; } public function print_accounts_payable_aging_summary(Request $request) { $bills_query = "SELECT * FROM hospital_bills WHERE deleted_at IS NULL AND (balance IS NULL OR balance > 0) ORDER BY vendor ASC"; $bills = DB::select($bills_query); $data = ["data" => $this->get_payable_aging_report_data($bills)]; $pdf = SnappyPDF::loadView("finance_reports::finance_reports/print_accounts_payable_aging_summary", $data) ->setOrientation('landscape') ->setPaper('a4') ->setOption('margin-bottom', 10) ->setOption('margin-top', 5) ->setOption('footer-html', '© ' . date('Y') . ' Stre@mline') ->setOption('footer-right', '[page] of [toPage]'); return $pdf->inline('Accounts Payable Aging Summary Report - ' . date("d-m-y h:ia") . '.pdf'); } public function print_accounts_payable_aging_detail(Request $request) { $vendor_id = $request->vendor; if ($vendor_id == '0' || $vendor_id == null) { $bills_query = "SELECT * FROM hospital_bills WHERE deleted_at IS NULL AND (balance IS NULL OR balance > 0) ORDER BY vendor ASC"; $bills = DB::select($bills_query); } else { $bills_query = "SELECT * FROM hospital_bills WHERE deleted_at IS NULL AND vendor = {$vendor_id} AND (balance IS NULL OR balance > 0) ORDER BY id ASC"; if ($vendor_id == 0) { $bills_query = "SELECT * FROM hospital_bills WHERE deleted_at IS NULL AND vendor IS NULL AND (balance IS NULL OR balance > 0) ORDER BY id ASC"; } $bills = DB::select($bills_query); } $data = ["data" => $this->get_payable_aging_report_data($bills)]; $pdf = SnappyPDF::loadView("finance_reports::finance_reports/print_accounts_payable_aging_detail", $data) ->setOrientation('landscape') ->setPaper('a4') ->setOption('margin-bottom', 10) ->setOption('margin-top', 5) ->setOption('footer-html', '© ' . date('Y') . ' Stre@mline') ->setOption('footer-right', '[page] of [toPage]'); return $pdf->inline('Accounts Payable Aging Detail Report - ' . date("d-m-y h:ia") . '.pdf'); } public function operating_activities(Request $request) { /*========== enter this creed ==============*/ $start_of_fiscal_year = $end_date = null; if (empty($request->all())) { $start_of_fiscal_year = get_fiscal_year_start_from_hospital_information(Carbon::today()); $request->request->add(['start_date' => $start_of_fiscal_year]); $end_date = Carbon::today()->toDateString(); } else { switch ($request->dates) { case 'custom_date_range': $start_of_fiscal_year = Carbon::parse($request->start_date); $end_date = Carbon::parse($request->end_date)->startOfDay()->toDateString(); break; } } $request->request->add(['dates' => 'custom_date_range']); $request->request->add(['start_date' => $start_of_fiscal_year]); $request->request->add(['end_date' => $end_date]); $display = "As at " . streamline_date($end_date); /*============== leave this creed after becoming a better man =================*/ $display = dateLabelSetter($request); $net_income_data = getNetIncome($request); $depreciation_data = getDepreciation($request); $data = [ 'a_net_profit' => $net_income_data["accrual_net_income"], 'c_net_profit' => $net_income_data["cash_net_income"], 'depreciation_data' => $depreciation_data, 'display' => $display ]; return $data; } /** * The Start date constitutes the opening period so all computations up to that date make up the opening figure * The end date is the closing so all computations till then make up that figure */ public function working_capital(Request $request) { $accounts_receivable_closing = $accounts_receivable_opening = $inventory_closing = $inventory_opening = $accounts_payable_closing = $accounts_payable_opening = 0; // Receivables Closing & Opening $receivables = $this->receivables_data($request); $accounts_receivable_opening = $receivables['receivables_opening']; $accounts_receivable_closing = $receivables['receivables_closing']; $receivables_data_string = $receivables['receivables_data_string']; // Inventory Closing & Opening $inventory = $this->inventory_data($request); $inventory_opening = $inventory['inventory_opening']; $inventory_closing = $inventory['inventory_closing']; $inventory_data_strings = $inventory['inventory_data_strings']; // Payables Closing & Opening $payables = $this->payables_data($request); $accounts_payable_opening = $payables['payables_opening']; $accounts_payable_closing = $payables['payables_closing']; $payables_data_strings = $payables['payables_data_strings']; $data = [ 'accounts_receivable_closing' => $accounts_receivable_closing, 'accounts_receivable_opening' => $accounts_receivable_opening, 'receivables_data_string' => $receivables_data_string, 'inventory_closing' => $inventory_closing, 'inventory_opening' => $inventory_opening, 'inventory_data_strings' => $inventory_data_strings, 'accounts_payable_closing' => $accounts_payable_closing, 'accounts_payable_opening' => $accounts_payable_opening, 'accounts_payable_data_strings' => $payables_data_strings ]; return $data; } public function receivables_data(Request $request) { $receivables = []; $receivables_closing = $receivables_opening = 0; $accounts_receivables_tables = ['patient_category_invoices', 'debtors', 'debt_plan']; foreach ($accounts_receivables_tables as $table) { if (empty($request->all())) { $start_of_fiscal_year = get_fiscal_year_start_from_hospital_information(Carbon::today()); $request->request->add(['start_date' => $start_of_fiscal_year]); $end_date = Carbon::today()->toDateString(); } else { switch ($request->dates) { case 'custom_date_range': $start_of_fiscal_year = Carbon::parse($request->start_date); $end_date = Carbon::parse($request->end_date)->startOfDay()->toDateString(); break; } } if ($table == 'patient_category_invoices') { $receivables[$table]['closing'] = DB::table($table)->whereDate('created_at', '<=', $end_date)->whereNull('deleted_at')->where('invoice_generated', 1)->whereNull('balance_remaining')->orWhere('balance_remaining', '>', 0)->get(); $receivables[$table]['opening'] = DB::table($table)->whereDate('created_at', '<=', $start_of_fiscal_year)->whereNull('deleted_at')->where('invoice_generated', 1)->whereNull('balance_remaining')->orWhere('balance_remaining', '>', 0)->get(); } else { $receivables[$table]['closing'] = DB::table($table)->whereDate('created_at', '<=', $end_date)->whereNull('deleted_at')->whereNull('balance_remaining')->orWhere('balance_remaining', '>', 0)->get(); $receivables[$table]['opening'] = DB::table($table)->whereDate('created_at', '<=', $start_of_fiscal_year)->whereNull('deleted_at')->whereNull('balance_remaining')->orWhere('balance_remaining', '>', 0)->get(); } } // patient_category_invoices if (count($receivables['patient_category_invoices']['closing']) > 0) { foreach ($receivables['patient_category_invoices']['closing'] as $item) { $amount = is_null($item->balance_remaining) ? $item->patient_amount : $item->balance_remaining; $receivables_closing += $amount; } } if (count($receivables['patient_category_invoices']['opening']) > 0) { foreach ($receivables['patient_category_invoices']['opening'] as $item) { $amount = is_null($item->balance_remaining) ? $item->patient_amount : $item->balance_remaining; $receivables_opening += $amount; } } // debtors if (count($receivables['debtors']['closing']) > 0) { foreach ($receivables['debtors']['closing'] as $item) { $amount = is_null($item->balance_remaining) ? $item->balance : $item->balance_remaining; $receivables_closing += $amount; } } if (count($receivables['debtors']['opening']) > 0) { foreach ($receivables['debtors']['opening'] as $item) { $amount = is_null($item->balance_remaining) ? $item->balance : $item->balance_remaining; $receivables_opening += $amount; } } // debt_plan if (count($receivables['debt_plan']['closing']) > 0) { foreach ($receivables['debt_plan']['closing'] as $item) { $amount = is_null($item->balance_remaining) ? $item->staff_guarantor_to_pay : $item->balance_remaining; $receivables_closing += $amount; } } if (count($receivables['debt_plan']['opening']) > 0) { foreach ($receivables['debt_plan']['opening'] as $item) { $amount = is_null($item->balance_remaining) ? $item->staff_guarantor_to_pay : $item->balance_remaining; $receivables_opening += $amount; } } $receivables_data_string = $request->dates . "," . $request->start_date . "," . $request->end_date . "," . 'accounts_receivables' . "," . '16' . ","; $data = [ 'receivables_closing' => $receivables_closing, 'receivables_opening' => $receivables_opening, 'receivables_data_string' => $receivables_data_string ]; return $data; } public function inventory_data(Request $request) { $inventory_closing = $inventory_opening = 0; $stock_data_strings = []; $inventory_accounts = ChartOfAccount::where('type', 10)->whereNull('deleted_at')->pluck('id')->toArray(); if ($request->dates == 'custom_date_range') { $start = Carbon::parse($request->start_date)->startOfDay(); $end = Carbon::parse($request->end_date)->endOfDay(); } else { $start = Carbon::today()->startOfDay(); $end = Carbon::today()->endOfDay(); } $inventory_accounts_array = []; foreach ($inventory_accounts as $inventory_account) { $inventory_accounts_array[$inventory_account] = [ 'id' => $inventory_account, 'closing_stock_value' => 0, 'opening_stock_value' => 0, 'data' => $request->dates . "," . $request->start_date . "," . $request->end_date . "," . 'stock_watcher' . "," . $inventory_account ]; } $drugs = DB::table('drugs')->whereNull('deleted_at')->whereBetween('created_at', [$start, $end]) ->whereIn('inventory_account', $inventory_accounts)->get(['id', 'cost_price', 'pharmacy_stock', 'inventory_account', 'store_stock']); $sundries = DB::table('sundries')->whereNull('deleted_at')->whereBetween('created_at', [$start, $end]) ->whereIn('inventory_account', $inventory_accounts)->get(['id', 'cost_price', 'pharmacy_stock', 'inventory_account', 'store_stock']); // turn dates to ->toDateString() $start = $start->toDateString(); $end = $end->toDateString(); foreach ($drugs as $drug) { $stock_watcher_record = DB::table('batch_stock_watcher')->where('item_type', 1) ->where('item_id', $drug->id)->first(); if ($stock_watcher_record) { $details_arr = json_decode($stock_watcher_record->details, true); if (!isset($details_arr[$start])) { // just get the dates into their own array $dates_array = array_keys($details_arr); // search for the closest date to ours of interest and set that as our reference $details = $details_arr[get_closest_element_in_array($dates_array, $start)]; } else { $details = $details_arr[$start]; } $opening_stock_value = ($details["buying_price"] * ($details["pharmacy_stock"] + $details["store_stock"])); if (!isset($details_arr[$end])) { // just get the dates into their own array $dates_array = array_keys($details_arr); // search for the closest date to ours of interest and set that as our reference $details = $details_arr[get_closest_element_in_array($dates_array, $end)]; } else { $details = $details_arr[$end]; } $closing_stock_value = ($details["buying_price"] * ($details["pharmacy_stock"] + $details["store_stock"])); } else { $opening_stock_value = ($drug->cost_price * ($drug->pharmacy_stock + $drug->store_stock)); $closing_stock_value = ($drug->cost_price * ($drug->pharmacy_stock + $drug->store_stock)); } $inventory_accounts_array[$drug->inventory_account]['opening_stock_value'] = $inventory_accounts_array[$drug->inventory_account]['opening_stock_value'] + $opening_stock_value; $inventory_accounts_array[$drug->inventory_account]['closing_stock_value'] = $inventory_accounts_array[$drug->inventory_account]['closing_stock_value'] + $closing_stock_value; } foreach ($sundries as $sundry) { $stock_watcher_record = DB::table('batch_stock_watcher')->where('item_type', 2) ->where('item_id', $sundry->id)->first(); if ($stock_watcher_record) { $details_arr = json_decode($stock_watcher_record->details, true); if (!isset($details_arr[$start])) { // just get the dates into their own array $dates_array = array_keys($details_arr); // search for the closest date to ours of interest and set that as our reference $details = $details_arr[get_closest_element_in_array($dates_array, $start)]; } else { $details = $details_arr[$start]; } $opening_stock_value = ($details["buying_price"] * ($details["pharmacy_stock"] + $details["store_stock"])); if (!isset($details_arr[$end])) { // just get the dates into their own array $dates_array = array_keys($details_arr); // search for the closest date to ours of interest and set that as our reference $details = $details_arr[get_closest_element_in_array($dates_array, $end)]; } else { $details = $details_arr[$end]; } $closing_stock_value = ($details["buying_price"] * ($details["pharmacy_stock"] + $details["store_stock"])); } else { $opening_stock_value = ($sundry->cost_price * ($sundry->pharmacy_stock + $sundry->store_stock)); $closing_stock_value = ($sundry->cost_price * ($sundry->pharmacy_stock + $sundry->store_stock)); } $inventory_accounts_array[$sundry->inventory_account]['opening_stock_value'] = $inventory_accounts_array[$sundry->inventory_account]['opening_stock_value'] + $opening_stock_value; $inventory_accounts_array[$sundry->inventory_account]['closing_stock_value'] = $inventory_accounts_array[$sundry->inventory_account]['closing_stock_value'] + $closing_stock_value; } foreach ($inventory_accounts_array as $account) { $inventory_closing += $account["closing_stock_value"]; $inventory_opening += $account["opening_stock_value"]; $stock_data_strings[] = $account["data"]; } return [ 'inventory_closing' => $inventory_closing, 'inventory_opening' => $inventory_opening, 'inventory_data_strings' => $stock_data_strings ]; } public function payables_data(Request $request) { $end = Carbon::parse($request->end_date)->endOfDay()->toDateTimeString(); $start = Carbon::parse($request->start_date)->startOfDay()->toDateTimeString(); $hospital_bills_opening_total = $hospital_bills_closing_total = 0; $probable_duplicate_records = []; $payables_data_strings = []; //Current Liabilities $accounts = ChartOfAccount::where('type', 6)->whereNotIn('id', [15,])->orWhere('type', 9)->pluck('id')->toArray(); foreach ($accounts as $account_id) { $hospital_bills = []; switch ($request->dates) { case 'custom_date_range': $hospital_bills = DB::table('hospital_bills')->whereNull('deleted_at')->whereDate('created_at', '<=', $end)->whereRaw('FIND_IN_SET(' . $account_id . ',payable_account)')->get(); break; } foreach ($hospital_bills as $bill) { $bill_number = $bill->bill_number; if (strpos($bill_number, 'Journal') !== false) { $bill_number_trim1 = trim($bill_number, "Journal ("); $bill_number_trim2 = trim($bill_number_trim1, ")"); $journal_number = (int)$bill_number_trim2; $probable_duplicate_records[] = $journal_number; } $_amount_paid = (int)$bill->total_amount - (!is_null($bill->balance) ? (int)$bill->balance : (int)$bill->total_amount); $hospital_bill_balance = (int)$bill->total_amount - $_amount_paid; if ($bill->created_at <= $start) { $hospital_bills_opening_total += $hospital_bill_balance; } else { $hospital_bills_closing_total += $hospital_bill_balance; } } array_push($payables_data_strings, $request->dates . "," . $request->start_date . "," . $request->end_date . "," . 'hospital_bills' . "," . $account_id . ","); } $journals = []; switch ($request->dates) { case 'custom_date_range': $journals = DB::table('journals')->whereNull('deleted_at')->where('journal_date', '<=', $end)->whereNotIn('journal_number', $probable_duplicate_records)->get(); break; } $journals_opening_total = $journals_closing_total = 0; foreach ($journals as $journal) { $account_ids = explode(",", $journal->account_ids); $credits = explode(",", $journal->credits); $liability_account_id = null; for ($i = 0; $i < count($account_ids); $i++) { // If it's a current liability account if (get_name($account_ids[$i], 'id', 'type', 'chart_of_accounts') == 6) { $liability_account_id = $account_ids[$i]; $credit = $credits[$i]; if ($credit != null) { // This Liability Account's value was Increased via the Journal $liabilty_value = (int)$credit; foreach ($accounts as $account_id) { if ($account_id == $liability_account_id) { if ($bill->created_at <= $start) { $journals_opening_total += $liabilty_value; } else { $journals_closing_total += $liabilty_value; } } } } } } } // TODO: Figure out why the difference is too big; compare with current liabilities total in balance sheet $data = [ 'payables_closing' => $hospital_bills_closing_total + $journals_closing_total, 'payables_opening' => $hospital_bills_opening_total + $journals_opening_total, 'payables_data_strings' => $payables_data_strings ]; return $data; } public function financing_activities(Request $request) { $non_current_liabilities = getNonCurrentLiabilitiesByAccountBalanceSheet($request); $equities = getEquitiesByAccountCustom($request); $data = [ 'non_current_liabilities' => $non_current_liabilities, 'equities' => $equities ]; return $data; } /** * From bank and cash balances at the end of the previous period */ public function peroid_start_cash(Request $request) { $cash = 0; $banks = ChartOfAccount::where('type', 4)->pluck('id')->toArray(); $latest_banking_record = []; foreach ($banks as $bank) { switch ($request->dates) { case 'custom_date_range': $latest_banking_record = get_latest_banking_record($bank, Carbon::parse($request->start_date)->subDays(1)->toDateString()); break; } $cash += (!is_null($latest_banking_record) && !empty($latest_banking_record)) ? (int)($latest_banking_record->account_balance) : (int)(get_name($bank, 'id', 'balance', 'chart_of_accounts')); } return $cash; } public function patient_dependants_report(Request $request) { $dependants_consumption_colllections_array = []; $patient_discounts = DB::table('patient_discounts')->whereNotNull('threshold_type')->orderBy('created_at', 'desc')->get(); $patient_categories_array = []; foreach ($patient_discounts as $patient_discount) { $patient_categories_array[] = $patient_discount->patient_category; } $patient_categories = DB::table('patient_categories')->whereIn('id', $patient_categories_array)->pluck("name", "id")->toArray(); $patient_categories = ['' => '- select -'] + $patient_categories; $search_string = ""; if (!is_null($request->patient_category)) { $category_patient_dependants = CategoryPatientDependant::where('patient_category_id', $request->patient_category)->get(); $today = Carbon::today()->toDateTimeString(); $yesterday = Carbon::yesterday()->toDateTimeString(); $end_date = Carbon::parse($request->end_date)->endOfDay()->toDateTimeString(); $start_date = Carbon::parse($request->start_date)->startOfDay()->toDateTimeString(); foreach ($category_patient_dependants as $record) { $dependants_array = explode(",", $record->dependant_patient_ids); $main_patient_id = $record->main_patient_id; $dependants_array[] = $main_patient_id; //add the main patient fro easy querying if ($request->dates == "today") { $patient_consumptions = DependantsConsumption::whereIn('dependant_patient_id', $dependants_array)->whereDate('created_at', $today)->get(); $dependants_consumption_colllections_array[][$main_patient_id] = $patient_consumptions; $search_string = "Showing results for ".streamline_date(Carbon::today()->toDateString()).""; } else if ($request->dates == "yesterday") { $patient_consumptions = DependantsConsumption::whereIn('dependant_patient_id', $dependants_array)->whereDate('created_at', $yesterday)->get(); $dependants_consumption_colllections_array[][$main_patient_id] = $patient_consumptions; $search_string = "Showing results for ".streamline_date(Carbon::yesterday()->toDateString()).""; } else if ($request->dates == "custom_date") { $patient_consumptions = DependantsConsumption::whereIn('dependant_patient_id', $dependants_array)->whereDate('created_at', $start_date)->get(); $dependants_consumption_colllections_array[][$main_patient_id] = $patient_consumptions; $search_string = "Showing results for ".streamline_date(Carbon::parse($start_date)->toDateString()).""; } else if ($request->dates == "custom_date_range") { $patient_consumptions = DependantsConsumption::whereIn('dependant_patient_id', $dependants_array)->whereBetween('created_at', [$start_date, $end_date])->get(); $dependants_consumption_colllections_array[][$main_patient_id] = $patient_consumptions; $search_string = "Showing results between ".streamline_date(Carbon::parse($start_date)->toDateString())." and ".streamline_date(Carbon::parse($end_date)->toDateString()).""; } } $patients = Patient::where('category_id', $request->patient_category)->get(); } return view('finance_reports::finance_reports.patient_dependants_report', compact('request', 'patient_discounts', 'patient_categories', 'dependants_consumption_colllections_array', 'search_string')); } public function dependant_consumption_details(Request $request) { $main_patient_id = $request->main_patient_id; $today = Carbon::today()->toDateTimeString(); $yesterday = Carbon::yesterday()->toDateTimeString(); $end_date = Carbon::parse($request->end_date)->endOfDay()->toDateTimeString(); $start_date = Carbon::parse($request->start_date)->startOfDay()->toDateTimeString(); $search_string = ""; if ($request->dates == "today") { $patient_consumptions = DependantsConsumption::where('main_patient_id', $main_patient_id)->whereDate('created_at', $today)->get(); $search_string = "Showing results for ".streamline_date(Carbon::today()->toDateString()).""; } else if ($request->dates == "yesterday") { $patient_consumptions = DependantsConsumption::where('main_patient_id', $main_patient_id)->whereDate('created_at', $yesterday)->get(); $search_string = "Showing results for ".streamline_date(Carbon::yesterday()->toDateString()).""; } else if ($request->dates == "custom_date") { $patient_consumptions = DependantsConsumption::where('main_patient_id', $main_patient_id)->whereDate('created_at', $start_date)->get(); $search_string = "Showing results for ".streamline_date(Carbon::parse($start_date)->toDateString()).""; } else if ($request->dates == "custom_date_range") { $patient_consumptions = DependantsConsumption::where('main_patient_id', $main_patient_id)->whereBetween('created_at', [$start_date, $end_date])->get(); $search_string = "Showing results between ".streamline_date(Carbon::parse($start_date)->toDateString())." and ".streamline_date(Carbon::parse($end_date)->toDateString()).""; } return view('finance_reports::finance_reports.patient_dependants_report_details', compact('main_patient_id', 'patient_consumptions', 'search_string')); } public function renew_dependant_threshold(Request $request){ //1. record it as a new consumption with -negative consumption //2. Put all the excessive consumptions into an invoice to be paid by the patient //3. Let the running balance be reset to the threshold amount $category_dependants_record = CategoryPatientDependant::where('main_patient_id', $request->main_patient_id)->first(); $group_consumed_amount = $group_unpaid_balances = 0; $consumptions = DependantsConsumption::where('main_patient_id', $request->main_patient_id)->get(); foreach($consumptions as $dependant_consumption){ $group_consumed_amount += $dependant_consumption->amount_consumed; $group_unpaid_balances += $dependant_consumption->unpaid_balance; if ($dependant_consumption->unpaid_balance > 0 && $dependant_consumption->invoice_number == null) { $invoice_generated_status_array[] = 1; } $dependant_consumption->is_consumption_in_previous_subscription = 1; //mark this consumption as one in a past consumption $dependant_consumption->update(); } if ($group_unpaid_balances > 0){ if (in_array(1, $invoice_generated_status_array)){ $this->generate_dependant_invoice($request->main_patient_id); } } //record it as a new consumption with -negative consumption $new_consumption_record = new DependantsConsumption; $renewal_record = new PatientDependantRenewal; $patient = Patient::withTrashed()->find($request->main_patient_id); if ($patient) { $theshold_amt = is_null($patient->category_id) ? 0 : get_name($patient->category_id, "patient_category", "threshold_amount", "patient_discounts"); $renewal_record->main_patient_id = $request->main_patient_id; $renewal_record->renewal_amount = $theshold_amt; $renewal_record->renewal_date = now(); $renewal_record->save(); //update the current subscription dates in the category_patient_dependants table $category_dependants_record->current_subscription_start_date = $category_dependants_record->start_date ?? $category_dependants_record->created_at; $category_duration_in_months = 0; $threshold_type = get_name($patient->category_id, "patient_category", "threshold_type", "patient_discounts"); if ($threshold_type == 2) { $category_duration_in_months = 12; //12 months } if ($threshold_type == 1) { $category_duration_in_months = 1; //1 month } $carbon_start_date = Carbon::parse($category_dependants_record->current_subscription_start_date); $calculated_end_date = $carbon_start_date->addMonth($category_duration_in_months); $category_dependants_record->current_subscription_end_date = $calculated_end_date; //if the start and duration date do not exit, update them too $category_dependants_record->start_date = $category_dependants_record->start_date ?? $category_dependants_record->current_subscription_start_date; $category_dependants_record->duration = $category_dependants_record->duration ?? $category_duration_in_months; if ($category_dependants_record->update()) { flash("Subscription for ".get_full_name($patient->id, 'id', 'first_name', 'last_name', 'patients')." has been renewed")->success(); return redirect('patient_dependants_report'); } // $new_consumption_record->dependant_patient_id = $request->main_patient_id; // $new_consumption_record->main_patient_id = $request->main_patient_id; // $new_consumption_record->episode_id = 0; // $new_consumption_record->amount_consumed = -$theshold_amt; // $new_consumption_record->dependant_patient_category = $patient->category_id; // $new_consumption_record->main_patient_category = $patient->category_id; // $new_consumption_record->tag_id = 0; // $new_consumption_record->created_by = auth()->user()->id; // $new_consumption_record->created_at = now(); // if ($new_consumption_record->save()) { // flash("Subscription for ".get_full_name($patient->id, 'id', 'first_name', 'last_name', 'patients')." has been renewed")->success(); // return redirect('patient_dependants_report'); // } } flash("System could not renew subsription ")->error(); return redirect('patient_dependants_report'); } public function generate_dependant_invoice($main_patient_id){ $dependants_array = []; $dependants = CategoryPatientDependant::where('main_patient_id', $main_patient_id)->get(); $consumptions = DependantsConsumption::where('main_patient_id', $main_patient_id)->get(); $patient_category_id = 0; foreach ($dependants as $record) { $dependants_array = explode(",", $record->dependant_patient_ids); $patient_category_id = $record->patient_category_id; } $dependants_array[] = $main_patient_id; //add the main patient in array $start_of_year = Carbon::now()->startOfYear(); $start = $start_of_year->toDateTimeString(); $end = Carbon::now()->toDateString(); $patient_category_name = get_name($patient_category_id, "id", "name", "patient_categories"); $invoice_number = generateInvoiceNumberFromDB($patient_category_name); $invoice_start = Carbon::parse($start)->format('d-m-Y'); $invoice_date = $invoice_start."/".$end; //according to how Benjamin organized it $invoice_with_payment_amount_paid = $invoice_with_payment_balance = 0; $update = PatientCategoryInvoice::where('invoice_generated', 0) ->where('patient_category', $patient_category_id) ->whereIn('patient_id', $dependants_array) ->update( [ 'invoice_generated' => 1, 'invoice_date' => $invoice_date, 'invoice_number' => $invoice_number, 'is_invoice_for_individual' => $main_patient_id ] ); $track_invoice = new TrackInvoice; $track_invoice->reason = $patient_category_id; $track_invoice->created_by = auth()->user()->id; if (!is_null($update) && $track_invoice->save()) { $start_date = Carbon::parse($start)->startOfDay()->toDateTimeString(); $end_date = Carbon::parse($end)->endOfDay()->toDateTimeString(); //update the dependant consumption table with the generated invoices number $consumption = DependantsConsumption::where('main_patient_id', $main_patient_id)->whereNull('invoice_number') ->where('unpaid_balance', '>', 0) ->whereBetween('created_at', [$start_date, $end_date]) ->update(['invoice_number' => $invoice_number]); $last_invoice = DB::table('patient_category_invoices')->select('invoice_number')->distinct()->orderBy('invoice_number', 'desc')->first(); $last_invoice_number = $invoice_number; $invoices = DB::table('patient_category_invoices') ->whereNotIn('patient_id', findTestOrDemoPatients()) ->whereBetween('created_at', [$start_date, $end_date]) ->where('patient_category', $patient_category_id) ->where('invoice_generated', 1) ->where('status', 0) ->where('invoice_number', $last_invoice_number) ->groupBy('episode_id')->selectRaw('*, sum(patient_amount) as sum') ->get() ->toArray(); } else { return back()->withInput(); } } public function dependants_renewals_report(Request $request) { if ($request->start_date) { $start_date = $request->start_date; $end_date = $request->end_date; } else { $start_date = date('Y-m-d h:i:s'); $end_date = date('Y-m-d h:i:s'); } $start_date = Carbon::parse($start_date)->startOfDay(); $end_date = Carbon::parse($end_date)->endOfDay(); $patient_categories = PatientCategory::pluck('name', 'id')->prepend('-select-', '')->toArray(); $criteria = 'Renewals Made Between ' . streamline_date($start_date) . ' And ' . streamline_date($end_date); //$records = PatientDependantRenewal::where('patient')->whereBetween('created_at', [$start_date, $end_date])->orderBy('created_at', 'desc')->get(); $records = DB::table('patient_dependant_renewals')->join('patients', 'patients.id', '=', 'patient_dependant_renewals.main_patient_id') ->whereNull('patient_dependant_renewals.deleted_at') ->whereNull('patients.deleted_at') ->where('patients.category_id', $request->patient_category) ->get(); return view('finance_reports::finance_reports.dependants_renewals_report', compact('criteria', 'records', 'start_date', 'end_date', 'patient_categories')); } public function sales_by_patient_category(Request $request) { if ($request->start_date) { $start_date = $request->start_date; $end_date = $request->end_date; } else { $start_date = date('Y-m-d h:i:s'); $end_date = date('Y-m-d h:i:s'); } $start_date = Carbon::parse($start_date)->startOfDay(); $end_date = Carbon::parse($end_date)->endOfDay(); $criteria = 'Sales Made Between ' . streamline_date($start_date) . ' And ' . streamline_date($end_date) . ' By Patient Categories'; $patient_categories = DB::table('patient_categories')->whereNull('deleted_at')->orderBy('id', 'asc')->pluck('name', 'id'); // copy array to another to keep track of the money using the keys of the previous array $patient_categories_amounts = array_fill_keys(array_keys($patient_categories->toArray()), 0); // begin to check each deposits table and add the amounts $invoices = DB::table('patient_category_invoices') ->whereNull('deleted_at') ->whereBetween('created_at', [$start_date, $end_date]) ->get(['patient_category', 'patient_amount']); foreach ($invoices as $invoice) { if (isset($patient_categories_amounts[$invoice->patient_category])) { $patient_categories_amounts[$invoice->patient_category] += $invoice->patient_amount; } } $treatments = DB::table('treatment_deposits') ->whereNull('deleted_at') ->whereBetween('created_at', [$start_date, $end_date]) ->get(['patient_id', 'patient_amount_paid']); foreach ($treatments as $record) { $patient_category_id = get_name($record->patient_id, 'id', 'category_id', 'patients'); if (isset($patient_categories_amounts[$patient_category_id])) { $patient_categories_amounts[$patient_category_id] += $record->patient_amount_paid; } } $sundries = DB::table('sundries_deposits') ->whereNull('deleted_at') ->whereBetween('created_at', [$start_date, $end_date]) ->get(['patient_id', 'patient_amount_paid']); foreach ($sundries as $record) { $patient_category_id = get_name($record->patient_id, 'id', 'category_id', 'patients'); if (isset($patient_categories_amounts[$patient_category_id])) { $patient_categories_amounts[$patient_category_id] += $record->patient_amount_paid; } } $optics = DB::table('eye_glasses_deposits') ->whereNull('deleted_at') ->whereBetween('created_at', [$start_date, $end_date]) ->get(['patient_id', 'patient_amount_paid']); foreach ($optics as $record) { $patient_category_id = get_name($record->patient_id, 'id', 'category_id', 'patients'); if (isset($patient_categories_amounts[$patient_category_id])) { $patient_categories_amounts[$patient_category_id] += $record->patient_amount_paid; } } $services = DB::table('service_deposits') ->whereNull('deleted_at') ->whereBetween('created_at', [$start_date, $end_date]) ->get(['patient_id', 'patient_amount_paid']); foreach ($services as $record) { $patient_category_id = get_name($record->patient_id, 'id', 'category_id', 'patients'); if (isset($patient_categories_amounts[$patient_category_id])) { $patient_categories_amounts[$patient_category_id] += $record->patient_amount_paid; } } $procedures = DB::table('procedure_deposits') ->whereNull('deleted_at') ->whereBetween('created_at', [$start_date, $end_date]) ->get(['patient_id', 'patient_amount_paid']); foreach ($procedures as $record) { $patient_category_id = get_name($record->patient_id, 'id', 'category_id', 'patients'); if (isset($patient_categories_amounts[$patient_category_id])) { $patient_categories_amounts[$patient_category_id] += $record->patient_amount_paid; } } $investigations = DB::table('investigation_deposits') ->whereNull('deleted_at') ->whereBetween('created_at', [$start_date, $end_date]) ->get(['patient_id', 'patient_amount_paid']); foreach ($investigations as $record) { $patient_category_id = get_name($record->patient_id, 'id', 'category_id', 'patients'); if (isset($patient_categories_amounts[$patient_category_id])) { $patient_categories_amounts[$patient_category_id] += $record->patient_amount_paid; } } $debtor_payments = DB::table('debtor_payments') ->whereNull('deleted_at') ->whereBetween('created_at', [$start_date, $end_date]) ->get(['patient_id', 'amount_paid']); foreach ($debtor_payments as $record) { $patient_category_id = get_name($record->patient_id, 'id', 'category_id', 'patients'); if (isset($patient_categories_amounts[$patient_category_id])) { $patient_categories_amounts[$patient_category_id] += $record->amount_paid; } } $debt_plans = DB::table('debt_plan') ->whereNull('deleted_at') ->whereBetween('created_at', [$start_date, $end_date]) ->get(['patient_id', 'amount_paid_off']); foreach ($debt_plans as $record) { $patient_category_id = get_name($record->patient_id, 'id', 'category_id', 'patients'); if (isset($patient_categories_amounts[$patient_category_id])) { $patient_categories_amounts[$patient_category_id] += $record->amount_paid_off; } } // combine the arrays here $records = []; $counter = 0; foreach ($patient_categories as $key => $value) { $records[$counter]['id'] = $key; $records[$counter]['name'] = $value; $records[$counter]['amount'] = $patient_categories_amounts[$key]; $counter++; } return view('finance_reports::finance_reports.sales_by_patient_category', compact('criteria', 'records', 'start_date', 'end_date')); } public function get_patient_category_sales_details($id, $start_date, $end_date) { $treatments_total = 0; $consultation_total = 0; $services_total = 0; $inpatient_total = 0; $procedures_total = 0; $investigations_total = 0; $sundries_total = 0; $optics_total = 0; $other_total = 0; $treatments = DB::table('treatment_deposits') ->whereBetween('created_at', [$start_date, $end_date]) ->get(['patient_id', 'patient_amount_paid']); foreach ($treatments as $record) { $patient_category_id = get_name($record->patient_id, 'id', 'category_id', 'patients'); if ($patient_category_id == $id) { $treatments_total += $record->patient_amount_paid; } } $sundries = DB::table('sundries_deposits') ->whereBetween('created_at', [$start_date, $end_date]) ->get(['patient_id', 'patient_amount_paid']); foreach ($sundries as $record) { $patient_category_id = get_name($record->patient_id, 'id', 'category_id', 'patients'); if ($patient_category_id == $id) { $sundries_total += $record->patient_amount_paid; } } $services = DB::table('service_deposits') ->whereBetween('created_at', [$start_date, $end_date]) ->get(['patient_id', 'patient_amount_paid', 'service_type']); foreach ($services as $record) { $patient_category_id = get_name($record->patient_id, 'id', 'category_id', 'patients'); if ($patient_category_id == $id) { switch ($record->service_type) { case "Consultation": $consultation_total += $record->patient_amount_paid; break; case "Services": $services_total += $record->patient_amount_paid; break; case "Inpatient_Deposit": $inpatient_total += $record->patient_amount_paid; break; } } } $procedures = DB::table('procedure_deposits') ->whereBetween('created_at', [$start_date, $end_date]) ->get(['patient_id', 'patient_amount_paid']); foreach ($procedures as $record) { $patient_category_id = get_name($record->patient_id, 'id', 'category_id', 'patients'); if ($patient_category_id == $id) { $procedures_total += $record->patient_amount_paid; } } $investigations = DB::table('investigation_deposits') ->whereBetween('created_at', [$start_date, $end_date]) ->get(['patient_id', 'patient_amount_paid']); foreach ($investigations as $record) { $patient_category_id = get_name($record->patient_id, 'id', 'category_id', 'patients'); if ($patient_category_id == $id) { $investigations_total += $record->patient_amount_paid; } } $optics = DB::table('eye_glasses_deposits') ->whereBetween('created_at', [$start_date, $end_date]) ->get(['patient_id', 'patient_amount_paid']); foreach ($optics as $record) { $patient_category_id = get_name($record->patient_id, 'id', 'category_id', 'patients'); if ($patient_category_id == $id) { $optics_total += $record->patient_amount_paid; } } // begin to check each deposits table and add the amounts $invoices = DB::table('patient_category_invoices') ->whereBetween('created_at', [$start_date, $end_date]) ->where('patient_category', $id) ->get(['tag_id', 'patient_amount']); foreach ($invoices as $invoice) { switch ($invoice->tag_id) { case 2: $investigations_total += $invoice->patient_amount; break; case 3: $treatments_total += $invoice->patient_amount; break; case 4: $procedures_total += $invoice->patient_amount; break; case 5: $sundries_total += $invoice->patient_amount; break; case 6: $consultation_total += $invoice->patient_amount; break; case 8: $services_total += $invoice->patient_amount; break; case 10: $inpatient_total += $invoice->patient_amount; break; } } $debtor_payments = DB::table('debtor_payments') ->leftJoin('debtors', 'debtors.id', '=', 'debtor_payments.debt_id') ->whereNull('debtor_payments.deleted_at') ->whereBetween('debtor_payments.created_at', [$start_date, $end_date]) ->get(['debtor_payments.patient_id', 'debtor_payments.amount_paid', 'debtors.tag_id']); foreach ($debtor_payments as $record) { $patient_category_id = get_name($record->patient_id, 'id', 'category_id', 'patients'); if ($patient_category_id == $id) { switch ($record->tag_id) { case 2: $investigations_total += $record->amount_paid; break; case 3: $treatments_total += $record->amount_paid; break; case 4: $procedures_total += $record->amount_paid; break; case 5: $sundries_total += $record->amount_paid; break; case 6: $consultation_total += $record->amount_paid; break; case 8: $services_total += $record->amount_paid; break; case 10: $other_total += $record->amount_paid; break; } } } $debt_plans = DB::table('debt_plan') ->whereNull('deleted_at') ->whereBetween('created_at', [$start_date, $end_date]) ->get(['patient_id', 'amount_paid_off', 'tag_id']); foreach ($debt_plans as $record) { $patient_category_id = get_name($record->patient_id, 'id', 'category_id', 'patients'); if ($patient_category_id == $id) { switch ($record->tag_id) { case 2: $investigations_total += $record->amount_paid_off; break; case 3: $treatments_total += $record->amount_paid_off; break; case 4: $procedures_total += $record->amount_paid_off; break; case 5: $sundries_total += $record->amount_paid_off; break; case 6: $consultation_total += $record->amount_paid_off; break; case 8: $services_total += $record->amount_paid_off; break; case 10: $other_total += $record->amount_paid_off; break; } } } return json_encode([ "treatments_total" => $treatments_total, "consultation_total" => $consultation_total, "services_total" => $services_total, "inpatient_total" => $inpatient_total, "procedures_total" => $procedures_total, "investigations_total" => $investigations_total, "sundries_total" => $sundries_total, "optics_total" => $optics_total, "other_total" => $other_total ]); } public function accounts_receivable_aging_summary() { $patient_categories = DB::table('patient_discounts')->where(['pay_later' => 1])->pluck('patient_category')->toArray(); $hospital_information = HospitalInformation::first(); $testOrDemoPatientsString = empty(findTestOrDemoPatients()) ? "''" : implode(",", findTestOrDemoPatients()); $invoices_query = "SELECT * FROM patient_category_invoices WHERE deleted_at IS NULL AND (balance_remaining IS NULL OR balance_remaining != 0) ORDER BY patient_category ASC"; $invoices = DB::select($invoices_query); $debtors_query = "SELECT * FROM debtors WHERE deleted_at IS NULL AND ((balance_remaining IS NULL OR balance_remaining > 0) OR amount_paid_off IS NULL) AND patient_id NOT IN (" . $testOrDemoPatientsString . ") ORDER BY patient_id ASC"; $debtors = DB::select($debtors_query); $debt_plans_query = "SELECT * FROM debt_plan WHERE deleted_at IS NULL AND ((balance_remaining IS NULL OR balance_remaining > 0) OR amount_paid_off IS NULL) AND patient_id NOT IN (" . $testOrDemoPatientsString . ") ORDER BY patient_id ASC"; $debt_plans = DB::select($debt_plans_query); $family_accounts_query = "SELECT * FROM family_accounts WHERE deleted_at IS NULL AND current_balance < 0 ORDER BY id ASC"; $family_accounts = DB::select($family_accounts_query); $data = [ 'invoices' => $this->get_invoices_aging_report_data($invoices), 'debtors' => $this->get_debtors_aging_report_data($debtors), 'debt_plans' => $this->get_debt_plans_aging_report_data($debt_plans), 'family_accounts' => $this->get_family_accounts_aging_report_data($family_accounts), ]; return view('finance_reports::finance_reports.accounts.accounts_receivable_aging_summary', compact('hospital_information', 'patient_categories', 'data')); } public function accounts_receivable_aging_detail(Request $request) { $invoices = []; $debtors = []; $debt_plans = []; $family_accounts = []; $patient_categories = DB::table('patient_discounts')->where(['pay_later' => 1])->pluck('patient_category')->toArray(); $hospital_information = HospitalInformation::first(); $patient_category_id = $request->patient_category; if ($patient_category_id == 'All') { $invoices_query = "SELECT * FROM patient_category_invoices WHERE deleted_at IS NULL AND (balance_remaining IS NULL OR balance_remaining > 0) ORDER BY patient_category ASC"; $invoices = DB::select($invoices_query); $debtors_query = "SELECT * FROM debtors WHERE deleted_at IS NULL AND (balance_remaining IS NULL OR balance_remaining > 0) OR amount_paid_off IS NULL ORDER BY patient_id ASC"; $debtors = DB::select($debtors_query); $debt_plans_query = "SELECT * FROM debt_plan WHERE deleted_at IS NULL AND (balance_remaining IS NULL OR balance_remaining > 0) OR amount_paid_off IS NULL ORDER BY patient_id ASC"; $debt_plans = DB::select($debt_plans_query); $family_accounts_query = "SELECT * FROM family_accounts WHERE deleted_at IS NULL AND current_balance < 0 ORDER BY id ASC"; $family_accounts = DB::select($family_accounts_query); } else if ($patient_category_id == 'Debtors') { $debtors_query = "SELECT * FROM debtors WHERE deleted_at IS NULL AND (balance_remaining IS NULL OR balance_remaining > 0) OR amount_paid_off IS NULL ORDER BY patient_id ASC"; $debtors = DB::select($debtors_query); } else if ($patient_category_id == 'DebtPlan') { $debt_plans_query = "SELECT * FROM debt_plan WHERE deleted_at IS NULL AND (balance_remaining IS NULL OR balance_remaining > 0) OR amount_paid_off IS NULL ORDER BY patient_id ASC"; $debt_plans = DB::select($debt_plans_query); } else if ($patient_category_id == 'Family') { $family_accounts_query = "SELECT * FROM family_accounts WHERE deleted_at IS NULL AND current_balance < 0 ORDER BY id ASC"; $family_accounts = DB::select($family_accounts_query); } else if ($patient_category_id != null || $patient_category_id == '') { $invoices_query = "SELECT * FROM patient_category_invoices WHERE deleted_at IS NULL AND patient_category = {$patient_category_id} AND (balance_remaining IS NULL OR balance_remaining > 0) ORDER BY id ASC"; if ($patient_category_id == 0) { $invoices_query = "SELECT * FROM patient_category_invoices WHERE deleted_at IS NULL AND patient_category IS NULL AND (balance_remaining IS NULL OR balance_remaining > 0) ORDER BY id ASC"; } $invoices = DB::select($invoices_query); } $data = [ 'invoices' => $this->get_invoices_aging_report_data($invoices), 'debtors' => $this->get_debtors_aging_report_data($debtors), 'debt_plans' => $this->get_debt_plans_aging_report_data($debt_plans), 'family_accounts' => $this->get_family_accounts_aging_report_data($family_accounts), ]; return view('finance_reports::finance_reports.accounts.accounts_receivable_aging_detail', compact('invoices', 'hospital_information', 'patient_categories', 'data', 'patient_category_id')); } public function get_invoices_aging_report_data($invoices) { $data = []; $today = Carbon::today()->toDateTimeString(); $today_minus_thirty = Carbon::today()->subDays(30)->toDateTimeString(); $today_minus_sixty = Carbon::today()->subDays(60)->toDateTimeString(); $today_minus_ninety = Carbon::today()->subDays(90)->toDateTimeString(); foreach ($invoices as $invoice) { $balance = is_null($invoice->balance_remaining) ? (int)$invoice->patient_amount - (int)$invoice->amount_paid_off : (int)$invoice->balance_remaining; $created_at = Carbon::parse($invoice->created_at)->toDateTimeString(); if ($created_at >= $today) { if (isset($data[$invoice->patient_category]['current'])) { if ($invoice->invoice_generated == 1) { if (isset($data[$invoice->patient_category]['current']['generated'])) { $data[$invoice->patient_category]['current']['generated'] += $balance; } else { $data[$invoice->patient_category]['current']['generated'] = $balance; } } else { if (isset($data[$invoice->patient_category]['current']['not_generated'])) { $data[$invoice->patient_category]['current']['not_generated'] += $balance; } else { $data[$invoice->patient_category]['current']['not_generated'] = $balance; } } } else { if ($invoice->invoice_generated == 1) { $data[$invoice->patient_category]['current']['generated'] = $balance; } else { $data[$invoice->patient_category]['current']['not_generated'] = $balance; } $data[$invoice->patient_category]['current_invoices']['generated'] = []; $data[$invoice->patient_category]['current_invoices']['not_generated'] = []; } if ($invoice->invoice_generated == 1) { array_push($data[$invoice->patient_category]['current_invoices']['generated'], ["id" => $invoice->id, "patient_id" => $invoice->patient_id, "created_at" => $created_at, "invoice_date" => $invoice->invoice_date, "receipt_number" => $invoice->receipt_number, "invoice_number" => $invoice->invoice_number, "balance" => $balance, "category" => "current"]); } else { array_push($data[$invoice->patient_category]['current_invoices']['not_generated'], ["id" => $invoice->id, "patient_id" => $invoice->patient_id, "created_at" => $created_at, "invoice_date" => $invoice->invoice_date, "receipt_number" => $invoice->receipt_number, "invoice_number" => $invoice->invoice_number, "balance" => $balance, "category" => "current"]); } } elseif ($created_at < $today && $created_at >= $today_minus_thirty) { if (isset($data[$invoice->patient_category]['one_to_thirty'])) { if ($invoice->invoice_generated == 1) { if (isset($data[$invoice->patient_category]['one_to_thirty']['generated'])) { $data[$invoice->patient_category]['one_to_thirty']['generated'] += $balance; } else { $data[$invoice->patient_category]['one_to_thirty']['generated'] = $balance; } } else { if (isset($data[$invoice->patient_category]['one_to_thirty']['not_generated'])) { $data[$invoice->patient_category]['one_to_thirty']['not_generated'] += $balance; } else { $data[$invoice->patient_category]['one_to_thirty']['not_generated'] = $balance; } } } else { if ($invoice->invoice_generated == 1) { $data[$invoice->patient_category]['one_to_thirty']['generated'] = $balance; } else { $data[$invoice->patient_category]['one_to_thirty']['not_generated'] = $balance; } $data[$invoice->patient_category]['one_to_thirty_invoices']['generated'] = []; $data[$invoice->patient_category]['one_to_thirty_invoices']['not_generated'] = []; } if ($invoice->invoice_generated == 1) { array_push($data[$invoice->patient_category]['one_to_thirty_invoices']['generated'], ["id" => $invoice->id, "patient_id" => $invoice->patient_id, "created_at" => $created_at, "invoice_date" => $invoice->invoice_date, "receipt_number" => $invoice->receipt_number, "invoice_number" => $invoice->invoice_number, "balance" => $balance, "category" => "one_to_thirty"]); } else { array_push($data[$invoice->patient_category]['one_to_thirty_invoices']['not_generated'], ["id" => $invoice->id, "patient_id" => $invoice->patient_id, "created_at" => $created_at, "invoice_date" => $invoice->invoice_date, "receipt_number" => $invoice->receipt_number, "invoice_number" => $invoice->invoice_number, "balance" => $balance, "category" => "one_to_thirty"]); } } elseif ($created_at < $today_minus_thirty && $created_at >= $today_minus_sixty) { if (isset($data[$invoice->patient_category]['thirty_one_to_sixty'])) { if ($invoice->invoice_generated == 1) { if (isset($data[$invoice->patient_category]['thirty_one_to_sixty']['generated'])) { $data[$invoice->patient_category]['thirty_one_to_sixty']['generated'] += $balance; } else { $data[$invoice->patient_category]['thirty_one_to_sixty']['generated'] = $balance; } } else { if (isset($data[$invoice->patient_category]['thirty_one_to_sixty']['not_generated'])) { $data[$invoice->patient_category]['thirty_one_to_sixty']['not_generated'] += $balance; } else { $data[$invoice->patient_category]['thirty_one_to_sixty']['not_generated'] = $balance; } } } else { if ($invoice->invoice_generated == 1) { $data[$invoice->patient_category]['thirty_one_to_sixty']['generated'] = $balance; } else { $data[$invoice->patient_category]['thirty_one_to_sixty']['not_generated'] = $balance; } $data[$invoice->patient_category]['thirty_one_to_sixty_invoices']['generated'] = []; $data[$invoice->patient_category]['thirty_one_to_sixty_invoices']['not_generated'] = []; } if ($invoice->invoice_generated == 1) { array_push($data[$invoice->patient_category]['thirty_one_to_sixty_invoices']['generated'], ["id" => $invoice->id, "patient_id" => $invoice->patient_id, "created_at" => $created_at, "invoice_date" => $invoice->invoice_date, "receipt_number" => $invoice->receipt_number, "invoice_number" => $invoice->invoice_number, "balance" => $balance, "category" => "thirty_one_to_sixty"]); } else { array_push($data[$invoice->patient_category]['thirty_one_to_sixty_invoices']['not_generated'], ["id" => $invoice->id, "patient_id" => $invoice->patient_id, "created_at" => $created_at, "invoice_date" => $invoice->invoice_date, "receipt_number" => $invoice->receipt_number, "invoice_number" => $invoice->invoice_number, "balance" => $balance, "category" => "thirty_one_to_sixty"]); } } elseif ($created_at < $today_minus_sixty && $created_at >= $today_minus_ninety) { if (isset($data[$invoice->patient_category]['sixty_one_to_ninety'])) { if ($invoice->invoice_generated == 1) { if (isset($data[$invoice->patient_category]['sixty_one_to_ninety']['generated'])) { $data[$invoice->patient_category]['sixty_one_to_ninety']['generated'] += $balance; } else { $data[$invoice->patient_category]['sixty_one_to_ninety']['generated'] = $balance; } } else { if (isset($data[$invoice->patient_category]['sixty_one_to_ninety']['not_generated'])) { $data[$invoice->patient_category]['sixty_one_to_ninety']['not_generated'] += $balance; } else { $data[$invoice->patient_category]['sixty_one_to_ninety']['not_generated'] = $balance; } } } else { if ($invoice->invoice_generated == 1) { $data[$invoice->patient_category]['sixty_one_to_ninety']['generated'] = $balance; } else { $data[$invoice->patient_category]['sixty_one_to_ninety']['not_generated'] = $balance; } $data[$invoice->patient_category]['sixty_one_to_ninety_invoices']['generated'] = []; $data[$invoice->patient_category]['sixty_one_to_ninety_invoices']['not_generated'] = []; } if ($invoice->invoice_generated == 1) { array_push($data[$invoice->patient_category]['sixty_one_to_ninety_invoices']['generated'], ["id" => $invoice->id, "patient_id" => $invoice->patient_id, "created_at" => $created_at, "invoice_date" => $invoice->invoice_date, "receipt_number" => $invoice->receipt_number, "invoice_number" => $invoice->invoice_number, "balance" => $balance, "category" => "sixty_one_to_ninety"]); } else { array_push($data[$invoice->patient_category]['sixty_one_to_ninety_invoices']['not_generated'], ["id" => $invoice->id, "patient_id" => $invoice->patient_id, "created_at" => $created_at, "invoice_date" => $invoice->invoice_date, "receipt_number" => $invoice->receipt_number, "invoice_number" => $invoice->invoice_number, "balance" => $balance, "category" => "sixty_one_to_ninety"]); } } elseif ($created_at < $today_minus_ninety) { if (isset($data[$invoice->patient_category]['ninety_one_and_over'])) { if ($invoice->invoice_generated == 1) { if (isset($data[$invoice->patient_category]['ninety_one_and_over']['generated'])) { $data[$invoice->patient_category]['ninety_one_and_over']['generated'] += $balance; } else { $data[$invoice->patient_category]['ninety_one_and_over']['generated'] = $balance; } } else { if (isset($data[$invoice->patient_category]['ninety_one_and_over']['not_generated'])) { $data[$invoice->patient_category]['ninety_one_and_over']['not_generated'] += $balance; } else { $data[$invoice->patient_category]['ninety_one_and_over']['not_generated'] = $balance; } } } else { if ($invoice->invoice_generated == 1) { $data[$invoice->patient_category]['ninety_one_and_over']['generated'] = $balance; } else { $data[$invoice->patient_category]['ninety_one_and_over']['not_generated'] = $balance; } $data[$invoice->patient_category]['ninety_one_and_over_invoices']['generated'] = []; $data[$invoice->patient_category]['ninety_one_and_over_invoices']['not_generated'] = []; } if ($invoice->invoice_generated == 1) { array_push($data[$invoice->patient_category]['ninety_one_and_over_invoices']['generated'], ["id" => $invoice->id, "patient_id" => $invoice->patient_id, "created_at" => $created_at, "invoice_date" => $invoice->invoice_date, "receipt_number" => $invoice->receipt_number, "invoice_number" => $invoice->invoice_number, "balance" => $balance, "category" => "ninety_one_and_over"]); } else { array_push($data[$invoice->patient_category]['ninety_one_and_over_invoices']['not_generated'], ["id" => $invoice->id, "patient_id" => $invoice->patient_id, "created_at" => $created_at, "invoice_date" => $invoice->invoice_date, "receipt_number" => $invoice->receipt_number, "invoice_number" => $invoice->invoice_number, "balance" => $balance, "category" => "ninety_one_and_over"]); } } } return $data; } public function get_debtors_aging_report_data($debtors) { $data = []; $today = Carbon::today()->toDateTimeString(); $today_minus_thirty = Carbon::today()->subDays(30)->toDateTimeString(); $today_minus_sixty = Carbon::today()->subDays(60)->toDateTimeString(); $today_minus_ninety = Carbon::today()->subDays(90)->toDateTimeString(); foreach ($debtors as $debtor) { $balance = is_null($debtor->balance_remaining) ? (int)$debtor->balance : (int)$debtor->balance_remaining; if ($debtor->created_at >= $today) { if (isset($data[$debtor->patient_id]['current'])) { $data[$debtor->patient_id]['current'] += $balance; } else { $data[$debtor->patient_id]['current_debtors'] = $balance; $data[$debtor->patient_id]['current_debtors'] = []; } array_push($data[$debtor->patient_id]['current_debtors'], ["id" => $debtor->id, "balance" => $balance, "created_at" => $debtor->created_at, "created_by" => $debtor->created_by, "receipt_number" => $debtor->receipt_number, "category" => "current"]); } elseif ($debtor->created_at < $today && $debtor->created_at >= $today_minus_thirty) { if (isset($data[$debtor->patient_id]['one_to_thirty'])) { $data[$debtor->patient_id]['one_to_thirty'] += $balance; } else { $data[$debtor->patient_id]['one_to_thirty'] = $balance; $data[$debtor->patient_id]['one_to_thirty_debtors'] = []; } array_push($data[$debtor->patient_id]['one_to_thirty_debtors'], ["id" => $debtor->id, "balance" => $balance, "created_at" => $debtor->created_at, "created_by" => $debtor->created_by, "receipt_number" => $debtor->receipt_number, "category" => "one_to_thirty"]); } elseif ($debtor->created_at < $today_minus_thirty && $debtor->created_at >= $today_minus_sixty) { if (isset($data[$debtor->patient_id]['thirty_one_to_sixty'])) { $data[$debtor->patient_id]['thirty_one_to_sixty'] += $balance; } else { $data[$debtor->patient_id]['thirty_one_to_sixty'] = $balance; $data[$debtor->patient_id]['thirty_one_to_sixty_debtors'] = []; } array_push($data[$debtor->patient_id]['thirty_one_to_sixty_debtors'], ["id" => $debtor->id, "balance" => $balance, "created_at" => $debtor->created_at, "created_by" => $debtor->created_by, "receipt_number" => $debtor->receipt_number, "category" => "thirty_one_to_sixty"]); } elseif ($debtor->created_at < $today_minus_sixty && $debtor->created_at >= $today_minus_ninety) { if (isset($data[$debtor->patient_id]['sixty_one_to_ninety'])) { $data[$debtor->patient_id]['sixty_one_to_ninety'] += $balance; } else { $data[$debtor->patient_id]['sixty_one_to_ninety'] = $balance; $data[$debtor->patient_id]['sixty_one_to_ninety_debtors'] = []; } array_push($data[$debtor->patient_id]['sixty_one_to_ninety_debtors'], ["id" => $debtor->id, "balance" => $balance, "created_at" => $debtor->created_at, "created_by" => $debtor->created_by, "receipt_number" => $debtor->receipt_number, "category" => "sixty_one_to_ninety"]); } elseif ($debtor->created_at < $today_minus_ninety) { if (isset($data[$debtor->patient_id]['ninety_one_and_over'])) { $data[$debtor->patient_id]['ninety_one_and_over'] += $balance; } else { $data[$debtor->patient_id]['ninety_one_and_over'] = $balance; $data[$debtor->patient_id]['ninety_one_and_over_debtors'] = []; } array_push($data[$debtor->patient_id]['ninety_one_and_over_debtors'], ["id" => $debtor->id, "balance" => $balance, "created_at" => $debtor->created_at, "created_by" => $debtor->created_by, "receipt_number" => $debtor->receipt_number, "category" => "ninety_one_and_over"]); } } return $data; } public function get_debt_plans_aging_report_data($debt_plans) { $data = []; $today = Carbon::today()->toDateTimeString(); $today_minus_thirty = Carbon::today()->subDays(30)->toDateTimeString(); $today_minus_sixty = Carbon::today()->subDays(60)->toDateTimeString(); $today_minus_ninety = Carbon::today()->subDays(90)->toDateTimeString(); foreach ($debt_plans as $debt_plan) { $balance = is_null($debt_plan->balance_remaining) ? ((int)$debt_plan->staff_guarantor_to_pay > 0 ? (int)$debt_plan->staff_guarantor_to_pay : (int)$debt_plan->amount_owed) : (int)$debt_plan->balance_remaining; if ($debt_plan->created_at >= $today) { if (isset($data[$debt_plan->patient_id]['current'])) { $data[$debt_plan->patient_id]['current'] += $balance; } else { $data[$debt_plan->patient_id]['current_debt_plans'] = $balance; $data[$debt_plan->patient_id]['current_debt_plans'] = []; } array_push($data[$debt_plan->patient_id]['current_debt_plans'], ["id" => $debt_plan->id, "balance" => $balance, "created_at" => $debt_plan->created_at, "staff_guarantor" => $debt_plan->staff_guarantor, "authorised_by" => $debt_plan->authorised_by, "category" => "current"]); } elseif ($debt_plan->created_at < $today && $debt_plan->created_at >= $today_minus_thirty) { if (isset($data[$debt_plan->patient_id]['one_to_thirty'])) { $data[$debt_plan->patient_id]['one_to_thirty'] += $balance; } else { $data[$debt_plan->patient_id]['one_to_thirty'] = $balance; $data[$debt_plan->patient_id]['one_to_thirty_debt_plans'] = []; } array_push($data[$debt_plan->patient_id]['one_to_thirty_debt_plans'], ["id" => $debt_plan->id, "balance" => $balance, "created_at" => $debt_plan->created_at, "staff_guarantor" => $debt_plan->staff_guarantor, "authorised_by" => $debt_plan->authorised_by, "category" => "one_to_thirty"]); } elseif ($debt_plan->created_at < $today_minus_thirty && $debt_plan->created_at >= $today_minus_sixty) { if (isset($data[$debt_plan->patient_id]['thirty_one_to_sixty'])) { $data[$debt_plan->patient_id]['thirty_one_to_sixty'] += $balance; } else { $data[$debt_plan->patient_id]['thirty_one_to_sixty'] = $balance; $data[$debt_plan->patient_id]['thirty_one_to_sixty_debt_plans'] = []; } array_push($data[$debt_plan->patient_id]['thirty_one_to_sixty_debt_plans'], ["id" => $debt_plan->id, "balance" => $balance, "created_at" => $debt_plan->created_at, "staff_guarantor" => $debt_plan->staff_guarantor, "authorised_by" => $debt_plan->authorised_by, "category" => "thirty_one_to_sixty"]); } elseif ($debt_plan->created_at < $today_minus_sixty && $debt_plan->created_at >= $today_minus_ninety) { if (isset($data[$debt_plan->patient_id]['sixty_one_to_ninety'])) { $data[$debt_plan->patient_id]['sixty_one_to_ninety'] += $balance; } else { $data[$debt_plan->patient_id]['sixty_one_to_ninety'] = $balance; $data[$debt_plan->patient_id]['sixty_one_to_ninety_debt_plans'] = []; } array_push($data[$debt_plan->patient_id]['sixty_one_to_ninety_debt_plans'], ["id" => $debt_plan->id, "balance" => $balance, "created_at" => $debt_plan->created_at, "staff_guarantor" => $debt_plan->staff_guarantor, "authorised_by" => $debt_plan->authorised_by, "category" => "sixty_one_to_ninety"]); } elseif ($debt_plan->created_at < $today_minus_ninety) { if (isset($data[$debt_plan->patient_id]['ninety_one_and_over'])) { $data[$debt_plan->patient_id]['ninety_one_and_over'] += $balance; } else { $data[$debt_plan->patient_id]['ninety_one_and_over'] = $balance; $data[$debt_plan->patient_id]['ninety_one_and_over_debt_plans'] = []; } array_push($data[$debt_plan->patient_id]['ninety_one_and_over_debt_plans'], ["id" => $debt_plan->id, "balance" => $balance, "created_at" => $debt_plan->created_at, "staff_guarantor" => $debt_plan->staff_guarantor, "authorised_by" => $debt_plan->authorised_by, "category" => "ninety_one_and_over"]); } } return $data; } public function get_family_accounts_aging_report_data($family_accounts) { $data = []; $today = Carbon::today()->toDateTimeString(); $today_minus_thirty = Carbon::today()->subDays(30)->toDateTimeString(); $today_minus_sixty = Carbon::today()->subDays(60)->toDateTimeString(); $today_minus_ninety = Carbon::today()->subDays(90)->toDateTimeString(); foreach ($family_accounts as $family_account) { $balance = (int)$family_account->current_balance * -1; if ($family_account->created_at >= $today) { if (isset($data[$family_account->family_head_id]['current'])) { $data[$family_account->family_head_id]['current'] += $balance; } else { $data[$family_account->family_head_id]['current'] = $balance; $data[$family_account->family_head_id]['current_family_accounts'] = []; } array_push($data[$family_account->family_head_id]['current_family_accounts'], ["id" => $family_account->id, "balance" => $balance, "created_at" => $family_account->created_at, "created_by" => $family_account->created_by, "family_head_id" => $family_account->family_head_id, "category" => "current"]); } elseif ($family_account->created_at < $today && $family_account->created_at >= $today_minus_thirty) { if (isset($data[$family_account->family_head_id]['one_to_thirty'])) { $data[$family_account->family_head_id]['one_to_thirty'] += $balance; } else { $data[$family_account->family_head_id]['one_to_thirty'] = $balance; $data[$family_account->family_head_id]['one_to_thirty_family_accounts'] = []; } array_push($data[$family_account->family_head_id]['one_to_thirty_family_accounts'], ["id" => $family_account->id, "balance" => $balance, "created_at" => $family_account->created_at, "created_by" => $family_account->created_by, "family_head_id" => $family_account->family_head_id, "category" => "one_to_thirty"]); } elseif ($family_account->created_at < $today_minus_thirty && $family_account->created_at >= $today_minus_sixty) { if (isset($data[$family_account->family_head_id]['thirty_one_to_sixty'])) { $data[$family_account->family_head_id]['thirty_one_to_sixty'] += $balance; } else { $data[$family_account->family_head_id]['thirty_one_to_sixty'] = $balance; $data[$family_account->family_head_id]['thirty_one_to_sixty_family_accounts'] = []; } array_push($data[$family_account->family_head_id]['thirty_one_to_sixty_family_accounts'], ["id" => $family_account->id, "balance" => $balance, "created_at" => $family_account->created_at, "created_by" => $family_account->created_by, "family_head_id" => $family_account->family_head_id, "category" => "thirty_one_to_sixty"]); } elseif ($family_account->created_at < $today_minus_sixty && $family_account->created_at >= $today_minus_ninety) { if (isset($data[$family_account->family_head_id]['sixty_one_to_ninety'])) { $data[$family_account->family_head_id]['sixty_one_to_ninety'] += $balance; } else { $data[$family_account->family_head_id]['sixty_one_to_ninety'] = $balance; $data[$family_account->family_head_id]['sixty_one_to_ninety_family_accounts'] = []; } array_push($data[$family_account->family_head_id]['sixty_one_to_ninety_family_accounts'], ["id" => $family_account->id, "balance" => $balance, "created_at" => $family_account->created_at, "created_by" => $family_account->created_by, "family_head_id" => $family_account->family_head_id, "category" => "sixty_one_to_ninety"]); } elseif ($family_account->created_at < $today_minus_ninety) { if (isset($data[$family_account->family_head_id]['ninety_one_and_over'])) { $data[$family_account->family_head_id]['ninety_one_and_over'] += $balance; } else { $data[$family_account->family_head_id]['ninety_one_and_over'] = $balance; $data[$family_account->family_head_id]['ninety_one_and_over_family_accounts'] = []; } array_push($data[$family_account->family_head_id]['ninety_one_and_over_family_accounts'], ["id" => $family_account->id, "balance" => $balance, "created_at" => $family_account->created_at, "created_by" => $family_account->created_by, "family_head_id" => $family_account->family_head_id, "category" => "ninety_one_and_over"]); } } return $data; } public function print_accounts_receivable_aging_summary(Request $request) { $invoices_query = "SELECT * FROM patient_category_invoices WHERE deleted_at IS NULL AND (balance_remaining IS NULL OR balance_remaining > 0) ORDER BY patient_category ASC"; $invoices = DB::select($invoices_query); $debtors_query = "SELECT * FROM debtors WHERE deleted_at IS NULL AND (balance_remaining IS NULL OR balance_remaining > 0) OR amount_paid_off IS NULL ORDER BY patient_id ASC"; $debtors = DB::select($debtors_query); $debt_plans_query = "SELECT * FROM debt_plan WHERE deleted_at IS NULL AND (balance_remaining IS NULL OR balance_remaining > 0) OR amount_paid_off IS NULL ORDER BY patient_id ASC"; $debt_plans = DB::select($debt_plans_query); $family_accounts_query = "SELECT * FROM family_accounts WHERE deleted_at IS NULL AND current_balance < 0 ORDER BY id ASC"; $family_accounts = DB::select($family_accounts_query); $data = [ "data" => [ 'invoices' => $this->get_invoices_aging_report_data($invoices), 'debtors' => $this->get_debtors_aging_report_data($debtors), 'debt_plans' => $this->get_debt_plans_aging_report_data($debt_plans), 'family_accounts' => $this->get_family_accounts_aging_report_data($family_accounts), ] ]; $pdf = SnappyPDF::loadView("finance_reports::finance_reports/print_accounts_receivable_aging_summary", $data) ->setOrientation('landscape') ->setPaper('a4') ->setOption('margin-bottom', 10) ->setOption('margin-top', 5) ->setOption('footer-html', '© ' . date('Y') . ' Stre@mline') ->setOption('footer-right', '[page] of [toPage]'); return $pdf->inline('Accounts Receivable Aging Summary Report - ' . date("d-m-y h:ia") . '.pdf'); } public function print_accounts_receivable_aging_detail(Request $request) { $debtors = []; $debt_plans = []; $family_accounts = []; $patient_category_id = $request->patient_category; if ($patient_category_id == 'All') { $invoices_query = "SELECT * FROM patient_category_invoices WHERE deleted_at IS NULL AND (balance_remaining IS NULL OR balance_remaining > 0) ORDER BY patient_category ASC"; $invoices = DB::select($invoices_query); $debtors_query = "SELECT * FROM debtors WHERE deleted_at IS NULL AND (balance_remaining IS NULL OR balance_remaining > 0) OR amount_paid_off IS NULL ORDER BY patient_id ASC"; $debtors = DB::select($debtors_query); $debt_plans_query = "SELECT * FROM debt_plan WHERE deleted_at IS NULL AND (balance_remaining IS NULL OR balance_remaining > 0) OR amount_paid_off IS NULL ORDER BY patient_id ASC"; $debt_plans = DB::select($debt_plans_query); $family_accounts_query = "SELECT * FROM family_accounts WHERE deleted_at IS NULL AND current_balance < 0 ORDER BY id ASC"; $family_accounts = DB::select($family_accounts_query); } else if ($patient_category_id == 'Debtors') { $debtors_query = "SELECT * FROM debtors WHERE deleted_at IS NULL AND (balance_remaining IS NULL OR balance_remaining > 0) OR amount_paid_off IS NULL ORDER BY patient_id ASC"; $debtors = DB::select($debtors_query); } else if ($patient_category_id == 'DebtPlan') { $debt_plans_query = "SELECT * FROM debt_plan WHERE deleted_at IS NULL AND (balance_remaining IS NULL OR balance_remaining > 0) OR amount_paid_off IS NULL ORDER BY patient_id ASC"; $debt_plans = DB::select($debt_plans_query); } else if ($patient_category_id == 'Family') { $family_accounts_query = "SELECT * FROM family_accounts WHERE deleted_at IS NULL AND current_balance < 0 ORDER BY id ASC"; $family_accounts = DB::select($family_accounts_query); } else if ($patient_category_id != null || $patient_category_id == '') { $invoices_query = "SELECT * FROM patient_category_invoices WHERE deleted_at IS NULL AND patient_category = {$patient_category_id} AND (balance_remaining IS NULL OR balance_remaining > 0) ORDER BY id ASC"; if ($patient_category_id == 0) { $invoices_query = "SELECT * FROM patient_category_invoices WHERE deleted_at IS NULL AND patient_category IS NULL AND (balance_remaining IS NULL OR balance_remaining > 0) ORDER BY id ASC"; } $invoices = DB::select($invoices_query); } $data = [ "data" => [ 'invoices' => $this->get_invoices_aging_report_data($invoices), 'debtors' => $this->get_debtors_aging_report_data($debtors), 'debt_plans' => $this->get_debt_plans_aging_report_data($debt_plans), 'family_accounts' => $this->get_family_accounts_aging_report_data($family_accounts), ] ]; $pdf = SnappyPDF::loadView("finance_reports::finance_reports/print_accounts_receivable_aging_detail", $data) ->setOrientation('landscape') ->setPaper('a4') ->setOption('margin-bottom', 10) ->setOption('margin-top', 5) ->setOption('footer-html', '© ' . date('Y') . ' Stre@mline') ->setOption('footer-right', '[page] of [toPage]'); return $pdf->inline('Accounts Receivable Aging Detail Report - ' . date("d-m-y h:ia") . '.pdf'); } public function patient_accounts_sales_details(Request $request) { $staff_member = $request->user_id; if ($request->date_type == "yesterday") { $end_date = Carbon::yesterday()->endOfDay(); $start_date = Carbon::yesterday()->startOfDay(); } else if ($request->date_type == "custom_date") { $dates = explode("/", $request->dates); $end_date = Carbon::parse($dates[0])->endOfDay(); $start_date = Carbon::parse($dates[0])->startOfDay(); } else if ($request->date_type == "custom_date_range") { $dates = explode("/", $request->dates); $end_date = Carbon::parse($dates[1])->endOfDay(); $start_date = Carbon::parse($dates[0])->startOfDay(); } else { $end_date = Carbon::today()->endOfDay(); $start_date = Carbon::today()->startOfDay(); } if ($staff_member == 0) { $patient_consumptions = PatientAccountConsumption::whereBetween('created_at', [$start_date, $end_date])->get(); } else { $patient_consumptions = PatientAccountConsumption::whereBetween('created_at', [$start_date, $end_date])->where('created_by', $staff_member)->get(); } $reg_date = $start_date; $patient_numbers = DB::table('patients')->orderBy('number')->distinct()->pluck('number'); return view('patient_discounts::patient_accounts.consumptions_report', compact('patient_consumptions', 'reg_date', 'start_date', 'end_date', 'patient_numbers')); } public function patient_accounts_deposits_details(Request $request) { $staff_member = $request->user_id; if ($request->date_type == "yesterday") { $end_date = Carbon::yesterday()->endOfDay(); $start_date = Carbon::yesterday()->startOfDay(); } else if ($request->date_type == "custom_date") { $dates = explode("/", $request->dates); $end_date = Carbon::parse($dates[0])->endOfDay(); $start_date = Carbon::parse($dates[0])->startOfDay(); } else if ($request->date_type == "custom_date_range") { $dates = explode("/", $request->dates); $end_date = Carbon::parse($dates[1])->endOfDay(); $start_date = Carbon::parse($dates[0])->startOfDay(); } else { $end_date = Carbon::today()->endOfDay(); $start_date = Carbon::today()->startOfDay(); } if ($staff_member == 0) { $patient_deposits = PatientAccountsDeposit::whereBetween('created_at', [$start_date, $end_date])->get(); } else { $patient_deposits = PatientAccountsDeposit::whereBetween('created_at', [$start_date, $end_date])->where('created_by', $staff_member)->get(); } $reg_date = $start_date; $patient_numbers = DB::table('patients')->orderBy('number')->distinct()->pluck('number'); return view('patient_discounts::patient_accounts.deposits_report', compact('patient_deposits', 'reg_date', 'start_date', 'end_date', 'patient_numbers')); } public function direct_bank_deposits_details(Request $request) { if ($request->date_type == "yesterday") { $end = Carbon::yesterday()->endOfDay(); $start = Carbon::yesterday()->startOfDay(); } else if ($request->date_type == "custom_date") { $dates = explode("/", $request->dates); $end = Carbon::parse($dates[0])->endOfDay(); $start = Carbon::parse($dates[0])->startOfDay(); } else if ($request->date_type == "custom_date_range") { $dates = explode("/", $request->dates); $end = Carbon::parse($dates[1])->endOfDay(); $start = Carbon::parse($dates[0])->startOfDay(); } else { $end = Carbon::today()->endOfDay(); $start = Carbon::today()->startOfDay(); } $filters = []; if ($request->user_id != 0) { $filters[] = ['created_by', '=', $request->user_id]; } $direct_deposits = DB::table('other_incomes') ->whereNull('deleted_at') ->where('deposit_memo', 'NOT LIKE', '%Stock reconciliation%') ->whereBetween('deposit_date', [$start, $end]) ->where($filters) ->get(); return view('finance_reports::finance_reports.otherIncomes', compact('direct_deposits', 'start', 'end')); } public function check_if_cash_is_direct_deposit(Request $request) { $cashier_income_id = $request->cashier_income_id; $other_income_record = OtherIncome::where('received',$cashier_income_id)->first(); if ($other_income_record) { return true; } return false; } public function delete_direct_deposit_from_cashier_income($id) { $track_receipt = new TrackReceipt; $track_receipt->reason = "deduction from undeposited funds."; $track_receipt->created_by = Auth::id(); $track_receipt->save(); $receipt_number = sprintf("%04u", $track_receipt->id); $received_cash = CashierIncome::where('id', $id)->first(); if ($received_cash) { $undeposited_funds_account_id = get_name("undeposited_funds", "slug", "id", "chart_of_accounts"); //$latest_undeposited_funds_bank_record = get_latest_banking_record_based_on_transaction_date($undeposited_funds_account_id, Carbon::now()); //if cashier income has already been update with 'received' as null, the only link remaining with cashier_income and other_incomes table can only be with cashier_incomes.reason == other_incomes.deposit_memo, brought_by=created_by $other_incomes = OtherIncome::where('received',$id)->get(); if (count($other_incomes) > 0) { foreach ($other_incomes as $record) { $transaction_id_string = sprintf("%04u", $record->trans_id); //how banking table stores it using sprintf() $bank_records = Banking::where('bank', $undeposited_funds_account_id) ->where('trans_id', $transaction_id_string) //->where('credit', $record->deposit_amount) ->whereNull('deleted_at') ->get(); if (count($bank_records) > 0) { foreach ($bank_records as $bank_record) { $new_memo = $bank_record->memo . " (Deleted by " . get_name(Auth::id(), 'id', 'username', 'users') . ")"; $bank_record->memo = $new_memo; $bank_record->update(); if ($bank_record->delete()) : $orderByCreatedAtIfTransDateIsTheSame = "created_at ASC"; $orderByIdIfTransDateIsTheSame = "id ASC"; $previous_bank_record = Banking::where('bank', $bank_record->bank) ->whereNull('deleted_at') ->where('trans_date', '<', $bank_record->trans_date) ->orderBy('trans_date', 'asc') ->orderByRaw($orderByCreatedAtIfTransDateIsTheSame) ->orderByRaw($orderByIdIfTransDateIsTheSame) ->first(); if ($previous_bank_record) { update_banking_record_balances(Carbon::parse($previous_bank_record->trans_date)->toDateString(), $bank_record->bank, $previous_bank_record->id, $previous_bank_record->account_balance); } else { //there exists no previous record i.e what we deleted is the first bank record so let bal = $balance_to_use_for_updating = 0;//$bank_record->account_balance; update_banking_record_balances(Carbon::parse($bank_record->trans_date)->toDateString(), $bank_record->bank, $bank_record->id, $balance_to_use_for_updating); } flash("Money has been deleted successfully from Bank: " . get_name($bank_record->bank, 'id', 'name', 'chart_of_accounts'))->success(); endif; } } //delete the money from the other_incomes table $record->delete(); } } if ($received_cash->delete()) : flash("Received direct income has been deducted from undeposited funds.")->success(); endif; } else{ flash('Sorry, system could not find the received money')->error(); } return redirect()->route('finance_reports.received_cash'); } public function clean_equities_transaction_date() { $equities = Equity::all(); foreach ($equities as $equity) { $equity->transaction_date = $equity->created_at; $equity->update(); //pick the equity and update it with the journal date if it was journaled if (str_contains($equity, 'Journal (')) { $journal_number = getStringBetweenCharacters($equity->name,"(",")"); $journal = Journal::find($journal_number); if($journal){ //update the equity record's transaction date with the date it was journaled $equity->transaction_date = $journal->journal_date; $equity->update(); } } } return "equities cleaned"; } public function custom_debtors($category) { $debtors = []; $today = Carbon::today()->toDateTimeString(); $today_minus_thirty = Carbon::today()->subDays(30)->toDateTimeString(); $today_minus_sixty = Carbon::today()->subDays(60)->toDateTimeString(); $today_minus_ninety = Carbon::today()->subDays(90)->toDateTimeString(); $chart_of_account = get_name('accounts_receivables', 'slug', 'id', 'chart_of_accounts'); $title = get_name($chart_of_account, 'id', 'name', 'chart_of_accounts'); $title .= ' - (Debtors)'; switch ($category) { case 'current_debtors': $title .= " for today, the " . streamline_date($today); $debtors_query = "SELECT * FROM debtors WHERE deleted_at IS NULL AND ((balance_remaining IS NULL OR balance_remaining > 0) OR amount_paid_off IS NULL) AND created_at >= '{$today}' ORDER BY patient_id ASC"; $debtors = DB::select($debtors_query); break; case 'one_to_thirty_debtors': $title .= " from " . streamline_date($today_minus_thirty) . " to " . streamline_date($today); $debtors_query = "SELECT * FROM debtors WHERE deleted_at IS NULL AND ((balance_remaining IS NULL OR balance_remaining > 0) OR amount_paid_off IS NULL) AND created_at BETWEEN '{$today_minus_thirty}' AND '{$today}' ORDER BY patient_id ASC"; $debtors = DB::select($debtors_query); break; case 'thirty_one_to_sixty_debtors': $title .= " from " . streamline_date($today_minus_sixty) . " to " . streamline_date($today_minus_thirty); $debtors_query = "SELECT * FROM debtors WHERE deleted_at IS NULL AND ((balance_remaining IS NULL OR balance_remaining > 0) OR amount_paid_off IS NULL) AND created_at BETWEEN '{$today_minus_sixty}' AND '{$today_minus_thirty}' ORDER BY patient_id ASC"; $debtors = DB::select($debtors_query); break; case 'sixty_one_to_ninety_debtors': $title .= " from " . streamline_date($today_minus_ninety) . " to " . streamline_date($today_minus_sixty); $debtors_query = "SELECT * FROM debtors WHERE deleted_at IS NULL AND ((balance_remaining IS NULL OR balance_remaining > 0) OR amount_paid_off IS NULL) AND created_at BETWEEN '{$today_minus_ninety}' AND '{$today_minus_sixty}' ORDER BY patient_id ASC"; $debtors = DB::select($debtors_query); break; case 'ninety_one_and_over_debtors': $title .= " before " . streamline_date($today_minus_ninety); $debtors_query = "SELECT * FROM debtors WHERE deleted_at IS NULL AND ((balance_remaining IS NULL OR balance_remaining > 0) OR amount_paid_off IS NULL) AND created_at < '{$today_minus_ninety}' ORDER BY patient_id ASC"; $debtors = DB::select($debtors_query); break; } $table = 'accounts_receivables'; $result['debtors'] = $debtors; $result['patient_category_invoices'] = []; $result['debt_plan'] = []; $result['inpatient_bills'] = []; return view('finance_reports::finance_reports.accounts.accounts_receivables', compact('result', 'chart_of_account', 'title', 'table')); } public function custom_debtor($debtor, $category) { $debtors = []; $debtor = intval($debtor); $today = Carbon::today()->toDateTimeString(); $today_minus_thirty = Carbon::today()->subDays(30)->toDateTimeString(); $today_minus_sixty = Carbon::today()->subDays(60)->toDateTimeString(); $today_minus_ninety = Carbon::today()->subDays(90)->toDateTimeString(); $chart_of_account = get_name('accounts_receivables', 'slug', 'id', 'chart_of_accounts'); $title = get_name($chart_of_account, 'id', 'name', 'chart_of_accounts'); $title .= ' - (Debtor) ' . get_full_name($debtor, 'id', 'first_name', 'last_name', 'patients') . ' '; switch ($category) { case 'current': $title .= " for today, the " . streamline_date($today); $debtors_query = "SELECT * FROM debtors WHERE deleted_at IS NULL AND patient_id = {$debtor} AND ((balance_remaining IS NULL OR balance_remaining > 0) OR amount_paid_off IS NULL) AND created_at >= '{$today}' ORDER BY id ASC"; if ($debtor == 0) { $debtors_query = "SELECT * FROM debtors WHERE deleted_at IS NULL AND patient_id IS NULL AND ((balance_remaining IS NULL OR balance_remaining > 0) OR amount_paid_off IS NULL) AND created_at >= '{$today}' ORDER BY id ASC"; } $debtors = DB::select($debtors_query); break; case 'one_to_thirty': $title .= " from " . streamline_date($today_minus_thirty) . " to " . streamline_date($today); $debtors_query = "SELECT * FROM debtors WHERE deleted_at IS NULL AND patient_id = {$debtor} AND ((balance_remaining IS NULL OR balance_remaining > 0) OR amount_paid_off IS NULL) AND created_at BETWEEN '{$today_minus_thirty}' AND '{$today}' ORDER BY id ASC"; if ($debtor == 0) { $debtors_query = "SELECT * FROM debtors WHERE deleted_at IS NULL AND patient_id IS NULL AND ((balance_remaining IS NULL OR balance_remaining > 0) OR amount_paid_off IS NULL) AND created_at BETWEEN '{$today_minus_thirty}' AND '{$today}' ORDER BY id ASC"; } $debtors = DB::select($debtors_query); break; case 'thirty_one_to_sixty': $title .= " from " . streamline_date($today_minus_sixty) . " to " . streamline_date($today_minus_thirty); $debtors_query = "SELECT * FROM debtors WHERE deleted_at IS NULL AND patient_id = {$debtor} AND ((balance_remaining IS NULL OR balance_remaining > 0) OR amount_paid_off IS NULL) AND created_at BETWEEN '{$today_minus_sixty}' AND '{$today_minus_thirty}' ORDER BY id ASC"; if ($debtor == 0) { $debtors_query = "SELECT * FROM debtors WHERE deleted_at IS NULL AND patient_id IS NULL AND ((balance_remaining IS NULL OR balance_remaining > 0) OR amount_paid_off IS NULL) AND created_at BETWEEN '{$today_minus_sixty}' AND '{$today_minus_thirty}' ORDER BY id ASC"; } $debtors = DB::select($debtors_query); break; case 'sixty_one_to_ninety': $title .= " from " . streamline_date($today_minus_ninety) . " to " . streamline_date($today_minus_sixty); $debtors_query = "SELECT * FROM debtors WHERE deleted_at IS NULL AND patient_id = {$debtor} AND ((balance_remaining IS NULL OR balance_remaining > 0) OR amount_paid_off IS NULL) AND created_at BETWEEN '{$today_minus_ninety}' AND '{$today_minus_sixty}' ORDER BY id ASC"; if ($debtor == 0) { $debtors_query = "SELECT * FROM debtors WHERE deleted_at IS NULL AND patient_id IS NULL AND ((balance_remaining IS NULL OR balance_remaining > 0) OR amount_paid_off IS NULL) AND created_at BETWEEN '{$today_minus_ninety}' AND '{$today_minus_sixty}' ORDER BY id ASC"; } $debtors = DB::select($debtors_query); break; case 'ninety_one_and_over': $title .= " before " . streamline_date($today_minus_ninety); $debtors_query = "SELECT * FROM debtors WHERE deleted_at IS NULL AND patient_id = {$debtor} AND ((balance_remaining IS NULL OR balance_remaining > 0) OR amount_paid_off IS NULL) AND created_at < '{$today_minus_ninety}' ORDER BY id ASC"; if ($debtor == 0) { $debtors_query = "SELECT * FROM debtors WHERE deleted_at IS NULL AND patient_id IS NULL AND ((balance_remaining IS NULL OR balance_remaining > 0) OR amount_paid_off IS NULL) AND created_at < '{$today_minus_ninety}' ORDER BY id ASC"; } $debtors = DB::select($debtors_query); break; } $table = 'accounts_receivables'; $result['debtors'] = $debtors; $result['patient_category_invoices'] = []; $result['debt_plan'] = []; $result['inpatient_bills'] = []; return view('finance_reports::finance_reports.accounts.accounts_receivables', compact('result', 'chart_of_account', 'title', 'table')); } public function custom_debt_plans($category) { $debt_plans = []; $today = Carbon::today()->toDateTimeString(); $today_minus_thirty = Carbon::today()->subDays(30)->toDateTimeString(); $today_minus_sixty = Carbon::today()->subDays(60)->toDateTimeString(); $today_minus_ninety = Carbon::today()->subDays(90)->toDateTimeString(); $chart_of_account = get_name('accounts_receivables', 'slug', 'id', 'chart_of_accounts'); $title = get_name($chart_of_account, 'id', 'name', 'chart_of_accounts'); $title .= ' - (Debt Plans)'; switch ($category) { case 'current': $title .= " for today, the " . streamline_date($today); $debt_plans_query = "SELECT * FROM debt_plan WHERE deleted_at IS NULL AND (balance_remaining IS NULL OR balance_remaining > 0) AND created_at >= '{$today}' ORDER BY id ASC"; $debt_plans = DB::select($debt_plans_query); break; case 'one_to_thirty': $title .= " from " . streamline_date($today_minus_thirty) . " to " . streamline_date($today); $debt_plans_query = "SELECT * FROM debt_plan WHERE deleted_at IS NULL AND (balance_remaining IS NULL OR balance_remaining > 0) AND created_at BETWEEN '{$today_minus_thirty}' AND '{$today}' ORDER BY id ASC"; $debt_plans = DB::select($debt_plans_query); break; case 'thirty_one_to_sixty': $title .= " from " . streamline_date($today_minus_sixty) . " to " . streamline_date($today_minus_thirty); $debt_plans_query = "SELECT * FROM debt_plan WHERE deleted_at IS NULL AND (balance_remaining IS NULL OR balance_remaining > 0) AND created_at BETWEEN '{$today_minus_sixty}' AND '{$today_minus_thirty}' ORDER BY id ASC"; $debt_plans = DB::select($debt_plans_query); break; case 'sixty_one_to_ninety': $title .= " from " . streamline_date($today_minus_ninety) . " to " . streamline_date($today_minus_sixty); $debt_plans_query = "SELECT * FROM debt_plan WHERE deleted_at IS NULL AND (balance_remaining IS NULL OR balance_remaining > 0) AND created_at BETWEEN '{$today_minus_ninety}' AND '{$today_minus_sixty}' ORDER BY id ASC"; $debt_plans = DB::select($debt_plans_query); break; case 'ninety_one_and_over': $title .= " before " . streamline_date($today_minus_ninety); $debt_plans_query = "SELECT * FROM debt_plan WHERE deleted_at IS NULL AND (balance_remaining IS NULL OR balance_remaining > 0) AND created_at < '{$today_minus_ninety}' ORDER BY id ASC"; $debt_plans = DB::select($debt_plans_query); break; } $table = 'accounts_receivables'; $result['debt_plan'] = $debt_plans; $result['patient_category_invoices'] = []; $result['debtors'] = []; $result['inpatient_bills'] = []; return view('finance_reports::finance_reports.accounts.accounts_receivables', compact('result', 'chart_of_account', 'title', 'table')); } public function custom_debt_plan($patient_id, $category) { $debt_plans = []; $today = Carbon::today()->toDateTimeString(); $today_minus_thirty = Carbon::today()->subDays(30)->toDateTimeString(); $today_minus_sixty = Carbon::today()->subDays(60)->toDateTimeString(); $today_minus_ninety = Carbon::today()->subDays(90)->toDateTimeString(); $chart_of_account = get_name('accounts_receivables', 'slug', 'id', 'chart_of_accounts'); $title = get_name($chart_of_account, 'id', 'name', 'chart_of_accounts'); $title .= ' - (Debt Plan) ' . get_full_name($patient_id, 'id', 'first_name', 'last_name', 'patients') . ' '; switch ($category) { case 'current': $title .= " for today, the " . streamline_date($today); $debt_plans_query = "SELECT * FROM debt_plan WHERE deleted_at IS NULL AND (balance_remaining IS NULL OR balance_remaining > 0) AND patient_id = {$patient_id} AND created_at >= '{$today}' ORDER BY id ASC"; if ($patient_id == 0) { $debt_plans_query = "SELECT * FROM debt_plan WHERE deleted_at IS NULL AND (balance_remaining IS NULL OR balance_remaining > 0) AND patient_id IS NULL AND created_at >= '{$today}' ORDER BY id ASC"; } $debt_plans = DB::select($debt_plans_query); break; case 'one_to_thirty': $title .= " from " . streamline_date($today_minus_thirty) . " to " . streamline_date($today); $debt_plans_query = "SELECT * FROM debt_plan WHERE deleted_at IS NULL AND (balance_remaining IS NULL OR balance_remaining > 0) AND patient_id = {$patient_id} AND created_at BETWEEN '{$today_minus_thirty}' AND '{$today}' ORDER BY id ASC"; if ($patient_id == 0) { $debt_plans_query = "SELECT * FROM debt_plan WHERE deleted_at IS NULL AND (balance_remaining IS NULL OR balance_remaining > 0) AND patient_id IS NULL AND created_at BETWEEN '{$today_minus_thirty}' AND '{$today}' ORDER BY id ASC"; } $debt_plans = DB::select($debt_plans_query); break; case 'thirty_one_to_sixty': $title .= " from " . streamline_date($today_minus_sixty) . " to " . streamline_date($today_minus_thirty); $debt_plans_query = "SELECT * FROM debt_plan WHERE deleted_at IS NULL AND (balance_remaining IS NULL OR balance_remaining > 0) AND patient_id = {$patient_id} AND created_at BETWEEN '{$today_minus_sixty}' AND '{$today_minus_thirty}' ORDER BY id ASC"; if ($patient_id == 0) { $debt_plans_query = "SELECT * FROM debt_plan WHERE deleted_at IS NULL AND (balance_remaining IS NULL OR balance_remaining > 0) AND patient_id IS NULL AND created_at BETWEEN '{$today_minus_sixty}' AND '{$today_minus_thirty}' ORDER BY id ASC"; } $debt_plans = DB::select($debt_plans_query); break; case 'sixty_one_to_ninety': $title .= " from " . streamline_date($today_minus_ninety) . " to " . streamline_date($today_minus_sixty); $debt_plans_query = "SELECT * FROM debt_plan WHERE deleted_at IS NULL AND (balance_remaining IS NULL OR balance_remaining > 0) AND patient_id = {$patient_id} AND created_at BETWEEN '{$today_minus_ninety}' AND '{$today_minus_sixty}' ORDER BY id ASC"; if ($patient_id == 0) { $debt_plans_query = "SELECT * FROM debt_plan WHERE deleted_at IS NULL AND (balance_remaining IS NULL OR balance_remaining > 0) AND patient_id IS NULL AND created_at BETWEEN '{$today_minus_ninety}' AND '{$today_minus_sixty}' ORDER BY id ASC"; } $debt_plans = DB::select($debt_plans_query); break; case 'ninety_one_and_over': $title .= " before " . streamline_date($today_minus_ninety); $debt_plans_query = "SELECT * FROM debt_plan WHERE deleted_at IS NULL AND (balance_remaining IS NULL OR balance_remaining > 0) AND patient_id = {$patient_id} AND created_at < '{$today_minus_ninety}' ORDER BY id ASC"; if ($patient_id == 0) { $debt_plans_query = "SELECT * FROM debt_plan WHERE deleted_at IS NULL AND (balance_remaining IS NULL OR balance_remaining > 0) AND patient_id IS NULL AND created_at < '{$today_minus_ninety}' ORDER BY id ASC"; } $debt_plans = DB::select($debt_plans_query); break; } $table = 'accounts_receivables'; $result['debt_plan'] = $debt_plans; $result['patient_category_invoices'] = []; $result['debtors'] = []; $result['inpatient_bills'] = []; return view('finance_reports::finance_reports.accounts.accounts_receivables', compact('result', 'chart_of_account', 'title', 'table')); } }