Files
streamline-emr/docker/streamline-src/app/Http/Helpers/Finance.php
T
alec.turner 4a89356390 Import latest app updates from streamline
An updated set of source files and initialization was provided by streamline to
address issues observed during initial testing. These files have been updated in
order to generate a new set of app images.
2024-04-11 11:16:51 -07:00

4794 lines
227 KiB
PHP
Executable File

<?php
use Streamline\Models\Banking;
use Streamline\Models\ChartOfAccount;
use Streamline\Models\DebtPlan;
use Streamline\Models\DebtPlanPaymentStaff;
use Streamline\Models\Drug;
use Streamline\Models\Equity;
use Streamline\Models\HospitalBill;
use Streamline\Models\PatientAccountConsumption;
use Streamline\Models\PatientAccountsDeposit;
use Streamline\Models\TrackReceipt;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use Streamline\Models\PatientDiscount;
use Streamline\Models\ServiceDeposit;
use Streamline\Models\OtherIncome;
use Streamline\Models\StockWatcher;
use Streamline\Models\Sundry;
use Streamline\Models\FamilyAccountConsumption;
use Streamline\Models\FamilyAccountDeposit;
use Streamline\Models\WardBedStay;
use Streamline\Models\WardConsultationsAndService;
use Streamline\Models\WardExtra;
use Streamline\Models\WardInvestigationPricing;
use Streamline\Models\WardProcedure;
use Streamline\Models\WardSundryDispensation;
use Streamline\Models\WardTreatmentDispensation;
function check_patient_category_co_payment_status($category)
{
$status = PatientDiscount::where('patient_category', $category)->where('co_payment', 1)->first();
if ($status) {
return $status->toArray();
} else {
return [];
}
}
function get_latest_other_income_record($income_account, $date)
{
$orderByTransIdQuery = "CAST(trans_id AS DECIMAL(10,0)) DESC";
$record = DB::table('other_incomes')
->whereNull('deleted_at')
->where('income_account', '=', $income_account)
->whereDate('donation_date', '<=', Carbon::parse($date)->toDateString())
->orderBy('donation_date', 'desc')
->orderByRaw($orderByTransIdQuery)
->first();
return $record;
}
function get_latest_banking_record($id, $date)
{
$orderByTransIdQuery = "CAST(trans_id AS DECIMAL(10,0)) DESC";
$record = DB::table('banking')
->whereNull('deleted_at')
->where('bank', '=', $id)
->whereDate('trans_date', '<=', Carbon::parse($date)->toDateString())
->orderBy('id', 'desc')
->orderByRaw($orderByTransIdQuery)
->first();
return $record;
}
function clearBill($id)
{
$bill = HospitalBill::find($id);
$payable_account_array = [];
$item_amount_paid = [];
$item_balance_remaining = [];
$deductions = [];
$items_array = explode(',', $bill->item_ids);
$items_subtotal_array = explode(',', $bill->item_subtotals);
$bill_balance = $bill->balance;
$bill_total = $bill->total_amount;
$bill_amount_paid = (is_null($bill_balance) ? 0 : (int)$bill_total - (int)$bill_balance);
for ($x = 0; $x < count($items_array); $x++) {
$new_amount = $bill_amount_paid - array_sum($deductions);
if (is_null($bill_balance)) {
$item_amount_paid[] = 0;
$item_balance_remaining[] = $items_subtotal_array[$x];
} else if ($bill_balance == 0) {
$item_amount_paid[] = $items_subtotal_array[$x];
$item_balance_remaining[] = 0;
} else {
if ($items_subtotal_array[$x] <= $new_amount) {
$item_amount_paid[] = $items_subtotal_array[$x];
$item_balance_remaining[] = 0;
$deductions[] = $items_subtotal_array[$x];
} else {
$item_amount_paid[] = $new_amount;
$item_balance_remaining[] = (int)$items_subtotal_array[$x] - (int)$new_amount;
$deductions[] = $new_amount;
}
}
}
\Streamline\Models\HospitalBill::where('id', $id)->update([
//'payable_account' => implode(',', $payable_account_array),
'item_amount_paid' => implode(',', $item_amount_paid),
'item_balance_remaining' => implode(',', $item_balance_remaining)
]);
}
function split_service_payment($id)
{
$payment = ServiceDeposit::find($id);
$item_amount_paid = $item_balance_remaining = $deductions = [];
$items_array = explode(',', $payment->items_ids);
$items_subtotal_array = explode(',', $payment->items_amounts);
$payment_total = array_sum(explode(',', $payment->items_amounts));
$payment_amount_paid = $payment->patient_amount_paid;
$payment_balance = (int)$payment_total - (int)$payment_amount_paid;
for ($x = 0; $x < count($items_array); $x++) {
$new_amount = $payment_amount_paid - array_sum($deductions);
if ($payment_balance == 0) {
$item_amount_paid[] = isset($items_subtotal_array[$x]) ? $items_subtotal_array[$x] : 0;
$item_balance_remaining[] = 0;
} else {
if ($items_subtotal_array[$x] <= $new_amount) {
$item_amount_paid[] = isset($items_subtotal_array[$x]) ? $items_subtotal_array[$x] : 0;
$item_balance_remaining[] = 0;
$deductions[] = isset($items_subtotal_array[$x]) ? $items_subtotal_array[$x] : 0;
} else {
$item_amount_paid[] = $new_amount;
$item_balance_remaining[] = (int)$items_subtotal_array[$x] - (int)$new_amount;
$deductions[] = $new_amount;
}
}
}
ServiceDeposit::where('id', $id)->update([
'item_amount_paid' => implode(',', $item_amount_paid),
'item_balance_remaining' => implode(',', $item_balance_remaining)
]);
}
function split_procedure_payment($id)
{
$payment = \Streamline\Models\ProcedureDeposit::find($id);
$item_amount_paid = $item_balance_remaining = $deductions = [];
$items_array = explode(',', $payment->procedure_items);
$items_subtotal_array = explode(',', $payment->procedure_amounts);
$payment_total = array_sum(explode(',', $payment->procedure_amounts));
$payment_amount_paid = $payment->patient_amount_paid;
$payment_balance = (int)$payment_total - (int)$payment_amount_paid;
for ($x = 0; $x < count($items_array); $x++) {
$new_amount = $payment_amount_paid - array_sum($deductions);
if ($payment_balance == 0) {
$item_amount_paid[] = isset($items_subtotal_array[$x]) ? $items_subtotal_array[$x] : 0;
$item_balance_remaining[] = 0;
} else {
if ($items_subtotal_array[$x] <= $new_amount) {
$item_amount_paid[] = isset($items_subtotal_array[$x]) ? $items_subtotal_array[$x] : 0;
$item_balance_remaining[] = 0;
$deductions[] = isset($items_subtotal_array[$x]) ? $items_subtotal_array[$x] : 0;
} else {
$item_amount_paid[] = $new_amount;
$item_balance_remaining[] = (int)$items_subtotal_array[$x] - (int)$new_amount;
$deductions[] = $new_amount;
}
}
}
\Streamline\Models\ProcedureDeposit::where('id', $id)->update([
'item_amount_paid' => implode(',', $item_amount_paid),
'item_balance_remaining' => implode(',', $item_balance_remaining)
]);
}
function split_investigation_payment($id)
{
$payment = \Streamline\Models\InvestigationDeposit::find($id);
$item_amount_paid = $item_balance_remaining = $deductions = [];
$items_array = explode(',', $payment->investigation_items);
$items_subtotal_array = explode(',', $payment->investigation_amounts);
$payment_total = array_sum(explode(',', $payment->investigation_amounts));
$payment_amount_paid = $payment->patient_amount_paid;
$payment_balance = (int)$payment_total - (int)$payment_amount_paid;
for ($x = 0; $x < count($items_array); $x++) {
$new_amount = $payment_amount_paid - array_sum($deductions);
if ($payment_balance == 0) {
$item_amount_paid[] = isset($items_subtotal_array[$x]) ? $items_subtotal_array[$x] : 0;
$item_balance_remaining[] = 0;
} else {
if ($items_subtotal_array[$x] <= $new_amount) {
$item_amount_paid[] = isset($items_subtotal_array[$x]) ? $items_subtotal_array[$x] : 0;
$item_balance_remaining[] = 0;
$deductions[] = isset($items_subtotal_array[$x]) ? $items_subtotal_array[$x] : 0;
} else {
$item_amount_paid[] = $new_amount;
$item_balance_remaining[] = (int)$items_subtotal_array[$x] - (int)$new_amount;
$deductions[] = $new_amount;
}
}
}
\Streamline\Models\InvestigationDeposit::where('id', $id)->update([
'item_amount_paid' => implode(',', $item_amount_paid),
'item_balance_remaining' => implode(',', $item_balance_remaining)
]);
}
function split_treatment_payment($id)
{
$payment = \Streamline\Models\TreatmentDeposits::find($id);
$item_amount_paid = $item_balance_remaining = $deductions = [];
$items_array = explode(',', $payment->treatment_items);
$items_subtotal_array = explode(',', $payment->treatment_subtotals);
$payment_total = array_sum(explode(',', $payment->treatment_subtotals));
$payment_amount_paid = $payment->patient_amount_paid;
$payment_balance = (int)$payment_total - (int)$payment_amount_paid;
for ($x = 0; $x < count($items_array); $x++) {
$new_amount = $payment_amount_paid - array_sum($deductions);
if ($payment_balance == 0) {
$item_amount_paid[] = isset($items_subtotal_array[$x]) ? $items_subtotal_array[$x] : 0;
$item_balance_remaining[] = 0;
} else {
if ($items_subtotal_array[$x] <= $new_amount) {
$item_amount_paid[] = isset($items_subtotal_array[$x]) ? $items_subtotal_array[$x] : 0;
$item_balance_remaining[] = 0;
$deductions[] = isset($items_subtotal_array[$x]) ? $items_subtotal_array[$x] : 0;
} else {
$item_amount_paid[] = $new_amount;
$item_balance_remaining[] = (int)$items_subtotal_array[$x] - (int)$new_amount;
$deductions[] = $new_amount;
}
}
}
\Streamline\Models\TreatmentDeposits::where('id', $id)->update([
'item_amount_paid' => implode(',', $item_amount_paid),
'item_balance_remaining' => implode(',', $item_balance_remaining)
]);
}
function split_sundry_payment($id)
{
$payment = \Streamline\Models\SundryDeposit::find($id);
$item_amount_paid = $item_balance_remaining = $deductions = [];
$items_array = explode(',', $payment->sundry_items);
$items_subtotal_array = explode(',', $payment->sundry_subtotals);
$payment_total = array_sum(explode(',', $payment->sundry_subtotals));
$payment_amount_paid = $payment->patient_amount_paid;
$payment_balance = (int)$payment_total - (int)$payment_amount_paid;
for ($x = 0; $x < count($items_array); $x++) {
$new_amount = $payment_amount_paid - array_sum($deductions);
if ($payment_balance == 0) {
$item_amount_paid[] = isset($items_subtotal_array[$x]) ? $items_subtotal_array[$x] : 0;
$item_balance_remaining[] = 0;
} else {
if ($items_subtotal_array[$x] <= $new_amount) {
$item_amount_paid[] = isset($items_subtotal_array[$x]) ? $items_subtotal_array[$x] : 0;
$item_balance_remaining[] = 0;
$deductions[] = $items_subtotal_array[$x];
} else {
$item_amount_paid[] = $new_amount;
$item_balance_remaining[] = (int)$items_subtotal_array[$x] - (int)$new_amount;
$deductions[] = $new_amount;
}
}
}
\Streamline\Models\SundryDeposit::where('id', $id)->update([
'item_amount_paid' => implode(',', $item_amount_paid),
'item_balance_remaining' => implode(',', $item_balance_remaining)
]);
}
function split_optics_payment($id) {
$payment = \Streamline\Models\EyeGlassesDeposits::find($id);
$item_amount_paid = $item_balance_remaining = $deductions = [];
$items_array = explode(',', $payment->items);
$items_subtotal_array = explode(',', $payment->subtotals);
$payment_total = array_sum(explode(',', $payment->subtotals));
$payment_amount_paid = $payment->patient_amount_paid;
$payment_balance = (int)$payment_total - (int)$payment_amount_paid;
for ($x = 0; $x < count($items_array); $x++) {
$new_amount = $payment_amount_paid - array_sum($deductions);
if ($payment_balance == 0) {
$item_amount_paid[] = $items_subtotal_array[$x] ?? 0;
$item_balance_remaining[] = 0;
} else {
if ($items_subtotal_array[$x] <= $new_amount) {
$item_amount_paid[] = $items_subtotal_array[$x] ?? 0;
$item_balance_remaining[] = 0;
$deductions[] = $items_subtotal_array[$x];
} else {
$item_amount_paid[] = $new_amount;
$item_balance_remaining[] = (int)$items_subtotal_array[$x] - (int)$new_amount;
$deductions[] = $new_amount;
}
}
}
\Streamline\Models\EyeGlassesDeposits::where('id', $id)->update([
'item_amount_paid' => implode(',', $item_amount_paid),
'item_balance_remaining' => implode(',', $item_balance_remaining)
]);
}
function split_inpatient_deposit($patient_id, $episode_id, $receipt_number, $dependant_amount) {
$amount_paid = 0;
if ($dependant_amount && ($dependant_amount > 0)) {
$amount_paid += $dependant_amount;
}
$previous_payments_if_any = ServiceDeposit::where(['patient_id' => $patient_id, 'episode_id' => $episode_id, 'service_type' => 'Inpatient_Deposit'])->get();
foreach ($previous_payments_if_any as $payment) :
$amount_paid += (int)$payment->patient_amount_paid;
endforeach;
$item_array = $deductions = [];
$item_array['services'] = WardConsultationsAndService::where(['patient_id' => $patient_id, 'episode_id' => $episode_id])->get();
$item_array['drugs'] = WardTreatmentDispensation::where(['patient_id' => $patient_id, 'episode_id' => $episode_id])->get();
$item_array['investigations'] = WardInvestigationPricing::where(['patient_id' => $patient_id, 'episode_id' => $episode_id])->get();
$item_array['procedures'] = WardProcedure::where(['patient_id' => $patient_id, 'episode_id' => $episode_id])->get();
$item_array['sundries'] = WardSundryDispensation::where(['patient_id' => $patient_id, 'episode_id' => $episode_id])->get();
$item_array['bed_stays'] = WardBedStay::where(['patient_id' => $patient_id, 'episode_id' => $episode_id])->get();
$item_array['extras'] = WardExtra::where(['patient_id' => $patient_id, 'episode_id' => $episode_id])->get();
if (count($item_array['services']) > 0) {
foreach ($item_array['services'] as $item) {
$subtotal = ((int)$item->staff_fee + ((int)$item->unit_price) * (int)$item->quantity_given);
$new_amount = $amount_paid - array_sum($deductions);
$item_amount_paid = $item_balance_remaining = 0;
if ($subtotal <= $new_amount) {
$item_amount_paid = $subtotal;
$item_balance_remaining = 0;
$deductions[] = $subtotal;
} else {
$item_amount_paid = $new_amount;
$item_balance_remaining = $subtotal - (int)$new_amount;
$deductions[] = $new_amount;
}
WardConsultationsAndService::where('id', $item->id)->update(
[
'amount_paid' => $item_amount_paid,
'balance' => $item_balance_remaining,
'receipt_number' => $receipt_number
]
);
}
}
if (count($item_array['investigations']) > 0) {
foreach ($item_array['investigations'] as $item) {
$subtotal = (int)$item->price;
$new_amount = $amount_paid - array_sum($deductions);
$item_amount_paid = $item_balance_remaining = 0;
if ($subtotal <= $new_amount) {
$item_amount_paid = $subtotal;
$item_balance_remaining = 0;
$deductions[] = $subtotal;
} else {
$item_amount_paid = $new_amount;
$item_balance_remaining = $subtotal - (int)$new_amount;
$deductions[] = $new_amount;
}
WardInvestigationPricing::where('id', $item->id)->update(
[
'amount_paid' => $item_amount_paid,
'balance' => $item_balance_remaining,
'receipt_number' => $receipt_number
]
);
}
}
if (count($item_array['procedures']) > 0) {
foreach ($item_array['procedures'] as $item) {
$subtotal = ((int)$item->hospital_fee + (int)$item->staff_fee);
$new_amount = $amount_paid - array_sum($deductions);
$item_amount_paid = $item_balance_remaining = 0;
if ($subtotal <= $new_amount) {
$item_amount_paid = $subtotal;
$item_balance_remaining = 0;
$deductions[] = $subtotal;
} else {
$item_amount_paid = $new_amount;
$item_balance_remaining = $subtotal - (int)$new_amount;
$deductions[] = $new_amount;
}
WardProcedure::where('id', $item->id)->update(
[
'amount_paid' => $item_amount_paid,
'balance' => $item_balance_remaining,
'receipt_number' => $receipt_number
]
);
}
}
if (count($item_array['drugs']) > 0) {
foreach ($item_array['drugs'] as $item) {
$subtotal = ((int)$item->quantity_given * (int)$item->price);
$new_amount = $amount_paid - array_sum($deductions);
$item_amount_paid = $item_balance_remaining = 0;
if ($subtotal <= $new_amount) {
$item_amount_paid = $subtotal;
$item_balance_remaining = 0;
$deductions[] = $subtotal;
} else {
$item_amount_paid = $new_amount;
$item_balance_remaining = $subtotal - (int)$new_amount;
$deductions[] = $new_amount;
}
WardTreatmentDispensation::where('id', $item->id)->update(
[
'amount_paid' => $item_amount_paid,
'balance' => $item_balance_remaining,
'receipt_number' => $receipt_number
]
);
}
}
if (count($item_array['sundries']) > 0) {
foreach ($item_array['sundries'] as $item) {
$subtotal = ((int)$item->quantity_given * (int)$item->price);
$new_amount = $amount_paid - array_sum($deductions);
$item_amount_paid = $item_balance_remaining = null;
if ($subtotal <= $new_amount) {
$item_amount_paid = $subtotal;
$item_balance_remaining = 0;
$deductions[] = $subtotal;
} else {
$item_amount_paid = $new_amount;
$item_balance_remaining = $subtotal - (int)$new_amount;
$deductions[] = $new_amount;
}
WardSundryDispensation::where('id', $item->id)->update(
[
'amount_paid' => $item_amount_paid,
'balance' => $item_balance_remaining,
'receipt_number' => $receipt_number
]
);
}
}
if (count($item_array['bed_stays']) > 0) {
foreach ($item_array['bed_stays'] as $item) {
$subtotal = ((int)$item->bed_fee_rate * (int)$item->duration);
$new_amount = $amount_paid - array_sum($deductions);
$item_amount_paid = $item_balance_remaining = 0;
if ($subtotal <= $new_amount) {
$item_amount_paid = $subtotal;
$item_balance_remaining = 0;
$deductions[] = $subtotal;
} else {
$item_amount_paid = $new_amount;
$item_balance_remaining = $subtotal - (int)$new_amount;
$deductions[] = $new_amount;
}
WardBedStay::where('id', $item->id)->update(
[
'amount_paid' => $item_amount_paid,
'balance' => $item_balance_remaining,
'receipt_number' => $receipt_number
]
);
}
}
if (count($item_array['extras']) > 0) {
foreach ($item_array['extras'] as $item) {
$subtotal = (int)$item->extra_cost;
$new_amount = $amount_paid - array_sum($deductions);
$item_amount_paid = $item_balance_remaining = 0;
if ($subtotal <= $new_amount) {
$item_amount_paid = $subtotal;
$item_balance_remaining = 0;
$deductions[] = $subtotal;
} else {
$item_amount_paid = $new_amount;
$item_balance_remaining = $subtotal - (int)$new_amount;
$deductions[] = $new_amount;
}
WardExtra::where('id', $item->id)->update(
[
'amount_paid' => $item_amount_paid,
'balance' => $item_balance_remaining,
'receipt_number' => $receipt_number
]
);
}
}
}
function clearDebtPlan($debt_id)
{
$debt = DebtPlan::where('id', $debt_id)->first();
$payment = DebtPlanPaymentStaff::where('debt_plan_id', $debt_id)->first();
if (!is_null($payment)) {
$amount_paid = (int)$payment->amount_owed - (int)$payment->balance;
DebtPlan::where('id', $debt_id)->update(['balance_remaining' => $payment->balance, 'amount_paid_off' => $amount_paid]);
}
}
function findTestOrDemoPatients(): array
{
return DB::table('patients')->whereNull('deleted_at')->where('is_test_patient', 1)
->pluck('id')->toArray();
}
function capture_bank_record($trans_type, $trans_date, $bank, $other_account, $account_balance, $credit, $debit, $memo, $trans_id)
{
$bank_record = new Banking;
$bank_record->trans_type = $trans_type;
$bank_record->trans_date = $trans_date;
$bank_record->bank = $bank;
$bank_record->other_accounts = $other_account;
$bank_record->account_balance = $account_balance;
$bank_record->credit = $credit;
$bank_record->debit = $debit;
$bank_record->memo = $memo;
$bank_record->trans_id = $trans_id;
$bank_record->created_by = Auth::id();
$bank_record->save();
return $bank_record->id; // last_insert_id in db
}
function dateLabelSetter($request)
{
$today = Carbon::today()->toDateString();
$yesterday = Carbon::yesterday()->toDateString();
$display = "Report for ";
// add the user searched for
$staff_member = $request->staff_member;
if ($staff_member == 0) {
$display .= "all users ";
} else {
$display .= get_full_name($staff_member, 'id', 'first_name', 'last_name', 'users') . " ";
}
if ($request->dates == 'today' || $request->date_type == 'today') {
$display .= "from today, the " . streamline_date($today);
} elseif ($request->dates == 'yesterday' || $request->date_type == 'yesterday') {
$display .= "from yesterday, the " . streamline_date($yesterday);
} elseif ($request->dates == 'custom_date' || $request->date_type == 'custom_date') {
$start_date = Carbon::parse($request->start_date)->toDateString();
$display .= "from the " . streamline_date($start_date);
} else {
$start_date = Carbon::parse($request->start_date)->toDateString();
$end_date = Carbon::parse($request->end_date)->toDateString();
$display .= "between " . streamline_date($start_date) . " and " . streamline_date($end_date);
}
return $display;
}
function dateLabelSetter2($request)
{
$today = Carbon::today()->toDateString();
$yesterday = Carbon::yesterday()->toDateString();
$display = "Report";
if ($request->dates == 'today' || $request->date_type == 'today') {
$display .= " for today, the " . streamline_date($today);
} elseif ($request->dates == 'yesterday' || $request->date_type == 'yesterday') {
$display .= " from yesterday, the " . streamline_date($yesterday);
} elseif ($request->dates == 'custom_date' || $request->date_type == 'custom_date') {
$start_date = Carbon::parse($request->start_date)->toDateString();
$display .= " for the " . streamline_date($start_date);
} else {
$start_date = Carbon::parse($request->start_date)->toDateString();
$end_date = Carbon::parse($request->end_date)->toDateString();
$display .= " from " . streamline_date($start_date) . " to " . streamline_date($end_date);
}
return $display;
}
function bank_register_label_setter(Request $request)
{
$today = Carbon::today()->toDateString();
$yesterday = Carbon::yesterday()->toDateString();
$display = "Bank Register Report for " . get_name($request->bank, 'id', 'name', 'chart_of_accounts');
if ($request->dates == 'today' || $request->date_type == 'today') {
$display .= " for today, the " . streamline_date($today);
} elseif ($request->dates == 'yesterday' || $request->date_type == 'yesterday') {
$display .= " from yesterday, the " . streamline_date($yesterday);
} elseif ($request->dates == 'custom_date' || $request->date_type == 'custom_date') {
$start_date = Carbon::parse($request->start_date)->toDateString();
$display .= " for the " . streamline_date($start_date);
} else {
$start_date = Carbon::parse($request->start_date)->toDateString();
$end_date = Carbon::parse($request->end_date)->toDateString();
$display .= " from " . streamline_date($start_date) . " to " . streamline_date($end_date);
}
return $display;
}
function bank_reconciliation_label_setter($bank, $start, $end)
{
$display = "Bank Reconciliation for " . (($bank == "ALL BANKS") ? "ALL BANKS" : get_name($bank, 'id', 'name', 'chart_of_accounts'));
$start_date = Carbon::parse($start)->toDateString();
$end_date = Carbon::parse($end)->toDateString();
$display .= " from " . streamline_date($start_date) . " to " . streamline_date($end_date);
return $display;
}
function expense_report_label_setter(Request $request)
{
$today = Carbon::today()->toDateString();
$yesterday = Carbon::yesterday()->toDateString();
$display = "Expense Report ";
if ($request->dates == 'today' || $request->date_type == 'today') {
$display .= " for today, the " . streamline_date($today);
} elseif ($request->dates == 'yesterday' || $request->date_type == 'yesterday') {
$display .= " from yesterday, the " . streamline_date($yesterday);
} elseif ($request->dates == 'custom_date' || $request->date_type == 'custom_date') {
$start_date = Carbon::parse($request->start_date)->toDateString();
$display .= " for the " . streamline_date($start_date);
} else {
$start_date = Carbon::parse($request->start_date)->toDateString();
$end_date = Carbon::parse($request->end_date)->toDateString();
$display .= " from " . streamline_date($start_date) . " to " . streamline_date($end_date);
}
return $display;
}
function getExpensesByAccount(Request $request)
{
$moneys_on_account = $deposit_per_account = [];
$end = Carbon::parse($request->end_date)->endOfDay();
$start = Carbon::parse($request->start_date)->startOfDay();
// double id value so that we can use faster isset instead of slower in_array
$accounts = !empty($request->expense_ids) ? $request->expense_ids : ChartOfAccount::where('type', 2)->pluck('id', 'id')->toArray();
if ($request->dates == "yesterday") {
$date_of_interest = Carbon::yesterday();
} elseif ($request->dates == "custom_date") {
$date_of_interest = $start;
} else {
$date_of_interest = Carbon::today();
}
if ($request->dates == "custom_date_range") {
$payments = DB::table('payments')->whereNull('bill_id')->whereNull('deleted_at')
->whereBetween('expense_date', [$start, $end])->get(['expense_account', 'amount']);
$discounts = DB::table('discounts')->whereNull('deleted_at')->whereBetween('created_at', [$start, $end])
->get(['patient_category', 'discount_amount']);
$bills = DB::table('hospital_bills')->whereNull('deleted_at')->whereBetween('bill_date', [$start->toDateString(), $end->toDateString()])
->get(['item_subtotals', 'item_amount_paid', 'item_accounts']);
$ward_procedure_staff_fees = DB::table('ward_procedures')->whereNull('deleted_at')->where('expense_chart_of_account', $accounts)->whereBetween('created_at', [$start, $end])
->get();
$one_off_discounts = DB::table('patient_one_off_discounts')->whereBetween('created_at', [$start, $end])
->get(['amount_discounted'])->sum('amount_discounted');
$ward_discounts = DB::table('inpatient_ward_discounts')->whereNull('deleted_at')->whereBetween('created_at', [$start, $end])
->get(['amount'])->sum('amount');
} else {
$payments = DB::table('payments')->whereNull('bill_id')->whereNull('deleted_at')
->whereDate('expense_date', $date_of_interest)->get(['expense_account', 'amount']);
$discounts = DB::table('discounts')->whereNull('deleted_at')
->whereDate('created_at', $date_of_interest)->get(['patient_category', 'discount_amount']);
$bills = DB::table('hospital_bills')->whereNull('deleted_at')
->whereDate('bill_date', $date_of_interest->toDateString())->get(['item_subtotals', 'item_amount_paid', 'item_accounts']);
$ward_procedure_staff_fees = DB::table('ward_procedures')->whereNull('deleted_at')->whereDate('created_at', $date_of_interest)
->whereIn('expense_chart_of_account', $accounts)->get(['staff_fee', 'expense_chart_of_account']);
$one_off_discounts = DB::table('patient_one_off_discounts')->whereDate('created_at', $date_of_interest)
->get(['amount_discounted'])->sum('amount_discounted');
$ward_discounts = DB::table('inpatient_ward_discounts')->whereNull('deleted_at')->whereDate('created_at', $date_of_interest)
->get(['amount'])->sum('amount');
}
$ward_discounts_account_id = get_name("ward_discounts", "slug", "id", "chart_of_accounts");
if (is_numeric($ward_discounts_account_id)) {
$deposit_per_account[$ward_discounts_account_id]['cash'][] = 0;
$deposit_per_account[$ward_discounts_account_id]['accrual'][] = $ward_discounts;
} else {
flash('The ward discounts chart of account is missing. Please contact Stre@mline support immediately!')->error();
}
$one_off_discounts_account_id = get_name("one_off_discounts", "slug", "id", "chart_of_accounts");
if (is_numeric($one_off_discounts_account_id)) {
$deposit_per_account[$one_off_discounts_account_id]['cash'][] = 0;
$deposit_per_account[$one_off_discounts_account_id]['accrual'][] = $one_off_discounts;
} else {
flash('The one off discounts chart of account is missing. Please contact Stre@mline support immediately!')->error();
}
foreach ($payments as $item) {
$deposit_per_account[$item->expense_account]['cash'][] = (int)$item->amount;
$deposit_per_account[$item->expense_account]['accrual'][] = (int)$item->amount;
}
foreach ($bills as $bill) {
$item_amounts_array = explode(',', $bill->item_subtotals);
$item_amount_paid_array = explode(',', $bill->item_amount_paid);
$item_account_array = explode(',', $bill->item_accounts);
for ($x = 0; $x < count($item_amounts_array); $x++) {
if (isset($item_account_array[$x])) {
$deposit_per_account[$item_account_array[$x]]['cash'][] = $item_amount_paid_array[$x] ?? 0;
$deposit_per_account[$item_account_array[$x]]['accrual'][] = $item_amounts_array[$x] ?? 0;
}
}
}
foreach ($discounts as $discount) {
$expense_account = get_discount_tracking_expense_account($discount->patient_category);
if (!is_null($expense_account)) {
$deposit_per_account[$expense_account]['cash'][] = 0;
$deposit_per_account[$expense_account]['accrual'][] = $discount->discount_amount;
}
}
foreach ($ward_procedure_staff_fees as $item) {
$deposit_per_account[$item->expense_chart_of_account]['cash'][] = 0;
$deposit_per_account[$item->expense_chart_of_account]['accrual'][] = $item->staff_fee;
}
foreach ($deposit_per_account as $key => $value) {
if (isset($accounts[$key])) {
$data_string = $request->dates . "," . $request->start_date . "," . $request->end_date . "," . 'payments' . "," . $key . "," . "3";
$moneys_on_account[$key] = array('cash' => array_sum($value['cash']), 'accrual' => array_sum($value['accrual']), 'id' => $key, 'data' => $data_string);
}
}
return $moneys_on_account;
}
function date_query_builder_using_date_time($start_date, $end_date, $date_search_column, $search_type)
{
$date_filter = array();
$start_of_today = Carbon::today()->startOfDay()->toDateTimeString();
$end_of_today = Carbon::today()->endOfDay()->toDateTimeString();
$start_of_yesterday = Carbon::yesterday()->startOfDay()->toDateTimeString();
$end_of_yesterday = Carbon::yesterday()->endOfDay()->toDateTimeString();
$start = Carbon::parse($start_date)->startOfDay()->toDateTimeString();
$end_of_start = Carbon::parse($start_date)->endOfDay()->toDateTimeString();
$end = Carbon::parse($end_date)->endOfDay()->toDateTimeString();
switch ($search_type):
case 'today':
$start_array = [$date_search_column, '>', $start_of_today];
$end_array = [$date_search_column, '<', $end_of_today];
array_push($date_filter, $start_array);
array_push($date_filter, $end_array);
break;
case 'yesterday':
$start_array = [$date_search_column, '>', $start_of_yesterday];
$end_array = [$date_search_column, '<', $end_of_yesterday];
array_push($date_filter, $start_array);
array_push($date_filter, $end_array);
break;
case 'custom_date':
$start_array = [$date_search_column, '>', $start];
$end_array = [$date_search_column, '<', $end_of_start];
array_push($date_filter, $start_array);
array_push($date_filter, $end_array);
break;
case 'custom_date_range':
$start_filter = [$date_search_column, '>', $start];
$end_filter = [$date_search_column, '<', $end];
array_push($date_filter, $start_filter);
array_push($date_filter, $end_filter);
break;
endswitch;
return $date_filter;
}
function getDateStringBasedOnDateSearchType($request)
{
switch ($request->dates) {
case 'today':
return Carbon::today()->toDateTimeString();
break;
case 'yesterday':
return Carbon::yesterday()->toDateTimeString();
break;
case 'custom_date':
return Carbon::parse($request->start_date)->toDateTimeString();
break;
case 'custom_date_range':
return (Carbon::parse($request->start_date)->toDateTimeString() . "/" . Carbon::parse($request->end_date)->toDateTimeString());
break;
}
}
function queryDateFilter($table, Request $request)
{
$result = [];
$today = Carbon::today()->toDateString();
$yesterday = Carbon::yesterday()->toDateString();
$end = Carbon::parse($request->end_date)->endOfDay()->toDateTimeString();
$start = Carbon::parse($request->start_date)->startOfDay()->toDateTimeString();
$staff_member = $request->staff_member;
if ($request->staff_member == "ALL STAFF") {
if ($request->dates == "today") {
$result = DB::table($table)->whereDate('created_at', $today)->whereNull('deleted_at')->get();
} else if ($request->dates == "yesterday") {
$result = DB::table($table)->whereDate('created_at', $yesterday)->whereNull('deleted_at')->get();
} else if ($request->dates == "custom_date") {
$result = DB::table($table)->whereDate('created_at', $start)->whereNull('deleted_at')->get();
} else if ($request->dates == "custom_date_range") {
$result = DB::table($table)->whereBetween('created_at', [$start, $end])->whereNull('deleted_at')->get();
}
} else {
if ($request->dates == "today") {
$result = DB::table($table)->whereDate('created_at', $today)->where('created_by', $staff_member)->whereNull('deleted_at')->get();
} else if ($request->dates == "yesterday") {
$result = DB::table($table)->whereDate('created_at', $yesterday)->where('created_by', $staff_member)->get();
} else if ($request->dates == "custom_date") {
$result = DB::table($table)->whereDate('created_at', $start)->where('created_by', $staff_member)->whereNull('deleted_at')->get();
} else if ($request->dates == "custom_date_range") {
$result = DB::table($table)->whereBetween('created_at', [$start, $end])->where('created_by', $staff_member)->whereNull('deleted_at')->get();
}
}
return $result;
}
function update_account_balance_by_id($account_id, $amount)
{
$previous_account_balance = \Streamline\Models\ChartOfAccount::where('id', $account_id)->pluck('balance')->first();
\Streamline\Models\ChartOfAccount::where('id', $account_id)->update(['balance' => (int)$amount + (int)$previous_account_balance]);
}
function getNonCurrentAssetsByAccount($request)
{
$data = $filters = [];
$other_date = "";
$non_current_asset_accounts = DB::table('chart_of_accounts')->where('type', 3)->whereNull('deleted_at')->get();
if ($request->dates == "yesterday") {
$date = Carbon::yesterday()->toDateString();
$filters[] = ['acquisition_date', '<=', $date];
} elseif ($request->dates == "custom_date") {
$date = Carbon::parse($request->start_date)->toDateString();
$filters[] = ['acquisition_date', '<=', $date];
} elseif ($request->dates == "custom_date_range") {
$date = Carbon::parse($request->end_date)->toDateString();
$other_date = Carbon::parse($request->start_date)->toDateString();
$filters[] = ['acquisition_date', '>', Carbon::parse($request->start_date)->subDay()->toDateString()];
$filters[] = ['acquisition_date', '<', Carbon::parse($request->end_date)->addDay()->toDateString()];
} else {
$date = Carbon::today()->toDateString();
$filters[] = ['acquisition_date', '<=', $date];
}
foreach ($non_current_asset_accounts as $account) {
if ($account->slug != 'accumulated_depreciation') {
$total_value = 0;
$non_current_assets = DB::table('fixed_assets')
->whereNull('deleted_at')
->where('fixed_asset_account_id', $account->id)
->where($filters)
->get();
foreach ($non_current_assets as $asset) {
/* $time_difference = Carbon::parse($asset->acquisition_date)->diffInYears($date);
$current_cost_price = ((int)$asset->cost_price * $asset->depreciation) * $time_difference;
$total_value += ($asset->cost_price - $current_cost_price); */
$total_value += $asset->cost_price;
}
} else {
$total_value = $account->balance;
}
$data_string = $request->dates . "," . $date . "," . $other_date . "," . 'fixed_assets' . "," . $account->id . ",";
$data[] = ['id' => $account->id, 'amount' => $total_value, 'data' => $data_string];
}
return $data;
}
function getCurrentAssetsByAccountBalanceSheet($request)
{
$inventory_accounts_array = $data = [];
$banks = ChartOfAccount::where('type', 4)->pluck('id')->toArray();
$inventory_accounts = ChartOfAccount::where('type', 10)->whereNull('deleted_at')->pluck('id')->toArray();
$end = Carbon::parse($request->end_date)->endOfDay();
$start = Carbon::parse($request->start_date)->startOfDay();
//$date_of_interest = Carbon::parse($request->end_date)->toDateString();
$date_of_interest = Carbon::parse($request->start_date)->toDateString(); //when custom date, use start instead of end date
if ($request->dates == "yesterday") {
$start = Carbon::yesterday()->toDateString();
$date_of_interest = $start;
}
// Banking
foreach ($banks as $bank) {
//$latest_banking_record = get_latest_banking_record($bank, $end);
$latest_banking_record = get_latest_banking_record_based_on_transaction_date($bank, $start);
// This excludes undeposited funds ie. Bank A/C with sub_account_of as 10
$bank_data_string = $request->dates . "," . $request->start_date . "," . $request->end_date . "," . 'banking' . "," . $bank . ",";
$data[] = [
'id' => $bank,
'amount' => $latest_banking_record ? $latest_banking_record->account_balance : 0,
'data' => $bank_data_string
];
}
// prep the inventory accounts array
foreach ($inventory_accounts as $inventory_account) {
$inventory_accounts_array[$inventory_account] = [
'id' => $inventory_account, 'amount' => 0, 'data' => $request->dates . "," . $request->start_date . "," . $request->end_date . "," . 'stock_watcher' . "," . $inventory_account
];
}
$drugs = DB::table('drugs')->whereNull('deleted_at')
->whereIn('inventory_account', $inventory_accounts)->get(['id', 'cost_price', 'pharmacy_stock', 'inventory_account', 'store_stock']);
$sundries = DB::table('sundries')->whereNull('deleted_at')
->whereIn('inventory_account', $inventory_accounts)->get(['id', 'cost_price', 'pharmacy_stock', 'inventory_account', 'store_stock']);
$eye_glasses = DB::table('eye_glasses')->whereNull('deleted_at')
->whereIn('inventory_account', $inventory_accounts)->get(['id', 'cost_price', 'inventory_account', 'store_stock']);
$inventory_items = [
["item_type" => 1, "data" => $drugs],
["item_type" => 2, "data" => $sundries],
["item_type" => 7, "data" => $eye_glasses]
];
foreach ($inventory_items as $inventory_item) {
foreach ($inventory_item['data'] as $inventory_item_data) {
$all_stock_watcher_records = DB::table('batch_stock_watcher')->where('item_type', $inventory_item['item_type'])
->where('item_id', $inventory_item_data->id)->get();
$stock_value = 0;
if ($all_stock_watcher_records) {
foreach ($all_stock_watcher_records as $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"] ?? 0) * (($details["pharmacy_stock"] ?? 0) + ($details["store_stock"] ?? 0) + ($details["ward_stock"] ?? 0)));
}
} 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;
}
}
$inventory_accounts_array[$inventory_item_data->inventory_account]['amount'] = $inventory_accounts_array[$inventory_item_data->inventory_account]['amount'] + $stock_value;
}
}
foreach ($inventory_accounts_array as $account) {
$data[] = $account;
}
if ($request->dates == 'custom_date_range') {
$date_filter = [['created_at', '>=', $start], ['created_at', '<=', $end]];
$date_updated_fillter = [['created_at', '>=', $start], ['created_at', '<=', $end]];
} else {
//$date_filter[] = ['created_at', '<=', $date_of_interest];
$date_of_interest = Carbon::createFromFormat('Y-m-d', $date_of_interest);
$date_filter[] = ['created_at', '<=', $date_of_interest]; //override the $date_filter just above
$date_updated_fillter[] = ['created_at', '<=', $date_of_interest];
}
$patient_category_invoices_balance_remaining = DB::table('patient_category_invoices')
->whereNull('receivable_account')
->whereNull('deleted_at')
->where($date_filter)
->where('balance_remaining', '>', 0)
->select(DB::raw('SUM(balance_remaining) as balance_remaining'))
->first()->balance_remaining;
$patient_category_invoices_no_balance = DB::table('patient_category_invoices')
->whereNull('receivable_account')
->whereNull('deleted_at')
->where($date_filter)
->whereNull('balance_remaining')
->select(DB::raw('SUM(patient_amount) as patient_amount'))
->first()->patient_amount;
$debtors_balance_remaining = DB::table('debtors')
->whereNull('receivable_account')
->whereNull('deleted_at')
->where($date_filter)
->where('balance_remaining', '>', 0)
->select(DB::raw('SUM(balance_remaining) as balance_remaining'))
->first()->balance_remaining;
$debtors_no_balance = DB::table('debtors')
->whereNull('receivable_account')
->whereNull('deleted_at')
->where($date_filter)
->whereNull('balance_remaining')
->select(DB::raw('SUM(balance) as balance'))
->first()->balance;
$debt_plan_balance_remaining = DB::table('debt_plan')
->whereNull('receivable_account')
->whereNull('deleted_at')
->where($date_filter)
->where('balance_remaining', '>', 0)
->select(DB::raw('SUM(balance_remaining) as balance_remaining'))
->first()->balance_remaining;
$debt_plan_no_balance = DB::table('debt_plan')
->whereNull('receivable_account')
->whereNull('deleted_at')
->where($date_filter)
->whereNull('balance_remaining')
->select(DB::raw('SUM(staff_guarantor_to_pay) as amount_owed'))
->first()->amount_owed;
$unpaid_inpatient_amount = DB::table('inpatient_bills')
//->whereBetween('updated_at', [$start, $end])
->where($date_updated_fillter)
->get(['amount_to_pay'])
->sum('amount_to_pay');
$total_accounts_receivable = $debtors_balance_remaining + $debtors_no_balance + $debt_plan_balance_remaining + $debt_plan_no_balance + $patient_category_invoices_balance_remaining + $patient_category_invoices_no_balance + $unpaid_inpatient_amount;
$accounts_receivables_data_string = $request->dates . "," . $request->start_date . "," . $request->end_date . "," . 'accounts_receivables' . "," . '16' . ",";
$data[] = ['id' => 16, 'amount' => $total_accounts_receivable, 'data' => $accounts_receivables_data_string];
return $data;
}
function getOtherCurrentAssetsByAccountBalanceSheet($request)
{
$data = [];
$other_current_assets = ChartOfAccount::whereIn('type', [13, 15])->whereNull('deleted_at')->get();
foreach ($other_current_assets as $account) {
$data_string = $request->dates . "," . $request->start_date . "," . $request->end_date . "," . 'chart_of_accounts' . "," . $account->id . ",";
$data[] = ['id' => $account->id, 'amount' => $account->balance, 'data' => $data_string];
}
return $data;
}
function getNonCurrentLiabilitiesByAccountBalanceSheet($request)
{
$data = $probable_duplicate_records = [];
$non_current_liabilities = ChartOfAccount::where('type', 12)->get();
$today = Carbon::today();
$yesterday = Carbon::yesterday();
$end = Carbon::parse($request->end_date)->endOfDay();
$start = Carbon::parse($request->start_date)->startOfDay();
foreach ($non_current_liabilities as $account) {
$hospital_bills = [];
switch ($request->dates) {
case 'today':
$hospital_bills = DB::table('hospital_bills')->whereNull('deleted_at')->whereDate('created_at', '<=', $today)->where('payable_account', $account->id)->get();
break;
case 'yesterday':
$hospital_bills = DB::table('hospital_bills')->whereNull('deleted_at')->whereDate('created_at', '<=', $yesterday)->where('payable_account', $account->id)->get();
break;
case 'custom_date':
$hospital_bills = DB::table('hospital_bills')->whereNull('deleted_at')->whereDate('created_at', '<=', $start)->where('payable_account', $account->id)->get();
break;
case 'custom_date_range':
$hospital_bills = DB::table('hospital_bills')->whereNull('deleted_at')->whereBetween('created_at', [$start, $end])->where('payable_account', $account->id)->get();
break;
}
$hospital_bills_total = $hospital_bills_amount = $hospital_bills_paid_amount = 0;
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;
}
$item_amount_array = explode(',', $bill->item_subtotals);
$payable_account_array = explode(',', $bill->payable_account);
$item_balance_remaining_array = explode(',', $bill->item_balance_remaining);
if (is_integer($bill->balance)) {
if ($bill->balance != 0) {
for ($i = 0; $i < count($item_amount_array); $i++) {
if (isset($payable_account_array[$i]) && $payable_account_array[$i] == $account->id) {
$loan_amount = ((int)$item_balance_remaining_array[$i] != null) ? (int)$item_balance_remaining_array[$i] : (int)$item_amount_array[$i];
$hospital_bills_total += $loan_amount;
$hospital_bills_amount += (int)$item_amount_array[$i];
$hospital_bills_paid_amount += $hospital_bills_amount - $loan_amount;
}
}
}
} else {
for ($i = 0; $i < count($item_amount_array); $i++) {
if (isset($payable_account_array[$i]) && $payable_account_array[$i] == $account->id && isset($item_amount_array[$i])) {
$hospital_bills_total += (int)$item_amount_array[$i];
$hospital_bills_amount += (int)$item_amount_array[$i];
$hospital_bills_paid_amount += $hospital_bills_amount - $hospital_bills_total;
}
}
}
}
$accounts_payable_data_string = $request->dates . "," . $request->start_date . "," . $request->end_date . "," . 'hospital_bills' . "," . $account->id . ",";
$data[] = ['id' => $account->id, 'amount' => $hospital_bills_total, 'bill_amount' => $hospital_bills_amount, 'bill_paid_amount' => $hospital_bills_paid_amount, 'data' => $accounts_payable_data_string];
}
$journals = [];
switch ($request->dates) {
case 'today':
$journals = DB::table('journals')->whereNull('deleted_at')->whereDate('journal_date', '<=', $today->toDateString())->whereNotIn('journal_number', $probable_duplicate_records)->get();
break;
case 'yesterday':
$journals = DB::table('journals')->whereNull('deleted_at')->whereDate('journal_date', '<=', $yesterday->toDateString())->whereNotIn('journal_number', $probable_duplicate_records)->get();
break;
case 'custom_date':
$journals = DB::table('journals')->whereNull('deleted_at')->whereDate('journal_date', '<=', $start->toDateString())->whereNotIn('journal_number', $probable_duplicate_records)->get();
break;
case 'custom_date_range':
$journals = DB::table('journals')->whereNull('deleted_at')->whereBetween('journal_date', [$start->toDateString(), $end->toDateString()])->whereNotIn('journal_number', $probable_duplicate_records)->get();
break;
}
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 non-current liability account
if (get_name($account_ids[$i], 'id', 'type', 'chart_of_accounts') == 11) {
$liability_account_id = $account_ids[$i];
$credit = $credits[$i];
$non_current_liabilty_value = 0;
if ($credit != null) {
// This Liability Account's value was Increased via the Journal
$non_current_liabilty_value = (int)$credit;
foreach ($data as $key => $value) {
if ($data[$key]['id'] == $liability_account_id) {
$data[$key]['amount'] = $value['amount'] + $non_current_liabilty_value;
$data_string = $request->dates . "," . $request->start_date . "," . $request->end_date . "," . 'journals' . "," . $liability_account_id . ",";
$data[$key]['data'] = $data_string;
}
}
}
}
}
}
return $data;
}
function getCurrentLiabilitiesByAccountBalanceSheet($request)
{
$data = $family_account_deposits = $hospital_bills = $probable_duplicate_records = $patient_account_deposits = [];
$patient_account_refunds = $patient_account_consumptions = [];
$family_account_deposit_total = 0;
$accounts = \Streamline\Models\ChartOfAccount::where('type', 6)
->whereNotIn('slug', ['family_account_deposits', 'patient_account_balance'])
->orWhere('type', 9)
->pluck('id')
->toArray();
if ($request->has('dates') == false) {
$request->request->add(['dates' => 'today']); //default to today
}
$today = Carbon::today()->endOfDay();
$yesterday = Carbon::yesterday()->endOfDay();
$end = Carbon::parse($request->end_date)->endOfDay();
$start = Carbon::parse($request->start_date)->startOfDay();
//liabilities
$family_account_id = get_name('family_account_deposits', 'slug', 'id', 'chart_of_accounts');
if (is_numeric($family_account_id)) {
switch ($request->dates) {
case 'today':
$family_account_deposit_total = DB::table('family_accounts')->whereNull('deleted_at')->whereDate('created_at', '<=', $today)->select(DB::raw('SUM(current_balance) as current_balance'))->first()->current_balance;
break;
case 'yesterday':
$family_account_deposit_total = DB::table('family_accounts')->whereNull('deleted_at')->whereDate('created_at', '<=', $yesterday)->select(DB::raw('SUM(current_balance) as current_balance'))->first()->current_balance;
break;
case 'custom_date':
$family_account_deposit_total = DB::table('family_accounts')->whereNull('deleted_at')->whereDate('created_at', '<=', $start)->select(DB::raw('SUM(current_balance) as current_balance'))->first()->current_balance;
break;
case 'custom_date_range':
$family_account_deposit_total = DB::table('family_accounts')->whereNull('deleted_at')->whereBetween('created_at', [$start, $end])->select(DB::raw('SUM(current_balance) as current_balance'))->first()->current_balance;
break;
}
$family_account_data_string = $request->dates . "," . $request->start_date . "," . $request->end_date . "," . 'family_account_deposits' . "," . $family_account_id;
$data[] = ['id' => $family_account_id, 'amount' => $family_account_deposit_total, 'data' => $family_account_data_string];
}
$patient_account_id = get_name('patient_account_balance', 'slug', 'id', 'chart_of_accounts');
if (is_numeric($patient_account_id)) {
switch ($request->dates) {
case 'yesterday':
$patient_account_balance = DB::table('patients')->whereNull('deleted_at')->whereDate('created_at', '<=', $yesterday)->select(DB::raw('SUM(patient_account_balance) as deposit_amount'))->first()->deposit_amount;
break;
case 'custom_date':
$patient_account_balance = DB::table('patients')->whereNull('deleted_at')->whereDate('created_at', '<=', $start)->select(DB::raw('SUM(patient_account_balance) as patient_account_balance'))->first()->patient_account_balance;
break;
case 'custom_date_range':
$patient_account_balance = DB::table('patients')->whereNull('deleted_at')->whereBetween('created_at', [$start, $end])->select(DB::raw('SUM(patient_account_balance) as patient_account_balance'))->first()->patient_account_balance;
break;
default:
$patient_account_balance = DB::table('patients')->whereNull('deleted_at')->whereDate('created_at', '<=', $today)->select(DB::raw('SUM(patient_account_balance) as patient_account_balance'))->first()->patient_account_balance;
break;
}
$patient_account_data_string = $request->dates . "," . $request->start_date . "," . $request->end_date . "," . 'patient_accounts_deposits' . "," . $patient_account_id;
$data[] = ['id' => $patient_account_id, 'amount' => $patient_account_balance, 'data' => $patient_account_data_string];
}
foreach ($accounts as $account_id) {
$hospital_bills = [];
switch ($request->dates) {
case 'today':
$hospital_bills = DB::table('hospital_bills')->whereNull('deleted_at')->whereDate('bill_date', '<=', $today)->whereRaw('FIND_IN_SET(' . $account_id . ',payable_account)')->get();
break;
case 'yesterday':
$hospital_bills = DB::table('hospital_bills')->whereNull('deleted_at')->whereDate('bill_date', '<=', $yesterday)->whereRaw('FIND_IN_SET(' . $account_id . ',payable_account)')->get();
break;
case 'custom_date':
$hospital_bills = DB::table('hospital_bills')->whereNull('deleted_at')->whereDate('bill_date', '<=', $start)->whereRaw('FIND_IN_SET(' . $account_id . ',payable_account)')->get();
break;
case 'custom_date_range':
$hospital_bills = DB::table('hospital_bills')->whereNull('deleted_at')->whereBetween('bill_date', [$start, $end])->whereRaw('FIND_IN_SET(' . $account_id . ',payable_account)')->get();
break;
}
$hospital_bills_total = 0;
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;
$hospital_bills_total += $hospital_bill_balance;
}
$accounts_payable_data_string = $request->dates . "," . $request->start_date . "," . $request->end_date . "," . 'hospital_bills' . "," . $account_id . ",";
$data[] = ['id' => $account_id, 'amount' => $hospital_bills_total, 'data' => $accounts_payable_data_string];
}
$journals = [];
switch ($request->dates) {
case 'today':
$journals = DB::table('journals')->whereNull('deleted_at')->whereDate('journal_date', '<=', $today->toDateString())->whereNotIn('journal_number', $probable_duplicate_records)->get();
break;
case 'yesterday':
$journals = DB::table('journals')->whereNull('deleted_at')->whereDate('journal_date', '<=', $yesterday->toDateString())->whereNotIn('journal_number', $probable_duplicate_records)->get();
break;
case 'custom_date':
$journals = DB::table('journals')->whereNull('deleted_at')->whereDate('journal_date', '<=', $start->toDateString())->whereNotIn('journal_number', $probable_duplicate_records)->get();
break;
case 'custom_date_range':
$journals = DB::table('journals')->whereNull('deleted_at')->whereBetween('journal_date', [$start->toDateString(), $end->toDateString()])->whereNotIn('journal_number', $probable_duplicate_records)->get();
break;
}
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];
$non_current_liabilty_value = 0;
if ($credit != null) {
// This Liability Account's value was Increased via the Journal
$non_current_liabilty_value = (int)$credit;
foreach ($data as $key => $value) {
if ($data[$key]['id'] == $liability_account_id) {
$data[$key]['amount'] = $value['amount'] + $non_current_liabilty_value;
$data_string = $request->dates . "," . $request->start_date . "," . $request->end_date . "," . 'journals' . "," . $liability_account_id . ",";
$data[$key]['data'] = $data_string;
}
}
}
}
}
}
return $data;
}
function getOtherCurrentLiabilitiesByAccountBalanceSheet($request)
{
$data = $probable_duplicate_records = [];
$other_current_liabilities = ChartOfAccount::where('type', 12)->get();
$today = Carbon::today()->endOfDay();
$yesterday = Carbon::yesterday()->endOfDay();
$end = Carbon::parse($request->end_date)->endOfDay();
$start = Carbon::parse($request->start_date)->startOfDay();
foreach ($other_current_liabilities as $account) {
$hospital_bills = [];
switch ($request->dates) {
case 'today':
$hospital_bills = DB::table('hospital_bills')->whereNull('deleted_at')->whereDate('created_at', '<=', $today)->where('payable_account', $account->id)->get();
break;
case 'yesterday':
$hospital_bills = DB::table('hospital_bills')->whereNull('deleted_at')->whereDate('created_at', '<=', $yesterday)->where('payable_account', $account->id)->get();
break;
case 'custom_date':
$hospital_bills = DB::table('hospital_bills')->whereNull('deleted_at')->whereDate('created_at', '<=', $start)->where('payable_account', $account->id)->get();
break;
case 'custom_date_range':
$hospital_bills = DB::table('hospital_bills')->whereNull('deleted_at')->whereBetween('created_at', [$start, $end])->where('payable_account', $account->id)->get();
break;
}
$hospital_bills_total = 0;
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;
}
$item_amount_array = explode(',', $bill->item_subtotals);
$payable_account_array = explode(',', $bill->payable_account);
$item_balance_remaining_array = explode(',', $bill->item_balance_remaining);
if (is_integer($bill->balance)) {
if ($bill->balance != 0) {
for ($i = 0; $i < count($item_amount_array); $i++) {
if (isset($payable_account_array[$i]) && $payable_account_array[$i] == $account->id) {
$loan_amount = (isset($item_balance_remaining_array[$i])) ? (int)$item_balance_remaining_array[$i] : (int)$item_amount_array[$i];
$hospital_bills_total += $loan_amount;
}
}
}
} else {
for ($i = 0; $i < count($item_amount_array); $i++) {
if (isset($payable_account_array[$i]) && $payable_account_array[$i] == $account->id && isset($item_amount_array[$i])) {
$hospital_bills_total += (int)$item_amount_array[$i];
}
}
}
}
$accounts_payable_data_string = $request->dates . "," . $request->start_date . "," . $request->end_date . "," . 'hospital_bills' . "," . $account->id . ",";
$data[] = ['id' => $account->id, 'amount' => $hospital_bills_total, 'data' => $accounts_payable_data_string];
}
$journals = [];
switch ($request->dates) {
case 'today':
$journals = DB::table('journals')->whereNull('deleted_at')->whereDate('journal_date', '<=', $today->toDateString())->whereNotIn('journal_number', $probable_duplicate_records)->get();
break;
case 'yesterday':
$journals = DB::table('journals')->whereNull('deleted_at')->whereDate('journal_date', '<=', $yesterday->toDateString())->whereNotIn('journal_number', $probable_duplicate_records)->get();
break;
case 'custom_date':
$journals = DB::table('journals')->whereNull('deleted_at')->whereDate('journal_date', $start->toDateString())->whereNotIn('journal_number', $probable_duplicate_records)->get();
break;
case 'custom_date_range':
$journals = DB::table('journals')->whereNull('deleted_at')->whereBetween('journal_date', [$start->toDateString(), $end->toDateString()])->whereNotIn('journal_number', $probable_duplicate_records)->get();
break;
}
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 an other current liability account
if (get_name($account_ids[$i], 'id', 'type', 'chart_of_accounts') == 12) {
$liability_account_id = $account_ids[$i];
$credit = $credits[$i];
$other_current_liabilty_value = 0;
if ($credit != null) {
// This Liability Account's value was Increased via the Journal
$other_current_liabilty_value = (int)$credit;
foreach ($data as $key => $value) {
if ($data[$key]['id'] == $liability_account_id) {
$data[$key]['amount'] = $value['amount'] + $other_current_liabilty_value;
$data_string = $request->dates . "," . $request->start_date . "," . $request->end_date . "," . 'journals' . "," . $liability_account_id . ",";
$data[$key]['data'] = $data_string;
}
}
}
}
}
}
return $data;
}
function getEquitiesByAccount($request)
{
$data = [];
$accounts = ChartOfAccount::where('type', 5)->pluck('id')->toArray();
$start_date = Carbon::parse($request->start_date)->toDateTimeString();
$filters[] = ['transaction_date', '<=', $start_date];
for ($i = 0; $i < count($accounts); $i++) {
$slug = get_name($accounts[$i], 'id', 'slug', 'chart_of_accounts');
//if ($slug != 'opening_inventory') {
$equities_total = 0;
$equities = DB::table('equities')->where('account_id', $accounts[$i])->where($filters)->get();
foreach ($equities as $equity) {
$equities_total += (int)$equity->amount;
}
$data_string = $request->dates . "," . $request->start_date . "," . $request->end_date . "," . 'equities' . "," . $accounts[$i] . ",";
$data[] = ['id' => $accounts[$i], 'amount' => $equities_total, 'data' => $data_string];
//}
}
// opening balances for banks
$banks = ChartOfAccount::where('type', 4)->pluck('id')->toArray();
$opening_balance_record = [];
$_today = Carbon::today();
$_yesterday = Carbon::yesterday();
$total_banks_opening_balance = 0;
foreach ($banks as $bank) {
switch ($request->dates) {
case 'today':
$opening_balance_record = get_actual_opening_balance_record_of_account($bank, $_today);
break;
case 'yesterday':
$opening_balance_record = get_actual_opening_balance_record_of_account($bank, $_yesterday);
break;
case 'custom_date':
//$start = Carbon::parse($request->start_date)->startOfDay()->toDateTimeString();
$opening_balance_record = get_actual_opening_balance_record_of_account($bank, $request->start_date);
break;
case 'custom_date_range':
$end = Carbon::parse($request->end_date)->endOfDay()->toDateTimeString();
$opening_balance_record = get_actual_opening_balance_record_of_account($bank, $end);
break;
}
$total_banks_opening_balance += $opening_balance_record ? $opening_balance_record->account_balance : 0;
}
$bank_id = get_name('opening_balance_for_banks', 'slug', 'id', 'chart_of_accounts');
$bank_data_string = $request->dates . "," . $request->start_date . "," . $request->end_date . "," . 'banking' . "," . $bank_id . ",";
foreach ($data as $key => $value) {
if ($data[$key]['id'] == $bank_id) {
$data[$key]['amount'] = $value['amount'] + $total_banks_opening_balance;
$data[$key]['data'] = $bank_data_string;
}
}
// opening inventory from stores and pharmacy and lab for sundries drugs and radiologies.
// So in the drugs and sundries tables, there's a column called "opening stock" that holds the opening quantity of the respective items.
// For example: if for Paracetamol the opening stock has a value of 600, it means that the hospital opened with 600 tablets of Paracetamol.
// When the column value is null, it means that the opening quantity of that item has not been taken yet and vice versa.
$total_inventory_opening_balance = 0;
switch ($request->dates) {
case 'yesterday':
$drugs = DB::table('drugs')->whereNotNull('opening_stock')->whereDate('opening_stock_date', '<=', $_yesterday)->get(['id', 'opening_stock', 'opening_cost_price']);
$sundries = DB::table('sundries')->whereNotNull('opening_stock')->whereDate('opening_stock_date', '<=', $_yesterday)->get(['id', 'opening_stock', 'opening_cost_price']);
break;
case 'custom_date':
$start = Carbon::parse($request->start_date)->startOfDay()->toDateTimeString();
$drugs = DB::table('drugs')->whereNotNull('opening_stock')->whereDate('opening_stock_date', '<=', $start)->get(['id', 'opening_stock', 'opening_cost_price']);
$sundries = DB::table('sundries')->whereNotNull('opening_stock')->whereDate('opening_stock_date', '<=', $start)->get(['id', 'opening_stock', 'opening_cost_price']);
break;
case 'custom_date_range':
$start = Carbon::parse($request->start_date)->startOfDay()->toDateTimeString();
$end = Carbon::parse($request->end_date)->endOfDay()->toDateTimeString();
$drugs = DB::table('drugs')->whereNotNull('opening_stock')->whereDate('opening_stock_date', '<=', $end)->get(['id', 'opening_stock', 'opening_cost_price']);
$sundries = DB::table('sundries')->whereNotNull('opening_stock')->whereDate('opening_stock_date', '<=', $end)->get(['id', 'opening_stock', 'opening_cost_price']);
break;
case 'today':
default:
$drugs = DB::table('drugs')->whereNotNull('opening_stock')->whereDate('opening_stock_date', '<=', $_today)->get(['id', 'opening_stock', 'opening_cost_price']);
$sundries = DB::table('sundries')->whereNotNull('opening_stock')->whereDate('opening_stock_date', '<=', $_today)->get(['id', 'opening_stock', 'opening_cost_price']);
break;
}
foreach ($drugs as $drug) {
$opening_stock = $drug->opening_stock;
if ($drug->opening_cost_price == 0) {
$opening_drugs_inventory_balance = get_first_cost_of_good($drug->id, 1) * $opening_stock;
} else {
$opening_drugs_inventory_balance = $drug->opening_cost_price * $opening_stock;
}
$total_inventory_opening_balance += $opening_drugs_inventory_balance;
}
foreach ($sundries as $sundry) {
$opening_stock = $sundry->opening_stock;
if ($sundry->opening_cost_price == 0) {
$opening_sundries_inventory_balance = get_first_cost_of_good($sundry->id, 2) * $opening_stock;
} else {
$opening_sundries_inventory_balance = ($sundry->opening_cost_price * $opening_stock);
}
$total_inventory_opening_balance += $opening_sundries_inventory_balance;
}
$account = get_name('opening_inventory', 'slug', 'id', 'chart_of_accounts');
$opening_inventory_data_string = $request->dates . "," . $request->start_date . "," . $request->end_date . "," . 'opening_inventory' . "," . $account;
$data[] = ['id' => $account, 'amount' => $total_inventory_opening_balance, 'data' => $opening_inventory_data_string];
return $data;
}
function getEquitiesByAccountCustom($request)
{
// TODO: Get data for Standard Equity account `Opening Inventory`. Consult Bright
$data = $equities = [];
$equities_total = 0;
$_today = Carbon::today();
$_yesterday = Carbon::yesterday();
$start = Carbon::parse($request->start_date)->startOfDay()->toDateTimeString();
$end = Carbon::parse($request->end_date)->endOfDay()->toDateTimeString();
$accounts = \Streamline\Models\ChartOfAccount::where('type', 5)->pluck('id')->toArray();
for ($i = 0; $i < count($accounts); $i++) {
$slug = get_name($accounts[$i], 'id', 'slug', 'chart_of_accounts');
// $balance = get_name($accounts[$i], 'id', 'balance', 'chart_of_accounts');
if ($slug != 'opening_inventory') {
$equities_total = 0;
$equities = \Streamline\Models\Equity::where('account_id', $accounts[$i])->whereBetween('created_at', [$start, $end])->get();
foreach ($equities as $equity) {
$equities_total += (int)$equity->amount;
}
$data_string = $request->dates . "," . $request->start_date . "," . $request->end_date . "," . 'equities' . "," . $accounts[$i] . ",";
$data[] = ['id' => $accounts[$i], 'amount' => $equities_total, 'data' => $data_string];
}
}
// opening balances for banks
$banks = \Streamline\Models\ChartOfAccount::where('type', 4)->pluck('id')->toArray();
$opening_balance_record = [];
$total_banks_opening_balance = 0;
foreach ($banks as $bank) {
switch ($request->dates) {
case 'today':
$opening_balance_record = get_latest_opening_balance_record($bank, $_today);
break;
case 'yesterday':
$opening_balance_record = get_latest_opening_balance_record($bank, $_yesterday);
break;
case 'custom_date':
$opening_balance_record = get_latest_opening_balance_record($bank, $start);
break;
case 'custom_date_range':
$opening_balance_record = get_latest_opening_balance_record($bank, $end);
break;
}
$total_banks_opening_balance += (!is_null($opening_balance_record) && !empty($opening_balance_record)) ? $opening_balance_record->account_balance : 0;
}
$bank_id = get_name('opening_balance_for_banks', 'slug', 'id', 'chart_of_accounts');
$bank_data_string = $request->dates . "," . $request->start_date . "," . $request->end_date . "," . 'banking' . "," . $bank_id . ",";
foreach ($data as $key => $value) {
if ($data[$key]['id'] == $bank_id) {
$data[$key]['amount'] = $value['amount'] + $total_banks_opening_balance;
$data[$key]['data'] = $bank_data_string;
}
}
return $data;
}
function getRevenueSumByAccount(Request $request): array
{
$end = Carbon::parse($request->end_date)->endOfDay()->toDateTimeString();
$start = Carbon::parse($request->start_date)->startOfDay()->toDateTimeString();
$accounts = !empty($request->income_ids) ? $request->income_ids : ChartOfAccount::where('type', 1)->pluck('id')->toArray();
$cog_accounts = !empty($request->cost_of_goods_ids) ? $request->cost_of_goods_ids : ChartOfAccount::where('type', 7)->pluck('id')->toArray();
$accounts_array = $accounts_cog_array = $exclude_receipts = [];
$inpatient_deposits_account_id = get_name("inpatient_deposits", "slug", "id", "chart_of_accounts");
// sales tables
for ($w = 0; $w < count($accounts); $w++) {
$patient_category_invoices = DB::table('patient_category_invoices')->whereRaw('FIND_IN_SET(' . $accounts[$w] . ',income_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', 'income_account', 'patient_id', 'patient_category', 'cost_of_goods_account', 'items_ids']);
foreach ($patient_category_invoices as $item) {
$invoice_items_ids_array = explode(",", $item->items_ids);
$invoice_item_amounts_sum = array_sum(explode(",", $item->items_amounts));
$invoice_items_quantity_array = explode(",", $item->items_quantity);
$invoice_item_cost_price_array = explode(",", $item->cost_price);
$invoice_item_selling_price_array = explode(",", $item->items_amounts);
$income_accounts_array = explode(",", $item->income_account);
$cost_of_goods_account_array = explode(",", $item->cost_of_goods_account);
//loop through per item since column values are comma separated values
for ($z = 0; $z < count($invoice_items_ids_array); $z++) {
//only if the item income accounts is the same as the one in the loop coz columns value = "income1,income2" etc
if (isset($income_accounts_array[$z])) {
if ($income_accounts_array[$z] == $accounts[$w]) {
$accounts_array[$accounts[$w]]['accrual'] = ($invoice_item_selling_price_array[$z] ?? 0) + ($accounts_array[$accounts[$w]]['accrual'] ?? 0);
// this section is for instances involving pay later co-payments so there is no repetition involving the accrual amount,
// so we have to exclude it from the deposit tables and add that deficit amount here to the accounts array
if ($invoice_item_amounts_sum != $item->patient_amount) {
$accounts_array[$accounts[$w]]['accrual'] = ($invoice_item_amounts_sum - ($invoice_item_selling_price_array[$z] ?? 0)) + ($accounts_array[$accounts[$w]]['accrual'] ?? 0);
$exclude_receipts[$item->receipt_number] = $item->receipt_number;
}
// for drugs and sundries, get the cost of goods if there is no cash payment
if (($item->tag_id == 3 || $item->tag_id == 5)) {
$cost_price = 0;
//====== check if the patient is a dependant of another patient and overide category ========//
$patient_is_a_dependant_of = patient_is_a_dependant_of($item->patient_id);
$does_patient_category_have_threshold = does_patient_category_have_threshold($item->patient_category);
if ($does_patient_category_have_threshold || !is_null($patient_is_a_dependant_of)) {
$cost_price += (isset($invoice_items_quantity_array[$z]) && is_numeric($invoice_items_quantity_array[$z]) ? $invoice_items_quantity_array[$z] : 1) * (isset($invoice_item_cost_price_array[$z]) && is_numeric($invoice_item_cost_price_array[$z]) ? $invoice_item_cost_price_array[$z] : 1);
$accounts_cog_array[$cost_of_goods_account_array[$z]]['accrual'] = $cost_price + ($accounts_cog_array[$cost_of_goods_account_array[$z]]['accrual'] ?? 0);
//$accounts_cog_array[$cost_of_goods_account_array[$z]]['cash'] = 0;
} else {
if ($invoice_item_amounts_sum == $item->patient_amount) {
$cost_price += (isset($invoice_items_quantity_array[$z]) && is_numeric($invoice_items_quantity_array[$z]) ? $invoice_items_quantity_array[$z] : 1) * (isset($invoice_item_cost_price_array[$z]) && is_numeric($invoice_item_cost_price_array[$z]) ? $invoice_item_cost_price_array[$z] : 1);
$accounts_cog_array[$cost_of_goods_account_array[$z]]['accrual'] = $cost_price + ($accounts_cog_array[$cost_of_goods_account_array[$z]]['accrual'] ?? 0);
//$accounts_cog_array[$cost_of_goods_account_array[$z]]['cash'] = 0;
}
}
}
}
}
}
}
}
$services_deposits = DB::table('service_deposits')->whereNull('deleted_at')
->whereBetween('created_at', [$start, $end])
->where('service_type', '!=', 'Inpatient_Deposit')
->get(['item_amount_paid', 'current_chart_of_accounts', 'items_amounts', 'receipt_number']);
foreach ($services_deposits as $deposit) {
$item_amount_array = explode(',', $deposit->items_amounts);
$item_account_array = explode(',', $deposit->current_chart_of_accounts);
$item_cash_amount_array = explode(',', $deposit->item_amount_paid);
$is_receipt_excluded = isset($exclude_receipts[$deposit->receipt_number]);
for ($x = 0; $x < count($item_amount_array); $x++) {
if (isset($item_account_array[$x]) && is_numeric($item_account_array[$x])) {
$accounts_array[$item_account_array[$x]]['cash'] = $item_cash_amount_array[$x] + ($accounts_array[$item_account_array[$x]]['cash'] ?? 0);
if (!$is_receipt_excluded) {
$accounts_array[$item_account_array[$x]]['accrual'] = $item_amount_array[$x] + ($accounts_array[$item_account_array[$x]]['accrual'] ?? 0);
}
}
}
}
$procedure_deposits = DB::table('procedure_deposits')->whereNull('deleted_at')
->whereBetween('created_at', [$start, $end])
->get(['item_amount_paid', 'current_chart_of_accounts', 'procedure_amounts', 'receipt_number']);
foreach ($procedure_deposits as $deposit) {
$item_amount_array = explode(',', $deposit->procedure_amounts);
$item_account_array = explode(',', $deposit->current_chart_of_accounts);
$item_cash_amount_array = explode(',', $deposit->item_amount_paid);
$is_receipt_excluded = isset($exclude_receipts[$deposit->receipt_number]);
for ($x = 0; $x < count($item_amount_array); $x++) {
if (isset($item_account_array[$x]) && is_numeric($item_account_array[$x])) {
$accounts_array[$item_account_array[$x]]['cash'] = $item_cash_amount_array[$x] + ($accounts_array[$item_account_array[$x]]['cash'] ?? 0);
if (!$is_receipt_excluded) {
$accounts_array[$item_account_array[$x]]['accrual'] = $item_amount_array[$x] + ($accounts_array[$item_account_array[$x]]['accrual'] ?? 0);
}
}
}
}
$optic_deposits = DB::table('eye_glasses_deposits')->whereNull('deleted_at')
->whereBetween('created_at', [$start, $end])
->get(['item_amount_paid', 'current_chart_of_accounts', 'subtotals', 'receipt_number', 'cost_price', 'quantity', 'patient_amount_paid', 'cost_of_goods_account']);
foreach ($optic_deposits as $deposit) {
$item_amount_array = explode(',', $deposit->subtotals);
$item_account_array = explode(',', $deposit->current_chart_of_accounts);
$item_cash_amount_array = $deposit->item_amount_paid == '' ? explode(',', $deposit->subtotals) : explode(',', $deposit->item_amount_paid);
$is_receipt_excluded = isset($exclude_receipts[$deposit->receipt_number]);
$cost_price_array = explode(',', $deposit->cost_price);
$quantities = explode(',', $deposit->quantity);
$patient_amount_paid = $deposit->patient_amount_paid;
$item_total = array_sum($item_amount_array);
$cost_of_goods_account_array = $deposit->cost_of_goods_account;
for ($x = 0; $x < count($item_amount_array); $x++){
if (isset($item_account_array[$x]) && is_numeric($item_account_array[$x])) {
$accounts_array[$item_account_array[$x]]['cash'] = $item_cash_amount_array[$x] + ($accounts_array[$item_account_array[$x]]['cash'] ?? 0);
if (!$is_receipt_excluded) {
$accounts_array[$item_account_array[$x]]['accrual'] = $item_amount_array[$x] + ($accounts_array[$item_account_array[$x]]['accrual'] ?? 0);
}
// for cost of goods
$cost_price = (is_numeric($quantities[$x]) ? $quantities[$x] : 1) * $cost_price_array[$x];
$accounts_cog_array[$cost_of_goods_account_array]['accrual'] = $cost_price + ($accounts_cog_array[$cost_of_goods_account_array]['accrual'] ?? 0);
if ($patient_amount_paid == $item_total) {
$accounts_cog_array[$cost_of_goods_account_array]['cash'] = $cost_price + ($accounts_cog_array[$cost_of_goods_account_array]['cash'] ?? 0);
} else {
$accounts_cog_array[$cost_of_goods_account_array]['cash'] = (($cost_price > 0 && $patient_amount_paid > 0) ? (int)(($patient_amount_paid / $item_total) * $cost_price) : 0) + ($accounts_cog_array[$cost_of_goods_account_array]['cash'] ?? 0);
}
}
}
}
$sundries_deposits = DB::table('sundries_deposits')->whereNull('deleted_at')
->whereBetween('created_at', [$start, $end])
->get(['item_amount_paid', 'current_chart_of_accounts', 'sundry_subtotals', 'receipt_number', 'cost_price', 'sundry_quantity', 'patient_amount_paid', 'cost_of_goods_account']);
foreach ($sundries_deposits as $deposit) {
$item_amount_array = explode(',', $deposit->sundry_subtotals);
$item_account_array = explode(',', $deposit->current_chart_of_accounts);
$cost_of_goods_account = $deposit->cost_of_goods_account;
$item_cash_amount_array = explode(',', $deposit->item_amount_paid);
$is_receipt_excluded = isset($exclude_receipts[$deposit->receipt_number]);
$cost_price_array = explode(',', $deposit->cost_price);
$quantities = explode(',', $deposit->sundry_quantity);
$patient_amount_paid = $deposit->patient_amount_paid;
$item_total = array_sum($item_amount_array);
for ($x = 0; $x < count($item_amount_array); $x++) {
if (isset($item_account_array[$x]) && is_numeric($item_account_array[$x])) {
$accounts_array[$item_account_array[$x]]['cash'] = $item_cash_amount_array[$x] + ($accounts_array[$item_account_array[$x]]['cash'] ?? 0);
if (!$is_receipt_excluded) {
$accounts_array[$item_account_array[$x]]['accrual'] = $item_amount_array[$x] + ($accounts_array[$item_account_array[$x]]['accrual'] ?? 0);
}
// for cost of goods
$cost_price = (is_numeric($quantities[$x]) ? $quantities[$x] : 1) * $cost_price_array[$x];
$accounts_cog_array[$cost_of_goods_account]['accrual'] = $cost_price + ($accounts_cog_array[$cost_of_goods_account]['accrual'] ?? 0);
if ($patient_amount_paid == $item_total) {
$accounts_cog_array[$cost_of_goods_account]['cash'] = $cost_price + ($accounts_cog_array[$cost_of_goods_account]['cash'] ?? 0);
} else {
$accounts_cog_array[$cost_of_goods_account]['cash'] = (($cost_price > 0 && $patient_amount_paid > 0) ? (int)(($patient_amount_paid / $item_total) * $cost_price) : 0) + ($accounts_cog_array[$cost_of_goods_account]['cash'] ?? 0);
}
}
}
}
$investigation_deposits = DB::table('investigation_deposits')->whereNull('deleted_at')
->whereBetween('created_at', [$start, $end])
->get(['item_amount_paid', 'current_chart_of_accounts', 'investigation_amounts', 'receipt_number']);
foreach ($investigation_deposits as $deposit) {
$item_amount_array = explode(',', $deposit->investigation_amounts);
$item_account_array = explode(',', $deposit->current_chart_of_accounts);
$item_cash_amount_array = explode(',', $deposit->item_amount_paid);
$is_receipt_excluded = isset($exclude_receipts[$deposit->receipt_number]);
for ($x = 0; $x < count($item_amount_array); $x++) {
if (isset($item_account_array[$x]) && is_numeric($item_account_array[$x])) {
$accounts_array[$item_account_array[$x]]['cash'] = $item_cash_amount_array[$x] + ($accounts_array[$item_account_array[$x]]['cash'] ?? 0);
if (!$is_receipt_excluded) {
$accounts_array[$item_account_array[$x]]['accrual'] = $item_amount_array[$x] + ($accounts_array[$item_account_array[$x]]['accrual'] ?? 0);
}
}
}
}
$treatment_deposits = DB::table('treatment_deposits')->whereNull('deleted_at')
->whereBetween('created_at', [$start, $end])
->get(['item_amount_paid', 'current_chart_of_accounts', 'treatment_subtotals', 'receipt_number', 'cost_price', 'treatment_quantities', 'patient_amount_paid', 'cost_of_goods_account','treatment_items','patient_id','treatment_id']);
foreach ($treatment_deposits as $deposit) {
$treatment_items_array = explode(',', $deposit->treatment_items);
$item_amount_array = explode(',', $deposit->treatment_subtotals);
$item_account_array = explode(',', $deposit->current_chart_of_accounts);
$item_cash_amount_array = explode(',', $deposit->item_amount_paid);
$is_receipt_excluded = isset($exclude_receipts[$deposit->receipt_number]);
$item_total = array_sum($item_amount_array);
$cost_price_array = explode(',', $deposit->cost_price);
$quantities = explode(',', $deposit->treatment_quantities);
$cost_of_goods_account = $deposit->cost_of_goods_account;
$patient_amount_paid = $deposit->patient_amount_paid;
for ($x = 0; $x < count($item_amount_array); $x++) {
if (isset($item_account_array[$x]) && is_numeric($item_account_array[$x])) {
$accounts_array[$item_account_array[$x]]['cash'] = $item_cash_amount_array[$x] + ($accounts_array[$item_account_array[$x]]['cash'] ?? 0);
if (!$is_receipt_excluded) {
$accounts_array[$item_account_array[$x]]['accrual'] = $item_amount_array[$x] + ($accounts_array[$item_account_array[$x]]['accrual'] ?? 0);
}
// for cost of goods
$batch_tracking_record = \Streamline\Models\BatchConsumptionTracking::where(['item_type'=> 1, 'item_id' => $treatment_items_array[$x], 'patient_id' => $deposit->patient_id, 'reduction_table' => 'treatments', 'reduction_table_id' => $deposit->treatment_id])->first();
if($batch_tracking_record){
$batch_record = \Streamline\Models\ItemBatchWatcher::where(['item_type'=> 1, 'item_id' => $treatment_items_array[$x], 'batch_number' => $batch_tracking_record->batch_number])->first();
if($batch_record){
$cost_price = (is_numeric($quantities[$x]) ? $quantities[$x] : 1) * $batch_record->cost_price;
}
} else{
$cost_price = (is_numeric($quantities[$x]) ? $quantities[$x] : 1) * $cost_price_array[$x];
}
// accrual, get all the money
$accounts_cog_array[$cost_of_goods_account]['accrual'] = $cost_price + ($accounts_cog_array[$cost_of_goods_account]['accrual'] ?? 0);
if ($patient_amount_paid == $item_total) {
// if patient paid all, get all
$accounts_cog_array[$cost_of_goods_account]['cash'] = $cost_price + ($accounts_cog_array[$cost_of_goods_account]['cash'] ?? 0);
} else {
// if patient paid some, get percentage of what they paid against the total price and apply that to the cost price
$accounts_cog_array[$cost_of_goods_account]['cash'] = (($cost_price > 0 && $patient_amount_paid > 0) ? (int)(($patient_amount_paid / $item_total) * $cost_price) : 0) + ($accounts_cog_array[$cost_of_goods_account]['cash'] ?? 0);
}
}
}
}
$other_incomes = DB::table('other_incomes')->whereIn('income_account', $accounts)
->whereNull('deleted_at')->whereBetween('deposit_date', [$start, $end])
->get(['deposit_amount', 'deposit_amount', 'income_account']);
foreach ($other_incomes as $item) {
$accounts_array[$item->income_account]['cash'] = $item->deposit_amount + ($accounts_array[$item->income_account]['cash'] ?? 0);
$accounts_array[$item->income_account]['accrual'] = $item->deposit_amount + ($accounts_array[$item->income_account]['accrual'] ?? 0);
}
$debtors = DB::table('debtor_payments')
->leftJoin('debtors', 'debtors.id', '=', 'debtor_payments.debt_id')
->whereIn('debtors.income_account', $accounts)
->whereNull('debtor_payments.deleted_at')->whereBetween('debtor_payments.created_at', [$start, $end])
->get(['debtor_payments.amount_paid', 'debtors.income_account']);
foreach ($debtors as $item) {
$accounts_array[$item->income_account]['cash'] = $item->amount_paid + ($accounts_array[$item->income_account]['cash'] ?? 0);
}
$debt_plan = DB::table('debt_plan')->whereIn('income_account', $accounts)
->whereNull('deleted_at')->whereBetween('created_at', [$start, $end])
->get(['staff_guarantor_to_pay', 'balance_remaining', 'amount_paid_off', 'income_account']);
foreach ($debt_plan as $item) {
if (!is_null($item->amount_paid_off)) {
$accounts_array[$item->income_account]['cash'] = $item->amount_paid_off + ($accounts_array[$item->income_account]['cash'] ?? 0);
}
}
$ward_extras = DB::table('ward_extras')->whereNull('deleted_at')->whereIn('current_chart_of_account', $accounts)
->whereBetween('created_at', [$start, $end])
->get(['amount_paid', 'extra_cost', 'current_chart_of_account']);
foreach ($ward_extras as $item) {
$accounts_array[$item->current_chart_of_account]['cash'] = $item->amount_paid + ($accounts_array[$item->current_chart_of_account]['cash'] ?? 0);
$accounts_array[$item->current_chart_of_account]['accrual'] = $item->extra_cost + ($accounts_array[$item->current_chart_of_account]['accrual'] ?? 0);
// balances out money from deposits and ward_ tables (look at trial balance treatment dispensation for details)
if (isset($accounts_array[$inpatient_deposits_account_id])) {
$accounts_array[$inpatient_deposits_account_id]['cash'] = ($accounts_array[$inpatient_deposits_account_id]['cash'] ?? 0) - $item->amount_paid;
$accounts_array[$inpatient_deposits_account_id]['accrual'] = ($accounts_array[$inpatient_deposits_account_id]['accrual'] ?? 0) - $item->extra_cost;
}
}
$ward_procedures = DB::table('ward_procedures')->whereNull('deleted_at')->whereIn('current_chart_of_account', $accounts)
->whereBetween('created_at', [$start, $end])
->get(['hospital_fee', 'staff_fee', 'amount_paid', 'current_chart_of_account']);
foreach ($ward_procedures as $item) {
$accounts_array[$item->current_chart_of_account]['cash'] = $item->amount_paid + ($accounts_array[$item->current_chart_of_account]['cash'] ?? 0);
$accounts_array[$item->current_chart_of_account]['accrual'] = $item->hospital_fee + $item->staff_fee + ($accounts_array[$item->current_chart_of_account]['accrual'] ?? 0);
// balances out money from deposits and ward_ tables (look at trial balance treatment dispensation for details)
if (isset($accounts_array[$inpatient_deposits_account_id])) {
$accounts_array[$inpatient_deposits_account_id]['cash'] = ($accounts_array[$inpatient_deposits_account_id]['cash'] ?? 0) - $item->amount_paid;
$accounts_array[$inpatient_deposits_account_id]['accrual'] = ($accounts_array[$inpatient_deposits_account_id]['accrual'] ?? 0) - ($item->hospital_fee + $item->staff_fee);
}
}
$ward_bed_stays = DB::table('ward_bed_stays')->whereNull('deleted_at')->whereIn('current_chart_of_account', $accounts)
->whereBetween('created_at', [$start, $end])
->get(['duration', 'bed_fee_rate', 'amount_paid', 'current_chart_of_account']);
foreach ($ward_bed_stays as $item) {
$accounts_array[$item->current_chart_of_account]['cash'] = $item->amount_paid + ($accounts_array[$item->current_chart_of_account]['cash'] ?? 0);
$accounts_array[$item->current_chart_of_account]['accrual'] = ($item->bed_fee_rate * $item->duration) + ($accounts_array[$item->current_chart_of_account]['accrual'] ?? 0);
// balances out money from deposits and ward_ tables (look at trial balance treatment dispensation for details)
if (isset($accounts_array[$inpatient_deposits_account_id])) {
$accounts_array[$inpatient_deposits_account_id]['cash'] = ($accounts_array[$inpatient_deposits_account_id]['cash'] ?? 0) - $item->amount_paid;
$accounts_array[$inpatient_deposits_account_id]['accrual'] = ($accounts_array[$inpatient_deposits_account_id]['accrual'] ?? 0) - ($item->bed_fee_rate * $item->duration);
}
}
$ward_consultations_and_services = DB::table('ward_consultations_and_services')->whereNull('deleted_at')->whereIn('current_chart_of_account', $accounts)
->whereBetween('created_at', [$start, $end])
->get(['amount_paid', 'quantity_given', 'unit_price', 'current_chart_of_account']);
foreach ($ward_consultations_and_services as $item) {
$accounts_array[$item->current_chart_of_account]['cash'] = $item->amount_paid + ($accounts_array[$item->current_chart_of_account]['cash'] ?? 0);
$accounts_array[$item->current_chart_of_account]['accrual'] = ($item->unit_price * $item->quantity_given) + ($accounts_array[$item->current_chart_of_account]['accrual'] ?? 0);
// balances out money from deposits and ward_ tables (look at trial balance treatment dispensation for details)
if (isset($accounts_array[$inpatient_deposits_account_id])) {
$accounts_array[$inpatient_deposits_account_id]['cash'] = ($accounts_array[$inpatient_deposits_account_id]['cash'] ?? 0) - $item->amount_paid;
$accounts_array[$inpatient_deposits_account_id]['accrual'] = ($accounts_array[$inpatient_deposits_account_id]['accrual'] ?? 0) - ($item->unit_price * $item->quantity_given);
}
}
$ward_investigation_pricings = DB::table('ward_investigation_pricings')->whereNull('deleted_at')->whereIn('current_chart_of_account', $accounts)
->whereBetween('created_at', [$start, $end])
->get(['amount_paid', 'price', 'current_chart_of_account']);
foreach ($ward_investigation_pricings as $item) {
$accounts_array[$item->current_chart_of_account]['cash'] = $item->amount_paid + ($accounts_array[$item->current_chart_of_account]['cash'] ?? 0);
$accounts_array[$item->current_chart_of_account]['accrual'] = $item->price + ($accounts_array[$item->current_chart_of_account]['accrual'] ?? 0);
// balances out money from deposits and ward_ tables (look at trial balance treatment dispensation for details)
if (isset($accounts_array[$inpatient_deposits_account_id])) {
$accounts_array[$inpatient_deposits_account_id]['cash'] = ($accounts_array[$inpatient_deposits_account_id]['cash'] ?? 0) - $item->amount_paid;
$accounts_array[$inpatient_deposits_account_id]['accrual'] = ($accounts_array[$inpatient_deposits_account_id]['accrual'] ?? 0) - ($item->price);
}
}
$ward_sundry_dispensations = DB::table('ward_sundry_dispensations')->whereNull('deleted_at')->whereIn('current_chart_of_account', $accounts)
->whereBetween('created_at', [$start, $end])
->get(['amount_paid', 'quantity_given', 'price', 'current_chart_of_account', 'cost_price', 'cost_of_goods_account', 'sundry_id', 'patient_id', 'id']);
foreach ($ward_sundry_dispensations as $item) {
$accounts_array[$item->current_chart_of_account]['cash'] = $item->amount_paid + ($accounts_array[$item->current_chart_of_account]['cash'] ?? 0);
$accounts_array[$item->current_chart_of_account]['accrual'] = ($item->price * $item->quantity_given) + ($accounts_array[$item->current_chart_of_account]['accrual'] ?? 0);
// balances out money from deposits and ward_ tables (look at trial balance treatment dispensation for details)
if (isset($accounts_array[$inpatient_deposits_account_id])) {
$accounts_array[$inpatient_deposits_account_id]['cash'] = ($accounts_array[$inpatient_deposits_account_id]['cash'] ?? 0) - $item->amount_paid;
$accounts_array[$inpatient_deposits_account_id]['accrual'] = ($accounts_array[$inpatient_deposits_account_id]['accrual'] ?? 0) - ($item->price * $item->quantity_given);
}
// for cost of goods
$item_total = $item->price;
$patient_amount_paid = $item->amount_paid ?? 0;
//check if this record exists in batch consumption trackings table to use particular batch details else use generic
//check if this record exists in batch consumption trackings table to use particular batch details else use generic
$batch_tracking_record = \Streamline\Models\BatchConsumptionTracking::where(['item_type'=> 2, 'item_id' => $item->sundry_id, 'patient_id' => $item->patient_id, 'reduction_table' => 'ward_sundry_dispensations', 'reduction_table_id' => $item->id])->first();
if($batch_tracking_record){
$batch_record = \Streamline\Models\ItemBatchWatcher::where(['item_type'=> 2, 'item_id' => $item->sundry_id, 'batch_number' => $batch_tracking_record->batch_number])->first();
$cost_price = $batch_record->cost_price * (is_numeric($item->quantity_given) ? (int)$item->quantity_given : 0);
} else{
$cost_price = (int)$item->quantity_given * (int)$item->cost_price;
}
$accounts_cog_array[$item->cost_of_goods_account]['accrual'] = $cost_price + ($accounts_cog_array[$item->cost_of_goods_account]['accrual'] ?? 0);
if ($patient_amount_paid == $item_total) {
$accounts_cog_array[$item->cost_of_goods_account]['cash'] = $cost_price + ($accounts_cog_array[$item->cost_of_goods_account]['cash'] ?? 0);
} else {
$accounts_cog_array[$item->cost_of_goods_account]['cash'] = (($cost_price > 0 && $patient_amount_paid > 0) ? (int)(($patient_amount_paid / $item_total) * $cost_price) : 0) + ($accounts_cog_array[$item->cost_of_goods_account]['cash'] ?? 0);
}
}
$ward_treatment_dispensations = DB::table('ward_treatment_dispensations')->whereNull('deleted_at')->whereIn('current_chart_of_account', $accounts)
->whereBetween('created_at', [$start, $end])
->get(['amount_paid', 'quantity_given', 'price', 'current_chart_of_account', 'cost_price', 'id', 'cost_of_goods_account', 'drug_id', 'patient_id']);
foreach ($ward_treatment_dispensations as $item) {
$accounts_array[$item->current_chart_of_account]['cash'] = $item->amount_paid + ($accounts_array[$item->current_chart_of_account]['cash'] ?? 0);
$accounts_array[$item->current_chart_of_account]['accrual'] = ($item->price * $item->quantity_given) + ($accounts_array[$item->current_chart_of_account]['accrual'] ?? 0);
// balances out money from deposits and ward_ tables (look at trial balance treatment dispensation for details)
if (isset($accounts_array[$inpatient_deposits_account_id])) {
$accounts_array[$inpatient_deposits_account_id]['cash'] = ($accounts_array[$inpatient_deposits_account_id]['cash'] ?? 0) - $item->amount_paid;
$accounts_array[$inpatient_deposits_account_id]['accrual'] = ($accounts_array[$inpatient_deposits_account_id]['accrual'] ?? 0) - ($item->price * $item->quantity_given);
}
// for cost of goods
$item_total = $item->price;
$patient_amount_paid = $item->amount_paid ?? 0;
//check if this record exists in batch consumption trackings table to use particular batch details else use generic
$batch_tracking_record = \Streamline\Models\BatchConsumptionTracking::where(['item_type'=> 1, 'item_id' => $item->drug_id, 'patient_id' => $item->patient_id, 'reduction_table' => 'ward_treatment_dispensations', 'reduction_table_id' => $item->id])->first();
if($batch_tracking_record){
$batch_record = \Streamline\Models\ItemBatchWatcher::where(['item_type'=> 1, 'item_id' => $item->drug_id, 'batch_number' => $batch_tracking_record->batch_number])->first();
if ($batch_record) {
$cost_price = $batch_record->cost_price * (is_numeric($item->quantity_given) ? (int)$item->quantity_given : 0);
}
} else{
$cost_price = $item->quantity_given * $item->cost_price;
}
$accounts_cog_array[$item->cost_of_goods_account]['accrual'] = $cost_price + ($accounts_cog_array[$item->cost_of_goods_account]['accrual'] ?? 0);
if ($patient_amount_paid == $item_total) {
$accounts_cog_array[$item->cost_of_goods_account]['cash'] = $cost_price + ($accounts_cog_array[$item->cost_of_goods_account]['cash'] ?? 0);
} else {
// there are some instances where the amount the patient is more than that of the item total which doesn't make sense
// so balance them out here
if ($patient_amount_paid <= $item_total && $cost_price > 0 && $patient_amount_paid > 0) {
$accounts_cog_array[$item->cost_of_goods_account]['cash'] = (int)(($patient_amount_paid / $item_total) * $cost_price) + ($accounts_cog_array[$item->cost_of_goods_account]['cash'] ?? 0);
}
}
}
$opd_treatments_with_inpatient = DB::table('treatments')->whereNull('deleted_at')
->where('inpatient_bill_generated', 1)
->whereBetween('created_at', [$start, $end])
->get(['amount_paid', 'quantities_dispensed', 'unit_selling_prices', 'current_chart_of_account', 'unit_cost_price', 'cost_of_goods_account']);
foreach ($opd_treatments_with_inpatient as $item) {
if (is_int($item->amount_paid) && is_int($item->unit_selling_prices)) {
$accounts_array[$item->current_chart_of_account]['cash'] = $item->amount_paid + ($accounts_array[$item->current_chart_of_account]['cash'] ?? 0);
$accounts_array[$item->current_chart_of_account]['accrual'] = ($item->unit_selling_prices * $item->quantities_dispensed) + ($accounts_array[$item->current_chart_of_account]['accrual'] ?? 0);
// balances out money from deposits and ward_ tables (look at trial balance treatment dispensation for details)
if (isset($accounts_array[$inpatient_deposits_account_id])) {
$accounts_array[$inpatient_deposits_account_id]['cash'] = ($accounts_array[$inpatient_deposits_account_id]['cash'] ?? 0) - $item->amount_paid;
$accounts_array[$inpatient_deposits_account_id]['accrual'] = ($accounts_array[$inpatient_deposits_account_id]['accrual'] ?? 0) - ($item->unit_selling_prices * $item->quantities_dispensed);
}
// for cost of goods
$item_total = $item->unit_selling_prices;
$patient_amount_paid = $item->amount_paid ?? 0;
$cost_price = $item->quantities_dispensed * $item->unit_cost_price;
$accounts_cog_array[$item->cost_of_goods_account]['accrual'] = $cost_price + ($accounts_cog_array[$item->cost_of_goods_account]['accrual'] ?? 0);
if ($patient_amount_paid == $item_total) {
$accounts_cog_array[$item->cost_of_goods_account]['cash'] = $cost_price + ($accounts_cog_array[$item->cost_of_goods_account]['cash'] ?? 0);
} else {
// there are some instances where the amount the patient is more than that of the item total which doesn't make sense
// so balance them out here
if ($patient_amount_paid <= $item_total && $cost_price > 0 && $patient_amount_paid > 0) {
$accounts_cog_array[$item->cost_of_goods_account]['cash'] = (int)(($patient_amount_paid / $item_total) * $cost_price) + ($accounts_cog_array[$item->cost_of_goods_account]['cash'] ?? 0);
}
}
}
}
$cost_of_goods_value = $income_value = [];
foreach ($accounts as $account) {
if (isset($accounts_array[$account])) {
$data_string = $request->dates . "," . $request->start_date . "," . $request->end_date . "," . 'incomes' . "," . $account . "," . "6";
$income_value[$account] = array('cash' => ($accounts_array[$account]['cash'] ?? 0), 'accrual' => ($accounts_array[$account]['accrual'] ?? 0), 'id' => $account, 'data' => $data_string);
}
}
foreach ($cog_accounts as $account) {
if (isset($accounts_cog_array[$account])) {
$data_string = $request->dates . "," . $request->start_date . "," . $request->end_date . "," . 'inventory' . "," . $account . "," . "3";
$cost_of_goods_value[$account] = array('cash' => ($accounts_cog_array[$account]['cash'] ?? 0), 'accrual' => ($accounts_cog_array[$account]['accrual'] ?? 0), 'id' => $account, 'data' => $data_string);
}
}
return [$income_value, $cost_of_goods_value];
}
function get_latest_inventory_cost_price($item_id, $item_type, $date)
{
$stock_watcher_record = StockWatcher::where('item_id', $item_id)->where('item_type', $item_type)->first();
if ($stock_watcher_record) {
$details_arr = json_decode($stock_watcher_record->details, true);
if (!isset($details_arr[$date])) {
// 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);
if ($closest_date < $date) {
// 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];
}
} else {
$details = $details_arr[$date];
}
$cost_price = $details["buying_price"];
} else {
if ($item_type == 1) {
$cost_price = Drug::where('id', $item_id)->pluck('cost_price')->first();
} elseif ($item_type == 2) {
$cost_price = Sundry::where('id', $item_id)->pluck('cost_price')->first();
}
}
return $cost_price;
}
function color_selector($key_word)
{
$color = '';
switch ($key_word) {
case 'red':
$color = "rgba(255,0,0,0.7)";
break;
case 'green':
$color = "rgba(0,255,0,0.7)";
break;
case 'blue':
$color = "rgba(0,0,255,0.7)";
break;
case 'yellow':
$color = "rgba(255,204,0,0.7)";
break;
case 'orange':
$color = "rgba(255,102,0,0.7)";
break;
}
return $color;
}
function plot_graph($graph_label, $type, $names_array, $values_array, $color)
{
// dd($graph_label, $type, $names_array, $values_array);
$graph_color = color_selector($color);
if ($type == 'line') {
$chart = app()->chartjs
->name($graph_label)
->type('line')
->size(['width' => 800, 'height' => 800])
->labels($names_array)
->datasets([
[
"label" => $graph_label,
'backgroundColor' => $graph_color,
'borderColor' => "rgba(38, 185, 154, 0.7)",
"pointBorderColor" => "rgba(38, 185, 154, 0.7)",
"pointBackgroundColor" => "rgba(38, 185, 154, 0.7)",
"pointHoverBackgroundColor" => "#fff",
"pointHoverBorderColor" => "rgba(220,220,220,1)",
'data' => $values_array,
]
])
->options([]);
} elseif ($type == 'bar') {
$chart = app()->chartjs
->name($graph_label)
->type('bar')
->size(['width' => 800, 'height' => 800])
->labels($names_array)
->datasets([
[
"label" => $graph_label,
'backgroundColor' => $graph_color,
'borderColor' => "rgba(38, 185, 154, 0.7)",
"pointBorderColor" => "rgba(38, 185, 154, 0.7)",
"pointBackgroundColor" => "rgba(38, 185, 154, 0.7)",
"pointHoverBackgroundColor" => "#fff",
"pointHoverBorderColor" => "rgba(220,220,220,1)",
'data' => $values_array,
]
])
->options([]);
}
return $chart;
}
function profit_v_loss_multi_color_graph($graph_label, $type, $names_array, $values_array)
{
// dd([$values_array[0]]);
$chart = app()->chartjs
->name($graph_label)
->type('bar')
->size(['width' => 800, 'height' => 800])
->labels($names_array)
->datasets([
[
"label" => 'income',
'backgroundColor' => color_selector('green'),
'borderColor' => "rgba(38, 185, 154, 0.7)",
"pointBorderColor" => "rgba(38, 185, 154, 0.7)",
"pointBackgroundColor" => "rgba(38, 185, 154, 0.7)",
"pointHoverBackgroundColor" => "#fff",
"pointHoverBorderColor" => "rgba(220,220,220,1)",
'data' => [$values_array[0], 0],
],
[
"label" => 'expense',
'backgroundColor' => color_selector('red'),
'borderColor' => "rgba(38, 185, 154, 0.7)",
"pointBorderColor" => "rgba(38, 185, 154, 0.7)",
"pointBackgroundColor" => "rgba(38, 185, 154, 0.7)",
"pointHoverBackgroundColor" => "#fff",
"pointHoverBorderColor" => "rgba(220,220,220,1)",
'data' => [0, $values_array[1]],
]
])
->options([]);
return $chart;
}
function dataForIncomeAccrualGraph(Request $request): array
{
$result = $dates = $amounts = $deposit_per_account = [];
$today = Carbon::today()->toDateString();
$yesterday = Carbon::yesterday()->toDateString();
$end = Carbon::parse($request->end_date)->endOfDay()->toDateTimeString();
$start = Carbon::parse($request->start_date)->startOfDay()->toDateTimeString();
$accounts = ChartOfAccount::where('type', 1)->get();
$tables = ['service_deposits', 'investigation_deposits', 'treatment_deposits', 'procedure_deposits', 'sundries_deposits'];
foreach ($tables as $table) {
switch ($request->dates) {
case 'today':
$result[$table] = DB::table($table)->whereNull('deleted_at')->whereDate('created_at', $today)->get()->toArray();
break;
case 'yesterday':
$result[$table] = DB::table($table)->whereNull('deleted_at')->whereDate('created_at', $yesterday)->get()->toArray();
break;
case 'custom_date':
$result[$table] = DB::table($table)->whereNull('deleted_at')->whereDate('created_at', $start)->get()->toArray();
break;
case 'custom_date_range':
$result[$table] = DB::table($table)->whereNull('deleted_at')->whereBetween('created_at', [$start, $end])->get()->toArray();
break;
}
}
if (!empty($result)) {
foreach ($result['service_deposits'] as $item) {
foreach ($accounts as $account) {
if ($item->current_chart_of_accounts == $account->id) {
$deposit_per_account['services'][$account->id][] = $item;
}
}
}
foreach ($result['procedure_deposits'] as $item) {
foreach ($accounts as $account) {
if ($item->current_chart_of_accounts == $account->id) {
$deposit_per_account['procedures'][$account->id][] = $item;
}
}
}
foreach ($result['treatment_deposits'] as $item) {
foreach ($accounts as $account) {
if ($item->current_chart_of_accounts == $account->id) {
$deposit_per_account['treatments'][$account->id][] = $item;
}
}
}
foreach ($result['sundries_deposits'] as $item) {
foreach ($accounts as $account) {
if ($item->current_chart_of_accounts == $account->id) {
$deposit_per_account['sundries'][$account->id][] = $item;
}
}
}
foreach ($result['investigation_deposits'] as $item) {
foreach ($accounts as $account) {
if ($item->current_chart_of_accounts == $account->id) {
$deposit_per_account['investigations'][$account->id][] = $item;
}
}
}
$c = 0;
$amounts = $dates = [];
if (isset($deposit_per_account['services'])) {
if ($deposit_per_account['services']) {
foreach ($deposit_per_account['services'] as $deposits) {
foreach ($deposits as $deposit) {
$dates[$c] = streamline_date($deposit->created_at);
$amounts[$c] = $deposit->items_amounts;
$c++;
}
}
}
}
if (isset($deposit_per_account['treatments'])) {
if ($deposit_per_account['treatments']) {
foreach ($deposit_per_account['treatments'] as $deposits) {
foreach ($deposits as $deposit) {
$dates[$c] = streamline_date($deposit->created_at);
$amounts[$c] = $deposit->treatment_subtotals;
$c++;
}
}
}
}
if (isset($deposit_per_account['procedures'])) {
if ($deposit_per_account['procedures']) {
foreach ($deposit_per_account['procedures'] as $deposits) {
foreach ($deposits as $deposit) {
$dates[$c] = streamline_date($deposit->created_at);
$amounts[$c] = $deposit->procedure_amounts;
$c++;
}
}
}
}
if (isset($deposit_per_account['sundries'])) {
if ($deposit_per_account['sundries']) {
foreach ($deposit_per_account['sundries'] as $deposits) {
foreach ($deposits as $deposit) {
$dates[$c] = streamline_date($deposit->created_at);
$amounts[$c] = $deposit->sundry_subtotals;
$c++;
}
}
}
}
if (isset($deposit_per_account['investigations'])) {
if ($deposit_per_account['investigations']) {
foreach ($deposit_per_account['investigations'] as $deposits) {
foreach ($deposits as $deposit) {
$dates[$c] = streamline_date($deposit->created_at);
$amounts[$c] = $deposit->investigation_amounts;
$c++;
}
}
}
}
}
return ['dates' => $dates, 'amounts' => $amounts];
}
function dataForIncomeCashGraph(Request $request): array
{
$data = $moneys_on_account = $result = $collection = $deposit_per_account = [];
$id = '';
$dates = $amounts = [];
$today = Carbon::today()->toDateString();
$yesterday = Carbon::yesterday()->toDateString();
$end = Carbon::parse($request->end_date)->endOfDay()->toDateTimeString();
$start = Carbon::parse($request->start_date)->startOfDay()->toDateTimeString();
$accounts = \Streamline\Models\ChartOfAccount::where('type', 1)->get();
$tables = ['service_deposits', 'investigation_deposits', 'treatment_deposits', 'procedure_deposits', 'sundries_deposits'];
foreach ($tables as $table) {
switch ($request->dates) {
case 'today':
$result[$table] = DB::table($table)->whereNull('deleted_at')->whereDate('created_at', $today)->get()->toArray();
break;
case 'yesterday':
$result[$table] = DB::table($table)->whereNull('deleted_at')->whereDate('created_at', $yesterday)->get()->toArray();
break;
case 'custom_date':
$result[$table] = DB::table($table)->whereNull('deleted_at')->whereDate('created_at', $start)->get()->toArray();
break;
case 'custom_date_range':
$result[$table] = DB::table($table)->whereNull('deleted_at')->whereBetween('created_at', [$start, $end])->get()->toArray();
break;
}
}
if (!empty($result)) {
foreach ($result['service_deposits'] as $item) {
foreach ($accounts as $account) {
if ($item->current_chart_of_accounts == $account->id) {
$deposit_per_account['services'][$account->id][] = $item;
}
}
}
foreach ($result['procedure_deposits'] as $item) {
foreach ($accounts as $account) {
if ($item->current_chart_of_accounts == $account->id) {
$deposit_per_account['procedures'][$account->id][] = $item;
}
}
}
foreach ($result['treatment_deposits'] as $item) {
foreach ($accounts as $account) {
if ($item->current_chart_of_accounts == $account->id) {
$deposit_per_account['treatments'][$account->id][] = $item;
}
}
}
foreach ($result['sundries_deposits'] as $item) {
foreach ($accounts as $account) {
if ($item->current_chart_of_accounts == $account->id) {
$deposit_per_account['sundries'][$account->id][] = $item;
}
}
}
foreach ($result['investigation_deposits'] as $item) {
foreach ($accounts as $account) {
if ($item->current_chart_of_accounts == $account->id) {
$deposit_per_account['investigations'][$account->id][] = $item;
}
}
}
$c = 0;
if (isset($deposit_per_account['services'])) {
if ($deposit_per_account['services']) {
foreach ($deposit_per_account['services'] as $deposits) {
foreach ($deposits as $deposit) {
$id = $deposit->current_chart_of_accounts;
$dates[$c] = streamline_date($deposit->created_at);
$amounts[$c] = $deposit->patient_amount_paid;
$c++;
}
}
}
}
if (isset($deposit_per_account['treatments'])) {
if ($deposit_per_account['treatments']) {
foreach ($deposit_per_account['treatments'] as $deposits) {
foreach ($deposits as $deposit) {
$id = $deposit->current_chart_of_accounts;
$dates[$c] = streamline_date($deposit->created_at);
$amounts[$c] = $deposit->patient_amount_paid;
$c++;
}
}
}
}
if (isset($deposit_per_account['procedures'])) {
if ($deposit_per_account['procedures']) {
foreach ($deposit_per_account['procedures'] as $deposits) {
foreach ($deposits as $deposit) {
$id = $deposit->current_chart_of_accounts;
$dates[$c] = streamline_date($deposit->created_at);
$amounts[$c] = $deposit->patient_amount_paid;
$c++;
}
}
}
}
if (isset($deposit_per_account['sundries'])) {
if ($deposit_per_account['sundries']) {
foreach ($deposit_per_account['sundries'] as $deposits) {
$id = '';
$cash = $accrual = 0;
foreach ($deposits as $deposit) {
$id = $deposit->current_chart_of_accounts;
$dates[$c] = streamline_date($deposit->created_at);
$amounts[$c] = $deposit->patient_amount_paid;
$c++;
}
}
}
}
if (isset($deposit_per_account['investigations'])) {
if ($deposit_per_account['investigations']) {
foreach ($deposit_per_account['investigations'] as $deposits) {
$id = '';
$cash = $accrual = 0;
foreach ($deposits as $deposit) {
$id = $deposit->current_chart_of_accounts;
$dates[$c] = streamline_date($deposit->created_at);
$amounts[$c] = $deposit->patient_amount_paid;
$c++;
}
}
}
}
}
return ['id' => $id, 'dates' => $dates, 'amounts' => $amounts];
}
function dataForCogGraph(Request $request): array
{
$data = $moneys_on_account = $result = $collection = $deposit_per_account = [];
$id = '';
$dates = $amounts = [];
$today = Carbon::today()->toDateString();
$yesterday = Carbon::yesterday()->toDateString();
$end = Carbon::parse($request->end_date)->endOfDay()->toDateTimeString();
$start = Carbon::parse($request->start_date)->startOfDay()->toDateTimeString();
$accounts = \Streamline\Models\ChartOfAccount::where('type', 7)->get();
$tables = ['treatment_deposits', 'sundries_deposits'];
foreach ($tables as $table) {
switch ($request->dates) {
case 'today':
$result[$table] = DB::table($table)->whereNull('deleted_at')->whereDate('created_at', $today)->get()->toArray();
break;
case 'yesterday':
$result[$table] = DB::table($table)->whereNull('deleted_at')->whereDate('created_at', $yesterday)->get()->toArray();
break;
case 'custom_date':
$result[$table] = DB::table($table)->whereNull('deleted_at')->whereDate('created_at', $start)->get()->toArray();
break;
case 'custom_date_range':
$result[$table] = DB::table($table)->whereNull('deleted_at')->whereBetween('created_at', [$start, $end])->get()->toArray();
break;
}
}
if (!empty($result)) {
foreach ($result['treatment_deposits'] as $item) {
foreach ($accounts as $account) {
if ($item->cost_of_goods_account == $account->id) {
$deposit_per_account['treatments'][$account->id][] = $item;
}
}
}
foreach ($result['sundries_deposits'] as $item) {
foreach ($accounts as $account) {
if ($item->cost_of_goods_account == $account->id) {
$deposit_per_account['sundries'][$account->id][] = $item;
}
}
}
$cost_of_sale = $c = 0;
if ($deposit_per_account) {
if (isset($deposit_per_account['treatments'])) {
foreach ($deposit_per_account['treatments'] as $deposits) {
foreach ($deposits as $deposit) {
$id = $deposit->cost_of_goods_account;
$cost_price_array = explode(',', $deposit->cost_price);
$quantity_array = explode(',', $deposit->treatment_quantities);
$subtotal = 0;
for ($i = 0; $i < count($cost_price_array); $i++) {
$subtotal = ($cost_price_array[$i] * $quantity_array[$i]);
$cost_of_sale += $subtotal;
}
$dates[$c] = streamline_date($deposit->created_at);
$amounts[$c] = $subtotal;
$c++;
}
}
}
if (isset($deposit_per_account['sundries'])) {
foreach ($deposit_per_account['sundries'] as $deposits) {
foreach ($deposits as $deposit) {
$id = $deposit->cost_of_goods_account;
$cost_price_array = explode(',', $deposit->cost_price);
$quantity_array = explode(',', $deposit->sundry_quantity);
for ($i = 0; $i < count($cost_price_array); $i++) {
$subtotal = ($cost_price_array[$i] * $quantity_array[$i]);
$cost_of_sale += $subtotal;
}
$dates[$c] = streamline_date($deposit->created_at);
$amounts[$c] = $subtotal;
$c++;
}
}
}
$data_string = $request->dates . "," . $request->start_date . "," . $request->end_date . "," . 'inventory' . "," . $id . "," . "3";
$moneys_on_account[$id] = array('cash' => $cost_of_sale, 'id' => $id, 'data' => $data_string);
}
}
return ['id' => $id, 'dates' => $dates, 'amounts' => $amounts];
}
function dataForExpenseGraph(Request $request)
{
$data = $moneys_on_account = $result = $collection = $deposit_per_account = [];
$id = '';
$dates = $amounts = [];
$today = Carbon::today()->toDateString();
$yesterday = Carbon::yesterday()->toDateString();
$end = Carbon::parse($request->end_date)->endOfDay()->toDateTimeString();
$start = Carbon::parse($request->start_date)->startOfDay()->toDateTimeString();
$accounts = \Streamline\Models\ChartOfAccount::where('type', 2)->get();
$tables = ['payments'];
foreach ($tables as $table) {
switch ($request->dates) {
case 'today':
$result[$table] = DB::table($table)->whereNull('deleted_at')->whereDate('created_at', $today)->get()->toArray();
break;
case 'yesterday':
$result[$table] = DB::table($table)->whereNull('deleted_at')->whereDate('created_at', $yesterday)->get()->toArray();
break;
case 'custom_date':
$result[$table] = DB::table($table)->whereNull('deleted_at')->whereDate('created_at', $start)->get()->toArray();
break;
case 'custom_date_range':
$result[$table] = DB::table($table)->whereNull('deleted_at')->whereBetween('created_at', [$start, $end])->get()->toArray();
break;
}
}
if (!empty($result)) {
foreach ($result['payments'] as $item) {
foreach ($accounts as $account) {
$expense_account = get_name($item->item_id, 'id', 'account_id', 'payment_items');
if ($expense_account == $account->id) {
$deposit_per_account['payments'][$account->id][] = $item;
}
}
}
if (isset($deposit_per_account['payments'])) {
if ($deposit_per_account['payments']) {
foreach ($deposit_per_account['payments'] as $deposits) {
$expense_amount = $x = 0;
foreach ($deposits as $deposit) {
$id = $deposit->expense_account;
$dates[$x] = streamline_date($deposit->created_at);
$amounts[$x] = $deposit->amount;
$x++;
}
}
}
}
}
return array('id' => $id, 'dates' => $dates, 'amounts' => $amounts);
}
function getSumServiceDeposit($table, Request $request)
{
$result = [];
$consult_sum = 0;
$service_sum = 0;
$co_payment_sum = 0;
$inpatient_deposit_sum = 0;
$consult_sum_income_cash = 0;
$service_sum_income_cash = 0;
$co_payment_sum_income_cash = 0;
$inpatient_deposit_sum_income_cash = 0;
$staff_member = $request->staff_member;
if ($request->dates == "yesterday") {
$start = Carbon::yesterday()->startOfDay();
$end = Carbon::yesterday()->endOfDay();
} else if ($request->dates == "custom_date") {
$start = Carbon::parse($request->start_date)->startOfDay();
$end = Carbon::parse($request->start_date)->endOfDay();
} else if ($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();
}
if ($staff_member == 0) {
$result = DB::table($table)->whereBetween('created_at', [$start, $end])->whereNotIn('patient_id', findTestOrDemoPatients())->get();
} else {
$result = DB::table($table)->whereBetween('created_at', [$start, $end])->where('created_by', $staff_member)->whereNotIn('patient_id', findTestOrDemoPatients())->get();
}
if (count($result) > 0) {
foreach ($result as $item) {
if ($item->service_type == "Consultation") {
$consult_sum_income_cash += $item->patient_amount_paid;
$donor_amount_paid = get_name($item->receipt_number, 'receipt_number', 'donor_to_pay', 'donor_discount_details');
if (is_numeric($donor_amount_paid)) {
$consult_sum += $donor_amount_paid;
}
$consult_sum += $item->patient_amount_paid;
} else if ($item->service_type == "Co_Payment") {
$co_payment_sum_income_cash += $item->patient_amount_paid;
$donor_amount_paid = get_name($item->receipt_number, 'receipt_number', 'donor_to_pay', 'donor_discount_details');
if (is_numeric($donor_amount_paid)) {
$co_payment_sum += $donor_amount_paid;
}
$co_payment_sum += $item->patient_amount_paid;
} else if ($item->service_type == "Service" || $item->service_type == "Services" || $item->service_type == "Other Service") {
$service_sum_income_cash += $item->patient_amount_paid;
$donor_amount_paid = get_name($item->receipt_number, 'receipt_number', 'donor_to_pay', 'donor_discount_details');
if (is_numeric($donor_amount_paid)) {
$service_sum += $donor_amount_paid;
}
$service_sum += $item->patient_amount_paid;
} else if ($item->service_type == "Inpatient_Deposit") {
$inpatient_deposit_sum_income_cash += $item->patient_amount_paid;
$donor_amount_paid = get_name($item->receipt_number, 'receipt_number', 'donor_to_pay', 'donor_discount_details');
if (is_numeric($donor_amount_paid)) {
$inpatient_deposit_sum += $donor_amount_paid;
}
$inpatient_deposit_sum += $item->patient_amount_paid;
}
}
} else {
return [0, 0, 0, 0, 0, 0, 0, 0];
}
return array($consult_sum, $service_sum, $co_payment_sum, $consult_sum_income_cash, $co_payment_sum_income_cash, $service_sum_income_cash, $inpatient_deposit_sum, $inpatient_deposit_sum_income_cash);
}
function getUnReceivedSumServiceDeposit($table, Request $request)
{
$result = [];
$amount = 0;
$consult_sum = 0;
$service_sum = 0;
$co_payment_sum = 0;
$inpatient_deposit_sum = 0;
$consult_sum_income_cash = 0;
$service_sum_income_cash = 0;
$co_payment_sum_income_cash = 0;
$inpatient_deposit_sum_income_cash = 0;
$today = Carbon::today()->toDateString();
$yesterday = Carbon::yesterday()->toDateString();
$end = Carbon::parse($request->end_date)->endOfDay()->toDateTimeString();
$start = Carbon::parse($request->start_date)->startOfDay()->toDateTimeString();
$staff_member = $request->staff_member;
if ($staff_member == 0) {
if ($request->dates == "today") {
$result = DB::table($table)->whereDate('created_at', $today)
->whereNotIn('patient_id', findTestOrDemoPatients())->whereNull('received')->get();
} else if ($request->dates == "yesterday") {
$result = DB::table($table)->whereDate('created_at', $yesterday)
->whereNotIn('patient_id', findTestOrDemoPatients())->whereNull('received')->get();
} else if ($request->dates == "custom_date") {
$result = DB::table($table)->whereDate('created_at', Carbon::parse($request->start_date)->toDateString())
->whereNotIn('patient_id', findTestOrDemoPatients())->whereNull('received')->get();
} else if ($request->dates == "custom_date_range") {
$result = DB::table($table)->whereBetween('created_at', [$start, $end])
->whereNotIn('patient_id', findTestOrDemoPatients())->whereNull('received')->get();
}
} else {
if ($request->dates == "today") {
$result = DB::table($table)->whereDate('created_at', $today)->where('created_by', $staff_member)
->whereNotIn('patient_id', findTestOrDemoPatients())->whereNull('received')->get();
} else if ($request->dates == "yesterday") {
$result = DB::table($table)->whereDate('created_at', $yesterday)->where('created_by', $staff_member)
->whereNotIn('patient_id', findTestOrDemoPatients())->whereNull('received')->get();
} else if ($request->dates == "custom_date") {
$result = DB::table($table)->whereDate('created_at', Carbon::parse($request->start_date)->toDateString())->where('created_by', $staff_member)
->whereNotIn('patient_id', findTestOrDemoPatients())->whereNull('received')->get();
} else if ($request->dates == "custom_date_range") {
$result = DB::table($table)->whereBetween('created_at', [$start, $end])->where('created_by', $staff_member)
->whereNotIn('patient_id', findTestOrDemoPatients())->whereNull('received')->get();
}
}
if (count($result) > 0) {
foreach ($result as $item) {
if ($item->service_type == "Consultation") {
$donor_amount_paid = getIdName($item->receipt_number, 'receipt_number', 'donor_to_pay', 'donor_discount_details');
$consult_sum_income_cash += $item->patient_amount_paid;
if (is_null($donor_amount_paid) || $donor_amount_paid == []) {
$donor_amount_paid = 0;
} else {
$amount = $donor_amount_paid[0];
}
$consult_sum += $amount + $item->patient_amount_paid;
} else if ($item->service_type == "Co_Payment") {
$donor_amount_paid = getIdName($item->receipt_number, 'receipt_number', 'donor_to_pay', 'donor_discount_details');
$co_payment_sum_income_cash += $item->patient_amount_paid;
if (is_null($donor_amount_paid) || $donor_amount_paid == []) {
$donor_amount_paid = 0;
} else {
$amount = $donor_amount_paid[0];
}
$co_payment_sum += $amount + $item->patient_amount_paid;
} else if ($item->service_type == "Service" || $item->service_type == "Services" || $item->service_type == "Other Service") {
$donor_amount_paid = getIdName($item->receipt_number, 'receipt_number', 'donor_to_pay', 'donor_discount_details');
$service_sum_income_cash += $item->patient_amount_paid;
if (is_null($donor_amount_paid) || $donor_amount_paid == []) {
$donor_amount_paid = 0;
} else {
$amount = $donor_amount_paid[0];
}
$service_sum += $amount + $item->patient_amount_paid;
} else if ($item->service_type == "Inpatient_Deposit") {
$donor_amount_paid = getIdName($item->receipt_number, 'receipt_number', 'donor_to_pay', 'donor_discount_details');
$inpatient_deposit_sum_income_cash += $item->patient_amount_paid;
if (is_null($donor_amount_paid) || $donor_amount_paid == []) {
$donor_amount_paid = 0;
} else {
$amount = $donor_amount_paid[0];
}
$inpatient_deposit_sum += $amount + $item->patient_amount_paid;
}
}
} else {
return [0, 0, 0, 0, 0, 0, 0, 0];
}
return array($consult_sum, $service_sum, $co_payment_sum, $consult_sum_income_cash, $co_payment_sum_income_cash, $service_sum_income_cash, $inpatient_deposit_sum, $inpatient_deposit_sum_income_cash);
}
function receivedCashFilter(Request $request)
{
$filters = date_query_builder_using_date_time($request->start_date, $request->end_date, 'created_at', $request->dates);
$cashier_filter = ['cashier_id', '=', $request->staff_member_cashier];
$account_filter = ['brought_by', '=', $request->staff_member_accountant];
if ($request->staff_member_cashier != "ALL STAFF") {
$filters[] = $cashier_filter;
}
if ($request->staff_member_accountant != "ALL STAFF") {
$filters[] = $account_filter;
}
return DB::table('cashier_income')->whereNull('deleted_at')->where($filters)->get()->toArray();
}
function getSum($table, $sum_column, Request $request)
{
$result = [];
$staff_member = $request->staff_member;
if ($request->dates == "yesterday") {
$start = Carbon::yesterday()->startOfDay();
$end = Carbon::yesterday()->endOfDay();
} else if ($request->dates == "custom_date") {
$start = Carbon::parse($request->start_date)->startOfDay();
$end = Carbon::parse($request->start_date)->endOfDay();
} else if ($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();
}
if ($table != "insurance_subscriptions" && $table != "single_group_receipts") {
if ($staff_member == 0) {
$result = DB::table($table)->whereBetween('created_at', [$start, $end])->whereNotIn('patient_id', findTestOrDemoPatients())->get()->sum($sum_column);
} else {
$result = DB::table($table)->whereBetween('created_at', [$start, $end])->where('created_by', $staff_member)->whereNotIn('patient_id', findTestOrDemoPatients())->get()->sum($sum_column);
}
} else {
if ($staff_member == 0) {
$result = DB::table($table)->whereBetween('created_at', [$start, $end])->get()->sum($sum_column);
} else {
$result = DB::table($table)->whereBetween('created_at', [$start, $end])->where('created_by', $staff_member)->get()->sum($sum_column);
}
}
return $result;
}
function getUnReceivedCashSum($table, $sum_column, Request $request)
{
$staff_member = $request->staff_member;
if ($request->dates == "yesterday") {
$start = Carbon::yesterday()->startOfDay();
$end = Carbon::yesterday()->endOfDay();
} else if ($request->dates == "custom_date") {
$start = Carbon::parse($request->start_date)->startOfDay();
$end = Carbon::parse($request->start_date)->endOfDay();
} else if ($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();
}
if ($table != "insurance_subscriptions" && $table != "single_group_receipts") {
if ($staff_member == 0) {
$result = DB::table($table)
->whereBetween('created_at', [$start, $end])
->whereNotIn('patient_id', findTestOrDemoPatients())
->whereNull('received')
->get()
->sum($sum_column);
} else {
$result = DB::table($table)
->whereBetween('created_at', [$start, $end])
->where('created_by', $staff_member)
->whereNull('received')
->whereNotIn('patient_id', findTestOrDemoPatients())
->get()
->sum($sum_column);
}
} else {
if ($staff_member == 0) {
$result = DB::table($table)->whereBetween('created_at', [$start, $end])->whereNull('received')->get()->sum($sum_column);
} else {
$result = DB::table($table)->whereBetween('created_at', [$start, $end])->whereNull('received')->where('created_by', $staff_member)->get()->sum($sum_column);
}
}
return $result;
}
function get_amounts_from_serial_data($object)
{
$total_amount_paid = 0;
$unreceived_amount = $received_amount = 0;
if (is_array($object)) {
foreach ($object as $payment) {
// get total amount paid regardless of whether its received or not.
$amount_history_array = unserialize($payment->amount_paid_history);
$received_amount_history_array = unserialize($payment->received_amount_history);
$total_amount_paid += is_array($amount_history_array) ? array_sum($amount_history_array) : 0;
// get total of payments received specifically.
if ($payment->received) {
$received_amount += is_array($received_amount_history_array) ? array_sum($received_amount_history_array) : 0;
}
}
// unreceived cash payments are difference between total_amount_paid and total_received_amount.
$unreceived_amount = $total_amount_paid - $received_amount;
}
return array(
'total' => $total_amount_paid,
'unreceived' => $unreceived_amount,
'received' => $received_amount
);
}
function getDonorInvoicePayments($table, Request $request)
{
$result = 0;
$staff_member = $request->staff_member;
$today = Carbon::today()->toDateTimeString();
$yesterday = Carbon::yesterday()->toDateTimeString();
$end = Carbon::parse($request->end_date)->endOfDay()->toDateTimeString();
$start = Carbon::parse($request->start_date)->startOfDay()->toDateTimeString();
if ($request->staff_member == 0) {
if ($request->dates == "today") {
$result = DB::table($table)->whereDate('created_at', $today)->whereNull('deleted_at')->get()->toArray();
} else if ($request->dates == "yesterday") {
$result = DB::table($table)->whereDate('created_at', $yesterday)->whereNull('deleted_at')->get()->toArray();
} else if ($request->dates == "custom_date") {
$result = DB::table($table)->whereDate('created_at', Carbon::parse($request->start_date)->toDateString())->whereNull('deleted_at')->get()->toArray();
} else if ($request->dates == "custom_date_range") {
$result = DB::table($table)->whereBetween('created_at', [$start, $end])->whereNull('deleted_at')->get()->toArray();
}
} else {
if ($request->dates == "today") {
$result = DB::table($table)->whereDate('created_at', $today)->where('created_by', $staff_member)->whereNull('deleted_at')->get()->toArray();
} else if ($request->dates == "yesterday") {
$result = DB::table($table)->whereDate('created_at', $yesterday)->where('created_by', $staff_member)->whereNull('deleted_at')->get()->toArray();
} else if ($request->dates == "custom_date") {
$result = DB::table($table)->whereDate('created_at', Carbon::parse($request->start_date)->toDateString())->where('created_by', $staff_member)->whereNull('deleted_at')->get()->toArray();
} else if ($request->dates == "custom_date_range") {
$result = DB::table($table)->whereBetween('created_at', [$start, $end])->where('created_by', $staff_member)->whereNull('deleted_at')->get()->toArray();
}
}
return $result;
}
function getDebtPaymentsSum(Request $request): array
{
$results = [];
$staff_member = $request->staff_member;
$today = date('Y-m-d');
$yesterday = date('Y-m-d', strtotime("-1 days"));
$end = Carbon::parse($request->end_date)->toDateString();
$start = Carbon::parse($request->start_date)->toDateString();
$total_amount_paid = 0;
$unreceived_amount = 0;
$received_amount = 0;
if ($request->staff_member == 0) {
if ($request->dates == "today") {
$results = DB::table('debtor_payments')->where('date_paid', $today)->whereNull('deleted_at')->get();
} else if ($request->dates == "yesterday") {
$results = DB::table('debtor_payments')->where('date_paid', $yesterday)->whereNull('deleted_at')->get();
} else if ($request->dates == "custom_date") {
$results = DB::table('debtor_payments')->where('date_paid', $request->start_date)->whereNull('deleted_at')->get();
} else if ($request->dates == "custom_date_range") {
$results = DB::table('debtor_payments')->whereBetween('date_paid', [$start, $end])->whereNull('deleted_at')->get();
}
} else {
if ($request->dates == "today") {
$results = DB::table('debtor_payments')->where('created_by', $staff_member)->where('date_paid', $today)->whereNull('deleted_at')->get();
} else if ($request->dates == "yesterday") {
$results = DB::table('debtor_payments')->where('created_by', $staff_member)->where('date_paid', $yesterday)->whereNull('deleted_at')->get();
} else if ($request->dates == "custom_date") {
$results = DB::table('debtor_payments')->where('created_by', $staff_member)->where('date_paid', $request->start_date)->whereNull('deleted_at')->get();
} else if ($request->dates == "custom_date_range") {
$results = DB::table('debtor_payments')->where('created_by', $staff_member)->whereBetween('date_paid', [$start, $end])->whereNull('deleted_at')->get();
}
}
foreach ($results as $result) {
if (is_null($result->received_amount)) {
$unreceived_amount += $result->amount_paid;
} else {
$received_amount += $result->received_amount;
}
$total_amount_paid += $result->amount_paid;
}
return ['total' => $total_amount_paid, 'unreceived' => $unreceived_amount, 'received' => $received_amount];
}
function getDebtPaymentsRecords(Request $request)
{
$results = [];
$return_values = [];
$staff_member = $request->user_id;
$today = date('d-m-Y');
$yesterday = date('d-m-Y', strtotime("-1 days"));
$dates = explode("/", $request->dates);
$end = $dates[1];
$start = $dates[0];
$date_type = $request->date_type;
$dates_to_search_for = [];
$counter = 0;
if ($staff_member == 0) {
if ($date_type == "today") {
$results = DB::table('debtor_payments')->where('date_paid_history', 'like', '%' . $today . '%')->whereNull('deleted_at')->get();
$dates_to_search_for[] = $today;
} else if ($date_type == "yesterday") {
$results = DB::table('debtor_payments')->where('date_paid_history', 'like', '%' . $yesterday . '%')->whereNull('deleted_at')->get();
$dates_to_search_for[] = $yesterday;
} else if ($date_type == "custom_date") {
$results = DB::table('debtor_payments')->where('date_paid_history', 'like', '%' . $request->start_date . '%')->whereNull('deleted_at')->get();
$dates_to_search_for[] = $request->start_date;
} else if ($date_type == "custom_date_range") {
// first get for the start date
$results = DB::table('debtor_payments')->where('date_paid_history', 'like', '%' . $start . '%')->whereNull('deleted_at')->get();
$dates_to_search_for[] = $start;
while ($start != $end) {
$start = date('d-m-Y', strtotime($start . ' + 1 days'));
$dates_to_search_for[] = $start;
$date_result = DB::table('debtor_payments')->where('date_paid_history', 'like', '%' . $start . '%')->whereNull('deleted_at')->get();
if (count($date_result) > 0) {
if (count($results) > 0) {
$results = $results->merge($date_result);
} else {
$results = $date_result;
}
}
}
}
// filter through the array and get the amounts
foreach ($results as $result) {
$date_paid_history = unserialize($result->date_paid_history);
$amount_paid_history = unserialize($result->amount_paid_history);
$receipt_history = unserialize($result->receipt_history);
$staff_in_charge_history = unserialize($result->staff_in_charge_history);
for ($i = 0; $i < count($amount_paid_history); $i++) {
if (in_array($date_paid_history[$i], $dates_to_search_for)) {
$return_values[$counter]['id'] = $result->id;
$return_values[$counter]['patient_id'] = $result->patient_id;
$return_values[$counter]['date_paid'] = $date_paid_history[$i];
$return_values[$counter]['staff_in_charge'] = $staff_in_charge_history[$i];
$return_values[$counter]['receipt_number'] = $receipt_history[$i];
$return_values[$counter]['amount_paid'] = $amount_paid_history[$i];
$counter++;
}
}
}
} else {
if ($date_type == "today") {
$results = DB::table('debtor_payments')->where('date_paid_history', 'like', '%' . $today . '%')
->where('staff_in_charge_history', 'like', '%' . $staff_member . '%')
->whereNull('deleted_at')->get();
$dates_to_search_for[] = $today;
} else if ($date_type == "yesterday") {
$results = DB::table('debtor_payments')->where('date_paid_history', 'like', '%' . $yesterday . '%')
->where('staff_in_charge_history', 'like', '%' . $staff_member . '%')
->whereNull('deleted_at')->get();
$dates_to_search_for[] = $yesterday;
} else if ($date_type == "custom_date") {
$results = DB::table('debtor_payments')->where('date_paid_history', 'like', '%' . $request->start_date . '%')
->where('staff_in_charge_history', 'like', '%' . $staff_member . '%')
->whereNull('deleted_at')->get();
$dates_to_search_for[] = $request->start_date;
} else if ($date_type == "custom_date_range") {
// first get for the start date
$results = DB::table('debtor_payments')->where('date_paid_history', 'like', '%' . $start . '%')
->where('staff_in_charge_history', 'like', '%' . $staff_member . '%')
->whereNull('deleted_at')->get();
$dates_to_search_for[] = $start;
while ($start != $end) {
$start = date('d-m-Y', strtotime($start . ' + 1 days'));
$dates_to_search_for[] = $start;
$date_result = DB::table('debtor_payments')->where('date_paid_history', 'like', '%' . $start . '%')
->where('staff_in_charge_history', 'like', '%' . $staff_member . '%')
->whereNull('deleted_at')->get();
if (count($date_result) > 0) {
if (count($results) > 0) {
$results = $results->merge($date_result);
} else {
$results = $date_result;
}
}
}
}
// filter through the array and get the amounts
foreach ($results as $result) {
$date_paid_history = unserialize($result->date_paid_history);
$amount_paid_history = unserialize($result->amount_paid_history);
$receipt_history = unserialize($result->receipt_history);
$staff_in_charge_history = unserialize($result->staff_in_charge_history);
for ($i = 0; $i < count($amount_paid_history); $i++) {
if (in_array($date_paid_history[$i], $dates_to_search_for) && $staff_in_charge_history[$i] == $staff_member) {
$return_values[$counter]['id'] = $result->id;
$return_values[$counter]['patient_id'] = $result->patient_id;
$return_values[$counter]['date_paid'] = $date_paid_history[$i];
$return_values[$counter]['staff_in_charge'] = $staff_in_charge_history[$i];
$return_values[$counter]['receipt_number'] = $receipt_history[$i];
$return_values[$counter]['amount_paid'] = $amount_paid_history[$i];
$counter++;
}
}
}
}
return $return_values;
}
function getDebtPlanPaymentsSum(Request $request)
{
$results = [];
$staff_member = $request->staff_member;
$today = date('d-m-Y');
$yesterday = date('d-m-Y', strtotime("-1 days"));
$end = $request->end_date;
$start = $request->start_date;
$total_amount_paid = 0;
$unreceived_amount = 0;
$received_amount = 0;
$dates_to_search_for = [];
if ($request->staff_member == 0) {
if ($request->dates == "today") {
$results = DB::table('debt_plan_payment_staffs')->where('date_paid_history', 'like', '%' . $today . '%')->whereNull('deleted_at')->get();
$dates_to_search_for[] = $today;
} else if ($request->dates == "yesterday") {
$results = DB::table('debt_plan_payment_staffs')->where('date_paid_history', 'like', '%' . $yesterday . '%')->whereNull('deleted_at')->get();
$dates_to_search_for[] = $yesterday;
} else if ($request->dates == "custom_date") {
$results = DB::table('debt_plan_payment_staffs')->where('date_paid_history', 'like', '%' . $request->start_date . '%')->whereNull('deleted_at')->get();
$dates_to_search_for[] = $request->start_date;
} else if ($request->dates == "custom_date_range") {
// first get for the start date
$results = DB::table('debt_plan_payment_staffs')->where('date_paid_history', 'like', '%' . $start . '%')->whereNull('deleted_at')->get();
$dates_to_search_for[] = $start;
while ($start != $end) {
$start = date('d-m-Y', strtotime($start . ' + 1 days'));
$dates_to_search_for[] = $start;
$date_result = DB::table('debt_plan_payment_staffs')->where('date_paid_history', 'like', '%' . $start . '%')->whereNull('deleted_at')->get();
if (count($date_result) > 0) {
if (count($results) > 0) {
$results = $results->merge($date_result);
} else {
$results = $date_result;
}
}
}
}
// filter through the array and get the amounts
foreach ($results as $result) {
$received_amount_history = unserialize($result->received_amount_history);
$date_paid_history = unserialize($result->date_paid_history);
$amount_paid_history = unserialize($result->amount_paid_history);
for ($i = 0; $i < count($amount_paid_history); $i++) {
if (in_array($date_paid_history[$i], $dates_to_search_for)) {
if (isset($received_amount_history[$i])) {
$received_amount += $amount_paid_history[$i];
} else {
$unreceived_amount += $amount_paid_history[$i];
}
$total_amount_paid += $amount_paid_history[$i];
}
}
}
} else {
if ($request->dates == "today") {
$results = DB::table('debt_plan_payment_staffs')->where('date_paid_history', 'like', '%' . $today . '%')
->where('staff_in_charge_history', 'like', '%' . $staff_member . '%')
->whereNull('deleted_at')->get();
$dates_to_search_for[] = $today;
} else if ($request->dates == "yesterday") {
$results = DB::table('debt_plan_payment_staffs')->where('date_paid_history', 'like', '%' . $yesterday . '%')
->where('staff_in_charge_history', 'like', '%' . $staff_member . '%')
->whereNull('deleted_at')->get();
$dates_to_search_for[] = $yesterday;
} else if ($request->dates == "custom_date") {
$results = DB::table('debt_plan_payment_staffs')->where('date_paid_history', 'like', '%' . $request->start_date . '%')
->where('staff_in_charge_history', 'like', '%' . $staff_member . '%')
->whereNull('deleted_at')->get();
$dates_to_search_for[] = $request->start_date;
} else if ($request->dates == "custom_date_range") {
// first get for the start date
$results = DB::table('debt_plan_payment_staffs')->where('date_paid_history', 'like', '%' . $start . '%')
->where('staff_in_charge_history', 'like', '%' . $staff_member . '%')
->whereNull('deleted_at')->get();
$dates_to_search_for[] = $start;
while ($start != $end) {
$start = date('d-m-Y', strtotime($start . ' + 1 days'));
$dates_to_search_for[] = $start;
$date_result = DB::table('debt_plan_payment_staffs')->where('date_paid_history', 'like', '%' . $start . '%')
->where('staff_in_charge_history', 'like', '%' . $staff_member . '%')
->whereNull('deleted_at')->get();
if (count($date_result) > 0) {
if (count($results) > 0) {
$results = $results->merge($date_result);
} else {
$results = $date_result;
}
}
}
}
// filter through the array and get the amounts
foreach ($results as $result) {
$received_amount_history = unserialize($result->received_amount_history);
$date_paid_history = unserialize($result->date_paid_history);
$amount_paid_history = unserialize($result->amount_paid_history);
$staff_in_charge_history = unserialize($result->staff_in_charge_history);
for ($i = 0; $i < count($amount_paid_history); $i++) {
if (in_array($date_paid_history[$i], $dates_to_search_for) && $staff_in_charge_history[$i] == $staff_member) {
if (isset($received_amount_history[$i])) {
$received_amount += $amount_paid_history[$i];
} else {
$unreceived_amount += $amount_paid_history[$i];
}
$total_amount_paid += $amount_paid_history[$i];
}
}
}
}
return ['total' => $total_amount_paid, 'unreceived' => $unreceived_amount, 'received' => $received_amount];
}
function getDebtPlanPaymentsRecords(Request $request) {
$results = [];
$return_values = [];
$staff_member = $request->user_id;
$today = date('d-m-Y');
$yesterday = date('d-m-Y', strtotime("-1 days"));
$dates = explode("/", $request->dates);
$end = $dates[1];
$start = $dates[0];
$date_type = $request->date_type;
$dates_to_search_for = [];
$counter = 0;
if ($staff_member == 0) {
if ($date_type == "today") {
$results = DB::table('debt_plan_payment_staffs')->where('date_paid_history', 'like', '%' . $today . '%')->whereNull('deleted_at')->get();
$dates_to_search_for[] = $today;
} else if ($date_type == "yesterday") {
$results = DB::table('debt_plan_payment_staffs')->where('date_paid_history', 'like', '%' . $yesterday . '%')->whereNull('deleted_at')->get();
$dates_to_search_for[] = $yesterday;
} else if ($date_type == "custom_date") {
$results = DB::table('debt_plan_payment_staffs')->where('date_paid_history', 'like', '%' . $request->start_date . '%')->whereNull('deleted_at')->get();
$dates_to_search_for[] = $request->start_date;
} else if ($date_type == "custom_date_range") {
// first get for the start date
$results = DB::table('debt_plan_payment_staffs')->where('date_paid_history', 'like', '%' . $start . '%')->whereNull('deleted_at')->get();
$dates_to_search_for[] = $start;
while ($start != $end) {
$start = date('d-m-Y', strtotime($start . ' + 1 days'));
$dates_to_search_for[] = $start;
$date_result = DB::table('debt_plan_payment_staffs')->where('date_paid_history', 'like', '%' . $start . '%')->whereNull('deleted_at')->get();
if (count($date_result) > 0) {
if (count($results) > 0) {
$results = $results->merge($date_result);
} else {
$results = $date_result;
}
}
}
}
// filter through the array and get the amounts
foreach ($results as $result) {
$date_paid_history = unserialize($result->date_paid_history);
$amount_paid_history = unserialize($result->amount_paid_history);
$receipt_history = unserialize($result->receipt_history);
$staff_in_charge_history = unserialize($result->staff_in_charge_history);
for ($i = 0; $i < count($amount_paid_history); $i++) {
if (in_array($date_paid_history[$i], $dates_to_search_for)) {
$return_values[$counter]['id'] = $result->id;
$return_values[$counter]['date_paid'] = $date_paid_history[$i];
$return_values[$counter]['staff_in_charge'] = $staff_in_charge_history[$i];
$return_values[$counter]['receipt_number'] = $receipt_history[$i];
$return_values[$counter]['amount_paid'] = $amount_paid_history[$i];
$counter++;
}
}
}
} else {
if ($date_type == "today") {
$results = DB::table('debt_plan_payment_staffs')->where('date_paid_history', 'like', '%' . $today . '%')
->where('staff_in_charge_history', 'like', '%' . $staff_member . '%')
->whereNull('deleted_at')->get();
$dates_to_search_for[] = $today;
} else if ($date_type == "yesterday") {
$results = DB::table('debt_plan_payment_staffs')->where('date_paid_history', 'like', '%' . $yesterday . '%')
->where('staff_in_charge_history', 'like', '%' . $staff_member . '%')
->whereNull('deleted_at')->get();
$dates_to_search_for[] = $yesterday;
} else if ($date_type == "custom_date") {
$results = DB::table('debt_plan_payment_staffs')->where('date_paid_history', 'like', '%' . $request->start_date . '%')
->where('staff_in_charge_history', 'like', '%' . $staff_member . '%')
->whereNull('deleted_at')->get();
$dates_to_search_for[] = $request->start_date;
} else if ($date_type == "custom_date_range") {
// first get for the start date
$results = DB::table('debt_plan_payment_staffs')->where('date_paid_history', 'like', '%' . $start . '%')
->where('staff_in_charge_history', 'like', '%' . $staff_member . '%')
->whereNull('deleted_at')->get();
$dates_to_search_for[] = $start;
while ($start != $end) {
$start = date('d-m-Y', strtotime($start . ' + 1 days'));
$dates_to_search_for[] = $start;
$date_result = DB::table('debt_plan_payment_staffs')->where('date_paid_history', 'like', '%' . $start . '%')
->where('staff_in_charge_history', 'like', '%' . $staff_member . '%')
->whereNull('deleted_at')->get();
if (count($date_result) > 0) {
if (count($results) > 0) {
$results = $results->merge($date_result);
} else {
$results = $date_result;
}
}
}
}
// filter through the array and get the amounts
foreach ($results as $result) {
$date_paid_history = unserialize($result->date_paid_history);
$amount_paid_history = unserialize($result->amount_paid_history);
$receipt_history = unserialize($result->receipt_history);
$staff_in_charge_history = unserialize($result->staff_in_charge_history);
for ($i = 0; $i < count($amount_paid_history); $i++) {
if (in_array($date_paid_history[$i], $dates_to_search_for) && $staff_in_charge_history[$i] == $staff_member) {
$return_values[$counter]['id'] = $result->id;
$return_values[$counter]['date_paid'] = $date_paid_history[$i];
$return_values[$counter]['staff_in_charge'] = $staff_in_charge_history[$i];
$return_values[$counter]['receipt_number'] = $receipt_history[$i];
$return_values[$counter]['amount_paid'] = $amount_paid_history[$i];
$counter++;
}
}
}
}
return $return_values;
}
function income_cash_family_accounts_consumption_amount($request)
{
$today = Carbon::today()->toDateString();
$yesterday = Carbon::yesterday()->toDateString();
$end = Carbon::parse($request->end_date)->endOfDay()->toDateTimeString();
$start = Carbon::parse($request->start_date)->startOfDay()->toDateTimeString();
$staff_member = $request->staff_member;
$result = null;
if ($staff_member == 0) {
if ($request->dates == "today") {
$result = FamilyAccountConsumption::whereDate('created_at', $today)
->whereNotIn('patient_id', findTestOrDemoPatients())->get()->sum('amount_consumed');
} else if ($request->dates == "yesterday") {
$result = FamilyAccountConsumption::whereDate('created_at', $yesterday)
->whereNotIn('patient_id', findTestOrDemoPatients())->get()->sum('amount_consumed');
} else if ($request->dates == "custom_date") {
$start = Carbon::parse($request->start_date)->startOfDay()->toDateTimeString();
$end = Carbon::parse($request->start_date)->endOfDay()->toDateTimeString();
$result = FamilyAccountConsumption::whereBetween('created_at', [$start, $end])
->whereNotIn('patient_id', findTestOrDemoPatients())->get()->sum('amount_consumed');
} else if ($request->dates == "custom_date_range") {
$result = FamilyAccountConsumption::whereBetween('created_at', [$start, $end])
->whereNotIn('patient_id', findTestOrDemoPatients())->get()->sum('amount_consumed');
}
} else {
if ($request->dates == "today") {
$result = FamilyAccountConsumption::whereDate('created_at', $today)->where('created_by', $staff_member)
->whereNotIn('patient_id', findTestOrDemoPatients())->get()->sum('amount_consumed');
} else if ($request->dates == "yesterday") {
$result = FamilyAccountConsumption::whereDate('created_at', $yesterday)->where('created_by', $staff_member)
->whereNotIn('patient_id', findTestOrDemoPatients())->get()->sum('amount_consumed');
} else if ($request->dates == "custom_date") {
$start = Carbon::parse($request->start_date)->startOfDay()->toDateTimeString();
$end = Carbon::parse($request->start_date)->endOfDay()->toDateTimeString();
$result = FamilyAccountConsumption::whereBetween('created_at', [$start, $end])->where('created_by', $staff_member)
->whereNotIn('patient_id', findTestOrDemoPatients())->get()->sum('amount_consumed');
} else if ($request->dates == "custom_date_range") {
$result = FamilyAccountConsumption::whereBetween('created_at', [$start, $end])->where('created_by', $staff_member)
->whereNotIn('patient_id', findTestOrDemoPatients())->get()->sum('amount_consumed');
}
}
return $result;
}
function get_unreceived_cash_family_accounts_consumption_amount($request)
{
$today = Carbon::today()->toDateString();
$yesterday = Carbon::yesterday()->toDateString();
$end = Carbon::parse($request->end_date)->endOfDay()->toDateTimeString();
$start = Carbon::parse($request->start_date)->startOfDay()->toDateTimeString();
$staff_member = $request->staff_member;
$result = null;
if ($staff_member == 0) {
if ($request->dates == "today") {
$result = FamilyAccountConsumption::whereDate('created_at', $today)
->whereNotIn('patient_id', findTestOrDemoPatients())->whereNull('received')->get()->sum('amount_consumed');
} else if ($request->dates == "yesterday") {
$result = FamilyAccountConsumption::whereDate('created_at', $yesterday)
->whereNotIn('patient_id', findTestOrDemoPatients())->whereNull('received')->get()->sum('amount_consumed');
} else if ($request->dates == "custom_date") {
$start = Carbon::parse($request->start_date)->startOfDay()->toDateTimeString();
$end = Carbon::parse($request->start_date)->endOfDay()->toDateTimeString();
$result = FamilyAccountConsumption::whereBetween('created_at', [$start, $end])
->whereNotIn('patient_id', findTestOrDemoPatients())->whereNull('received')->get()->sum('amount_consumed');
} else if ($request->dates == "custom_date_range") {
$result = FamilyAccountConsumption::whereBetween('created_at', [$start, $end])
->whereNotIn('patient_id', findTestOrDemoPatients())->whereNull('received')->get()->sum('amount_consumed');
}
} else {
if ($request->dates == "today") {
$result = FamilyAccountConsumption::whereDate('created_at', $today)->where('created_by', $staff_member)
->whereNotIn('patient_id', findTestOrDemoPatients())->whereNull('received')->get()->sum('amount_consumed');
} else if ($request->dates == "yesterday") {
$result = FamilyAccountConsumption::whereDate('created_at', $yesterday)->where('created_by', $staff_member)
->whereNotIn('patient_id', findTestOrDemoPatients())->whereNull('received')->get()->sum('amount_consumed');
} else if ($request->dates == "custom_date") {
$start = Carbon::parse($request->start_date)->startOfDay()->toDateTimeString();
$end = Carbon::parse($request->start_date)->endOfDay()->toDateTimeString();
$result = FamilyAccountConsumption::whereBetween('created_at', [$start, $end])->where('created_by', $staff_member)
->whereNotIn('patient_id', findTestOrDemoPatients())->whereNull('received')->get()->sum('amount_consumed');
} else if ($request->dates == "custom_date_range") {
$result = FamilyAccountConsumption::whereBetween('created_at', [$start, $end])->where('created_by', $staff_member)
->whereNotIn('patient_id', findTestOrDemoPatients())->whereNull('received')->get()->sum('amount_consumed');
}
}
return $result;
}
function get_family_accounts_deposit_amount($request)
{
$today = Carbon::today()->toDateString();
$yesterday = Carbon::yesterday()->toDateString();
$end = Carbon::parse($request->end_date)->endOfDay()->toDateTimeString();
$start = Carbon::parse($request->start_date)->startOfDay()->toDateTimeString();
$staff_member = $request->staff_member;
$result = null;
if ($staff_member == 0) {
if ($request->dates == "today") {
$result = FamilyAccountDeposit::whereDate('created_at', $today)->where('is_opening_amount', 0)->get()->sum('deposit_amount');
} else if ($request->dates == "yesterday") {
$result = FamilyAccountDeposit::whereDate('created_at', $yesterday)->where('is_opening_amount', 0)->get()->sum('deposit_amount');
} else if ($request->dates == "custom_date") {
$start = Carbon::parse($request->start_date)->startOfDay()->toDateTimeString();
$end = Carbon::parse($request->start_date)->endOfDay()->toDateTimeString();
$result = FamilyAccountDeposit::whereBetween('created_at', [$start, $end])->where('is_opening_amount', 0)->get()->sum('deposit_amount');
} else if ($request->dates == "custom_date_range") {
$result = FamilyAccountDeposit::whereBetween('created_at', [$start, $end])->where('is_opening_amount', 0)->get()->sum('deposit_amount');
}
} else {
if ($request->dates == "today") {
$result = FamilyAccountDeposit::whereDate('created_at', $today)->where('is_opening_amount', 0)->where('created_by', $staff_member)->get()->sum('deposit_amount');
} else if ($request->dates == "yesterday") {
$result = FamilyAccountDeposit::whereDate('created_at', $yesterday)->where('is_opening_amount', 0)->where('created_by', $staff_member)->get()->sum('deposit_amount');
} else if ($request->dates == "custom_date") {
$start = Carbon::parse($request->start_date)->startOfDay()->toDateTimeString();
$end = Carbon::parse($request->start_date)->endOfDay()->toDateTimeString();
$result = FamilyAccountDeposit::whereBetween('created_at', [$start, $end])->where('is_opening_amount', 0)->where('created_by', $staff_member)->get()->sum('deposit_amount');
} else if ($request->dates == "custom_date_range") {
$result = FamilyAccountDeposit::whereBetween('created_at', [$start, $end])->where('is_opening_amount', 0)->where('created_by', $staff_member)->get()->sum('deposit_amount');
}
}
return $result;
}
function get_unreceived_family_accounts_deposit_amount($request)
{
$today = Carbon::today()->toDateString();
$yesterday = Carbon::yesterday()->toDateString();
$end = Carbon::parse($request->end_date)->endOfDay()->toDateTimeString();
$start = Carbon::parse($request->start_date)->startOfDay()->toDateTimeString();
$staff_member = $request->staff_member;
$result = null;
if ($staff_member == 0) {
if ($request->dates == "today") {
$result = FamilyAccountDeposit::whereDate('created_at', $today)->where('is_opening_amount', 0)->whereNull('received')->get()->sum('deposit_amount');
} else if ($request->dates == "yesterday") {
$result = FamilyAccountDeposit::whereDate('created_at', $yesterday)->where('is_opening_amount', 0)->whereNull('received')->get()->sum('deposit_amount');
} else if ($request->dates == "custom_date") {
$start = Carbon::parse($request->start_date)->startOfDay()->toDateTimeString();
$end = Carbon::parse($request->start_date)->endOfDay()->toDateTimeString();
$result = FamilyAccountDeposit::whereBetween('created_at', [$start, $end])->where('is_opening_amount', 0)->whereNull('received')->get()->sum('deposit_amount');
} else if ($request->dates == "custom_date_range") {
$result = FamilyAccountDeposit::whereBetween('created_at', [$start, $end])->where('is_opening_amount', 0)->whereNull('received')->get()->sum('deposit_amount');
}
} else {
if ($request->dates == "today") {
$result = FamilyAccountDeposit::whereDate('created_at', $today)->where('created_by', $staff_member)->where('is_opening_amount', 0)->whereNull('received')->get()->sum('deposit_amount');
} else if ($request->dates == "yesterday") {
$result = FamilyAccountDeposit::whereDate('created_at', $yesterday)->where('created_by', $staff_member)->where('is_opening_amount', 0)->whereNull('received')->get()->sum('deposit_amount');
} else if ($request->dates == "custom_date") {
$start = Carbon::parse($request->start_date)->startOfDay()->toDateTimeString();
$end = Carbon::parse($request->start_date)->endOfDay()->toDateTimeString();
$result = FamilyAccountDeposit::whereBetween('created_at', [$start, $end])->where('created_by', $staff_member)->where('is_opening_amount', 0)->whereNull('received')->get()->sum('deposit_amount');
} else if ($request->dates == "custom_date_range") {
$result = FamilyAccountDeposit::whereBetween('created_at', [$start, $end])->where('created_by', $staff_member)->where('is_opening_amount', 0)->whereNull('received')->get()->sum('deposit_amount');
}
}
return $result;
}
function getSumServiceDepositSubtotals($table, Request $request)
{
$result = [];
$amount = 0;
$consult_sum = 0;
$service_sum = 0;
$co_payment_sum = 0;
$inpatient_deposit_sum = 0;
$consult_sum_income_cash = 0;
$service_sum_income_cash = 0;
$co_payment_sum_income_cash = 0;
$inpatient_deposit_sum_income_cash = 0;
//Bright's bright variables stuff :)
$consultation_subtotal = 0;
$other_services_subtotal = 0;
$copayment_subtotal = 0;
$inpatient_subtotal = 0;
$today = Carbon::today()->toDateString();
$yesterday = Carbon::yesterday()->toDateString();
$end = Carbon::parse($request->end_date)->endOfDay()->toDateTimeString();
$start = Carbon::parse($request->start_date)->startOfDay()->toDateTimeString();
$staff_member = $request->staff_member; // User::where('username', $request->staff_member)->pluck('id')->first();
if ($request->staff_member == "0") {
if ($request->dates == "today") {
$result = DB::table($table)->whereDate('created_at', $today)
->whereNotIn('patient_id', findTestOrDemoPatients())->get();
} else if ($request->dates == "yesterday") {
$result = DB::table($table)->whereDate('created_at', $yesterday)
->whereNotIn('patient_id', findTestOrDemoPatients())->get();
} else if ($request->dates == "custom_date") {
$result = DB::table($table)->whereDate('created_at', $request->start_date)
->whereNotIn('patient_id', findTestOrDemoPatients())->get();
} else if ($request->dates == "custom_date_range") {
$result = DB::table($table)->whereBetween('created_at', [$start, $end])
->whereNotIn('patient_id', findTestOrDemoPatients())->get();
}
} else {
if ($request->dates == "today") {
$result = DB::table($table)->whereDate('created_at', $today)->where('created_by', $staff_member)
->whereNotIn('patient_id', findTestOrDemoPatients())->get();
} else if ($request->dates == "yesterday") {
$result = DB::table($table)->whereDate('created_at', $yesterday)->where('created_by', $staff_member)
->whereNotIn('patient_id', findTestOrDemoPatients())->get();
} else if ($request->dates == "custom_date") {
$result = DB::table($table)->whereDate('created_at', $request->start_date)->where('created_by', $staff_member)
->whereNotIn('patient_id', findTestOrDemoPatients())->get();
} else if ($request->dates == "custom_date_range") {
$result = DB::table($table)->whereBetween('created_at', [$start, $end])->where('created_by', $staff_member)
->whereNotIn('patient_id', findTestOrDemoPatients())->get();
}
}
if (count($result) > 0) {
foreach ($result as $item) {
if ($item->service_type == "Consultation") {
//$item_subtotals
$consultations_subtotals_array = explode(",", $item->items_amounts);
for ($x = 0; $x < count($consultations_subtotals_array); $x++) {
$consultation_subtotal += $consultations_subtotals_array[$x] != "" ? $consultations_subtotals_array[$x] : 0;
}
} else if ($item->service_type == "Co_Payment") {
$copayments_subtotals_array = explode(",", $item->items_amounts);
for ($x = 0; $x < count($copayments_subtotals_array); $x++) {
$copayment_subtotal += $copayments_subtotals_array[$x] != "" ? $copayments_subtotals_array[$x] : 0;
}
} else if ($item->service_type == "Service" || $item->service_type == "Services" || $item->service_type == "Other Service") {
$other_services_subtotals_array = explode(",", $item->items_amounts);
for ($x = 0; $x < count($other_services_subtotals_array); $x++) {
$other_services_subtotal += $other_services_subtotals_array[$x] != "" ? $other_services_subtotals_array[$x] : 0;
}
} else if ($item->service_type == "Inpatient_Deposit") {
$inpatient_deposit_subtotals_array = explode(",", $item->items_amounts);
for ($x = 0; $x < count($inpatient_deposit_subtotals_array); $x++) {
$inpatient_subtotal += $inpatient_deposit_subtotals_array[$x] != "" ? $inpatient_deposit_subtotals_array[$x] : 0;
}
}
}
} else {
return [0, 0, 0, 0];
}
return array($consultation_subtotal, $copayment_subtotal, $other_services_subtotal, $inpatient_subtotal);
}
function getSumOfDepositSubtotals($table, $sum_column, Request $request)
{
$result = 0;
$insurance_amount = 0;
$today = Carbon::today()->toDateTimeString();
$yesterday = Carbon::yesterday()->toDateTimeString();
$end = Carbon::parse($request->end_date)->endOfDay()->toDateTimeString();
$start = Carbon::parse($request->start_date)->startOfDay()->toDateTimeString();
$staff_member = $request->staff_member; // User::where('username', $request->staff_member)->pluck('id')->first();
$sub_amount_total = 0;
if ($request->staff_member == "0") {
if ($request->dates == "today") {
$result = DB::table($table)
->whereDate('created_at', $today)
->whereNotIn('patient_id', findTestOrDemoPatients())
->pluck($sum_column)
->toArray();
for ($i = 0; $i < count($result); $i++) {
$subtotals_array = $table == "procedure_deposits" ? unserialize($result[$i]) : explode(",", $result[$i]);
for ($x = 0; $x < count($subtotals_array); $x++) {
$sub_amount_total += $subtotals_array[$x] != "" ? $subtotals_array[$x] : 0;
}
}
} else if ($request->dates == "yesterday") {
$result = DB::table($table)
->whereDate('created_at', $yesterday)
->whereNotIn('patient_id', findTestOrDemoPatients())
->pluck($sum_column)
->toArray();
for ($i = 0; $i < count($result); $i++) {
$subtotals_array = $table == "procedure_deposits" ? unserialize($result[$i]) : explode(",", $result[$i]);
for ($x = 0; $x < count($subtotals_array); $x++) {
$sub_amount_total += $subtotals_array[$x] != "" ? $subtotals_array[$x] : 0;
}
}
} else if ($request->dates == "custom_date") {
$result = DB::table($table)
->whereDate('created_at', $request->start_date)
->whereNotIn('patient_id', findTestOrDemoPatients())
->pluck($sum_column)
->toArray();
for ($i = 0; $i < count($result); $i++) {
$subtotals_array = $table == "procedure_deposits" ? unserialize($result[$i]) : explode(",", $result[$i]);
for ($x = 0; $x < count($subtotals_array); $x++) {
$sub_amount_total += $subtotals_array[$x] != "" ? $subtotals_array[$x] : 0;
}
}
} else if ($request->dates == "custom_date_range") {
$result = DB::table($table)
->whereBetween('created_at', [$start, $end])
->whereNotIn('patient_id', findTestOrDemoPatients())
->pluck($sum_column)
->toArray();
for ($i = 0; $i < count($result); $i++) {
$subtotals_array = $table == "procedure_deposits" ? unserialize($result[$i]) : explode(",", $result[$i]);
for ($x = 0; $x < count($subtotals_array); $x++) {
$sub_amount_total += $subtotals_array[$x] != "" ? $subtotals_array[$x] : 0;
}
}
}
} else {
if ($request->dates == "today") {
$result = DB::table($table)
->whereDate('created_at', $today)
->where('created_by', $staff_member)
->whereNotIn('patient_id', findTestOrDemoPatients())
->pluck($sum_column)
->toArray();
for ($i = 0; $i < count($result); $i++) {
$subtotals_array = $table == "procedure_deposits" ? unserialize($result[$i]) : explode(",", $result[$i]);
for ($x = 0; $x < count($subtotals_array); $x++) {
$sub_amount_total += $subtotals_array[$x] != "" ? $subtotals_array[$x] : 0;
}
}
} else if ($request->dates == "yesterday") {
$result = DB::table($table)
->whereDate('created_at', $yesterday)
->where('created_by', $staff_member)
->whereNotIn('patient_id', findTestOrDemoPatients())
->pluck($sum_column)
->toArray();
for ($i = 0; $i < count($result); $i++) {
$subtotals_array = $table == "procedure_deposits" ? unserialize($result[$i]) : explode(",", $result[$i]);
for ($x = 0; $x < count($subtotals_array); $x++) {
$sub_amount_total += $subtotals_array[$x] != "" ? $subtotals_array[$x] : 0;
}
}
} else if ($request->dates == "custom_date") {
$result = DB::table($table)
->whereDate('created_at', $request->start_date)
->where('created_by', $staff_member)
->whereNotIn('patient_id', findTestOrDemoPatients())
->pluck($sum_column)
->toArray();
for ($i = 0; $i < count($result); $i++) {
$subtotals_array = $table == "procedure_deposits" ? unserialize($result[$i]) : explode(",", $result[$i]);
for ($x = 0; $x < count($subtotals_array); $x++) {
$sub_amount_total += $subtotals_array[$x] != "" ? $subtotals_array[$x] : 0;
}
}
} else if ($request->dates == "custom_date_range") {
$result = DB::table($table)
->whereBetween('created_at', [$start, $end])
->where('created_by', $staff_member)
->whereNotIn('patient_id', findTestOrDemoPatients())
->pluck($sum_column)
->toArray();
for ($i = 0; $i < count($result); $i++) {
$subtotals_array = $table == "procedure_deposits" ? unserialize($result[$i]) : explode(",", $result[$i]);
for ($x = 0; $x < count($subtotals_array); $x++) {
$sub_amount_total += $subtotals_array[$x] != "" ? $subtotals_array[$x] : 0;
}
}
}
}
return $sub_amount_total;
}
function get_latest_opening_balance_record($id, $date)
{
$orderByTransIdQuery = "CAST(trans_id AS DECIMAL(10,0)) DESC";
$record = DB::table('banking')
->whereNull('deleted_at')
->where('bank', '=', $id)
->where('memo', 'Initial Deposit')
->whereDate('trans_date', '<=', Carbon::parse($date)->toDateString())
->orderBy('trans_date', 'desc')
->orderByRaw($orderByTransIdQuery)
->first();
if (is_null($record)) {
$record = DB::table('banking')
->whereNull('deleted_at')
->where('bank', '=', $id)
->where('memo', 'Initial Deposit')
->whereDate('trans_date', '>=', Carbon::parse($date)->toDateString())
->orderBy('trans_date', 'desc')
->orderByRaw($orderByTransIdQuery)
->first();
if (is_null($record)) {
$record = DB::table('banking')
->whereNull('deleted_at')
->where('bank', '=', $id)
->where('memo', 'Initial Deposit')
->orderBy('trans_date', 'desc')
->orderByRaw($orderByTransIdQuery)
->first();
}
}
return $record;
}
function get_fiscal_year_start_from_hospital_information($carbon_date_selected)
{
$hospital_information = \Streamline\Models\HospitalInformation::first();
$start_month_of_fiscal_year = $hospital_information->financial_year_start_date;
$month_of_selected_date = $carbon_date_selected->format('m');
$year_of_selected_date = $carbon_date_selected->format('Y');
$integer_month_of_selected_date = (int)$month_of_selected_date;
$integer_start_month_of_fiscal_year = (int)$start_month_of_fiscal_year;
if ($integer_month_of_selected_date >= $integer_start_month_of_fiscal_year) {
$financial_year_start_date_string = $year_of_selected_date . "-" . $integer_start_month_of_fiscal_year . "-01";
//dd('month is below above fiscal month');
$start_financial_year = Carbon::parse($financial_year_start_date_string);
} else {
$end_financial_year_start_date_string = $year_of_selected_date . "-" . $integer_start_month_of_fiscal_year . "-01";
$start_financial_year = Carbon::parse($end_financial_year_start_date_string)->subYear(1);
}
return $start_financial_year->toDateString();
}
function remove_an_element_from_serialized_data($element_position, $serialized_data_string)
{
$array_of_items = unserialize($serialized_data_string);
unset($array_of_items[$element_position]);
$array_keys = array_values($array_of_items);
$trimed_serialized_data = serialize($array_keys);
return $trimed_serialized_data;
}
function getIndividualAccountsReceivablesBalanceSheet($request)
{
$end = Carbon::parse($request->end_date)->endOfDay()->toDateTimeString();
$start = Carbon::parse($request->start_date)->startOfDay()->toDateTimeString();
$date_of_interest = Carbon::today()->toDateTimeString();
$receivable_account_arr = [];
$temp_arr = [];
$date_filter = [];
$today = "";
if ($request->dates == 'today') {
$date_of_interest = Carbon::today()->toDateTimeString();
} elseif ($request->dates == 'yesterday') {
$date_of_interest = Carbon::yesterday()->toDateString();
} elseif ($request->dates == 'custom_date') {
$date_of_interest = Carbon::parse($request->start_date)->toDateString();
} elseif ($request->dates == 'custom_date_range') {
$date_of_interest = Carbon::parse($request->end_date)->toDateString();
}
if ($request->dates == 'custom_date_range') {
$date_filter = [['created_at', '>=', $start], ['created_at', '<=', $end]];
//array_push($date_filter, ['created_at', '<=', $end]);
} else {
array_push($date_filter, ['created_at', '<=', $date_of_interest]);
}
$temp_arr[] = DB::table('patient_category_invoices')
->whereNotNull('receivable_account')
->whereNull('deleted_at')
->where($date_filter)
->where('balance_remaining', '>', 0)
->get(['balance_remaining', 'receivable_account'])
->groupBy('receivable_account')->map(function ($row) {
return $row->sum('balance_remaining');
});
$temp_arr[] = DB::table('patient_category_invoices')
->whereNotNull('receivable_account')
->whereNull('deleted_at')
->where($date_filter)
->whereNull('balance_remaining')
->get(['patient_amount', 'receivable_account'])
->groupBy('receivable_account')->map(function ($row) {
return $row->sum('patient_amount');
});
$temp_arr[] = DB::table('debtors')
->whereNotNull('receivable_account')
->whereNull('deleted_at')
->where($date_filter)
->where('balance_remaining', '>', 0)
->get(['balance_remaining', 'receivable_account'])
->groupBy('receivable_account')->map(function ($row) {
return $row->sum('balance_remaining');
});
$temp_arr[] = DB::table('debtors')
->whereNotNull('receivable_account')
->whereNull('deleted_at')
->where($date_filter)
->whereNull('balance_remaining')
->get(['balance', 'receivable_account'])
->groupBy('receivable_account')->map(function ($row) {
return $row->sum('balance');
});
$temp_arr[] = DB::table('debt_plan')
->whereNotNull('receivable_account')
->whereNull('deleted_at')
->where($date_filter)
->where('balance_remaining', '>', 0)
->get(['balance_remaining', 'receivable_account'])
->groupBy('receivable_account')->map(function ($row) {
return $row->sum('balance_remaining');
});
$temp_arr[] = DB::table('debt_plan')
->whereNotNull('receivable_account')
->whereNull('deleted_at')
->where($date_filter)
->whereNull('balance_remaining')
->get(['amount_owed', 'receivable_account'])
->groupBy('receivable_account')->map(function ($row) {
return $row->sum('amount_owed');
});
foreach ($temp_arr as $item) {
foreach ($item as $key => $value) {
$receivable_account_arr[$key] = ($receivable_account_arr[$key] ?? 0) + $value;
}
}
$data = [];
foreach ($receivable_account_arr as $account => $amount) {
$data_string = $request->dates . "," . $request->start_date . "," . $request->end_date . "," . 'chart_of_accounts' . "," . $account . ",";
$data[] = ['id' => $account, 'amount' => $amount, 'data' => $data_string];
}
return $data;
}
function getAssetTransactions($request)
{
$data = [];
$today = Carbon::today()->toDateString();
$yesterday = Carbon::yesterday()->toDateString();
$end = Carbon::parse($request->end_date)->endOfDay()->toDateTimeString();
$start = Carbon::parse($request->start_date)->startOfDay()->toDateTimeString();
$non_current_asset_accounts = \Streamline\Models\ChartOfAccount::where('type', 3)->whereNull('deleted_at')->where('slug', '!=', 'accumulated_depreciation')->pluck('id')->toArray();
$asset_transactions = \Streamline\Models\FixedAsset::whereNull('deleted_at')->where('acquisition_date', $today)->get();
switch ($request->dates) {
case 'today':
$asset_transactions = \Streamline\Models\FixedAsset::whereNull('deleted_at')->where('acquisition_date', $today)->get();
break;
case 'yesterday':
$asset_transactions = \Streamline\Models\FixedAsset::whereNull('deleted_at')->where('acquisition_date', $yesterday)->get();
break;
case 'custom_date':
$asset_transactions = \Streamline\Models\FixedAsset::whereNull('deleted_at')->where('acquisition_date', $start)->get();
break;
case 'custom_date_range':
$asset_transactions = \Streamline\Models\FixedAsset::whereNull('deleted_at')->whereBetween('acquisition_date', [$start, $end])->get();
break;
}
foreach ($asset_transactions as $record) {
if (in_array($record->fixed_asset_account_id, $non_current_asset_accounts)) {
$cost_price = ($record->cost_price != null) ? $record->cost_price : 0;
if (isset($data[$record->fixed_asset_account_id])) {
$data[$record->fixed_asset_account_id]['cost_price'] += $cost_price;
} else {
$data_string = $request->dates . "," . $request->start_date . "," . $request->end_date . "," . 'fixed_assets' . "," . $record->fixed_asset_account_id . ",";
$data[$record->fixed_asset_account_id]['data'] = $data_string;
$data[$record->fixed_asset_account_id]['cost_price'] = $cost_price;
}
}
}
return $data;
}
function getNetIncome(Request $request)
{
$accrual_income_total = $expenses_accrual_total = $cash_income_total = $expenses_cash_total = $cog_accrual_total = $cog_cash_total = 0;
$revenue = getRevenueSumByAccount($request);
$income_accounts = $revenue[0];
$cost_of_sales_accounts = $revenue[1];
$expense_accounts = getExpensesByAccount($request);
foreach ($income_accounts as $account) {
$cash_income_total += $account['cash'];
$accrual_income_total += $account['accrual'];
}
foreach ($expense_accounts as $account) {
$expenses_cash_total += $account['cash'];
$expenses_accrual_total += $account['accrual'];
}
foreach ($cost_of_sales_accounts as $account) {
$cog_accrual_total += $account['accrual'] ?? 0;
$cog_cash_total += $account['cash'];
}
$accrual_net_income = $accrual_income_total - ($expenses_accrual_total + $cog_accrual_total);
$cash_net_income = $cash_income_total - ($expenses_cash_total + $cog_cash_total);
return [
'accrual_net_income' => $accrual_net_income, 'cash_net_income' => $cash_net_income, 'accrual_income_total' => $accrual_income_total, 'expenses_accrual_total' => $expenses_accrual_total, 'cog_accrual_total' => $cog_accrual_total,
'cash_income_total' => $cash_income_total, 'expenses_cash_total' => $expenses_cash_total, 'cog_cash_total' => $cog_cash_total, 'revenue' => $revenue, 'expense_accounts' => $expense_accounts
];
}
function getDepreciation(Request $request)
{
// $depreciation = 0;
$data = [];
$today = Carbon::today()->toDateString();
$yesterday = Carbon::yesterday()->toDateString();
$end = Carbon::parse($request->end_date)->endOfDay()->toDateTimeString();
$start = Carbon::parse($request->start_date)->startOfDay()->toDateTimeString();
$non_current_asset_accounts = \Streamline\Models\ChartOfAccount::where('type', 3)->whereNull('deleted_at')->where('slug', 'accumulated_depreciation')->pluck('id')->toArray();
$asset_transactions = \Streamline\Models\FixedAsset::whereNull('deleted_at')->where('acquisition_date', $today)->get();
switch ($request->dates) {
case 'today':
$asset_transactions = \Streamline\Models\FixedAsset::whereNull('deleted_at')->where('acquisition_date', $today)->get();
break;
case 'yesterday':
$asset_transactions = \Streamline\Models\FixedAsset::whereNull('deleted_at')->where('acquisition_date', $yesterday)->get();
break;
case 'custom_date':
$asset_transactions = \Streamline\Models\FixedAsset::whereNull('deleted_at')->where('acquisition_date', $start)->get();
break;
case 'custom_date_range':
$asset_transactions = \Streamline\Models\FixedAsset::whereNull('deleted_at')->whereBetween('acquisition_date', [$start, $end])->get();
break;
}
foreach ($asset_transactions as $record) {
if (in_array($record->fixed_asset_account_id, $non_current_asset_accounts)) {
// $depreciation_rate = ($record->depreciation != null) ? $record->depreciation : 0;
$cost_price = ($record->cost_price != null) ? $record->cost_price : 0;
// $date1 = new DateTime($record->acquisition_date);
// $date2 = new DateTime($end);
// $interval = $date1->diff($date2);
// $years_depreciated = $interval->m / 12;
// $depreciation_value = $years_depreciated * $depreciation_rate * $cost_price;
// $depreciation += ($depreciation_value > 0) ? round($depreciation_value) : 0;
if (isset($data[$record->fixed_asset_account_id])) {
$data[$record->fixed_asset_account_id]['cost_price'] += $cost_price;
} else {
$data_string = $request->dates . "," . $request->start_date . "," . $request->end_date . "," . 'fixed_assets' . "," . $record->fixed_asset_account_id . ",";
$data[$record->fixed_asset_account_id]['data'] = $data_string;
$data[$record->fixed_asset_account_id]['cost_price'] = $cost_price;
}
}
}
return $data; //$depreciation;
}
function getRetainedEarnings(Request $request, $start_date_of_current_balance_sheet)
{
$retainer_end_date = Carbon::parse($start_date_of_current_balance_sheet)->subDay(1);
$retainer_end_date_string = $retainer_end_date->toDateString();
//get the date of the first episode to use as the start date
$first_episode = \Streamline\Models\PatientEpisode::first();
$retainer_start_date_string = $first_episode ? $first_episode->created_at->toDateString() : null;
//check to make sure the start date is less than the end date
if (is_null($retainer_start_date_string) || $first_episode->created_at->gt($retainer_end_date)) {
//create a start date of one day before the end date of retainer
$retainer_start_date = Carbon::parse($retainer_end_date)->subDay(1);
$retainer_start_date_string = $retainer_start_date->toDateString();
}
$request->request->add(['start_date' => $retainer_start_date_string]);
$request->request->add(['end_date' => $retainer_end_date_string]);
$net_income_from_past_years = getNetIncome($request);
$accrual_net_income = $net_income_from_past_years['accrual_net_income'];
$cash_net_income = $net_income_from_past_years['cash_net_income'];
return $accrual_net_income;
}
function get_unreceived_patient_accounts_deposit_amount($request)
{
$staff_member = $request->staff_member;
if ($request->dates == "yesterday") {
$end = Carbon::yesterday()->endOfDay()->toDateTimeString();
$start = Carbon::yesterday()->startOfDay()->toDateTimeString();
} else if ($request->dates == "custom_date") {
$start = Carbon::parse($request->start_date)->startOfDay()->toDateTimeString();
$end = Carbon::parse($request->start_date)->endOfDay()->toDateTimeString();
} else if ($request->dates == "custom_date_range") {
$end = Carbon::parse($request->end_date)->endOfDay()->toDateTimeString();
$start = Carbon::parse($request->start_date)->startOfDay()->toDateTimeString();
} else {
$end = Carbon::today()->endOfDay()->toDateTimeString();
$start = Carbon::today()->startOfDay()->toDateTimeString();
}
if ($staff_member == 0) {
$result = PatientAccountsDeposit::whereBetween('created_at', [$start, $end])->whereNull('received')->sum('deposit_amount');
} else {
$result = PatientAccountsDeposit::whereBetween('created_at', [$start, $end])->where('created_by', $staff_member)->whereNull('received')->sum('deposit_amount');
}
return $result;
}
function get_patient_accounts_deposit_amount($request)
{
$staff_member = $request->staff_member;
if ($request->dates == "yesterday") {
$end = Carbon::yesterday()->endOfDay()->toDateTimeString();
$start = Carbon::yesterday()->startOfDay()->toDateTimeString();
} else if ($request->dates == "custom_date") {
$start = Carbon::parse($request->start_date)->startOfDay()->toDateTimeString();
$end = Carbon::parse($request->start_date)->endOfDay()->toDateTimeString();
} else if ($request->dates == "custom_date_range") {
$end = Carbon::parse($request->end_date)->endOfDay()->toDateTimeString();
$start = Carbon::parse($request->start_date)->startOfDay()->toDateTimeString();
} else {
$end = Carbon::today()->endOfDay()->toDateTimeString();
$start = Carbon::today()->startOfDay()->toDateTimeString();
}
if ($staff_member == 0) {
$result = PatientAccountsDeposit::whereBetween('created_at', [$start, $end])->sum('deposit_amount');
} else {
$result = PatientAccountsDeposit::whereBetween('created_at', [$start, $end])->where('created_by', $staff_member)->sum('deposit_amount');
}
return $result;
}
function get_unreceived_cash_patient_accounts_consumption_amount($request)
{
$staff_member = $request->staff_member;
if ($request->dates == "yesterday") {
$end = Carbon::yesterday()->endOfDay()->toDateTimeString();
$start = Carbon::yesterday()->startOfDay()->toDateTimeString();
} else if ($request->dates == "custom_date") {
$start = Carbon::parse($request->start_date)->startOfDay()->toDateTimeString();
$end = Carbon::parse($request->start_date)->endOfDay()->toDateTimeString();
} else if ($request->dates == "custom_date_range") {
$end = Carbon::parse($request->end_date)->endOfDay()->toDateTimeString();
$start = Carbon::parse($request->start_date)->startOfDay()->toDateTimeString();
} else {
$end = Carbon::today()->endOfDay()->toDateTimeString();
$start = Carbon::today()->startOfDay()->toDateTimeString();
}
if ($staff_member == 0) {
$result = PatientAccountConsumption::whereBetween('created_at', [$start, $end])
->whereNull('received')
->sum('amount_consumed');
} else {
$result = PatientAccountConsumption::whereBetween('created_at', [$start, $end])->where('created_by', $staff_member)
->whereNull('received')
->sum('amount_consumed');
}
return $result;
}
function income_cash_patient_accounts_consumption_amount($request)
{
$staff_member = $request->staff_member;
if ($request->dates == "yesterday") {
$end = Carbon::yesterday()->endOfDay()->toDateTimeString();
$start = Carbon::yesterday()->startOfDay()->toDateTimeString();
} else if ($request->dates == "custom_date") {
$start = Carbon::parse($request->start_date)->startOfDay()->toDateTimeString();
$end = Carbon::parse($request->start_date)->endOfDay()->toDateTimeString();
} else if ($request->dates == "custom_date_range") {
$end = Carbon::parse($request->end_date)->endOfDay()->toDateTimeString();
$start = Carbon::parse($request->start_date)->startOfDay()->toDateTimeString();
} else {
$end = Carbon::today()->endOfDay()->toDateTimeString();
$start = Carbon::today()->startOfDay()->toDateTimeString();
}
if ($staff_member == 0) {
$result = PatientAccountConsumption::whereBetween('created_at', [$start, $end])
->sum('amount_consumed');
} else {
$result = PatientAccountConsumption::whereBetween('created_at', [$start, $end])->where('created_by', $staff_member)
->sum('amount_consumed');
}
return $result;
}
function record_cash_credits_to_daily_collection_account($patient_amount_paid, $receipt_number, $memo)
{
$daily_cash_collections_id = DB::table('chart_of_accounts')->where('slug', 'daily_cash_collections')->first();
if ($daily_cash_collections_id) {
$new_balance = $daily_cash_collections_id->balance + $patient_amount_paid;
ChartOfAccount::find($daily_cash_collections_id->id)->update(['balance' => $new_balance]);
$most_recent_undeposited_funds_banking_record = get_latest_banking_record($daily_cash_collections_id->id, Carbon::today());
$balance_after_addition = (($most_recent_undeposited_funds_banking_record) ? (int)$most_recent_undeposited_funds_banking_record->account_balance : 0) + $patient_amount_paid;
capture_bank_record(
'DEPOSIT',
Carbon::today()->toDateString(),
$daily_cash_collections_id->id,
'sales and payments',
$balance_after_addition,
$patient_amount_paid,
0,
$memo,
$receipt_number
);
}
}
function record_cash_debits_to_daily_collection_account($amount_debited, $receipt_number, $memo)
{
$daily_cash_collections_id = DB::table('chart_of_accounts')->where('slug', 'daily_cash_collections')->first();
if ($daily_cash_collections_id) {
$new_balance = $daily_cash_collections_id->balance - $amount_debited;
ChartOfAccount::find($daily_cash_collections_id->id)->update(['balance' => $new_balance]);
$most_recent_undeposited_funds_banking_record = get_latest_banking_record($daily_cash_collections_id->id, Carbon::today());
$balance_after_addition = (($most_recent_undeposited_funds_banking_record) ? (int)$most_recent_undeposited_funds_banking_record->account_balance : 0) - $amount_debited;
capture_bank_record(
'PAYMENT',
Carbon::today()->toDateString(),
$daily_cash_collections_id->id,
'sales and payments',
$balance_after_addition,
0,
$amount_debited,
$memo,
$receipt_number
);
}
}
function revert_cash_credits_to_daily_collection_account($amount_debited, $receipt_number, $is_full_revert)
{
$daily_cash_collections_id = DB::table('chart_of_accounts')->where('slug', 'daily_cash_collections')->first();
if ($daily_cash_collections_id) {
$new_balance = $daily_cash_collections_id->balance - $amount_debited;
ChartOfAccount::find($daily_cash_collections_id->id)->update(['balance' => $new_balance]);
$bank_records = Banking::where('trans_id', $receipt_number)->get();
if (count($bank_records) > 0) {
foreach ($bank_records as $bank_record) {
if (!$is_full_revert) {
$bank_record->account_balance = $new_balance;
$bank_record->credit = $bank_record->credit - $amount_debited;
$bank_record->updated_by = Auth::id();
$bank_record->save();
} else {
Banking::find($bank_record->id)->delete();
}
}
} else {
$most_recent_undeposited_funds_banking_record = get_latest_banking_record($daily_cash_collections_id->id, Carbon::today());
$balance_after_addition = (($most_recent_undeposited_funds_banking_record) ? (int)$most_recent_undeposited_funds_banking_record->account_balance : 0) - $amount_debited;
capture_bank_record(
'PAYMENT',
Carbon::today()->toDateString(),
$daily_cash_collections_id->id,
'sales and payments',
$balance_after_addition,
0,
$amount_debited,
'Reversion',
$receipt_number
);
}
}
}
function account_for_stock_reconciliations_difference($item_type, $item_id, $affected_account_id, $difference, $cost_price, $reconciliation_date)
{
if ($item_type == 1) {
$item = \Streamline\Models\Drug::withTrashed()->find($item_id);
$item_name = $item ? $item->name : "N/A";
} elseif ($item_type == 2) {
$item = \Streamline\Models\Sundry::withTrashed()->find($item_id);
$item_name = $item ? $item->name : "N/A";
}
$track_receipt = new TrackReceipt;
$track_receipt->reason = "Stock reconciliation";
$track_receipt->created_by = Auth::id();
$track_receipt->save();
$receipt_number = sprintf("%04u", $track_receipt->id);
$account_slug = get_name($affected_account_id, "id", "slug", "chart_of_accounts");
$difference_amount = $difference * $cost_price;
if ($account_slug != "opening_inventory") {
$other_income = new \Streamline\Models\OtherIncome;
$other_income->income_account = $affected_account_id;
$other_income->deposit_amount = $difference_amount;
$other_income->banked_amount = $difference_amount;
$other_income->deposit_date = $reconciliation_date;
$other_income->deposit_memo = "Stock reconciliation for " . $item_name;
$other_income->trans_id = $receipt_number;
$other_income->received = 1;
$other_income->created_by = Auth::id();
$other_income->save();
}
}
function get_latest_banking_record_based_on_transaction_date($id, $date)
{
$orderByCreatedAtIfTransDateIsTheSame = "created_at DESC";
$orderByIdIfTransDateIsTheSame = "id DESC";
$record = DB::table('banking')
->whereNull('deleted_at')
->where('bank', '=', $id)
->whereDate('trans_date', '<=', Carbon::parse($date)->toDateString())
->orderBy('trans_date', 'desc')
->orderByRaw($orderByCreatedAtIfTransDateIsTheSame)
->orderByRaw($orderByIdIfTransDateIsTheSame)
->first();
return $record;
}
function is_bill_payment_transaction_reconciled($bill_id)
{
$payments = \Streamline\Models\Payment::where('bill_id', $bill_id)->get();
$transaction_ids_array = [];
if (count($payments) > 0) {
foreach ($payments as $payment_record) {
$transaction_ids_array[] = $payment_record->transaction_id;
}
}
//check if any of those transactions is reconciled in the banking table
$reconciled_bank_records = \Streamline\Models\Banking::whereIn('trans_id', $transaction_ids_array)->where('reconciled', '!=', 0)->get();
if (count($reconciled_bank_records) > 0) {
return true;
}
return false;
}
function is_payment_transaction_reconciled($payment_id)
{
$payment = \Streamline\Models\Payment::find($payment_id);
if ($payment) {
//check if any of those transactions is reconciled in the banking table
if ($payment->transaction_id != null) {
$reconciled_bank_records = \Streamline\Models\Banking::where('trans_id', $payment->transaction_id)->where('reconciled', '!=', 0)->get();
if (count($reconciled_bank_records) > 0) {
return true;
}
}
}
return false;
}
function is_cashier_income_record_bank_reconciled($cashier_income_id)
{
$cashier_income_record = \Streamline\Models\CashierIncome::find($cashier_income_id);
if ($cashier_income_record) {
$banked_array = is_null($cashier_income_record->banked) ? [] : explode(",", $cashier_income_record->banked);
if (count($banked_array) > 0) {
$reconciled_bank_records = \Streamline\Models\Banking::whereIn('id', $banked_array)->where('reconciled', '!=', 0)->get();
if (count($reconciled_bank_records) > 0) {
return true;
}
}
}
}
function get_actual_opening_balance_record_of_account($id, $date)
{
$orderByTransIdQuery = "CAST(trans_id AS DECIMAL(10,0)) DESC";
$record = DB::table('banking')
->whereNull('deleted_at')
->where('bank', '=', $id)
->where('memo', 'Initial Deposit')
->whereDate('trans_date', '<=', Carbon::parse($date)->toDateString())
->orderBy('trans_date', 'desc')
->orderByRaw($orderByTransIdQuery)
->first();
if ($record) {
return $record;
}
return null;
}
function get_unreceived_direct_bank_deposits_amount($request)
{
$staff_member = $request->staff_member;
if ($request->dates == "yesterday") {
$end = Carbon::yesterday()->endOfDay()->toDateTimeString();
$start = Carbon::yesterday()->startOfDay()->toDateTimeString();
} else if ($request->dates == "custom_date") {
$start = Carbon::parse($request->start_date)->startOfDay()->toDateTimeString();
$end = Carbon::parse($request->start_date)->endOfDay()->toDateTimeString();
} else if ($request->dates == "custom_date_range") {
$end = Carbon::parse($request->end_date)->endOfDay()->toDateTimeString();
$start = Carbon::parse($request->start_date)->startOfDay()->toDateTimeString();
} else {
$end = Carbon::today()->endOfDay()->toDateTimeString();
$start = Carbon::today()->startOfDay()->toDateTimeString();
}
$cash_to_be_received = 0;
$other_incomes = [];
if ($staff_member == 0) {
//$result = OtherIncome::whereBetween('deposit_date', [$start, $end])->whereNull('received')->sum('deposit_amount');
$other_incomes = OtherIncome::whereBetween('deposit_date', [$start, $end])->whereNull('received')->get();
} else {
//$result = OtherIncome::whereBetween('deposit_date', [$start, $end])->where('created_by', $staff_member)->whereNull('received')->sum('deposit_amount');
$result = OtherIncome::whereBetween('deposit_date', [$start, $end])->where('created_by', $staff_member)->whereNull('received')->get();
}
if (count($other_incomes) > 0) {
foreach ($other_incomes 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 = \Streamline\Models\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
$cash_to_be_received += $other_income_record->deposit_amount;
}
}
} else {
$cash_to_be_received += $other_income_record->deposit_amount;
}
}
}
return $cash_to_be_received;
}
function get_direct_bank_deposits_amount($request)
{
$staff_member = $request->staff_member;
$other_incomes = [];
if ($request->dates == "today") {
$start = Carbon::today()->startOfDay()->toDateTimeString();
$end = Carbon::today()->endOfDay()->toDateTimeString();
} else if ($request->dates == "yesterday") {
$start = Carbon::yesterday()->startOfDay()->toDateTimeString();
$end = Carbon::yesterday()->endOfDay()->toDateTimeString();
} else if ($request->dates == "custom_date") {
$start = Carbon::parse($request->start_date)->startOfDay()->toDateTimeString();
$end = Carbon::parse($request->start_date)->endOfDay()->toDateTimeString();
} else if ($request->dates == "custom_date_range") {
$end = Carbon::parse($request->end_date)->endOfDay()->toDateTimeString();
$start = Carbon::parse($request->start_date)->startOfDay()->toDateTimeString();
} else {
$end = Carbon::today()->endOfDay()->toDateTimeString();
$start = Carbon::today()->startOfDay()->toDateTimeString();
}
if ($staff_member == 0) {
$other_incomes = OtherIncome::whereBetween('deposit_date', [$start, $end])->where('deposit_memo', 'NOT LIKE', '%Stock reconciliation%')->get();
} else {
$other_incomes = OtherIncome::whereBetween('deposit_date', [$start, $end])->where('created_by', $staff_member)->where('deposit_memo', 'NOT LIKE', '%Stock reconciliation%')->get();
}
$to_receive_amount = 0;
if (count($other_incomes) > 0) {
foreach ($other_incomes 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 = \Streamline\Models\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
$to_receive_amount += $other_income_record->deposit_amount;
}
}
} else {
$to_receive_amount += $other_income_record->deposit_amount;
}
}
}
return $to_receive_amount;
}
function record_opening_balance_for_family_account($family_head, $opening_account_id, $deposit_amount, $opening_amount_date)
{
$equity = new Equity;
$equity->name = "Family Account Opening Balance - Family ID(" . $family_head . ")";
$equity->account_id = !is_null($opening_account_id) ? $opening_account_id : get_name("opening_balance_for_family_accounts", "slug", "id", "chart_of_accounts");
$equity->amount = ($deposit_amount > 0) ? (-1 * $deposit_amount) : abs($deposit_amount); //if +ve, store a -ve & viceversa
$equity->created_by = auth()->user()->id;
$equity->updated_by = auth()->user()->id; // whoever created equities table made this compulsory
$equity->transaction_date = $opening_amount_date;
$equity->created_at = Carbon::now();
$equity->deposit_date = $opening_amount_date;
$equity->save();
}
function update_opening_balance_equity_record_for_family_account($family_head, $opening_account_id, $deposit_amount, $opening_amount_date)
{
$equity = Equity::where('name', "Family Account Opening Balance - Family ID(" . $family_head . ")")->first();
if ($equity) {
$equity->account_id = !is_null($opening_account_id) ? $opening_account_id : get_name("opening_balance_for_family_accounts", "slug", "id", "chart_of_accounts");
$equity->amount = ($deposit_amount > 0) ? (-1 * $deposit_amount) : abs($deposit_amount); //if +ve, store a -ve & viceversa
$equity->updated_by = auth()->user()->id; // whoever created equities table made this compulsory
$equity->transaction_date = $opening_amount_date;
$equity->deposit_date = $opening_amount_date;
$equity->update();
}
}