Files
streamline-emr/docker/streamline-src/Modules/Stores/Http/Controllers/StoresController.php
T

6361 lines
359 KiB
PHP
Executable File

<?php
namespace Modules\Stores\Http\Controllers;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Streamline\Models\BatchStockWatcher;
use Streamline\Models\Drug;
use Streamline\Models\EyeGlasses;
use Streamline\Models\HospitalInformation;
use Streamline\Models\InventoryStockDate;
use Streamline\Models\ItemBatchWatcher;
use Streamline\Models\OpticalStockReconciliation;
use Streamline\Models\Sundry;
use Streamline\Models\Dental;
use Streamline\Models\Radiology;
use Streamline\Models\Lab;
use Streamline\Models\GeneralItem;
use Illuminate\Support\Facades\DB;
use Streamline\Models\Supplier;
use Streamine\Models\GeneralForm;
use Carbon\Carbon;
use Streamline\Models\TemporaryQuotation;
use Illuminate\Support\Facades\Validator;
use Streamline\Models\PatientDispensing;
use Streamline\Models\TrackInvoice;
use Streamline\Models\WardDispensing;
use Streamline\Models\Quotation;
use Streamline\Models\StoreStockReconciliation;
use DateTime;
use Streamline\Models\Requisition;
use Streamline\Models\SundryStoreStockReconciliation;
use Streamline\Models\GeneralItemStoreStockReconciliation;
use Streamline\Models\BatchDetailsForTemporaryStockReconciliation;
use Streamline\Models\ChartOfAccount;
use Illuminate\Support\Facades\Crypt;
use Barryvdh\Snappy\Facades\SnappyPdf;
use Illuminate\Validation\Rules\Can;
use Streamline\Models\BatchIssuedTracking;
use Streamline\Models\GeneralStockReconciliation;
use Streamline\Models\HospitalBill;
use Streamline\Models\ReportStockValue;
use Barryvdh\DomPDF\Facade\Pdf as DomPDF;
use Streamline\Models\WardStock;
use Streamline\Models\WardTreatmentDispensation;
use Modules\Stores\Services\StoresItemService;
use Streamline\Services\UserService;
class StoresController extends Controller {
public function __construct(private StoresItemService $itemsStockService, protected UserService $userService )
{
$this->middleware('auth');
$this->middleware('permission:stores-home', ['only' => ['index']]);
}
/**
* Display a listing of the resource.
*/
public function index() {
return view('stores::stores.index');
}
/**
* Show the form for creating a new resource.
*/
public function create() {
//
}
/**
* Store a newly created resource in storage.
*/
public function store(Request $request) {
//
}
/**
* Display the specified resource.
*/
public function show($id) {
//
}
/**
* Show the form for editing the specified resource.
*/
public function edit($id) {
//
}
/**
* Update the specified resource in storage.
*/
public function update(Request $request, $id) {
//
}
/**
* Remove the specified resource from storage.
*/
public function destroy($id) {
//
}
/*
select a quotation type
*/
public function select_quotation_type() {
$quotation_type_options = DB::table('quotation_types')->pluck('name', 'id')->toArray();
$quotation_type_options = ['' => '- Select Quotation type -'] + $quotation_type_options;
return view('stores::stores.select_quotation', compact('quotation_type_options'));
}
/*
display page for requesting a quotation of the selected type from @select_quotation_type() method
*/
public function request_a_quotation(Request $request) {
$quotation_type = $request->quotation_type;
$items = null;
$suppliers = DB::table('suppliers')->where('available', 1)->whereNull('deleted_at')->orderBy('name')->pluck('name', 'id')->toArray();
$quotation_types_array = DB::table('quotation_types')->pluck('name', 'id')->toArray();
$package_units = DB::table('package_units')->whereNull('deleted_at')->orderBy('name')->pluck('name', 'id')->toArray();
$package_units = ['' => '- select -'] + $package_units;
//1-Drug 2-Sundry 3-Dental 4-Radiology 5-Lab 6-General Items
$item_ids_array = [];
if ($quotation_type == 1) {
$items = Drug::whereIn('id', $item_ids_array)->orderBy('name', 'asc')->get();
} elseif ($quotation_type == 2) {
$items = Sundry::whereIn('id', $item_ids_array)->whereNull('deleted_at')->orderBy('name', 'asc')->get();
} elseif ($quotation_type == 3) {
$items = Dental::whereIn('id', $item_ids_array)->whereNull('deleted_at')->orderBy('name', 'asc')->get();
} elseif ($quotation_type == 4) {
$items = Radiology::whereIn('id', $item_ids_array)->whereNull('deleted_at')->orderBy('name', 'asc')->get();
} elseif ($quotation_type == 5) {
$items = Lab::whereIn('id', $item_ids_array)->whereNull('deleted_at')->orderBy('name', 'asc')->get();
} elseif ($quotation_type == 6) {
$items = GeneralItem::whereIn('id', $item_ids_array)->whereNull('deleted_at')->orderBy('name', 'asc')->get();
} elseif ($quotation_type == 7) {
$items = EyeGlasses::whereIn('id', $item_ids_array)->whereNull('deleted_at')->orderBy('name', 'asc')->get();
}
$drugs = Drug::where('available', 1)->orderby('name')->pluck('name', 'id')->prepend('All drugs', 'all_items');
$sundries = Sundry::where('available', 1)->orderby('name')->pluck('name', 'id')->prepend('All sundries', 'all_items');
$dentals = Dental::orderBy('name')->pluck('name', 'id')->prepend('All dentals', 'all_items');
$radiologies = Radiology::orderBy('name')->pluck('name', 'id')->prepend('All radiologies', 'all_items');
$labs = Lab::orderBy('name')->pluck('name', 'id')->prepend('All labs', 'all_items');
$general_items = GeneralItem::orderBy('name')->pluck('name', 'id')->prepend('All general items', 'all_items');
$opticals = EyeGlasses::orderBy('name')->pluck('name', 'id')->prepend('All optical items', 'all_items');
return view('stores::stores.request_quotation', compact('items', 'quotation_type', 'suppliers', 'quotation_types_array', 'package_units', 'drugs', 'sundries', 'dentals', 'radiologies', 'labs', 'general_items', 'opticals'));
}
/*
function to save a new supplier
*/
public function save_new_supplier(Request $request)
{
$supplier = new Supplier;
$supplier->name = $request->supplier_name;
$supplier->company = $request->supplier_company;
$supplier->mobile_number = $request->supplier_contact;
$supplier->address = $request->supplier_address;
$supplier->created_by = Auth::id();
$supplier->updated_by = Auth::id();
$supplier->save();
return $supplier->id;
}
/* temporarily store the requested quotation */
public function store_request_quotation_temporarily(Request $request)
{
$validator = Validator::make($request->all(), [
/* 'expected_date' => 'required',
'supplier' => 'required' */
]);
if ($validator->fails()) {
$string = "";
foreach ($validator->errors()->getMessages() as $item) {
$string .= "{$item[0]}<br>";
}
flash('Please make sure you fill in the supplier and expected date')->error();
return redirect('select_quotation_type');
} else {
$item_id_array = $request->item_id;
$quantity_array = $request->quantity;
$expected_date = Carbon::createFromFormat('d/m/Y', $request->expected_date)->toDateString();
$item_type = $request->item_type;
if (array_sum($quantity_array) < 1) {
flash('Please insert in some values')->error();
return redirect('select_quotation_type');
}
$item_ids = implode(',', $item_id_array);
$quantity = implode(',', $quantity_array);
$supplier_id_array = $request->supplier;
if (!is_array($supplier_id_array)) {
$supplier_id_array = [$supplier_id_array];
}
for($y = 0; $y < count($supplier_id_array); $y++) {
$eloquent_model = is_null($request->quotation_id_temporary) ? null : TemporaryQuotation::find($request->quotation_id_temporary);
$eloquent_model = is_null($eloquent_model) ? New TemporaryQuotation : $eloquent_model;
$eloquent_model->quotation_type_id = $item_type;
$eloquent_model->drug_id = $item_ids;
$eloquent_model->package_unit = implode(",", $request->package_unit);
$eloquent_model->number_of_package_units = implode(",", $request->number_of_package_units);
$eloquent_model->quantity_per_package_unit = implode(",", $request->quantity_per_package_unit);
$eloquent_model->quantity = $quantity;
$eloquent_model->expected_date = $expected_date;
$eloquent_model->supplier_id = $supplier_id_array[$y];
$eloquent_model->created_by = Auth::id();
$eloquent_model->save();
}
flash('Saved Temporary Quotation Successfully')->success();
return redirect('select_temporary_quotation_type');
}
}
public function select_temporary_quotation()
{
$quotation_type_options = DB::table('quotation_types')->pluck('name', 'id')->toArray();
$quotation_type_options = ['' => '- Select Quotation type -'] + $quotation_type_options;
return view('stores::stores.select_temporary_quotation', compact('quotation_type_options'));
}
/* view all temporary quotations of a selected type */
public function temporary_quotations(Request $request)
{
$quotation_type = $request->quotation_type;
//1-drug 2-sundry 3-dental 4-radiology 5-Lab
$results = TemporaryQuotation::where(['quotation_type_id' => $quotation_type, 'completion_status' => 0])->orderBy('id', 'desc')->get();
return view('stores::stores.view_temporary_quotations', compact('results', 'quotation_type'));
}
/* edit temporary quotations */
public function edit_temporary_quotations(Request $request)
{
$quotation_type = $request->item_type;
$quotation_id = $request->quotation_id;
$suppliers = DB::table('suppliers')->where('available', 1)->whereNull('deleted_at')->orderBy('name')->pluck('name', 'id')->toArray();
$suppliers = ['' => '- select -'] + $suppliers;
$quotation_results = TemporaryQuotation::where(['id' => $quotation_id, 'completion_status' => 0])->orderBy('id', 'desc')->get();
$package_units = DB::table('package_units')->whereNull('deleted_at')->orderBy('name')->pluck('name', 'id')->toArray();
$package_units = ['' => '- select -'] + $package_units;
$added_items_collection = null;
$items = [];
//1-drug 2-sundry 3-dental 4-radiology 5-Lab
if ($quotation_type == 1) {
$items = Drug::whereNull('deleted_at')->orderBy('name', 'asc')->get();
} elseif ($quotation_type == 2) {
$items = Sundry::whereNull('deleted_at')->orderBy('name', 'asc')->get();
} elseif ($quotation_type == 3) {
$items = Dental::whereNull('deleted_at')->orderBy('name', 'asc')->get();
} elseif ($quotation_type == 4) {
$items = Radiology::whereNull('deleted_at')->orderBy('name', 'asc')->get();
} elseif ($quotation_type == 5) {
$items = Lab::whereNull('deleted_at')->orderBy('name', 'asc')->get();
} elseif ($quotation_type == 6) {
$items = GeneralItem::whereNull('deleted_at')->orderBy('name', 'asc')->get();
} elseif ($quotation_type == 6) {
$items = EyeGlasses::whereNull('deleted_at')->orderBy('name', 'asc')->get();
}
$drugs = Drug::where('available', 1)->orderby('name')->pluck('name', 'id')->prepend('All drugs', 'all_items');
$sundries = Sundry::where('available', 1)->orderby('name')->pluck('name', 'id')->prepend('All sundries', 'all_items');
$dentals = Dental::orderBy('name')->pluck('name', 'id')->prepend('All dentals', 'all_items');
$radiologies = Radiology::orderBy('name')->pluck('name', 'id')->prepend('All radiologies', 'all_items');
$labs = Lab::orderBy('name')->pluck('name', 'id')->prepend('All labs', 'all_items');
$general_items = GeneralItem::orderBy('name')->pluck('name', 'id')->prepend('All general items', 'all_items');
$opticals = EyeGlasses::orderBy('name')->pluck('name', 'id')->prepend('All optical items', 'all_items');
return view('stores::stores.edit_temporary_quotation', compact('items', 'quotation_type', 'suppliers', 'quotation_id', 'quotation_results', 'package_units', 'added_items_collection', 'drugs',
'sundries', 'dentals', 'radiologies', 'labs', 'general_items', 'opticals'));
}
/* store the requested quotation*/
public function store_request_quotation(Request $request)
{
$validator = Validator::make($request->all(), [
'expected_date' => 'required',
'supplier' => 'required'
]);
if ($validator->fails()) {
$string = "";
foreach ($validator->errors()->getMessages() as $item) {
$string .= "{$item[0]}<br>";
}
flash('Please make sure you fill in the supplier and expected date')->error();
return redirect('select_quotation_type');
} else {
$item_id_array = $request->item_id;
$quantity_array = $request->quantity;
$package_unit_array = $request->package_unit;
$number_of_package_units_array = $request->number_of_package_units;
$quantity_per_package_unit_array = $request->quantity_per_package_unit;
$expected_date = strpos($request->expected_date, '-') !== false ? $request->expected_date : Carbon::createFromFormat('d/m/Y', $request->expected_date)->toDateString();
$memo = $request->memo;
$user_id = Auth::id();
$item_type = $request->item_type;
$quotation_date = Carbon::now();
if (array_sum($quantity_array) < 1) {
flash('Please insert in some values')->error();
return redirect('select_quotation_type');
}
$supplier_id_array = $request->supplier;
if (!is_array($supplier_id_array)) {
$supplier_id_array = [$supplier_id_array];
}
$count = count($item_id_array);
$form_data = array();
for($y = 0; $y < count($supplier_id_array); $y++) {
$supplier_id = $supplier_id_array[$y];
$results = DB::select("select max(quotation_number) quotation_number from quotations limit 1");
$current_quotation_number = 0;
foreach ($results as $result) {
$current_quotation_number = $result->quotation_number + 1;
}
//$non_zero_count = count(array_filter($quantity_array, "nonzero")); generating an error for but to be reviewed
$non_zero_count = count($quantity_array);
$expected_last_quotation_number = $current_quotation_number + $non_zero_count;
for ($x = 0; $x < $count; $x++) :
if (empty($quantity_array[$x])) :
continue;
endif;
if (empty($item_id_array[$x])) :
continue;
endif;
$eloquent_model = new Quotation;
$eloquent_model->quotation_type_id = $item_type;
$eloquent_model->drug_id = $item_id_array[$x];
$eloquent_model->package_unit = $package_unit_array[$x];
$eloquent_model->number_of_package_units = $number_of_package_units_array[$x];
$eloquent_model->quantity_per_package_unit = $quantity_per_package_unit_array[$x];
$eloquent_model->quantity = $quantity_array[$x];
$eloquent_model->expected_date = $expected_date;
$eloquent_model->quotation_user = $user_id;
$eloquent_model->quotation_number = $current_quotation_number;
$eloquent_model->quotation_date = $quotation_date;
$eloquent_model->supplier_id = $supplier_id;
$eloquent_model->created_by = Auth::id();
$eloquent_model->save();
endfor;
$last_quotation_id = $eloquent_model->id;
$new_quotation_number = get_name($last_quotation_id, "id", "quotation_number", "quotations");
if (isset($request->submit_quotation_for_drugs) && ($new_quotation_number == $expected_last_quotation_number)) {
$temporary_quotation_id = $request->quotation_id_temporary;
$eloquent_model_to_update = TemporaryQuotation::find($temporary_quotation_id);
$eloquent_model_to_update->completion_status = 1;
$eloquent_model_to_update->updated_by = Auth::id();
$eloquent_model_to_update->updated_at = Carbon::now();
$eloquent_model_to_update->update();
}
}
flash('Request for quotation was successful')->success();
return redirect('items_purchase_order?item_type=' . $item_type . '&quotation_number=' . $current_quotation_number);
}
}
public function items_purchase_order()
{
$quotation_number = $_GET['quotation_number'];
$item_type = $_GET['item_type'];
$hospital_details = HospitalInformation::first();
$table_quotations = "quotations";
$quotation_results = DB::select("select * from $table_quotations where quotation_number = {$quotation_number}");
return view('stores::stores.items_purchase_order', compact('quotation_number', 'item_type', 'hospital_details', 'quotation_results', 'table_quotations'));
}
public function quotation_to_bill(Request $request)
{
$quotation_type_options = DB::table('quotation_types')->pluck('name', 'id')->toArray();
$quotation_type_options = ['' => '- Select Quotation type -'] + $quotation_type_options;
$results = 0;
$table_quotations = "";
$item_type = "";
if (isset($request->quotation_type)) {
$item_type = $request->quotation_type;
$table_quotations = "quotations";
$results = DB::select("select DISTINCT(quotation_number) from quotations where quotation_type_id= $item_type AND receive_status = 0 AND approval_status = 0 AND deleted_at IS NULL ORDER BY quotation_number desc");
$result_message = "There are no pending quotations for " . strtolower($item_type);
}
$package_units = DB::table('package_units')->whereNull('deleted_at')->orderBy('name')->pluck('name', 'id')->toArray();
$package_units = ['' => '- select -'] + $package_units;
$quotation_types_array = DB::table('quotation_types')->pluck('name', 'id')->toArray();
return view('stores::stores.quotation_to_bill', compact('quotation_type_options', 'item_type', 'results', 'table_quotations', 'quotation_types_array', 'package_units'));
}
public function bill_items(Request $request)
{
if (isset($request->add_bill_button)) {
$table_quotations = "quotations";
$package_units = DB::table('package_units')->whereNull('deleted_at')->orderBy('name')->pluck('name', 'id')->toArray();
$package_units = ['' => '- select -'] + $package_units;
$quotation_number = $request->quotation_number;
$item_type = $request->item_type;
$supplier_id = get_name($quotation_number, 'quotation_number', 'supplier_id', 'quotations');
$quotation_types_array = DB::table('quotation_types')->pluck('name', 'id')->toArray();
$results = DB::select("SELECT * FROM quotations where quotation_number = {$quotation_number}");
return view('stores::stores.bill_items', compact('quotation_number', 'item_type', 'results', 'table_quotations', 'supplier_id', 'quotation_types_array', 'package_units'));
} elseif (isset($request->delete_quotation)) {
$quotation_number = $request->quotation_number;
$eloquent_model = Quotation::where(['quotation_number' => $quotation_number])->delete();
if ($eloquent_model) {
flash('Quotation has been deleted')->success();
} else {
flash('Unable to delete quotation. Please try again')->error();
}
return redirect('quotation_to_bill');
} else {
return redirect('quotation_to_bill');
}
}
/* store billed drugs */
public function store_drug_bill(Request $request)
{
$hospital_details = HospitalInformation::first();
$quotation_id = $request->quotation_id;
$quantity_required = $request->quantity_required;
$bill = $request->bill;
$package_unit_array = $request->package_unit;
$number_of_package_units_array = $request->number_of_package_units;
$quantity_per_package_unit_array = $request->quantity_per_package_unit;
$quantity_per_package_unit_array = $request->quantity_per_package_unit;
$bill_per_package_unit_array = $request->bill_per_package_unit;
$billing_date = Carbon::now();
$billing_user = Auth::id();
$form_data = array();
$full_quotation_id_array = array();
$item_type = $request->item_type;
$supplier_reference = $request->supplier_reference;
$quotation_number_full = get_name($quotation_id[0], 'id', 'quotation_number', 'quotations');
$full_quotation_id_results = DB::select("SELECT id FROM quotations where quotation_number = {$quotation_number_full}");
foreach ($full_quotation_id_results as $result) {
array_push($full_quotation_id_array, $result->id);
}
$deletion_quotation_id_array = array_diff($full_quotation_id_array, $quotation_id);
$count = count($quotation_id);
for ($x = 0; $x < $count; $x++) :
//$total_price = ($quantity_required[$x] * $bill[$x]);
$total_price = ($number_of_package_units_array[$x] * $bill_per_package_unit_array[$x]);
$eloquent_model = Quotation::find($quotation_id[$x]);
$eloquent_model->quotation_type_id = $item_type;
$eloquent_model->bill = $bill[$x];
$eloquent_model->package_unit = $package_unit_array[$x];
$eloquent_model->number_of_package_units = $number_of_package_units_array[$x];
$eloquent_model->quantity_per_package_unit = $quantity_per_package_unit_array[$x];
$eloquent_model->bill_per_package_unit = $bill_per_package_unit_array[$x];
$eloquent_model->billing_date = $billing_date;
$eloquent_model->billing_user = $billing_user;
$eloquent_model->total_price = $total_price;
$eloquent_model->quantity = $quantity_required[$x];
$eloquent_model->supplier_reference = $supplier_reference;
$eloquent_model->updated_by = $billing_user;
$eloquent_model->updated_at = Carbon::now();
$update_bill = $eloquent_model->update();
endfor;
if ($update_bill) {
foreach ($deletion_quotation_id_array as $value) {
DB::table('quotations')->where('id', '=', $value)->delete();
}
}
// Acquiring the quotation number for use in the session
$quotation_number = get_name($quotation_id[0], "id", "quotation_number", "quotations");
// Setting the session to be used on the print
session()->put(['quotation_number' => $quotation_number]);
$table_quotations = 'quotations';
$quotations_results = DB::select("SELECT * FROM quotations where quotation_number = {$quotation_number}");
$billing_stage = 1;
return view('stores::stores.print_drug_bill', compact('quotation_number', 'item_type', 'quotations_results', 'hospital_details', 'table_quotations', 'supplier_reference', 'billing_stage'));
}
/* select a quotation to approve */
public function select_quotation_to_approve(Request $request)
{
$quotation_type_options = DB::table('quotation_types')->pluck('name', 'id')->toArray();
$quotation_type_options = ['' => '- Select Quotation type -'] + $quotation_type_options;
$results = 0;
$table_quotations = "";
$item_type = "";
if (isset($request->quotation_type)) {
$item_type = $request->quotation_type;
$table_quotations = "quotations";
$results = DB::select("select DISTINCT(quotation_number),supplier_id from $table_quotations where receive_status = 0 AND deleted_at IS NULL AND approval_status = 0 AND quotation_type_id = " . $item_type . " ORDER BY quotation_number desc");
$result_message = "There are no pending quotations for " . strtolower($item_type);
foreach($results as &$result){
$result->supplier_name = Supplier::find($result->supplier_id)->name??'';
$total_bill=0;
$get_bill = Quotation::where('quotation_number',$result->quotation_number)->get();
foreach($get_bill as $bill){
$total_bill += $bill->total_price;
}
$result->total_bill = $total_bill;
}
}
return view('stores::stores.select_quotation_to_approve', compact('quotation_type_options', 'item_type', 'results', 'table_quotations'));
}
/* approve or delete a quotation */
public function approve_or_delete_quotation(Request $request)
{
$package_units = DB::table('package_units')->whereNull('deleted_at')->orderBy('name')->pluck('name', 'id')->toArray();
$package_units = ['' => '- select -'] + $package_units;
if (isset($request->approve_purchase)) {
$quotation_number = $request->quotation_number;
$item_type = $request->item_type;
$table_quotations = "quotations";
$supplier_id = get_name($quotation_number, "quotation_number", "supplier_id", "quotations");
$supplier_reference = get_name($quotation_number, "quotation_number", "supplier_reference", "quotations");
$quotation_results = DB::select("SELECT * FROM $table_quotations where quotation_number={$quotation_number} AND deleted_at IS NULL");
return view('stores::stores.approve_purchase', compact('quotation_number', 'item_type', 'quotation_results', 'table_quotations', 'supplier_id', 'package_units', 'supplier_reference'));
} elseif (isset($request->delete_purchase)) {
$quotation_number = $request->quotation_number;
$eloquent_model = Quotation::where(['quotation_number' => $quotation_number])->delete();
if ($eloquent_model) {
flash('Quotation has been deleted')->success();
} else {
flash('Unable to delete quotation. Please try again')->error();
}
return redirect('select_quotation_to_approve');
} else {
return redirect('select_quotation_to_approve');
}
}
public function store_approved_purchase(Request $request)
{
$hospital_details = HospitalInformation::first();
$quotation_id = $request->quotation_id;
$quantity_required = $request->quantity_required;
$bill = $request->bill;
$package_unit_array = $request->package_unit;
$number_of_package_units_array = $request->number_of_package_units;
$quantity_per_package_unit_array = $request->quantity_per_package_unit;
$bill_per_package_unit_array = $request->bill_per_package_unit;
$approval_status = 1;
$approval_date = Carbon::now();
$approval_user = Auth::id();
$item_type = $request->item_type;
$count = count($quotation_id);
$form_data = array();
$table_quotations = "quotations";
for ($x = 0; $x < $count; $x++) :
if (empty($quantity_required[$x])) {
continue;
}
if (empty($bill[$x])) {
continue;
}
// calculating the total price
//$total_price = ($quantity_required[$x] * $bill[$x]);
$total_price = ($number_of_package_units_array[$x] * $bill_per_package_unit_array[$x]);
$eloquent_model = Quotation::find($quotation_id[$x]);
$eloquent_model->bill = $bill[$x];
$eloquent_model->package_unit = $package_unit_array[$x];
$eloquent_model->number_of_package_units = $number_of_package_units_array[$x];
$eloquent_model->quantity_per_package_unit = $quantity_per_package_unit_array[$x];
$eloquent_model->bill_per_package_unit = $bill_per_package_unit_array[$x];
$eloquent_model->approval_status = $approval_status;
$eloquent_model->approval_user = $approval_user;
$eloquent_model->approval_date = $approval_date;
$eloquent_model->quantity = $quantity_required[$x];
$eloquent_model->total_price = $total_price;
$eloquent_model->updated_at = Carbon::now();
$eloquent_model->update();
endfor;
// Aquiring the quotation number for use in the session
$quotation_number = get_name($quotation_id[0], "id", "quotation_number", $table_quotations);
$supplier_reference = get_name($quotation_number, "quotation_number", "supplier_reference", "quotations");
// Unsetting the session first. Just in case
session()->put(['quotation_number' => $quotation_number]);
$quotations_results = DB::select("SELECT * FROM $table_quotations where quotation_number = {$quotation_number}");
return view('stores::stores.print_drug_bill', compact('quotation_number', 'item_type', 'quotations_results', 'hospital_details', 'table_quotations', 'supplier_reference'));
}
/* function to receive items */
public function receive_items(Request $request) {
$quotation_type_options = DB::table('quotation_types')->pluck('name', 'id')->toArray();
$quotation_type_options = ['' => '- Select Quotation type -'] + $quotation_type_options;
$results = [];
$table_quotations = "";
$item_type = "";
if (isset($request->quotation_type)) {
$filters = [];
if ($request->search_by == 0) {
// last 24 hours
$last_day = Carbon::now()->subDay();
array_push($filters, ['created_at', '>', $last_day]);
} elseif ($request->search_by == 1) {
// custom date
$start_date = Carbon::parse($request->reg_date)->startOfDay()->toDateTimeString();
$end_date = Carbon::parse($request->reg_date)->endOfDay()->toDateTimeString();
array_push($filters, ['created_at', '>', $start_date]);
array_push($filters, ['created_at', '<', $end_date]);
} elseif ($request->search_by == 2) {
// custom date range
$start_date = Carbon::parse($request->start_date)->startOfDay()->toDateTimeString();
$end_date = Carbon::parse($request->end_date)->endOfDay()->toDateTimeString();
array_push($filters, ['created_at', '>', $start_date]);
array_push($filters, ['created_at', '<', $end_date]);
}
$item_type = $request->quotation_type;
$table_quotations = "quotations";
$results = DB::table($table_quotations)
->select(DB::raw('DISTINCT(quotation_number)'))
->where('receive_status', '=', 0)
->where('approval_status', '=', 1)
->whereNotNull('approval_user')
->whereNotNull('bill')
->whereNull('deleted_at')
->where('quotation_type_id', $item_type)
->where($filters)
->orderBy('quotation_number', 'desc')
->get();
$result_message = "There are no pending " . strtolower($item_type) . " purchase orders to clear";
}
return view('stores::stores.receive_items', compact('quotation_type_options', 'item_type', 'results', 'table_quotations'));
}
/* comfirm receipt of items */
public function confirm_item_receipt(Request $request)
{
$package_units = DB::table('package_units')->whereNull('deleted_at')->orderBy('name')->pluck('name', 'id')->toArray();
$package_units = ['' => '- select -'] + $package_units;
$quotation_number = $request->quotation_number;
if (isset($request->add_bill_button)) {
$item_type = $request->item_type;
$total_price = $request->total_price;
/* the query below is for only quotation_types of drugs only*/
$results = DB::select("select * from quotations quotation where quotation_number = {$quotation_number} AND receive_status = 0 AND approval_status = 1");
return view('stores::stores.confirm_items_receipt', compact('quotation_number', 'item_type', 'total_price', 'results', 'package_units'));
} elseif (isset($request->delete_bill_button)) {
$eloquent_model = Quotation::where(['quotation_number' => $quotation_number])->delete();
if ($eloquent_model) {
flash('Quotation has been deleted')->success();
} else {
flash('Unable to delete quotation. Please try again')->error();
}
return redirect('receive_items');
} else {
return redirect('receive_items');
}
}
/* function to store received items */
public function store_received_items(Request $request)
{
$validator = Validator::make($request->all(), [
'received_on_date' => 'required'
]);
if ($validator->fails()) {
$string = "";
foreach ($validator->errors()->getMessages() as $item) {
$string .= "{$item[0]}<br>";
}
flash('please ensure you have filled in the received date and batch number')->error();
return redirect('select_receive_items_option');
} else {
/* =============== */
//check if the items have required values to complete double entry before proceeding
if ($request->item_type == 3 || $request->item_type == 4 || $request->item_type == 5) {
for ($i=0; $i < count($request->item_id) ; $i++) {
if (($request->item_type == 3) && get_name($request->item_id[$i], "id", "expenses_account_id", "dentals") == null) {
flash("Please make sure that all dentals have expense accounts e.g ".get_name($request->item_id[$i], "id", "name", "dentals"))->error();
return redirect('select_receive_items_option');
}
if (($request->item_type == 4) && get_name($request->item_id[$i], "id", "expenses_account_id", "radiologies") == null) {
flash("Please make sure that all radiologies have expense accounts e.g ".get_name($request->item_id[$i], "id", "name", "radiologies"))->error();
return redirect('select_receive_items_option');
}
if (($request->item_type == 5) && get_name($request->item_id[$i], "id", "expenses_account_id", "labs") == null) {
flash("Please make sure that all labs have expense accounts e.g ".get_name($request->item_id[$i], "id", "name", "labs"))->error();
return redirect('select_receive_items_option');
}
if (($request->item_type == 6) && get_name($request->item_id[$i], "id", "expenses_account_id", "general_items") == null) {
flash("Please make sure that all general items have expense accounts e.g ".get_name($request->item_id[$i], "id", "name", "general_items"))->error();
return redirect('select_receive_items_option');
}
}
}
/* =============== */
$quotation_id_array = $request->quotation_id;
$package_unit_array = $request->package_unit;
$number_of_package_units_array = $request->number_of_package_units;
$quantity_per_package_unit_array = $request->quantity_per_package_unit;
$bill_per_package_unit_array = $request->bill_per_package_unit;
$quantity_array = $request->quantity;
$bill_array = $request->bill;
$receive_user = Auth::id();
$receive_date = Carbon::createFromFormat('d/m/Y', $request->received_on_date)->toDateString();
$expiry_date = $request->expiry_date;
$batch_numbers_array = $request->batch_number;
$item_type = $request->item_type;
$total_price = 0;
$table_quotations = "quotations";
$item_id_array = $request->item_id;
$already_updated_quotations = [];
//get next grn_number
$new_grn_number = Quotation::where('quotation_number', $request->quotation_number)->max('grn_number');
if (is_null($new_grn_number)) {
$new_grn_number = (float)$request->quotation_number +0.1;
} else {
$new_grn_number = (float)$new_grn_number + 0.1;
}
for ($x = 0; $x < count($quotation_id_array); $x++) {
//Expiry date of the drugs
$expiry_date_for_each = isset($expiry_date[$x]) ? Carbon::createFromFormat('d/m/Y', $expiry_date[$x])->toDateString() : "";
// Updating the total price incase it has changed
//$total_price = $bill_array[$x] * $quantity_array[$x];
$total_price = $bill_per_package_unit_array[$x] * $number_of_package_units_array[$x];
//check if the quotation has already been updated and this is a new batch of same quotation of same drug
$new_batch_quotation = false;
$extra_batch_of_same_drug = in_array($quotation_id_array[$x], $already_updated_quotations);
if (in_array($quotation_id_array[$x], $already_updated_quotations)) {
$eloquent_model = new Quotation;
$new_batch_quotation = true;
} else {
$eloquent_model = Quotation::find($quotation_id_array[$x]);
}
$quotation_type_id = $request->item_type;
$eloquent_model->quotation_type_id = $request->item_type;
$eloquent_model->drug_id = $item_id_array[$x];
$eloquent_model->receive_bill = $bill_array[$x];
$eloquent_model->package_unit = $package_unit_array[$x];
$eloquent_model->receive_number_of_package_units = $number_of_package_units_array[$x];
$eloquent_model->receive_quantity_per_package_unit = $quantity_per_package_unit_array[$x];
if ($new_batch_quotation) {
$eloquent_model->receive_bill_per_package_unit = $bill_array[$x] * $quantity_per_package_unit_array[$x];
}else{
$eloquent_model->receive_bill_per_package_unit = $bill_per_package_unit_array[$x];
}
$eloquent_model->receive_quantity = $quantity_array[$x];
$eloquent_model->receive_user = $receive_user;
$eloquent_model->receive_date = $receive_date;
$eloquent_model->receive_status = 1;
$eloquent_model->receiver_comment = $request->receiver_comment;
$eloquent_model->total_price = $total_price;
$eloquent_model->expiry_date = $expiry_date_for_each;
$eloquent_model->batch_number = $batch_numbers_array[$x];
$eloquent_model->batch_balance = $quantity_array[$x];
$eloquent_model->grn_number=$new_grn_number;
$eloquent_model->quotation_number = $request->quotation_number;
$eloquent_model->updated_at = Carbon::now();
$eloquent_model->updated_by = Auth::id();
$eloquent_model->save();
//keep a record of quotation_ids that have been updated. This is to help in quotation that have extra batches
$already_updated_quotations[] = $quotation_id_array[$x];
// Increasing the stock level in necessary inventory tables i.e //1-drug,2-sundry,3-dental,4-radiology 5-Lab
//check for the quotation_type_id then know what table to use in getting $old_quantity
$store_item = null;
$drug_id = get_name($quotation_id_array[$x], "id", "drug_id", "quotations");
$quantity_to_add = $quantity_array[$x];
if ($quotation_type_id == 1) {
$old_quantity = get_name($drug_id, "id", "store_stock", "drugs");
if ($old_quantity == "N/A") {
$old_quantity = 0;
};
$new_quantity = $old_quantity + (int)$quantity_to_add;
$store_item = Drug::find($drug_id);
if (!is_null($store_item)) {
$store_item->store_stock = $new_quantity;
$store_item->expiry_date = $expiry_date_for_each;
save_new_cost_of_good($drug_id, $quotation_type_id, $bill_array[$x]);
}
} elseif ($quotation_type_id == 2) {
$old_quantity = get_name($drug_id, "id", "store_stock", "sundries");
$new_quantity = $old_quantity + (int)$quantity_to_add;
$store_item = Sundry::find($drug_id);
if (!is_null($store_item)) {
$store_item->store_stock = $new_quantity;
$store_item->expiry_date = $expiry_date_for_each;
save_new_cost_of_good($drug_id, $quotation_type_id, $bill_array[$x]);
}
} elseif ($quotation_type_id == 3) {
$old_quantity = get_name($drug_id, "id", "store_stock", "dentals");
$new_quantity = $old_quantity + (int)$quantity_to_add;
$store_item = Dental::find($drug_id);
if (!is_null($store_item)) {
$store_item->store_stock = $new_quantity;
$store_item->expiry_date = $expiry_date_for_each;
save_new_cost_of_good($drug_id, $quotation_type_id, $bill_array[$x]);
}
} elseif ($quotation_type_id == 4) {
$old_quantity = get_name($drug_id, "id", "store_stock", "radiologies");
$new_quantity = $old_quantity + (int)$quantity_to_add;
$store_item = Radiology::find($drug_id);
if (!is_null($store_item)) {
$store_item->store_stock = $new_quantity;
$store_item->expiry_date = $expiry_date_for_each;
save_new_cost_of_good($drug_id, $quotation_type_id, $bill_array[$x]);
}
} elseif ($quotation_type_id == 5) {
$old_quantity = get_name($drug_id, "id", "store_stock", "labs");
$new_quantity = $old_quantity + (int)$quantity_to_add;
$store_item = Lab::find($drug_id);
if (!is_null($store_item)) {
$store_item->store_stock = $new_quantity;
$store_item->expiry_date = $expiry_date_for_each;
save_new_cost_of_good($drug_id, $quotation_type_id, $bill_array[$x]);
}
} elseif ($quotation_type_id == 6) {
$old_quantity = get_name($drug_id, "id", "store_stock", "general_items");
$new_quantity = $old_quantity + (int)$quantity_to_add;
$store_item = GeneralItem::find($drug_id);
if (!is_null($store_item)) {
$store_item->store_stock = $new_quantity;
$store_item->expiry_date = $expiry_date_for_each;
save_new_cost_of_good($drug_id, $quotation_type_id, $bill_array[$x]);
}
} elseif ($quotation_type_id == 7) {
$old_quantity = get_name($drug_id, "id", "store_stock", "eye_glasses");
$new_quantity = $old_quantity + (int)$quantity_to_add;
$store_item = EyeGlasses::find($drug_id);
if (!is_null($store_item)) {
$store_item->store_stock = $new_quantity;
$store_item->expiry_date = $expiry_date_for_each;
save_new_cost_of_good($drug_id, $quotation_type_id, $bill_array[$x]);
}
}
if (!is_null($store_item)) {
$store_item->updated_at = Carbon::now();
$store_item->updated_by = Auth::id();
$store_item->update();
create_batch_watcher_record($drug_id, $quotation_type_id, $bill_array[$x],$batch_numbers_array[$x], $quantity_array[$x], $pharmacy_stock = 0,$lab_stock=0, $expiry_date_for_each);
}
if ($old_quantity <= 0 && $new_quantity > 0) {
$query_stock_dates_results = DB::select("SELECT id FROM inventory_stock_dates WHERE item_id = $drug_id AND quotation_type_id = $item_type ORDER BY id DESC LIMIT 1");
$stock_id = isset($query_stock_dates_results[0]) ? $query_stock_dates_results[0]->id : 0;
if (count($query_stock_dates_results) != 0) {
$inventory_stock_date_model = InventoryStockDate::find($stock_id);
$inventory_stock_date_model->restock_date = $receive_date;
$inventory_stock_date_model->update();
}
}
$last_quotation_id = $eloquent_model->id;
$new_quotation_number = $request->quotation_number;
}
flash('Stock Levels Updated')->success();
//immediately create inventory bill for the received items to enforce double entry
$this->auto_create_inventory_bill_or_expense($request, $new_quotation_number);
return redirect('goods_received_note/' . $new_grn_number);
}
}
/* function to get the stock sheet */
public function stock_sheet()
{
$drugs = DB::table('drugs')->where('available', 1)->whereNull('deleted_at')->orderBy('name', 'asc')->get();
if (count($drugs) < 1) {
flash()->error("There is no out of stock drugs");
return redirect('/drugs/');
} else {
return view('stores::stores.stock_sheet', compact('drugs'));
}
}
/* function to update the stock_sheet */
public function update_stock_sheet(Request $request)
{
$drugs_ids = $request->drug_id;
$quantity = $request->quantity;
$cost_price = $request->cost_price;
$insured_price = $request->insured_price;
$non_insured_price = $request->non_insured_price;
$expired_dates = $request->expiry_date;
$batch_quotation_ids_array = $request->batch_quotation_id;
$batch_drug_ids_array = $request->batch_drug_id;
$batch_numbers_array = $request->batch_number;
$batch_expiry_dates_array = $request->expiry_date;
for ($x = 0; $x < count($drugs_ids); $x++) :
$drugs = Drug::find($drugs_ids[$x]);
$drugs->store_stock = $quantity[$x];
$drugs->cost_price = $cost_price[$x];
$drugs->insured_price = $insured_price[$x];
$drugs->non_insured_price = $non_insured_price[$x];
$drugs->expiry_date = $expired_dates[$x];
$update_store_stock = $drugs->update();
endfor;
/*==== do this to cater for the newer introduced editing batch number ======*/
if (is_array($batch_drug_ids_array)) {
for ($i = 0; $i < count($batch_drug_ids_array); $i++) :
if (!is_null($batch_drug_ids_array[$i]) && $batch_drug_ids_array[$i] != "") {
$quotation_record = Quotation::where(['drug_id' => $batch_drug_ids_array[$i], 'batch_number' => $batch_numbers_array[$i]])->first();
if (!is_null($quotation_record)) {
$quotation_record->expiry_date = $batch_expiry_dates_array[$i];
$quotation_record->update();
}
//update the expiry date on drugs table of the batch in use
$drug = Drug::withTrashed()->find($batch_drug_ids_array[$i]);
if (($drug->batch_number_in_use == $batch_numbers_array[$i]) && ($drug->quotation_id_of_batch_in_use == $batch_quotation_ids_array[$i])) {
$drugs->expiry_date = $batch_expiry_dates_array[$i];
}
}
endfor;
}
/*=========== end the catering for the newer introduced batch number ===========*/
if ($update_store_stock) :
flash('Store Stock Levels Updated')->success();
return redirect('stores_stock_sheet');
endif;
flash('Sorry, unable to update stock')->error();
return redirect()->back();
}
/* issue drugs */
public function issue_store_items() {
$quotation_results = DB::table('requisitions')->whereNull('issue_status')
->whereNull('deleted_at')
->orderBy('id', 'desc')
->get();
return view('stores::stores.issue_drugs', compact('quotation_results'));
}
/* issue out drugs form */
public function issue_out_drugs_form(Request $request) {
$requisition_id = $request->requisition_id;
$requisition = Requisition::find($requisition_id);
$drug_id_explode_array = explode(",", $requisition->drug_id);
$quantity_explode_array = explode(",", $requisition->quantity_requested);
$quantity_approved_array = $requisition->quantity_approved ? explode(",", $requisition->quantity_approved) : [];
$associative_requested_drugs_array = [];
$associative_approved_drugs_array = [];
$unit_of_measure = DB::table('unit_of_measure')->pluck("name", "id")->toArray();
$batches_array = DB::table('item_batch_watcher')->where('store_stock', '>', 0)->get();
$quotation_id = $requisition->quotation_type_id;
$drug_forms = DB::table('drug_forms')->pluck("name", "id")->prepend('-select-', '')->toArray();
$staff_array = $this->userService->pluckUserFullName();
$staff_array = ['' => 'Select Staff'] + $staff_array;
for ($i = 0; $i < count($drug_id_explode_array); $i++) {
if (isset($quantity_explode_array[$i]) && $quantity_explode_array[$i] != "") {
$associative_requested_drugs_array[$drug_id_explode_array[$i]] = $quantity_explode_array[$i];
$associative_approved_drugs_array[$drug_id_explode_array[$i]] = $quantity_approved_array[$i]??0;
}
}
// do this if requisition type is drugs
if ($requisition->quotation_type_id == 1){$table_name ='drugs'; }
// do this if the requisition type is for sundries
if ($requisition->quotation_type_id == 2){ $table_name ='sundries';}
if ($requisition->quotation_type_id == 4) {$table_name = 'radiologies';}
// do this if the requisition type is for labs
if ($requisition->quotation_type_id == 5){$table_name = 'labs';}
if ($requisition->quotation_type_id == 3) {$table_name = 'dentals';
// do this if the requisition type is for general items
for ($i = 0; $i < count($drug_id_explode_array); $i++) {
if ($quantity_explode_array[$i] != "") {
$associative_requested_drugs_array[$drug_id_explode_array[$i]] = $quantity_explode_array[$i];
}
}
return view('stores::stores.issue_out_general_items_form', compact('requisition','table_name','associative_approved_drugs_array', 'requisition_id', 'associative_requested_drugs_array', 'unit_of_measure', 'batches_array'));
}
if ($requisition->quotation_type_id == 6) {
$table_name = 'general_items';
// do this if the requisition type is for general items
for ($i = 0; $i < count($drug_id_explode_array); $i++) {
if ($quantity_explode_array[$i] != "") {
$associative_requested_drugs_array[$drug_id_explode_array[$i]] = $quantity_explode_array[$i];
}
}
return view('stores::stores.issue_out_general_items_form', compact('requisition','table_name','associative_approved_drugs_array', 'requisition_id', 'associative_requested_drugs_array', 'unit_of_measure', 'batches_array'));
}
if ($requisition->quotation_type_id == 7) {
$table_name='eye_glasses';
}
return view('stores::stores.issue_out_drugs_form', compact('requisition','staff_array','quotation_id', 'requisition_id', 'associative_requested_drugs_array', 'unit_of_measure', 'drug_forms', 'batches_array', 'associative_approved_drugs_array','table_name'));
}
/* issue out drugs e.g to the pharmacy */
public function issue_out_drugs(Request $request)
{
$requisition_id = $request->requisition_id;
$quantity_issued_array = $request->quantity_issued;
$drug_id_array = $request->drug_id;
$batch_number_id_array=$request->issued_batch_number;
$units_array = $request->units;
$cost_value_array = $request->cost_value;
$issued_cost_value = [];
//loop thru to formulate the issued_cost_value of issued items
// for ($y=0; $y < count($request->issued_batch_number) ; $y++) {
// # code...
// }
$associative_requested_drugs_array = [];
$associative_requested_batches_array = [];
$issued_by = Auth::id();
$issued_on = isset($request->issue_date) ? Carbon::createFromFormat('d/m/Y', $request->issue_date)->toDateString() : "";
$quantity_issued = "";
$inventory_data = "";
$update_inventory_items = "";
$units = "";
$item_batch_calculations = false;
$issue_out_comment = isset($request->issue_out_comment) ? $request->issue_out_comment : "";
$received_by = isset($request->received_by) ? $request->received_by : "";
$requisition = Requisition::find($requisition_id);
$requisition_type = $requisition->quotation_type_id; //might be 1=drugs, 2=sundries, labs etc
if ($requisition_type == 2) {
//do this for sundries
for ($i = 0; $i < count($drug_id_array); $i++) {
if ($quantity_issued_array[$i] != "") {
$drug_name = get_name($drug_id_array[$i], "id", "name", "sundries");
/* check just in case the same drug appears for the same patient twice then ++ quantity */
if (array_key_exists($drug_name, $associative_requested_drugs_array)) {
$previous_qty = $associative_requested_drugs_array[$drug_name];
$associative_requested_drugs_array[$drug_name] = $previous_qty + $quantity_issued_array[$i];
} else{
$associative_requested_drugs_array[$drug_name] = $quantity_issued_array[$i];
}
$associative_requested_batches_array[$drug_name]=$batch_number_id_array[$i];
}
}
for ($x = 0; $x < count($drug_id_array); $x++) :
//do this for sundries batches
$batch_number_id = $request->issued_batch_number[$x];
//Decreasing the store stock
$current_store_stock = get_name($drug_id_array[$x], 'id', 'store_stock', 'sundries');
$current_store_stock = is_numeric($current_store_stock) ? $current_store_stock : 0;
$new_store_stock = $current_store_stock - $quantity_issued_array[$x];
// Increasing the Pharmacy stock or the Lab stock
$drug = Sundry::withTrashed()->find($drug_id_array[$x]);
// Data to update the drugs table
if ($drug) {
if ($requisition->requisition_origin == 2) {
//if origin is from lab
$current_lab_stock = get_name($drug_id_array[$x], 'id', 'lab_stock', 'sundries');
$current_lab_stock = is_numeric($current_lab_stock) ? $current_lab_stock : 0;
$new_lab_stock = $current_lab_stock + $quantity_issued_array[$x];
$drug->lab_stock = $new_lab_stock;
$this->itemsStockService->move_batch_item_from_store_to_other_sections($item_type = 2, $drug_id_array[$x], $batch_number_id, $quantity_issued_array[$x], $requisition_id,'sundries','labs',['id','batch_number','store_stock','lab_stock'],'lab_stock');
}
else if($requisition->requisition_origin == 3){
//if origin is from Imaging
$this->itemsStockService->move_batch_item_from_store_to_other_sections($item_type = 2, $drug_id_array[$x], $batch_number_id, $quantity_issued_array[$x], $requisition_id,'sundries','Imaging',['id','batch_number','store_stock','radiology_stock'],'radiology_stock');
}
else {
$current_pharmacy_stock = get_name($drug_id_array[$x], 'id', 'pharmacy_stock', 'sundries');
$current_pharmacy_stock = is_numeric($current_pharmacy_stock) ? $current_pharmacy_stock : 0;
$new_pharmacy_stock = $current_pharmacy_stock + $quantity_issued_array[$x];
$drug->pharmacy_stock = $new_pharmacy_stock;
//move sundry items from store to pharmacy stock
$this->itemsStockService->move_batch_item_from_store_to_other_sections($item_type = 2, $drug_id_array[$x], $batch_number_id, $quantity_issued_array[$x], $requisition_id,'sundries','pharmacy',['id','batch_number','store_stock','pharmacy_stock'],'pharmacy_stock');
}
$drug->store_stock = $new_store_stock;
$drug->update();
}
if ($current_store_stock > 0 && $new_store_stock <= 0) {
$inventory_stock_date = new InventoryStockDate;
$inventory_stock_date->quotation_type_id = 2; //1 = quotation type for sundries
$inventory_stock_date->item_id = $drug_id_array[$x];
$inventory_stock_date->out_of_stock_date = $issued_on;
$inventory_stock_date->save();
}
endfor;
} else if ($requisition_type == 1) {
$drug_name = "";
if (is_array($drug_id_array)) {
for ($i = 0; $i < count($drug_id_array); $i++) {
if ($quantity_issued_array[$i] != "") {
$drug_name = get_name($drug_id_array[$i], "id", "name", "drugs");
/* check just in case the same drug appears for the same patient twice then ++ quantity */
if (array_key_exists($drug_name, $associative_requested_drugs_array)) {
$previous_qty = $associative_requested_drugs_array[$drug_name];
$associative_requested_drugs_array[$drug_name] = $previous_qty + $quantity_issued_array[$i];
} else{
$associative_requested_drugs_array[$drug_name] = $quantity_issued_array[$i];
}
$associative_requested_batches_array[$drug_name]=$batch_number_id_array[$i];
}
}
for ($x = 0; $x < count($drug_id_array); $x++) :
//do this for drugs batches
//$batch_number = null;
//if (batch_tracking_method() == "manual") {
$batch_number_id = $request->issued_batch_number[$x];
//}
//$item_batch_calculations = batch_calculations_for_item_based_on_fifo($drug_id_array[$x], $quantity_issued_array[$x], $batch_number, $item_type = 1);
/* i commented the auto calculation out since the users should now add several batches issuing from */
//Decreasing the store stock
$current_store_stock = get_name($drug_id_array[$x], 'id', 'store_stock', 'drugs');
$current_store_stock = is_numeric($current_store_stock) ? $current_store_stock : 0;
$new_store_stock = $current_store_stock - $quantity_issued_array[$x];
// Increasing the Pharmacy stock
$current_pharmacy_stock = get_name($drug_id_array[$x], 'id', 'pharmacy_stock', 'drugs');
$current_pharmacy_stock = is_numeric($current_pharmacy_stock) ? $current_pharmacy_stock : 0;
$new_pharmacy_stock = $current_pharmacy_stock + $quantity_issued_array[$x];
// Data to update the drugs table
$drug = Drug::find($drug_id_array[$x]);
if ($drug) {
$drug->pharmacy_stock = $new_pharmacy_stock;
$drug->store_stock = $new_store_stock;
$drug->update();
//move drug items from store to pharmacy stock
$this->itemsStockService->move_batch_item_from_store_to_other_sections($item_type = 1, $drug_id_array[$x], $batch_number_id, $quantity_issued_array[$x], $requisition_id,'drugs','pharmacy',['id','batch_number','store_stock','pharmacy_stock'],'pharmacy_stock');
}
if ($current_store_stock > 0 && $new_store_stock <= 0) {
$inventory_stock_date = new InventoryStockDate;
$inventory_stock_date->quotation_type_id = 1; //1 = quotation type for drug
$inventory_stock_date->item_id = $drug_id_array[$x];
$inventory_stock_date->out_of_stock_date = $issued_on;
$inventory_stock_date->save();
}
endfor;
} else {
$drug_id_array = [];
$quantity_issued_array = [];
}
} else if ($requisition_type == 4) {
//do this for radiologies
for ($i = 0; $i < count($drug_id_array); $i++) {
if ($quantity_issued_array[$i] != "") {
$drug_name = get_name($drug_id_array[$i], "id", "name", "radiologies");
$associative_requested_drugs_array[$drug_name] = $quantity_issued_array[$i];
$associative_requested_batches_array[$drug_name]=$batch_number_id_array[$i];
}
}
for ($x = 0; $x < count($drug_id_array); $x++) :
$batch_number_id = $request->issued_batch_number[$x];
//Decreasing the store stock
$current_store_stock = get_name($drug_id_array[$x], 'id', 'store_stock', 'radiologies');
$current_store_stock = is_numeric($current_store_stock) ? $current_store_stock : 0;
$new_store_stock = $current_store_stock - $quantity_issued_array[$x];
// Increasing the Pharmacy stock
$current_pharmacy_stock = get_name($drug_id_array[$x], 'id', 'pharmacy_stock', 'radiologies');
$current_pharmacy_stock = is_numeric($current_pharmacy_stock) ? $current_pharmacy_stock : 0;
$new_pharmacy_stock = $current_pharmacy_stock + $quantity_issued_array[$x];
// Data to update the radiology table
$radiology = Radiology::find($drug_id_array[$x]);
if ($radiology) {
$radiology->pharmacy_stock = $new_pharmacy_stock;
$radiology->store_stock = $new_store_stock;
$radiology->update();
//move lab items from store to lab stock
$this->itemsStockService->move_batch_item_from_store_to_other_sections($item_type = 4, $drug_id_array[$x], $batch_number_id, $quantity_issued_array[$x], $requisition_id,'radiologies','Imaging',['id','batch_number','store_stock','lab_stock'],'lab_stock');
}
if ($current_store_stock > 0 && $new_store_stock <= 0) {
$inventory_stock_date = new InventoryStockDate;
$inventory_stock_date->quotation_type_id = 4; //1 = quotation type for radiologies
$inventory_stock_date->item_id = $drug_id_array[$x];
$inventory_stock_date->out_of_stock_date = $issued_on;
$inventory_stock_date->save();
}
endfor;
} else if ($requisition_type == 5) {
//do this for labs
for ($i = 0; $i < count($drug_id_array); $i++) {
if ($quantity_issued_array[$i] != "") {
$drug_name = get_name($drug_id_array[$i], "id", "name", "labs");
$associative_requested_drugs_array[$drug_name] = $quantity_issued_array[$i];
$associative_requested_batches_array[$drug_name]=$batch_number_id_array[$i];
}
}
for ($x = 0; $x < count($drug_id_array); $x++) :
$batch_number_id = $request->issued_batch_number[$x];
//Decreasing the store stock
$current_store_stock = get_name($drug_id_array[$x], 'id', 'store_stock', 'labs');
$current_store_stock = is_numeric($current_store_stock) ? $current_store_stock : 0;
$new_store_stock = $current_store_stock - $quantity_issued_array[$x];
// Increasing the Laboratory stock
$current_laboratory_stock = get_name($drug_id_array[$x], 'id', 'laboratory_stock', 'labs');
$current_laboratory_stock = is_numeric($current_laboratory_stock) ? $current_laboratory_stock : 0;
$new_laboratory_stock = $current_laboratory_stock + $quantity_issued_array[$x];
// Data to update the drugs table
$drug = Lab::find($drug_id_array[$x]);
if ($drug) {
$drug->laboratory_stock = $new_laboratory_stock;
$drug->store_stock = $new_store_stock;
$drug->update();
//move lab items from store to lab stock
$this->itemsStockService->move_batch_item_from_store_to_other_sections($item_type = 5, $drug_id_array[$x], $batch_number_id, $quantity_issued_array[$x], $requisition_id,'labs','lab',['id','batch_number','store_stock','lab_stock'],'lab_stock');
}
if ($current_store_stock > 0 && $new_store_stock <= 0) {
$inventory_stock_date = new InventoryStockDate;
$inventory_stock_date->quotation_type_id = 5; //1 = quotation type for labs
$inventory_stock_date->item_id = $drug_id_array[$x];
$inventory_stock_date->out_of_stock_date = $issued_on;
$inventory_stock_date->save();
}
endfor;
}else if ($requisition_type == 3){
//do this for dentals
for ($i = 0; $i < count($drug_id_array); $i++) {
if ($quantity_issued_array[$i] != "") {
$drug_name = get_name($drug_id_array[$i], "id", "name", "dentals");
$associative_requested_drugs_array[$drug_name] = $quantity_issued_array[$i];
$associative_requested_batches_array[$drug_name]=$batch_number_id_array[$i]??0;
}
}
for ($x = 0; $x < count($drug_id_array); $x++) {
$batch_number_id = $request->issued_batch_number[$x]??0;
//Decreasing the store stock
$current_store_stock = get_name($drug_id_array[$x], 'id', 'store_stock', 'dentals');
$current_store_stock = is_numeric($current_store_stock) ? $current_store_stock : 0;
$new_store_stock = $current_store_stock - $quantity_issued_array[$x];
// Increasing the Pharmacy stock
$current_pharmacy_stock = get_name($drug_id_array[$x], 'id', 'pharmacy_stock', 'dentals');
$current_pharmacy_stock = is_numeric($current_pharmacy_stock) ? $current_pharmacy_stock : 0;
$new_pharmacy_stock = $current_pharmacy_stock + $quantity_issued_array[$x];
// Data to update the dental table
$dental = Dental::find($drug_id_array[$x]);
if ($dental) {
$dental->pharmacy_stock = $new_pharmacy_stock;
$dental->store_stock = $new_store_stock;
$dental->update();
//move drug items from store to pharmacy stock
// $this->itemsStockService->move_batch_item_from_store_to_other_sections($item_type = 3, $drug_id_array[$x], $batch_number_id, $quantity_issued_array[$x], $requisition_id,'Opticals','pharmacy',['id','batch_number','store_stock','pharmacy_stock'],'pharmacy_stock');
}
if ($current_store_stock > 0 && $new_store_stock <= 0) {
$inventory_stock_date = new InventoryStockDate;
$inventory_stock_date->quotation_type_id = 3;
$inventory_stock_date->item_id = $drug_id_array[$x];
$inventory_stock_date->out_of_stock_date = $issued_on;
$inventory_stock_date->save();
}
}
}else if ($requisition_type == 6) {
//do this for general itmes
for ($i = 0; $i < count($drug_id_array); $i++) {
if ($quantity_issued_array[$i] != "") {
$drug_name = get_name($drug_id_array[$i], "id", "name", "general_items");
$associative_requested_drugs_array[$drug_name] = $quantity_issued_array[$i];
}
}
for ($x = 0; $x < count($drug_id_array); $x++) :
//Decreasing the store stock
$current_store_stock = get_name($drug_id_array[$x], 'id', 'store_stock', 'general_items');
$current_store_stock = is_numeric($current_store_stock) ? $current_store_stock : 0;
$new_store_stock = $current_store_stock - $quantity_issued_array[$x];
if ($request->has('issue_out_to_lab')) {
// Increasing the Laboratory stock
$current_laboratory_stock = get_name($drug_id_array[$x], 'id', 'pharmacy_stock', 'general_items');
$current_laboratory_stock = is_numeric($current_laboratory_stock) ? $current_laboratory_stock : 0;
$new_laboratory_stock = $current_laboratory_stock + $quantity_issued_array[$x];
// Data to update the drugs table
$drug = Lab::find($drug_id_array[$x]);
if ($drug) {
$drug->laboratory_stock = $new_laboratory_stock;
$drug->store_stock = $new_store_stock;
$drug->update();
}
} elseif ($request->has('issue_out_to_pharmacy')) {
// Increasing the Pharmacy stock
$current_pharmacy_stock = get_name($drug_id_array[$x], 'id', 'pharmacy_stock', 'general_items');
$current_pharmacy_stock = is_numeric($current_pharmacy_stock) ? $current_pharmacy_stock : 0;
$new_pharmacy_stock = $current_pharmacy_stock + $quantity_issued_array[$x];
// Data to update the drugs table
$drug = Lab::find($drug_id_array[$x]);
if ($drug) {
$drug->pharmacy_stock = $new_pharmacy_stock;
$drug->store_stock = $new_store_stock;
$drug->update();
}
}
if ($current_store_stock > 0 && $new_store_stock <= 0) {
$inventory_stock_date = new InventoryStockDate;
$inventory_stock_date->quotation_type_id = 5; //1 = quotation type for labs
$inventory_stock_date->item_id = $drug_id_array[$x];
$inventory_stock_date->out_of_stock_date = $issued_on;
$inventory_stock_date->save();
}
endfor;
} else if ($requisition_type == 7) {
//do this for opticals
for ($i = 0; $i < count($drug_id_array); $i++) {
if ($quantity_issued_array[$i] != "") {
$drug_name = get_name($drug_id_array[$i], "id", "name", "eye_glasses");
$associative_requested_drugs_array[$drug_name] = $quantity_issued_array[$i];
$associative_requested_batches_array[$drug_name]=$batch_number_id_array[$i];
}
}
for ($x = 0; $x < count($drug_id_array); $x++) {
$batch_number_id = $request->issued_batch_number[$x];
//Decreasing the store stock
$current_store_stock = get_name($drug_id_array[$x], 'id', 'store_stock', 'eye_glasses');
$current_store_stock = is_numeric($current_store_stock) ? $current_store_stock : 0;
$new_store_stock = $current_store_stock - $quantity_issued_array[$x];
// Increasing the Pharmacy stock
$current_pharmacy_stock = get_name($drug_id_array[$x], 'id', 'pharmacy_stock', 'eye_glasses');
$current_pharmacy_stock = is_numeric($current_pharmacy_stock) ? $current_pharmacy_stock : 0;
$new_pharmacy_stock = $current_pharmacy_stock + $quantity_issued_array[$x];
// Data to update the drugs table
$drug = EyeGlasses::find($drug_id_array[$x]);
if ($drug) {
$drug->pharmacy_stock = $new_pharmacy_stock;
$drug->store_stock = $new_store_stock;
$drug->update();
//move drug items from store to pharmacy stock
$this->itemsStockService->move_batch_item_from_store_to_other_sections($item_type = 7, $drug_id_array[$x], $batch_number_id, $quantity_issued_array[$x], $requisition_id,'Opticals','pharmacy',['id','batch_number','store_stock','pharmacy_stock'],'pharmacy_stock');
}
if ($current_store_stock > 0 && $new_store_stock <= 0) {
$inventory_stock_date = new InventoryStockDate;
$inventory_stock_date->quotation_type_id = 7;
$inventory_stock_date->item_id = $drug_id_array[$x];
$inventory_stock_date->out_of_stock_date = $issued_on;
$inventory_stock_date->save();
}
}
} else {
redirect()->back()->withInput();
}
// Updating the requisitions table
$requisition = Requisition::find($requisition_id);
//check if requisition is approved
if ($requisition->approved_by == null){
$requisition->approved_by = Auth::user()->id;
$requisition->approved_date = date('Y-m-d H:i:s');
}
$requisition->item_ids_issued_out = implode(',', $drug_id_array);
$requisition->batch_issued_out = implode(', ', $batch_number_id_array??[]);
$requisition->quantity_issued = implode(',', $quantity_issued_array);
$requisition->cost_value = implode(',', $cost_value_array);
$requisition->issued_by = $issued_by;
$requisition->issue_status = 1;
$requisition->issued_on = $issued_on;
$requisition->received_by=$received_by;
$requisition->received_comment=$issue_out_comment;
//$requisition->unit_of_measure = isset($requisition->unit_of_measure) ? implode(',', $units_array) : null;
$requisition->update();
// recreating the session
session()->put(['requisition_id' => $requisition_id]);
$hospital_details = HospitalInformation::find(1);
if ($requisition_type == 2) {$table_name='sundries'; }
if ($requisition_type == 1) {$table_name= 'drugs';}
if ($requisition_type == 4) {$table_name='radiologies';}
if ($requisition_type == 5) {$table_name='labs'; }
if ($requisition_type == 3) {$table_name='dentals';$buyin_price='buying_price';
return view('stores::stores.print_issued_opticals', compact('requisition','table_name','buyin_price', 'hospital_details', 'associative_requested_drugs_array', 'requisition_id', 'requisition_type'));
}
if ($requisition_type == 6) {$table_name='general_items'; $buyin_price='cost_price';
return view('stores::stores.print_issued_opticals', compact('requisition','table_name','buyin_price', 'hospital_details', 'associative_requested_drugs_array', 'requisition_id', 'requisition_type'));
}
if ($requisition_type == 7) {
$table_name= 'eye_glasses';
// return view('stores::stores.print_issued_opticals', compact('requisition', 'hospital_details', 'associative_requested_drugs_array', 'requisition_id', 'requisition_type'));
}
return view('stores::stores.print_issued_drugs', compact('requisition', 'table_name','hospital_details', 'associative_requested_drugs_array','associative_requested_batches_array', 'requisition_id', 'requisition_type'));
}
/* previous received items */
public function previously_received_items(Request $request)
{
$quotation_type_options = DB::table('quotation_types')->pluck('name', 'id')->toArray();
$quotation_type_options = ['' => '- Select Quotation type -'] + $quotation_type_options;
$suppliers = DB::table('suppliers')->where('available', 1)->whereNull('deleted_at')->orderBy('name')->pluck('name', 'id')->toArray();
$suppliers = ['' => '- All Suppliers -'] + $suppliers;
$results = 0;
$table_quotations = "quotations";
$item_type = $display = "";
$supplier_id = $request->supplier_id;
if (isset($request->start_date) && isset($request->end_date)) {
if (isset($request->quotation_type)) {
$item_type = $request->quotation_type;
$start_date = Carbon::createFromFormat('d/m/Y', $request->start_date)->startOfDay()->toDateTimeString();
$end_date = Carbon::createFromFormat('d/m/Y', $request->end_date)->endOfDay()->toDateTimeString();
if(is_null($supplier_id)){
$results = DB::select("select DISTINCT(quotation_number),receive_date, quotation_type_id, bill_id from $table_quotations where quotation_type_id = '{$item_type}' AND deleted_at IS NULL AND receive_status = 1 AND approval_status = 1 AND approval_user IS NOT NULL AND receive_date BETWEEN '{$start_date}' AND '{$end_date}' ORDER BY receive_date");
$display = "Received between " . streamline_date($start_date) . " and " . streamline_date($end_date) . " from " . get_name($suppliers, "id", "name", "suppliers") ;
} else {
$results = DB::select("select DISTINCT(quotation_number),receive_date, quotation_type_id, bill_id from $table_quotations where quotation_type_id = '{$item_type}' AND deleted_at IS NULL AND supplier_id = '{$supplier_id}' AND receive_status = 1 AND approval_status = 1 AND approval_user IS NOT NULL AND receive_date BETWEEN '{$start_date}' AND '{$end_date}' ORDER BY receive_date");
$display = "Received between " . streamline_date($start_date) . " and " . streamline_date($end_date) . " from " . get_name($suppliers, "id", "name", "suppliers") ;
}
}
}
return view('stores::stores.previously_received_items', compact('results', 'quotation_type_options', 'suppliers', 'table_quotations', 'item_type', 'display'));
}
/* function to display details of previously received items */
public function previous_received_items_details(Request $request)
{
$quotation_number = $request->quotation_number;
$item_type = $request->quotation_type;
$table_quotations = "quotations";
$quotations_results = DB::select("SELECT * FROM $table_quotations where grn_number = {$quotation_number}");
return view('stores::stores.previously_received_items_details', compact('quotation_number', 'item_type', 'table_quotations', 'quotations_results'));
}
/* previous issued items */
public function previously_issued_items(Request $request)
{
$quotation_type_options = DB::table('quotation_types')->pluck('name', 'id')->toArray();
$quotation_type_options = ['' => '- Select Item Type -'] + $quotation_type_options;
$results = 0;
$date_filter = "issued_on BETWEEN CURDATE() - INTERVAL 30 DAY AND CURDATE()";
$display = "Issued out within this month";
$item_type = "1";
$start_date = Carbon::now()->startOfMonth()->toDateTimeString();
$end_date = Carbon::now()->endOfMonth()->toDateTimeString();
if (isset($request->start_date) && isset($request->end_date)) {
if (isset($request->quotation_type)) {
$item_type = $request->quotation_type;
$start_date = Carbon::createFromFormat('d/m/Y', $request->start_date)->startOfDay()->toDateTimeString();
$end_date = Carbon::createFromFormat('d/m/Y', $request->end_date)->endOfDay()->toDateTimeString();
$date_filter = "issued_on BETWEEN '{$start_date}' AND '{$end_date}'";
$display = "issued between " . streamline_date($start_date) . " and " . streamline_date($end_date);
}
}
$results = Requisition::select('id', 'quotation_type_id', 'drug_id','item_ids_issued_out', 'quantity_requested', 'created_at', 'issued_by', 'issued_on', 'cost_value')
->whereBetween('created_at', [$start_date, $end_date])->where(['issue_status'=>1,'quotation_type_id'=>$item_type])->orderBy('issued_on', 'desc')->limit(20)->get();
return view('stores::stores.previously_issued_items', compact('results', 'quotation_type_options', 'item_type', 'display'));
}
/* function to display details of previously issued items */
public function previous_issued_items_details(Request $request)
{
$requisition_id = $request->requisition_id;
$results = DB::select("select * from requisitions where id = {$requisition_id} AND issue_status = 1 ORDER BY id desc");
if (isset($results[0])) {
$item_type = $results[0]->quotation_type_id;
} else{
flash('no issues requisition has been found in Stre@mline')->success();
return redirect()->back();
}
return view('stores::stores.previously_issued_items_details', compact('requisition_id', 'item_type', 'results'));
}
/* previous quotations */
public function previous_quotations(Request $request)
{
$quotation_type_options = DB::table('quotation_types')->pluck('name', 'id')->toArray();
$quotation_type_options = ['' => '- Select Quotation type -'] + $quotation_type_options;
$results = 0;
$item_type = "";
$display = "";
if (isset($request->start_date) && isset($request->end_date)) {
if (isset($request->quotation_type)) {
$item_type = $request->quotation_type;
$start_date = Carbon::parse($request->start_date)->startOfDay()->toDateTimeString();
$end_date = Carbon::parse($request->end_date)->endOfDay()->toDateTimeString();
$approval_status = $request->approval_status;
if ($approval_status == 1) {
//approved
$results = DB::select("select DISTINCT(quotation_number), approval_status, bill from quotations where approval_status = 1 AND created_at BETWEEN '{$start_date}' AND '{$end_date}' AND deleted_at IS NULL ORDER BY quotation_number desc");
} elseif ($approval_status == 0) {
//pending
$results = DB::select("select DISTINCT(quotation_number), approval_status, bill from quotations where approval_status = 0 AND created_at BETWEEN '{$start_date}' AND '{$end_date}' AND deleted_at IS NULL ORDER BY quotation_number desc");
} elseif ($approval_status == 2) {
//all
$results = DB::select("select DISTINCT(quotation_number), approval_status, bill from quotations where created_at BETWEEN '{$start_date}' AND '{$end_date}' AND deleted_at IS NULL ORDER BY quotation_number desc");
}
$display = "Approval between " . streamline_date($start_date) . " and " . streamline_date($end_date);
}
}
return view('stores::stores.previous_quotations', compact('quotation_type_options', 'results', 'item_type', 'display'));
}
/* edit a previous quotation */
public function edit_previous_quotation(Request $request) {
$quotation_number = $request->quotation_number;
$item_type = $request->item_type;
$results = DB::table('quotations')->where('quotation_number', $quotation_number)->get();
$package_units = DB::table('package_units')->whereNull('deleted_at')->orderBy('name')->pluck('name', 'id')->toArray();
$package_units = ['' => '- select -'] + $package_units;
$suppliers = DB::table('suppliers')->where('available', 1)->whereNull('deleted_at')->orderBy('name')->pluck('name', 'id')->toArray();
$suppliers = ['' => '- Select Suppliers -'] + $suppliers;
return view('stores::stores.edit_previous_quotation', compact('quotation_number', 'item_type', 'results', 'package_units', 'suppliers'));
}
/* function to update edited previous quotation */
public function update_previous_quotation(Request $request) {
$quotation_id_array = $request->quotation_id;
$package_unit_array = $request->package_unit;
$number_of_package_units_array = $request->number_of_package_units;
$quantity_per_package_unit_array = $request->quantity_per_package_unit;
$quantity_array = $request->quantity;
$supplier_id = $request->supplier_id;
$expected_date = Carbon::createFromFormat('d/m/Y', $request->expected_date)->toDateString();
for ($x = 0; $x < count($quotation_id_array); $x++) {
$quotation_model = Quotation::find($quotation_id_array[$x]);
$quotation_model->quantity = $quantity_array[$x];
$quotation_model->quantity_per_package_unit = $quantity_per_package_unit_array[$x];
$quotation_model->number_of_package_units = $number_of_package_units_array[$x];
$quotation_model->package_unit = $package_unit_array[$x];
$quotation_model->supplier_id = $supplier_id;
$quotation_model->expected_date = $expected_date;
$quotation_model->update();
}
flash('Request for quotation was edited successfully')->success();
return redirect('previous_quotations');
}
/* view previous purchase orders */
public function previous_purchase_orders(Request $request)
{
$quotation_type_options = DB::table('quotation_types')->pluck('name', 'id')->toArray();
$quotation_type_options = ['' => '- Select Quotation type -'] + $quotation_type_options;
$results = [];
$item_type = "";
$display = "";
$result_message = "";
if (isset($request->start_date) && isset($request->end_date)) {
if (isset($request->quotation_type)) {
$item_type = $request->quotation_type;
$start_date = Carbon::createFromFormat('d/m/Y', $request->start_date)->startOfDay()->toDateTimeString();
$end_date = Carbon::createFromFormat('d/m/Y', $request->end_date)->endOfDay()->toDateTimeString();
$display = "Approved between " . streamline_date($start_date) . " and " . streamline_date($end_date);
$results = Quotation::select(DB::raw("DISTINCT (quotation_number) "))->where('approval_user', '!=', 0)->whereBetween('approval_date', [$start_date, $end_date])->where('quotation_type_id', $item_type)->orderBy('quotation_number', 'desc')->get();
$result_message = "No " . strtolower($item_type) . " purchase orders have been made";
}
}
return view('stores::stores.previous_purchase_orders', compact('quotation_type_options', 'item_type', 'results', 'display'));
}
/* view previous order history */
public function previous_order_history(Request $request) {
$item_options = [];
$quotation_type_options = DB::table('quotation_types')->pluck('name', 'id')->toArray();
$quotation_type_options = ['' => '- Select Quotation type -'] + $quotation_type_options;
$item_options['drugs'] = DB::table('drugs')->where('available', 1)->whereNull('deleted_at')->pluck('name', 'id')->toArray() + ['' => '-- select --'];
$item_options['sundries'] = DB::table('sundries')->whereNull('deleted_at')->pluck('name', 'id')->toArray() + ['' => '-- select --'];
$item_options['dentals'] = DB::table('dentals')->whereNull('deleted_at')->pluck('name', 'id')->toArray() + ['' => '-- select --'];
$item_options['labs'] = DB::table('labs')->whereNull('deleted_at')->pluck('name', 'id')->toArray() + ['' => '-- select --'];
$item_options['radiologies'] = DB::table('radiologies')->whereNull('deleted_at')->pluck('name', 'id')->toArray() + ['' => '-- select --'];
$item_options['general_items'] = DB::table('general_items')->whereNull('deleted_at')->pluck('name', 'id')->toArray() + ['' => '-- select --'];
$item_options['eye_glasses'] = DB::table('eye_glasses')->whereNull('deleted_at')->pluck('name', 'id')->toArray() + ['' => '-- select --'];
$item_type = 0;
$item_id = 0;
$quotation_type_id = 0;
$item_name = "N/A";
if (isset($request->start_date) && isset($request->end_date)) {
$start_date = Carbon::createFromFormat('d/m/Y', $request->start_date)->toDateTimeString();
$end_date = Carbon::createFromFormat('d/m/Y', $request->end_date)->toDateTimeString();
} else {
$start_date = Carbon::now()->toDateTimeString();
$end_date = Carbon::now()->toDateTimeString();
}
if (isset($request->selected_drugs) && $request->quotation_type == 1) {
//Drugs
$item_id = $request->selected_drugs;
$quotation_type_id = $request->quotation_type;
$item_name = DB::table('drugs')->find($request->selected_drugs)->name;
} elseif(isset($request->selected_sundries) && $request->quotation_type == 2) {
//Sundries
$item_id = $request->selected_sundries;
$quotation_type_id = $request->quotation_type;
$item_name = DB::table('sundries')->find($request->selected_sundries)->name;
} elseif(isset($request->selected_dentals) && $request->quotation_type == 3) {
//Dentals
$item_id = $request->selected_dentals;
$quotation_type_id = $request->quotation_type;
$item_name = DB::table('dentals')->find($request->selected_dentals)->name;
} elseif(isset($request->selected_radiologies) && $request->quotation_type == 4) {
//Radiologies
$item_id = $request->selected_radiologies;
$quotation_type_id = $request->quotation_type;
$item_name = DB::table('radiologies')->find($request->selected_radiologies)->name;
} elseif(isset($request->selected_labs) && $request->quotation_type == 5) {
//Labs
$item_id = $request->selected_labs;
$quotation_type_id = $request->quotation_type;
$item_name = DB::table('labs')->find($request->selected_labs)->name;
} elseif(isset($request->selected_general_items) && $request->quotation_type == 6) {
//General Items
$item_id = $request->selected_general_items;
$quotation_type_id = $request->quotation_type;
$item_name = DB::table('general_items')->find($request->selected_general_items)->name;
} elseif(isset($request->selected_eye_glasses) && $request->quotation_type == 7) {
//Eye Glasses
$item_id = $request->selected_eye_glasses;
$quotation_type_id = $request->quotation_type;
$item_name = DB::table('eye_glasses')->find($request->selected_eye_glasses)->name;
}
$display = "Records for " . $item_name . " between " . streamline_date($start_date) . " and " . streamline_date($end_date);
$results = DB::table('quotations')
->select('*')->whereNull('deleted_at')
->where('quotation_type_id', $quotation_type_id)
->where('drug_id', $item_id)
->whereBetween('created_at', [$start_date, $end_date])
->get();
return view('stores::stores.previous_order_history', compact('item_options', 'item_name', 'results', 'quotation_type_options', 'item_type', 'display'));
}
/* function to print the drug bill */
public function print_drug_bill(Request $request)
{
$quotation_number = $request->quotation_number;
$item_type = $request->item_type;
$hospital_details = HospitalInformation::find(1);
$table_quotations = 'quotations';
$quotations_results = DB::select("SELECT * FROM quotations where quotation_number = {$quotation_number}");
return view('stores::stores.print_drug_bill', compact('quotation_number', 'item_type', 'hospital_details', 'table_quotations', 'quotations_results'));
}
/* sundries stock sheet */
public function sundries_stock_sheet()
{
$sundries = DB::table('sundries')->whereNull('deleted_at')->orderBy('name', 'asc')->get();
if (count($sundries) < 1) {
flash()->error("There is no out of stock sundries");
return redirect('/sundries/');
} else {
return view('stores::stores.sundries_stock_sheet', compact('sundries'));
}
}
/* update stock sheet */
public function update_sundries_stock_sheet(Request $request)
{
$sundry_ids = $request->sundry_id;
$quantity = $request->quantity;
$expired_dates = $request->expiry_date;
for ($x = 0; $x < count($sundry_ids); $x++) :
$sundry = Sundry::find($sundry_ids[$x]);
$sundry->store_stock = $quantity[$x];
$sundry->expiry_date = $expired_dates[$x];
$update_store_stock = $sundry->update();
endfor;
if ($update_store_stock) :
flash('Sundry Store Stock Levels Updated')->success();
return redirect('sundries_stock_sheet');
endif;
flash('Sorry, unable to update stock')->error();
return redirect()->back();
}
public function physical_stock_count()
{
//check if there is a physical count that wasn't completed and alert the user otherwise allow the user go ahead with create new count
$ongoing_physical_count = StoreStockReconciliation::where('completion_status', 0)->get();
if (count($ongoing_physical_count) > 0) {
flash('There is an ongoing physical count. You can not start a new count, please resume previous count')->error();
return redirect()->back();
}
$drugs = [];
$batch_numbers = [];
$sql = "SELECT DISTINCT batch_number FROM quotations";
$results = DB::select($sql);
foreach ($results as $result) {
$batch_numbers[$result->batch_number] = $result->batch_number;
}
$chart_of_accounts = ChartOfAccount::orderBy('name', 'asc')->pluck('name', 'id')->toArray();
$chart_of_accounts = ['' => '- select -'] + $chart_of_accounts;
$batch_numbers = ['' => '- select -'] + $batch_numbers;
$drugs_dropdown = DB::table('drugs')->where('available', 1)->whereNull('deleted_at')->orderBy('name', 'asc')->pluck('name','id')->prepend('All drugs', 'all_items')->toArray();
return view('stores::stores.physical_stock_count', compact('drugs', 'batch_numbers', 'chart_of_accounts', 'drugs_dropdown'));
}
/* physical stock count */
public function resume_physical_stock_count()
{
//check if there is a physical count that wasn't completed and alert the user otherwise allow the user go ahead with create new count
$stock_reconciliations = DB::table('store_stock_reconciliations')->where('completion_status', 0)->get();
if (count($stock_reconciliations) < 1) {
flash()->error("There is no ongoing physical count");
return redirect('stores');
} else {
return view('stores::stores.resume_physical_stock_count', compact('stock_reconciliations'));
}
}
/* update physical stock count */
public function update_physical_stock_count(Request $request)
{
$batch_quotation_ids_array = $request->batch_quotation_id;
$batch_drug_ids_array = (isset($request->batch_drug_id) && is_array($request->batch_drug_id)) ? $request->batch_drug_id : [];
$unique_drug_ids_with_batches_array = array_unique($batch_drug_ids_array);
$batch_numbers_array = $request->batch_number;
$batch_unit_cost_array = $request->batch_unit_cost;
$batch_quantity_balances_array = $request->batch_quantity_balance;
$batch_expiry_dates_array = $request->expiry_date;
$batch_db_record_ids_array = $request->batch_db_record_id;
// TODO Please remove when merged into new batch tracking
// if (is_array($batch_numbers_array) && count(array_unique($batch_numbers_array)) < count($batch_numbers_array)) {
// flash('Duplicate batch numbers have been found!')->error();
// return redirect('physical_stock_count');
// }
$drugs_ids_array = $request->drug_id;
$system_stock_array = $request->system_stock;
$physical_stock_array = $request->physical_stock;
$cost_price_array = $request->cost_price;
$difference_array = $request->difference;
$shrinkage_array = $request->shrinkage;
$markup_array = $request->mark_up;
$reason_for_difference_array = $request->reason_for_difference;
$drugs_with_initial_stock_array = is_null($request->is_initial_stock) ? [] : $request->is_initial_stock;
$stock_adjustment_chart_of_account = ChartOfAccount::where('slug', 'stock_adjustment')->first();
$affected_account_id = $stock_adjustment_chart_of_account->id;
$opening_inventory_chart_of_account = ChartOfAccount::where('slug', 'opening_inventory')->first();
//get the max identifier
$max_stock_count_identifier = DB::table('store_stock_reconciliations')->max('stock_count_identifier');
$reconcile_drug_store_stock = true;
//update batch tracking tables with reconciliations
for ($i=0; $i < count($batch_numbers_array) ; $i++) {
if (!is_null($batch_numbers_array[$i]) && !is_null($batch_quantity_balances_array[$i])) {
//enforce double entry per batch
if (in_array($batch_drug_ids_array[$i], $drugs_with_initial_stock_array)) {
$affected_account_id = $opening_inventory_chart_of_account->id;//override adjustment a/c to be opening_inv
} else{
$affected_account_id = $stock_adjustment_chart_of_account->id;
}
//$batch_db_record_ids_array
account_for_batch_reconciliations_difference($item_type = 1, $batch_drug_ids_array[$i], $affected_account_id, $batch_numbers_array[$i], $batch_quantity_balances_array[$i], $request->reconciliation_date, "store", $ward_id = null);
reconcile_batches($item_type = 1, $batch_drug_ids_array[$i], $batch_numbers_array[$i], $batch_quantity_balances_array[$i], $batch_expiry_dates_array[$i], "store", $batch_unit_cost_array[$i]??0, $batch_db_record_ids_array[$i]??0, $ward_id=null);
}
}
if (isset($request->reconcile_stock)) {
for ($x = 0; $x < count($drugs_ids_array); $x++) :
/* check if the difference value is not null and then update the drug */
if (!is_null($difference_array[$x])) {
$physical_stock = new StoreStockReconciliation;
$physical_stock->drug_id = $drugs_ids_array[$x];
$physical_stock->system_stock = $system_stock_array[$x];
$physical_stock->physical_stock = $physical_stock_array[$x];
$physical_stock->difference = $difference_array[$x];
//$physical_stock->shrinkage = $shrinkage_array[$x];
$physical_stock->mark_up = $markup_array[$x];
$physical_stock->reason_for_difference = $reason_for_difference_array[$x];
$physical_stock->completion_status = 1;
$physical_stock->affected_account_id = $affected_account_id;
$physical_stock->reconciliation_date = $request->reconciliation_date;
$physical_stock->general_comment = $request->general_comment;
$physical_stock->created_by = Auth::id();
$physical_stock->save();
//add the stock_count_identifier of the newly counted stock
$physical_stock_record_to_update = StoreStockReconciliation::find($physical_stock->id);
$physical_stock_record_to_update->stock_count_identifier = $max_stock_count_identifier + 1; //increase ID by 1 for new
$physical_stock_record_to_update->update();
//update the system stock levels with the newly counted physical stock
//update only those with new physical value
$drugs = Drug::withTrashed()->find($drugs_ids_array[$x]);
$drugs->store_stock = $physical_stock_array[$x];
if (in_array($drugs->id, $drugs_with_initial_stock_array)) {
$existing_opening_stock = is_null($drugs->opening_stock) ? 0 : $drugs->opening_stock;
$drugs->opening_stock = $existing_opening_stock + $physical_stock_array[$x];
$drugs->opening_cost_price = $cost_price_array[$x]?? $drugs->cost_price;
$drugs->opening_stock_date = $request->reconciliation_date;
$drugs->store_opening_stock = $physical_stock_array[$x];
$affected_account_id = $opening_inventory_chart_of_account->id;//overide adjustment a/c to be opening_inv
} else{
$affected_account_id = $stock_adjustment_chart_of_account->id;
}
$drugs->updated_by = Auth::id();
//enforce double entry
//account_for_stock_reconciliations_difference($item_type = 1, $drugs_ids_array[$x], $affected_account_id, $difference_array[$x], $cost_price_array[$x], $request->reconciliation_date);
$reconcile_drug_store_stock = $drugs->update();
}
endfor;
/*==== do this to cater for the newer introduced editing batch number ======*/
if (track_items_using_batches()) :
for ($i = 0; $i < count($batch_numbers_array); $i++) :
if (!is_null($batch_numbers_array[$i]) && $batch_drug_ids_array[$i] != "") {
if ($batch_quotation_ids_array[$i] != '0') {
$quotation_record = Quotation::where(['drug_id' => $batch_drug_ids_array[$i], 'batch_number' => $batch_numbers_array[$i]])->first();
if (!is_null($quotation_record)) {
$quotation_record->batch_balance = $batch_quantity_balances_array[$i];
$quotation_record->update();
}
} elseif ($batch_quantity_balances_array[$i] != null && $batch_numbers_array[$i] != null && $batch_quotation_ids_array[$i] == '0') {
//assume that this batch doesnt have a corresponding quotation so make one
$new_quotation = new Quotation;
$new_quotation->quotation_type_id = 1;
$new_quotation->drug_id = $batch_drug_ids_array[$i];
$new_quotation->quantity = $batch_quantity_balances_array[$i];
$new_quotation->expected_date = date('Y-m-d');
$new_quotation->quotation_user = Auth::id();
$new_quotation->quotation_date = date('Y-m-d');
$new_quotation->billing_date = Carbon::now();
$new_quotation->billing_user = Auth::id();
$new_quotation->approval_date = Carbon::now();
$new_quotation->approval_status = 1;
$new_quotation->approval_user = Auth::id();
$new_quotation->receive_user = Auth::id();
$new_quotation->receive_date = date('Y-m-d');
$new_quotation->receive_status = 1;
$new_quotation->expiry_date = $batch_expiry_dates_array[$i];
$new_quotation->batch_number = $batch_numbers_array[$i];
$new_quotation->batch_balance = $batch_quantity_balances_array[$i];
$new_quotation->directly_received_items = 1;
$new_quotation->created_by = Auth::id();
$new_quotation->save();
}
}
endfor;
foreach ($unique_drug_ids_with_batches_array as $batch_drug) {
$all_batch_balances_for_drug = Quotation::where(['drug_id' => $batch_drug, 'quotation_type_id' => 1])->where('batch_balance', '>', 0)->sum('batch_balance');
if ($all_batch_balances_for_drug > 0) {
$drug_record = Drug::withTrashed()->find($batch_drug);
$drug_record->store_stock = $all_batch_balances_for_drug;
$drug_record->update();
}
}
endif;
/*=========== end the catering for the newer introduced batch number ===========*/
if ($reconcile_drug_store_stock) :
flash('Stock levels have been reconciled')->success();
return redirect('physical_stock_count');
endif;
} else if (isset($request->save_stock)) {
//save these for editing later on
for ($x = 0; $x < count($drugs_ids_array); $x++) :
$physical_stock = new StoreStockReconciliation;
$physical_stock->drug_id = $drugs_ids_array[$x];
$physical_stock->system_stock = $system_stock_array[$x];
$physical_stock->physical_stock = $physical_stock_array[$x];
$physical_stock->difference = $difference_array[$x];
//$physical_stock->shrinkage = $shrinkage_array[$x];
$physical_stock->mark_up = $markup_array[$x];
$physical_stock->reason_for_difference = $reason_for_difference_array[$x];
$physical_stock->completion_status = 0;
$physical_stock->created_by = Auth::id();
$saved_physical_stock = $physical_stock->save();
//add stock_count_identifier that will be used in resuming edit
$physical_stock_record_to_that_will_be_updated = StoreStockReconciliation::find($physical_stock->id);
$physical_stock_record_to_that_will_be_updated->stock_count_identifier = $max_stock_count_identifier + 1; //increase ID by 1 for new
$physical_stock_record_to_that_will_be_updated->update();
endfor;
/*==== do this to cater for the newer introduced editing batch number ======*/
if (track_items_using_batches()) :
for ($i = 0; $i < count($batch_drug_ids_array); $i++) :
if (!is_null($batch_drug_ids_array[$i]) && $batch_drug_ids_array[$i] != "") {
$temp_reconciliation_batch_details = new BatchDetailsForTemporaryStockReconciliation;
$temp_reconciliation_batch_details->drug_id = $batch_drug_ids_array[$i];
$temp_reconciliation_batch_details->batch_number = $batch_numbers_array[$i];
$temp_reconciliation_batch_details->batch_quantity = $batch_quantity_balances_array[$i];
$temp_reconciliation_batch_details->batch_quotation_id = $batch_quotation_ids_array[$i];
$temp_reconciliation_batch_details->stock_count_identifier = $max_stock_count_identifier + 1;
$temp_reconciliation_batch_details->save();
}
endfor;
endif;
/*=========== end the catering for the newer introduced batch number ===========*/
if ($saved_physical_stock) :
flash('Physical stock has been saved. You can resume later')->success();
return redirect('stores');
endif;
}
flash('Sorry, unable to update stock')->error();
return redirect()->back();
}
/* handle a resumed physical stock count */
public function complete_resumed_physical_stock_count(Request $request)
{
$batch_quotation_ids_array = $request->batch_quotation_id;
$batch_drug_ids_array = $request->batch_drug_id;
$batch_numbers_array = $request->batch_number;
$batch_quantity_balances_array = $request->batch_quantity_balance;
$reconciliation_ids_array = $request->reconciliation_record_ids;
$drugs_ids_array = $request->drug_id;
$system_stock_array = $request->system_stock;
$physical_stock_array = $request->physical_stock;
$difference_array = $request->difference;
//$shrinkage_array = $request->shrinkage;
$markup_array = $request->mark_up;
$reason_for_difference_array = $request->reason_for_difference;
if (isset($request->reconcile_stock)) {
for ($x = 0; $x < count($reconciliation_ids_array); $x++) {
$physical_stock = StoreStockReconciliation::find($reconciliation_ids_array[$x]);
$physical_stock->drug_id = $drugs_ids_array[$x];
$physical_stock->system_stock = $system_stock_array[$x];
$physical_stock->physical_stock = $physical_stock_array[$x];
$physical_stock->difference = $difference_array[$x];
//$physical_stock->shrinkage = $shrinkage_array[$x];
$physical_stock->mark_up = $markup_array[$x];
$physical_stock->reason_for_difference = $reason_for_difference_array[$x];
$physical_stock->completion_status = isset($request->reconcile_stock) ? 1 : 0;
if (isset($request->reconcile_stock_top)) {
$physical_stock->completion_status = 1;
}
if ($physical_stock->update()) {
//update the system stock levels with the newly counted physical stock
//update only those with new physical value
if (isset($drugs_ids_array[$x]) && !is_null($drugs_ids_array[$x]) && $drugs_ids_array[$x] != "") {
$drug = Drug::withTrashed()->find($drugs_ids_array[$x]);
$drug->store_stock = $physical_stock_array[$x];
$drug->updated_by = Auth::id();
$reconcile_drug_store_stock = $drug->update();
}
}
}
/*==== do this to cater for the newer introduced editing batch number ======*/
for ($i = 0; $i < count($batch_drug_ids_array); $i++) :
if (!is_null($batch_drug_ids_array[$i]) && $batch_drug_ids_array[$i] != "") {
$quotation_record = Quotation::where(['drug_id' => $batch_drug_ids_array[$i], 'batch_number' => $batch_numbers_array[$i]])->first();
if (!is_null($quotation_record)) {
$quotation_record->batch_balance = $batch_quantity_balances_array[$i];
$quotation_record->update();
}
}
endfor;
/*=========== end the catering for the newer introduced batch number ===========*/
flash('Stock levels details have been updated')->success();
return redirect('stores');
} else if (isset($request->save_stock)) {
//get the max identfier
$max_stock_count_identifier = DB::table('store_stock_reconciliations')->max('stock_count_identifier');
//save these for editing later on
for ($x = 0; $x < count($drugs_ids_array); $x++) :
$physical_stock = new StoreStockReconciliation;
$physical_stock->drug_id = $drugs_ids_array[$x];
$physical_stock->system_stock = $system_stock_array[$x];
$physical_stock->physical_stock = $physical_stock_array[$x];
$physical_stock->difference = $difference_array[$x];
//$physical_stock->shrinkage = $shrinkage_array[$x];
$physical_stock->mark_up = $markup_array[$x];
$physical_stock->reason_for_difference = $reason_for_difference_array[$x];
$physical_stock->completion_status = 0;
$physical_stock->created_by = Auth::id();
$saved_physical_stock = $physical_stock->save();
//add stock_count_identifier that will be used in resuming edit
$physical_stock_record_to_that_will_be_updated = StoreStockReconciliation::find($physical_stock->id);
$physical_stock_record_to_that_will_be_updated->stock_count_identifier = $max_stock_count_identifier + 1; //increase ID by 1 for new
$physical_stock_record_to_that_will_be_updated->update();
endfor;
/*==== do this to cater for the newer introduced editing batch number ======*/
for ($i = 0; $i < count($batch_drug_ids_array); $i++) :
if (!is_null($batch_drug_ids_array[$i]) && $batch_drug_ids_array[$i] != "") {
$temp_reconciliation_batch_details = new BatchDetailsForTemporaryStockReconciliation;
$temp_reconciliation_batch_details->drug_id = $batch_drug_ids_array[$i];
$temp_reconciliation_batch_details->batch_number = $batch_numbers_array[$i];
$temp_reconciliation_batch_details->batch_quantity = $batch_quantity_balances_array[$i];
$temp_reconciliation_batch_details->batch_quotation_id = $batch_quotation_ids_array[$i];
$temp_reconciliation_batch_details->stock_count_identifier = $max_stock_count_identifier + 1;
$temp_reconciliation_batch_details->save();
}
endfor;
/*=========== end the catering for the newer introduced batch number ===========*/
flash('Physical stock has been saved. You can resume later')->success();
return redirect('stores');
}
}
/* stock reconciliation report */
public function stock_reconciliation_report(Request $request)
{
if (!empty($request->dates)) {
if ($request->dates == "today") {
$today = Carbon::today()->startOfDay()->toDateString();
$end = Carbon::parse($today)->endOfDay()->toDateTimeString();
$reconciled_stocks = StoreStockReconciliation::groupBy("stock_count_identifier")->whereBetween('created_at', [$today, $end])->orderBy('stock_count_identifier', 'desc')->get();
} else if ($request->dates == "yesterday") {
$yesterday = Carbon::yesterday()->startOfDay()->toDateString();
$end = Carbon::parse($yesterday)->endOfDay()->toDateTimeString();
$reconciled_stocks = StoreStockReconciliation::groupBy("stock_count_identifier")->whereBetween('created_at', [$yesterday, $end])->orderBy('stock_count_identifier', 'desc')->get();
} else if ($request->dates == "custom_date") {
$start = Carbon::parse($request->start_date)->startOfDay()->toDateTimeString();
$end = Carbon::parse($request->start_date)->endOfDay()->toDateTimeString();
$reconciled_stocks = StoreStockReconciliation::groupBy("stock_count_identifier")->whereBetween('created_at', [$start, $end])->orderBy('stock_count_identifier', 'desc')->get();
} else if ($request->dates == "custom_date_range") {
$start = Carbon::parse($request->start_date)->startOfDay()->toDateTimeString();
$end = Carbon::parse($request->end_date)->endOfDay()->toDateTimeString();
$reconciled_stocks = StoreStockReconciliation::groupBy("stock_count_identifier")->whereBetween('created_at', [$start, $end])->orderBy('stock_count_identifier', 'desc')->get();
}
} else $reconciled_stocks = StoreStockReconciliation::groupBy("stock_count_identifier")->orderBy('stock_count_identifier', 'desc')->get();
return view('stores::stores.stock_reconciliation_report', compact('reconciled_stocks'));
}
public function labs_stock_reconciliation_report(Request $request){
$filters=[];
if (!empty($request->dates)) {
switch ($request->dates) {
case 'today':
$today = Carbon::today()->startOfDay()->toDateString();
$end = Carbon::parse($today)->endOfDay()->toDateTimeString();
array_push($filters, [$today, $end]);
break;
case 'yesterday':
$yesterday = Carbon::yesterday()->startOfDay()->toDateTimeString();
$end = Carbon::parse($yesterday)->endOfDay()->toDateTimeString();
array_push($filters, [$yesterday, $end]);
break;
case 'custom_date':
$start = Carbon::parse($request->start_date)->startOfDay()->toDateTimeString();
$end = Carbon::parse($request->start_date)->endOfDay()->toDateTimeString();
array_push($filters, [$start, $end]);
break;
case 'custom_date_range':
$start = Carbon::parse($request->start_date)->startOfDay()->toDateTimeString();
$end = Carbon::parse($request->end_date)->endOfDay()->toDateTimeString();
array_push($filters, [$start, $end]);
break;
default:
# code...
break;
}
} else{
$today = Carbon::today()->startOfDay()->toDateString();
$end = Carbon::parse($today)->endOfDay()->toDateTimeString();
array_push($filters, [$today, $end]);
}
$reconciled_stocks = GeneralStockReconciliation::groupBy("stock_count_identifier")->where(['source'=>1,'item_type'=>5])->whereBetween('reconciliation_date', $filters)->orderBy('stock_count_identifier', 'desc')->get();
$route='stores.labs_stock_reconciliation_report_details';
$title='stores.labs_reconciliation_report';
$route_filter='stores.labs_stock_reconciliation_report';
return view('stores::stores.sundries_stock_reconciliation_report', compact('reconciled_stocks','route','route_filter','title'));
}
public function labs_stock_reconciliation_report_details(Request $request){
$table_name='labs';
$active='stores.labs_stock_reconciliation_report_details';
$route = 'stores.labs_stock_reconciliation_report';
$route_title ='stores.labs_reconciliation_report';
$var=false;
$items_reconciled = GeneralStockReconciliation::where(['stock_count_identifier' => $request->stock_count_identifier])->get();
return view('stores::stores.items_stock_reconciliation_report_details', compact('items_reconciled','var','route_title','table_name','active','route'));
}
public function radiologies_stock_reconciliation_report(Request $request){
$filters=[];
if (!empty($request->dates)) {
switch ($request->dates) {
case 'today':
$today = Carbon::today()->startOfDay()->toDateString();
$end = Carbon::parse($today)->endOfDay()->toDateTimeString();
array_push($filters, [$today, $end]);
break;
case 'yesterday':
$yesterday = Carbon::yesterday()->startOfDay()->toDateString();
$end = Carbon::parse($yesterday)->endOfDay()->toDateTimeString();
array_push($filters, [$yesterday, $end]);
break;
case 'custom_date':
$start = Carbon::parse($request->start_date)->startOfDay()->toDateTimeString();
$end = Carbon::parse($request->start_date)->endOfDay()->toDateTimeString();
array_push($filters, [$start, $end]);
break;
case 'custom_date_range':
$start = Carbon::parse($request->start_date)->startOfDay()->toDateTimeString();
$end = Carbon::parse($request->end_date)->endOfDay()->toDateTimeString();
array_push($filters, [$start, $end]);
break;
default:
# code...
break;
}
} else{
$today = Carbon::today()->startOfDay()->toDateString();
$end = Carbon::parse($today)->endOfDay()->toDateTimeString();
array_push($filters, [$today, $end]);
}
$reconciled_stocks = GeneralStockReconciliation::groupBy("stock_count_identifier")->where(['source'=>1,'item_type'=>4])->whereBetween('reconciliation_date', $filters)->orderBy('stock_count_identifier', 'desc')->get();
$route='stores.radiologies_stock_reconciliation_report_details';
$title='stores.radiologies_reconciliation_report';
$route_filter='stores.radiologies_stock_reconciliation_report';
return view('stores::stores.sundries_stock_reconciliation_report', compact('reconciled_stocks','route','route_filter','title'));
}
public function radiologies_stock_reconciliation_report_details(Request $request){
$table_name='radiologies';
$active='stores.radiologies_stock_reconciliation_report_details';
$route = 'stores.radiologies_stock_reconciliation_report';
$route_title ='stores.radiologies_reconciliation_report';
$var=false;
$items_reconciled = GeneralStockReconciliation::where(['stock_count_identifier' => $request->stock_count_identifier])->get();
return view('stores::stores.items_stock_reconciliation_report_details', compact('items_reconciled','var','route_title','table_name','active','route'));
}
/* stock reconciliation report details */
public function stock_reconciliation_report_details(Request $request)
{
$drugs_reconciled = StoreStockReconciliation::where(['stock_count_identifier' => $request->stock_count_identifier])->get();
return view('stores::stores.stock_reconciliation_report_details', compact('drugs_reconciled'));
}
/* average monthly stock consumption */
public function average_monthly_consumption(Request $request)
{
$filters = [];
$drugs_array = [];
$month_consumption_array = [];
$drugs_quantity_array = [];
$month_consumption_array = [];
/* create associative array of drugs with their quantities */
$drugs_qty_associative_array = [];
//if the start and end date are set check with isset($request->start_date) and isset($request->end_date)
if (isset($request->start_date) && isset($request->end_date)) {
$start_date = Carbon::createFromFormat('d/m/Y', $request->start_date)->startOfDay()->toDateTimeString();
$end_date = Carbon::createFromFormat('d/m/Y', $request->end_date)->endOfDay()->toDateTimeString();
array_push($filters, ['created_at', '>', $start_date]);
array_push($filters, ['created_at', '<', $end_date]);
$drugs_dispensed_with_qty_array = [];
$opd_drugs_dispensed_with_qty_array = [];
$ipd_drugs_dispensed_with_qty_array = [];
$drugs_dispensed = [];
$quantity_dispensed = [];
$opd_dispensations = PatientDispensing::where($filters)->get();
if (count($opd_dispensations) > 0) {
foreach ($opd_dispensations as $opd_record) {
//dd($opd_record);
$dispensation_month_year = Carbon::parse($opd_record->created_at)->format('Y-m');
$drugs_array = explode(",", $opd_record->drugs);
$quantities_array = explode(",", $opd_record->quantity_dispensed);
$purchased_elsewhere_array = explode(",", $opd_record->purchased_elsewhere);
for ($i = 0; $i < count($drugs_array); $i++) {
if (isset($purchased_elsewhere_array[$i]) && $purchased_elsewhere_array[$i] == 0) {
/* ============ meet Ms.Elegant for the first date with opd stuff ==========*/
if (array_key_exists($drugs_array[$i], $drugs_qty_associative_array)) {
$drugs_qty_associative_array[$drugs_array[$i]] += is_numeric($quantities_array[$i]) ? $quantities_array[$i] : 0;
} else {
$drugs_qty_associative_array[$drugs_array[$i]] = $quantities_array[$i];
}
/*============ bye bye Ms.Elegant ========*/
/* ============ meet Ms.Elegant's little sister ==========*/
if (array_key_exists($drugs_array[$i], $opd_drugs_dispensed_with_qty_array)) {
$opd_drugs_dispensed_with_qty_array[$drugs_array[$i]] += is_numeric($quantities_array[$i]) ? $quantities_array[$i] : 0;
} else {
$opd_drugs_dispensed_with_qty_array[$drugs_array[$i]] = $quantities_array[$i];
}
/*============ bye bye Ms.Elegant's little sister ========*/
}
}
//check and caress the outer array at this point
$month_consumption_array[$dispensation_month_year] = $opd_drugs_dispensed_with_qty_array;
//dd($month_consumption_array);
/*if (array_key_exists($dispensation_month_year, $month_consumption_array)){
$month_consumption_array[$dispensation_month_year] = $opd_drugs_dispensed_with_qty_array;
}
else{
$month_consumption_array[$dispensation_month_year] = $opd_drugs_dispensed_with_qty_array;
}*/
}
//$month_consumption_array["2020-01" => [panadol=20, coertum=10], "2020-02" => [panadol=13, coertum=2]]
}
$ward_dispensations = WardTreatmentDispensation::where($filters)->get();
if (count($ward_dispensations) > 0) {
$ipd_drugs_dispensed_with_qty_array = [];
foreach ($ward_dispensations as $ward_record) {
//dd($ward_record->created_at);
$ward_dispensation_month_year = Carbon::parse($ward_record->created_at)->format('Y-m');
/* ============ meet Ms.Elegant for the second date with ward stuff ==========*/
if (array_key_exists($ward_record->drug_id, $drugs_qty_associative_array)) {
$drugs_qty_associative_array[$ward_record->drug_id] += $ward_record->quantity_given;
} else {
$drugs_qty_associative_array[$ward_record->drug_id] = $ward_record->quantity_given;
}
if (array_key_exists($ward_record->drug_id, $ipd_drugs_dispensed_with_qty_array)) {
$ipd_drugs_dispensed_with_qty_array[$ward_record->drug_id] += $ward_record->quantity_given;
} else {
$ipd_drugs_dispensed_with_qty_array[$ward_record->drug_id] = $ward_record->quantity_given;
}
/*============ bye bye Ms.Elegant's other little sister ========*/
//loop through the $month_consumption_array and find drugs quantity in that month and increase
if (array_key_exists($ward_dispensation_month_year, $month_consumption_array)) {
foreach ($month_consumption_array as $month_year => $drugs_qty_array) {
if ($ward_dispensation_month_year == $month_year) {
# look for the drug in the inner opd array and increase the quantity
foreach ($drugs_qty_array as $opd_drug_id => $opd_quantity_given_out) {
if ($opd_drug_id == $ward_record->drug_id) {
$month_consumption_array[$month_year][$ward_record->drug_id] = $opd_quantity_given_out + $ward_record->quantity_given;
}
}
}
}
} else {
$month_consumption_array[$ward_dispensation_month_year] = $ipd_drugs_dispensed_with_qty_array;
}
}
//dd($month_consumption_array);
}
}
return view('stores::stores.average_monthly_consumption', compact('month_consumption_array'));
}
/* average monthly stock consumption details */
public function average_monthly_consumption_details(Request $request)
{
$details_quantity = $request->total_consumption;
$details_month_year_array = explode("-", $request->month_year);
$details_month = $details_month_year_array[0];
$details_year = $details_month_year_array[1];
$details_drug_id = $request->drug_id;
$labelsDaysArray = [];
$datasetsDataQuantityArray = [];
$display = "Showing consumption for the month of " . $request->month_year;
$month_dispensation_details = DB::table('patient_dispensings')->whereMonth('created_at', $details_month)->whereYear('created_at', $details_year)->get();
//dd($month_dispensation_details);
$dispensed_drug_ids_for_the_month_array = [];
$dispensed_dates_for_the_month_array = [];
//inialize for the first day of the month
$dispensed_dates_for_the_month_array["1"] = 0;
$labelString = "";
foreach ($month_dispensation_details as $dispensation_details) {
//dd($dispensation_details);
$drug_ids_array = explode(",", $dispensation_details->drugs);
$quantity_dispensed_array = explode(",", $dispensation_details->quantity_dispensed);
//get the day of the month that this dispensation was given
$date = new DateTime($dispensation_details->created_at);
$dispensation_day_of_the_month = $date->format('d');
$labelString = $date->format('M Y');
for ($i = 0; $i < count($drug_ids_array); $i++) {
//add this if smt to handle that annoying trailing "" from old streamline and also check if the id is the same as the drug we are searching for
if (($drug_ids_array[$i] != "") && ($drug_ids_array[$i] == $details_drug_id)) {
if (array_key_exists($dispensation_day_of_the_month, $dispensed_dates_for_the_month_array)) {
//get the current quantity from the associative array $drugs_quantity_array and increase it by the new quantity.
$previous_drug_quantity = (int)$dispensed_dates_for_the_month_array[$dispensation_day_of_the_month];
//dd((int)$quantity_dispensed_array[$i]);
$dispensed_dates_for_the_month_array[$dispensation_day_of_the_month] = $previous_drug_quantity + (int)$quantity_dispensed_array[$i];
} else {
//add the first dispensed quantity of the drug in that particular month by adding it to drugs_quantity_array array
$dispensed_dates_for_the_month_array[$dispensation_day_of_the_month] = (int)$quantity_dispensed_array[$i];
}
}
}
}
$labelsDaysArray = array_keys($dispensed_dates_for_the_month_array);
$datasetsDataQuantityArray = array_values($dispensed_dates_for_the_month_array);
$drug_name = get_name($details_drug_id, "id", "name", "drugs");
$chartjs = app()->chartjs
->name('lineChartTest')
->type('line')
->size(['width' => 400, 'height' => 200])
->labels($labelsDaysArray)
->datasets([
[
"label" => $drug_name,
'backgroundColor' => "rgba(38, 185, 154, 0.31)",
'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" => $datasetsDataQuantityArray,
]
])
->optionsRaw([
'legend' => [
'display' => true,
'labels' => [
'fontColor' => '#000'
]
],
'scales' => [
'xAxes' => [
[
'stacked' => true,
'scaleLabel' => [
'display' => true,
'labelString' => $labelString
],
'stepSize' => 20,
'gridLines' => [
'display' => true
]
]
],
'yAxes' => [
[
'stacked' => true,
'scaleLabel' => [
'display' => true,
'labelString' => 'Quantity consumed ' . '(' . $details_quantity . ')'
],
'stepSize' => 40,
'gridLines' => [
'display' => true
]
]
],
]
])
->options([]);
return view('stores::stores.average_monthly_consumption_details', compact('chartjs', 'display'));
}
/* report to show issued drugs to pharmacy */
public function drugs_issued_to_pharmacy_report(Request $request)
{
$requisition_id = $request->requisition_id;
$item_type = $request->item_type;
$results = null;
if (isset($request->dates)) {
if ($request->dates == "today") {
$today = Carbon::today()->toDateString();
$results = DB::table('requisitions')->whereNull('deleted_at')->where('issue_status', 1)->whereDate('issued_on', $today)->orderBy('issued_on', 'desc')->get();
} else if ($request->dates == "yesterday") {
$yesterday = Carbon::yesterday()->toDateString();
$results = DB::table('requisitions')->whereNull('deleted_at')->where('issue_status', 1)->whereDate('issued_on', $yesterday)->orderBy('issued_on', 'desc')->get();
} else if ($request->dates == "custom_date") {
$start = Carbon::parse($request->start_date)->startOfDay()->toDateTimeString();
$results = DB::table('requisitions')->whereNull('deleted_at')->where('issue_status', 1)->whereDate('issued_on', $start)->orderBy('issued_on', 'desc')->get();
} else if ($request->dates == "custom_date_range") {
$start = Carbon::parse($request->start_date)->startOfDay()->toDateTimeString();
$end = Carbon::parse($request->end_date)->endOfDay()->toDateTimeString();
$results = DB::table('requisitions')->whereNull('deleted_at')->where('issue_status', 1)->whereBetween('issued_on', [$start, $end])->orderBy('issued_on', 'desc')->get();
}
} else {
$results = DB::table('requisitions')->whereNull('deleted_at')->where('issue_status', 1)->orderBy('issued_on', 'desc')->get();
}
return view('stores::stores.drugs_issued_to_pharmacy_report', compact('requisition_id', 'item_type', 'results'));
}
/* report to show issued drugs to pharmacy */
public function drugs_issued_to_pharmacy_report_details(Request $request)
{
$requisition_id = $request->requisition_id;
$item_type = $request->item_type;
$results = null;
$results = DB::table('requisitions')->whereNull('deleted_at')->where(['id' => $requisition_id, 'issue_status' => 1])->orderBy('id', 'desc')->get();
return view('stores::stores.drugs_issued_to_pharmacy_details', compact('requisition_id', 'item_type', 'results'));
}
public function daily_stock_value_report(Request $request) {
$filters = $items = $drug_ids = $sundry_ids = $general_ids = $optical_ids = [];
$date = now()->toDateString();
$total = [
'total_drugs_stock_value' => 0,
'total_drugs_pharmacy_value' => 0,
'total_sundries_stock_value' => 0,
'total_sundries_pharmacy_value' => 0,
'total_drugs_ward_value' => 0,
'total_drugs_ward_cost_value' => 0,
'total_general_items_stock_value' => 0,
'total_general_items_pharmacy_value' => 0,
'total_optical_items_stock_value' => 0,
'total_drugs_pharmacy_cost_value' => 0,
'total_radiology_stock_value' => 0,
'total_drugs_store_cost_value' => 0,
'total_sundries_store_cost_value' => 0,
'total_sundries_pharmacy_cost_value' => 0,
'total_sundries_ward_value' => 0,
'total_sundries_ward_cost_value'=> 0,
'total_general_items_pharmacy_cost_value' => 0,
'total_general_items_store_cost_value' => 0,
'total_labs_stock_value' => 0,
'total_labs_lab_value' => 0,
'total_labs_store_cost_value' => 0,
'total_labs_lab_cost_value' => 0,
'total_radiology_lab_cost_value' => 0,
'total_radiology_store_cost_value' => 0,
'total_radiology_lab_value' => 0,
];
$items = [];
$item_type=1;
if (isset($request->date_to_search)) {
$date = Carbon::parse($request->date_to_search)->toDateString();
}
if (isset($request->item_type)) {
$item_type = $request->item_type;
}
$drug_ids = $sundry_ids = $general_ids = $optical_ids = [];
$records = BatchStockWatcher::get();
foreach ($records as $record) {
$details_arr = json_decode($record->details, true);
$opening_stock_date=get_closest_element_in_array(array_keys($details_arr), $date);
if (isset($details_arr[$date]) || isset($details_arr[$opening_stock_date])){ $details = $details_arr[$date] ?? $details_arr[$opening_stock_date];}
else{$details =[];continue;} // explode ward stock
$ward_stock = $details['ward_stock'] ? explode(",",$details['ward_stock']) : [];
// get total ward stock
$total_ward_stock = array_sum($ward_stock);
// if($opening_stock_date <= $date){
if ($record->item_type == 1) {
if(get_name($record->item_batch_watcher_id, "id", "batch_number", "item_batch_watcher") =='N/A')continue;
if ($details["store_stock"] <= 0 && $details["pharmacy_stock"] <= 0 && $total_ward_stock <= 0) continue;
$total['total_drugs_stock_value'] += $details["selling_price"] * $details["store_stock"];
$total['total_drugs_pharmacy_value'] += $details["selling_price"] * $details["pharmacy_stock"];
$total['total_drugs_store_cost_value'] += $details["buying_price"] * $details["store_stock"];
$total['total_drugs_pharmacy_cost_value'] += $details["buying_price"] * $details["pharmacy_stock"];
$total['total_drugs_ward_cost_value'] += $details["buying_price"] * $total_ward_stock;
$total['total_drugs_ward_value'] += $details["selling_price"] * $total_ward_stock;
$drug_ids[] = $record->item_id;
} elseif ($record->item_type == 2) {
if(get_name($record->item_batch_watcher_id, "id", "batch_number", "item_batch_watcher") =='N/A')continue;
if ($details["store_stock"] <= 0 && $details["pharmacy_stock"] <= 0 && $total_ward_stock <= 0) continue;
$total['total_sundries_stock_value'] += $details["selling_price"] * $details["store_stock"];
$total['total_sundries_pharmacy_value'] += $details["selling_price"] * $details["pharmacy_stock"];
$total['total_sundries_store_cost_value'] += $details["buying_price"] * $details["store_stock"];
$total['total_sundries_pharmacy_cost_value'] += $details["buying_price"] * $details["pharmacy_stock"];
$total['total_sundries_ward_cost_value'] += $details["buying_price"] * $total_ward_stock;
$total['total_sundries_ward_value'] += $details["selling_price"] * $total_ward_stock;
$sundry_ids[] = $record->item_id;
} elseif ($record->item_type == 4) {
if(get_name($record->item_batch_watcher_id, "id", "batch_number", "item_batch_watcher") =='N/A')continue;
if ($details["store_stock"] <= 0 && ($details["lab_stock"] ?? 0) <= 0) continue;
$total['total_radiology_stock_value'] += $details["selling_price"] * $details["store_stock"];
$total['total_radiology_lab_value'] += $details["selling_price"] * ($details["lab_stock"] ?? 0);
$total['total_radiology_store_cost_value'] += $details["buying_price"] * $details["store_stock"];
$total['total_radiology_lab_cost_value'] += $details["buying_price"] * ($details["lab_stock"] ?? 0);
$sundry_ids[] = $record->item_id;
} elseif ($record->item_type == 5) {
if(get_name($record->item_batch_watcher_id, "id", "batch_number", "item_batch_watcher") =='N/A')continue;
if ($details["store_stock"] <= 0 && ($details["lab_stock"] ?? 0) <= 0) continue;
$total['total_labs_stock_value'] += $details["selling_price"] * $details["store_stock"];
$total['total_labs_lab_value'] += $details["selling_price"] * ($details["lab_stock"] ?? 0);
$total['total_labs_store_cost_value'] += $details["buying_price"] * $details["store_stock"];
$total['total_labs_lab_cost_value'] += $details["buying_price"] * ($details["lab_stock"] ?? 0);
$sundry_ids[] = $record->item_id;
} elseif ($record->item_type == 6) {
$total['total_general_items_stock_value'] += $details["selling_price"] * $details["store_stock"];
$total['total_general_items_pharmacy_value'] += $details["selling_price"] * $details["pharmacy_stock"];
$total['total_general_items_store_cost_value'] += $details["buying_price"] * $details["store_stock"];
$total['total_general_items_pharmacy_cost_value'] += $details["buying_price"] * $details["pharmacy_stock"];
$general_ids[] = $record->item_id;
} elseif ($record->item_type == 7) {
$total['total_optical_items_stock_value'] += $details["selling_price"] * $details["store_stock"];
$optical_ids[] = $record->item_id;
}
$name_table=get_table_name($record->item_type);
$items[] = [
"item_type_id"=> $record->item_type,
"item_type" => get_item_type_name($record->item_type),
"item_id" => $record->item_id,
"item_name" => get_name($record->item_id, 'id', 'name', "{$name_table}"),
"batch_number" => get_name($record->item_batch_watcher_id, "id", "batch_number", "item_batch_watcher"),
"pharmacy_stock" => $details["pharmacy_stock"],
"store_stock" => $details["store_stock"],
"ward_stock" => $total_ward_stock,
"lab_stock" => $details["lab_stock"] ?? 0,
"buying_price" => $details["buying_price"],
"selling_price" => $details["selling_price"],
"pharmacy_value" => $details["selling_price"] * $details["pharmacy_stock"],
"store_value" => $details["selling_price"] * $details["store_stock"],
"ward_value" => $details["selling_price"] * $total_ward_stock,
];
// }
}
$items = array_filter($items, function($item) use ($item_type){
return $item['item_type_id'] == $item_type;
});
$search_text = "Date: " . streamline_date($date);
return view('stores::stores.daily_stock_value_report', compact('search_text', 'item_type','date','items','total'));
}
public function sundries_physical_stock_count()
{
//check if there is a physical count that wasn't completed and alert the user otherwise allow the user go ahead with create new count
$ongoing_physical_count = SundryStoreStockReconciliation::where('completion_status', 0)->get();
if (count($ongoing_physical_count) > 0) {
flash('There is an ongoing physical count. You can not start a new count, please resume previous count')->error();
return redirect()->back();
}
$sundries = []; //DB::table('sundries')->whereNull('deleted_at')->orderBy('name', 'asc')->get();
$sundries_dropdown = DB::table('sundries')->whereNull('deleted_at')->orderBy('name', 'asc')->pluck('name','id')->prepend('All sundries', 'all_items')->toArray();
$chart_of_accounts = ChartOfAccount::orderBy('name', 'asc')->pluck('name', 'id')->toArray();
$chart_of_accounts = ['' => '- select -'] + $chart_of_accounts;
return view('stores::stores.sundries_physical_stock_count', compact('sundries', 'chart_of_accounts', 'sundries_dropdown'));
}
// labs reconcilation
public function labs_physical_stock_count(Request $request){
$item_ids_array=$stock_adjustment_chart_of_account = null;
if (isset($request->search_items_ids)){
$item_ids_array = $request->search_items_ids;
$is_all_items = in_array("all_items", $item_ids_array);
}
$labs =[];
if ($item_ids_array != null){
if ($is_all_items) {
$labs = Lab::orderby('name', 'asc')->get();
} else{
$labs = Lab::whereIn('id', $item_ids_array)->orderBy('name', 'asc')->get();
}
$stock_adjustment_chart_of_account = ChartOfAccount::where('slug', 'stock_adjustment')->first();
}
$labs_dropdown = Lab::orderBy('name', 'asc')->pluck('name', 'id')->prepend('All Labs', 'all_items')->toArray();
// $chart_of_accounts = ChartOfAccount::orderBy('name', 'asc')->pluck('name', 'id')->toArray();
// $chart_of_accounts = ['' => '- select -'] + $chart_of_accounts;
return view('stores::stores.labs_physical_stock_count', compact('labs', 'labs_dropdown','stock_adjustment_chart_of_account'));
}
public function update_labs_physical_stock_count(Request $request){
$batch_quotation_ids_array = $request->batch_quotation_id;
$batch_radiology_ids_array = (isset($request->batch_radiology_id) && is_array($request->batch_radiology_id)) ? $request->batch_radiology_id : [];
$unique_radiology_ids_with_batches_array = is_array($batch_radiology_ids_array) ? array_unique($batch_radiology_ids_array) : [];
$batch_numbers_array = $request->batch_number;
$batch_unit_cost_array = $request->batch_unit_cost;
$batch_quantity_balances_array = $request->batch_quantity_balance;
$batch_expiry_dates_array = $request->expiry_date;
$batch_db_record_ids_array = $request->batch_db_record_id;
$radiology_ids_array = $request->radiology_id;
$system_stock_array = $request->system_stock;
$physical_stock_array = $request->physical_stock;
$cost_price_array = $request->cost_price;
$difference_array = $request->difference;
$reason_for_difference_array = $request->reason_for_difference;
//get the max identifier
$sundries_with_initial_stock_array = is_null($request->is_initial_stock) ? [] : $request->is_initial_stock;
// $affected_account_id = $request->account_id;
$stock_adjustment_chart_of_account = ChartOfAccount::where('slug', 'stock_adjustment')->first();
$affected_account_id = $stock_adjustment_chart_of_account->id;
$opening_inventory_chart_of_account = ChartOfAccount::where('slug', 'opening_inventory')->first();
$reconcile_drug_store_stock = true;
$reconcile_date = $request->reconciliation_date;
//get the max identifier
$max_stock_count_identifier = DB::table('general_stock_reconciliations')->max('stock_count_identifier');
//update batch tracking tables with reconciliations
for ($i=0; $i < count($batch_numbers_array) ; $i++) {
if (!is_null($batch_numbers_array[$i]) && !is_null($batch_quantity_balances_array[$i])) {
//enforce double entry per batch
if (in_array($batch_radiology_ids_array[$i], $sundries_with_initial_stock_array)) {
$affected_account_id = $opening_inventory_chart_of_account->id;//overide adjustment a/c to be opening_inv
} else{
$affected_account_id = $stock_adjustment_chart_of_account->id;
}
reconcile_batches(5, $batch_radiology_ids_array[$i], $batch_numbers_array[$i], $batch_quantity_balances_array[$i], $batch_expiry_dates_array[$i], "store", $batch_unit_cost_array[$i]??0, $batch_db_record_ids_array[$i]??0, $ward_id=null);
}
}
if (isset($request->reconcile_stock)) {
for ($x = 0; $x < count($radiology_ids_array); $x++) :
/* check if the difference value is not null and then update the radiology */
if (!is_null($difference_array[$x])) {
record_stock_reconciliation(5,$radiology_ids_array[$x],$physical_stock_array[$x],$difference_array[$x],$system_stock_array[$x]
, $reason_for_difference_array[$x],1,$affected_account_id,$reconcile_date,$request->general_comment,1,$max_stock_count_identifier);
//update the system stock levels with the newly counted physical stock
//update only those with new physical value
$radiology = Lab::find($radiology_ids_array[$x]);
$radiology->store_stock = $physical_stock_array[$x];
$radiology->updated_by = Auth::id();
$reconcile_drug_store_stock = $radiology->update();
}
endfor;
/*==== do this to cater for the newer introduced editing batch number ======*/
if (track_items_using_batches()) :
for ($i = 0; $i < count($batch_radiology_ids_array); $i++) :
if (!is_null($batch_radiology_ids_array[$i]) && $batch_radiology_ids_array[$i] != "") {
if ($batch_quotation_ids_array[$i] != '0') {
$quotation_record = Quotation::where(['drug_id' => $batch_radiology_ids_array[$i], 'batch_number' => $batch_numbers_array[$i], 'quotation_type_id' => 5])->first();
if (!is_null($quotation_record)) {
$quotation_record->batch_balance = $batch_quantity_balances_array[$i];
$quotation_record->update();
}
}
elseif ($batch_quantity_balances_array[$i] != null && $batch_numbers_array[$i] != null && $batch_quotation_ids_array[$i] == '0') {
//assume that this batch doesn't have a corresponding quotation so make one
$new_quotation = new Quotation;
$new_quotation->quotation_type_id = 5;
$new_quotation->drug_id = $batch_radiology_ids_array[$i];
$new_quotation->quantity = $batch_quantity_balances_array[$i];
$new_quotation->expected_date = date('Y-m-d');
$new_quotation->quotation_user = Auth::id();
$new_quotation->quotation_date = date('Y-m-d');
$new_quotation->billing_date = Carbon::now();
$new_quotation->billing_user = Auth::id();
$new_quotation->approval_date = Carbon::now();
$new_quotation->approval_status = 1;
$new_quotation->approval_user = Auth::id();
$new_quotation->receive_user = Auth::id();
$new_quotation->receive_date = date('Y-m-d');
$new_quotation->receive_status = 1;
$new_quotation->expiry_date = $batch_expiry_dates_array[$i];
$new_quotation->batch_number = $batch_numbers_array[$i];
$new_quotation->batch_balance = $batch_quantity_balances_array[$i];
$new_quotation->directly_received_items = 1;
$new_quotation->created_by = Auth::id();
$new_quotation->save();
}
}
endfor;
foreach ($unique_radiology_ids_with_batches_array as $batch_sundry) {
$all_batch_balances_for_sundry = Quotation::where(['drug_id' => $batch_sundry, 'quotation_type_id' => 5])->where('batch_balance', '>', 0)->sum('batch_balance');
if ($all_batch_balances_for_sundry > 0) {
$sundry_record = Lab::withTrashed()->find($batch_sundry);
$sundry_record->store_stock = $all_batch_balances_for_sundry;
$sundry_record->update();
}
}
endif;
/*=========== end the catering for the newer introduced batch number ===========*/
if ($reconcile_drug_store_stock) :
flash('Stock levels have been reconciled')->success();
return redirect('stores_labs_stock_sheet');
endif;
}
flash('Sorry, unable to update stock')->error();
return redirect()->back();
}
// Radiology reconciliation
public function radiologies_physical_stock_count(Request $request){
$radiologies = [];
$item_ids_array=$stock_adjustment_chart_of_account = null;
if (isset($request->search_items_ids)){
$item_ids_array = $request->search_items_ids;
$is_all_items = in_array("all_items", $item_ids_array);
}
$labs =[];
if ($item_ids_array != null){
if ($is_all_items) {
$radiologies = Radiology::orderby('name', 'asc')->get();
} else{
$radiologies = Radiology::whereIn('id', $item_ids_array)->orderBy('name', 'asc')->get();
}
$stock_adjustment_chart_of_account = ChartOfAccount::where('slug', 'stock_adjustment')->first();
}
$radiologies_dropdown = Radiology::orderBy('name', 'asc')->pluck('name','id')->prepend('All Radiologies', 'all_items')->toArray();
$chart_of_accounts = ChartOfAccount::orderBy('name', 'asc')->pluck('name', 'id')->toArray();
$chart_of_accounts = ['' => '- select -'] + $chart_of_accounts;
return view('stores::stores.radiologies_physical_stock_count', compact('radiologies', 'chart_of_accounts', 'radiologies_dropdown','stock_adjustment_chart_of_account'));
}
public function update_radiologies_physical_stock_count(Request $request){
$batch_quotation_ids_array = $request->batch_quotation_id;
$batch_radiology_ids_array = (isset($request->batch_radiology_id) && is_array($request->batch_radiology_id)) ? $request->batch_radiology_id : [];
$unique_radiology_ids_with_batches_array = is_array($batch_radiology_ids_array) ? array_unique($batch_radiology_ids_array) : [];
$batch_numbers_array = $request->batch_number;
$batch_unit_cost_array = $request->batch_unit_cost;
$batch_quantity_balances_array = $request->batch_quantity_balance;
$batch_expiry_dates_array = $request->expiry_date;
$batch_db_record_ids_array = $request->batch_db_record_id;
$radiology_ids_array = $request->radiology_id;
$system_stock_array = $request->system_stock;
$physical_stock_array = $request->physical_stock;
$cost_price_array = $request->cost_price;
$difference_array = $request->difference;
$reason_for_difference_array = $request->reason_for_difference;
//get the max identifier
$sundries_with_initial_stock_array = is_null($request->is_initial_stock) ? [] : $request->is_initial_stock;
// $affected_account_id = $request->account_id;
$stock_adjustment_chart_of_account = ChartOfAccount::where('slug', 'stock_adjustment')->first();
$affected_account_id = $stock_adjustment_chart_of_account->id;
$opening_inventory_chart_of_account = ChartOfAccount::where('slug', 'opening_inventory')->first();
$reconcile_drug_store_stock = true;
$reconcile_date = $request->reconciliation_date;
//get the max identifier
$max_stock_count_identifier = DB::table('general_stock_reconciliations')->max('stock_count_identifier');
//update batch tracking tables with reconciliations
for ($i=0; $i < count($batch_numbers_array) ; $i++) {
if (!is_null($batch_numbers_array[$i]) && !is_null($batch_quantity_balances_array[$i])) {
//enforce double entry per batch
if (in_array($batch_radiology_ids_array[$i], $sundries_with_initial_stock_array)) {
$affected_account_id = $opening_inventory_chart_of_account->id;//overide adjustment a/c to be opening_inv
} else{
$affected_account_id = $stock_adjustment_chart_of_account->id;
}
reconcile_batches(4, $batch_radiology_ids_array[$i], $batch_numbers_array[$i], $batch_quantity_balances_array[$i], $batch_expiry_dates_array[$i], "store", $batch_unit_cost_array[$i]??0, $batch_db_record_ids_array[$i]??0, $ward_id=null);
}
}
if (isset($request->reconcile_stock)) {
for ($x = 0; $x < count($radiology_ids_array); $x++) :
/* check if the difference value is not null and then update the radiology */
if (!is_null($difference_array[$x])) {
record_stock_reconciliation(4,$radiology_ids_array[$x],$physical_stock_array[$x],$difference_array[$x],$system_stock_array[$x]
, $reason_for_difference_array[$x],1,$affected_account_id,$reconcile_date,$request->general_comment,1,$max_stock_count_identifier);
//update the system stock levels with the newly counted physical stock
//update only those with new physical value
$radiology = Radiology::find($radiology_ids_array[$x]);
$radiology->store_stock = $physical_stock_array[$x];
$radiology->updated_by = Auth::id();
$reconcile_drug_store_stock = $radiology->update();
}
endfor;
/*==== do this to cater for the newer introduced editing batch number ======*/
if (track_items_using_batches()) :
for ($i = 0; $i < count($batch_radiology_ids_array); $i++) :
if (!is_null($batch_radiology_ids_array[$i]) && $batch_radiology_ids_array[$i] != "") {
if ($batch_quotation_ids_array[$i] != '0') {
$quotation_record = Quotation::where(['drug_id' => $batch_radiology_ids_array[$i], 'batch_number' => $batch_numbers_array[$i], 'quotation_type_id' => 4])->first();
if (!is_null($quotation_record)) {
$quotation_record->batch_balance = $batch_quantity_balances_array[$i];
$quotation_record->update();
}
} elseif ($batch_quantity_balances_array[$i] != null && $batch_numbers_array[$i] != null && $batch_quotation_ids_array[$i] == '0') {
//assume that this batch doesn't have a corresponding quotation so make one
$new_quotation = new Quotation;
$new_quotation->quotation_type_id = 4;
$new_quotation->drug_id = $batch_radiology_ids_array[$i];
$new_quotation->quantity = $batch_quantity_balances_array[$i];
$new_quotation->expected_date = date('Y-m-d');
$new_quotation->quotation_user = Auth::id();
$new_quotation->quotation_date = date('Y-m-d');
$new_quotation->billing_date = Carbon::now();
$new_quotation->billing_user = Auth::id();
$new_quotation->approval_date = Carbon::now();
$new_quotation->approval_status = 1;
$new_quotation->approval_user = Auth::id();
$new_quotation->receive_user = Auth::id();
$new_quotation->receive_date = date('Y-m-d');
$new_quotation->receive_status = 1;
$new_quotation->expiry_date = $batch_expiry_dates_array[$i];
$new_quotation->batch_number = $batch_numbers_array[$i];
$new_quotation->batch_balance = $batch_quantity_balances_array[$i];
$new_quotation->directly_received_items = 1;
$new_quotation->created_by = Auth::id();
$new_quotation->save();
}
}
endfor;
foreach ($unique_radiology_ids_with_batches_array as $batch_sundry) {
$all_batch_balances_for_sundry = Quotation::where(['drug_id' => $batch_sundry, 'quotation_type_id' => 4])->where('batch_balance', '>', 0)->sum('batch_balance');
if ($all_batch_balances_for_sundry > 0) {
$sundry_record = Radiology::withTrashed()->find($batch_sundry);
$sundry_record->store_stock = $all_batch_balances_for_sundry;
$sundry_record->update();
}
}
endif;
/*=========== end the catering for the newer introduced batch number ===========*/
if ($reconcile_drug_store_stock) :
flash('Stock levels have been reconciled')->success();
return redirect('store_radiology_stock_sheet');
endif;
}
flash('Sorry, unable to update stock')->error();
return redirect()->back();
}
public function update_sundries_physical_stock_count(Request $request)
{
$batch_quotation_ids_array = $request->batch_quotation_id;
$batch_sundry_ids_array = (isset($request->batch_sundry_id) && is_array($request->batch_sundry_id)) ? $request->batch_sundry_id : [];
$unique_sundry_ids_with_batches_array = is_array($batch_sundry_ids_array) ? array_unique($batch_sundry_ids_array) : [];
$batch_numbers_array = $request->batch_number;
$batch_unit_cost_array = $request->batch_unit_cost;
$batch_quantity_balances_array = $request->batch_quantity_balance;
$batch_expiry_dates_array = $request->expiry_date;
$batch_db_record_ids_array = $request->batch_db_record_id;
$sundries_ids_array = $request->sundry_id;
$system_stock_array = $request->system_stock;
$physical_stock_array = $request->physical_stock;
$cost_price_array = $request->cost_price;
$difference_array = $request->difference;
$shrinkage_array = $request->shrinkage;
$markup_array = $request->mark_up;
$reason_for_difference_array = $request->reason_for_difference;
//get the max identifier
$sundries_with_initial_stock_array = is_null($request->is_initial_stock) ? [] : $request->is_initial_stock;
$affected_account_id = $request->account_id;
$stock_adjustment_chart_of_account = ChartOfAccount::where('slug', 'stock_adjustment')->first();
$affected_account_id = $stock_adjustment_chart_of_account->id;
$opening_inventory_chart_of_account = ChartOfAccount::where('slug', 'opening_inventory')->first();
$reconcile_drug_store_stock = true;
//get the max identifier
$max_stock_count_identifier = DB::table('sundry_store_stock_reconciliations')->max('stock_count_identifier');
//update batch tracking tables with reconciliations
for ($i=0; $i < count($batch_numbers_array) ; $i++) {
if (!is_null($batch_numbers_array[$i]) && !is_null($batch_quantity_balances_array[$i])) {
//enforce double entry per batch
if (in_array($batch_sundry_ids_array[$i], $sundries_with_initial_stock_array)) {
$affected_account_id = $opening_inventory_chart_of_account->id;//overide adjustment a/c to be opening_inv
} else{
$affected_account_id = $stock_adjustment_chart_of_account->id;
}
account_for_batch_reconciliations_difference($item_type = 2, $batch_sundry_ids_array[$i], $affected_account_id, $batch_numbers_array[$i], $batch_quantity_balances_array[$i], $request->reconciliation_date, "store", $ward_id = null);
reconcile_batches($item_type = 2, $batch_sundry_ids_array[$i], $batch_numbers_array[$i], $batch_quantity_balances_array[$i], $batch_expiry_dates_array[$i], "store", $batch_unit_cost_array[$i]??0, $batch_db_record_ids_array[$i]??0, $ward_id=null);
}
}
if (isset($request->reconcile_stock)) {
for ($x = 0; $x < count($sundries_ids_array); $x++) :
/* check if the difference value is not null and then update the drug */
if (!is_null($difference_array[$x])) {
$physical_stock = new SundryStoreStockReconciliation;
$physical_stock->sundry_id = $sundries_ids_array[$x];
$physical_stock->system_stock = $system_stock_array[$x];
$physical_stock->physical_stock = $physical_stock_array[$x];
$physical_stock->difference = $difference_array[$x];
//$physical_stock->shrinkage = $shrinkage_array[$x];
$physical_stock->mark_up = $markup_array[$x];
$physical_stock->reason_for_difference = $reason_for_difference_array[$x];
$physical_stock->completion_status = 1;
$physical_stock->affected_account_id = $affected_account_id;
$physical_stock->reconciliation_date = $request->reconciliation_date;
$physical_stock->general_comment = $request->general_comment;
$physical_stock->created_by = Auth::id();
$physical_stock->save();
//add the stock_count_identifier of the newly counted stock
$physical_stock_record_to_update = SundryStoreStockReconciliation::find($physical_stock->id);
$physical_stock_record_to_update->stock_count_identifier = $max_stock_count_identifier + 1; //increase ID by 1 for new
$physical_stock_record_to_update->update();
//update the system stock levels with the newly counted physical stock
//update only those with new physical value
$sundry = Sundry::find($sundries_ids_array[$x]);
$sundry->store_stock = $physical_stock_array[$x];
if (in_array($sundry->id, $sundries_with_initial_stock_array)) {
$existing_opening_stock = is_null($sundry->opening_stock) ? 0 : $sundry->opening_stock;
$sundry->opening_stock = $existing_opening_stock + $physical_stock_array[$x];
$sundry->opening_cost_price = $cost_price_array[$x];
$sundry->opening_stock_date = $request->reconciliation_date;
$sundry->store_opening_stock = $physical_stock_array[$x];
$affected_account_id = $opening_inventory_chart_of_account->id;//overide adjustment a/c to be opening_inv
} else{
$affected_account_id = $stock_adjustment_chart_of_account->id;
}
//enforce double entry
//account_for_stock_reconciliations_difference($item_type = 2, $sundries_ids_array[$x], $affected_account_id, $difference_array[$x], $cost_price_array[$x], $request->reconciliation_date);
$sundry->updated_by = Auth::id();
$reconcile_drug_store_stock = $sundry->update();
}
endfor;
/*==== do this to cater for the newer introduced editing batch number ======*/
if (track_items_using_batches()) :
for ($i = 0; $i < count($batch_sundry_ids_array); $i++) :
if (!is_null($batch_sundry_ids_array[$i]) && $batch_sundry_ids_array[$i] != "") {
if ($batch_quotation_ids_array[$i] != '0') {
$quotation_record = Quotation::where(['drug_id' => $batch_sundry_ids_array[$i], 'batch_number' => $batch_numbers_array[$i], 'quotation_type_id' => 2])->first();
if (!is_null($quotation_record)) {
$quotation_record->batch_balance = $batch_quantity_balances_array[$i];
$quotation_record->update();
}
} elseif ($batch_quantity_balances_array[$i] != null && $batch_numbers_array[$i] != null && $batch_quotation_ids_array[$i] == '0') {
//assume that this batch doesn't have a corresponding quotation so make one
$new_quotation = new Quotation;
$new_quotation->quotation_type_id = 2;
$new_quotation->drug_id = $batch_sundry_ids_array[$i];
$new_quotation->quantity = $batch_quantity_balances_array[$i];
$new_quotation->expected_date = date('Y-m-d');
$new_quotation->quotation_user = Auth::id();
$new_quotation->quotation_date = date('Y-m-d');
$new_quotation->billing_date = Carbon::now();
$new_quotation->billing_user = Auth::id();
$new_quotation->approval_date = Carbon::now();
$new_quotation->approval_status = 1;
$new_quotation->approval_user = Auth::id();
$new_quotation->receive_user = Auth::id();
$new_quotation->receive_date = date('Y-m-d');
$new_quotation->receive_status = 1;
$new_quotation->expiry_date = $batch_expiry_dates_array[$i];
$new_quotation->batch_number = $batch_numbers_array[$i];
$new_quotation->batch_balance = $batch_quantity_balances_array[$i];
$new_quotation->directly_received_items = 1;
$new_quotation->created_by = Auth::id();
$new_quotation->save();
}
}
endfor;
foreach ($unique_sundry_ids_with_batches_array as $batch_sundry) {
$all_batch_balances_for_sundry = Quotation::where(['drug_id' => $batch_sundry, 'quotation_type_id' => 2])->where('batch_balance', '>', 0)->sum('batch_balance');
if ($all_batch_balances_for_sundry > 0) {
$sundry_record = Sundry::withTrashed()->find($batch_sundry);
$sundry_record->store_stock = $all_batch_balances_for_sundry;
$sundry_record->update();
}
}
endif;
/*=========== end the catering for the newer introduced batch number ===========*/
if ($reconcile_drug_store_stock) :
flash('Stock levels have been reconciled')->success();
return redirect('sundries_stock_sheet');
endif;
} else if (isset($request->save_stock)) {
//save these for editing later on
for ($x = 0; $x < count($sundries_ids_array); $x++) :
$physical_stock = new SundryStoreStockReconciliation;
$physical_stock->sundry_id = $sundries_ids_array[$x];
$physical_stock->system_stock = $system_stock_array[$x];
$physical_stock->physical_stock = $physical_stock_array[$x];
$physical_stock->difference = $difference_array[$x];
//$physical_stock->shrinkage = $shrinkage_array[$x];
$physical_stock->mark_up = $markup_array[$x];
$physical_stock->reason_for_difference = $reason_for_difference_array[$x];
$physical_stock->completion_status = 0;
$physical_stock->created_by = Auth::id();
$saved_physical_stock = $physical_stock->save();
//add stock_count_identifier that will be used in resuming edit
$physical_stock_record_to_that_will_be_updated = SundryStoreStockReconciliation::find($physical_stock->id);
$physical_stock_record_to_that_will_be_updated->stock_count_identifier = $max_stock_count_identifier + 1; //increase ID by 1 for new
$physical_stock_record_to_that_will_be_updated->update();
endfor;
/*==== do this to cater for the newer introduced editing batch number ======*/
if (track_items_using_batches()) :
for ($i = 0; $i < count($batch_sundry_ids_array); $i++) :
if (!is_null($batch_sundry_ids_array[$i]) && $batch_sundry_ids_array[$i] != "") {
$temp_reconciliation_batch_details = new BatchDetailsForTemporaryStockReconciliation;
$temp_reconciliation_batch_details->drug_id = $batch_sundry_ids_array[$i];
$temp_reconciliation_batch_details->batch_number = $batch_numbers_array[$i];
$temp_reconciliation_batch_details->batch_quantity = $batch_quantity_balances_array[$i];
$temp_reconciliation_batch_details->batch_quotation_id = $batch_quotation_ids_array[$i];
$temp_reconciliation_batch_details->stock_count_identifier = $max_stock_count_identifier + 1;
$temp_reconciliation_batch_details->save();
}
endfor;
endif;
/*=========== end the catering for the newer introduced batch number ===========*/
if ($saved_physical_stock) :
flash('Physical stock has been saved. You can resume later')->success();
return redirect('stores');
endif;
}
flash('Sorry, unable to update stock')->error();
return redirect()->back();
}
public function resume_sundries_physical_stock_count()
{
//check if there is a physical count that wasn't completed and alert the user otherwise allow the user go ahead with create new count
$stock_reconciliations = DB::table('sundry_store_stock_reconciliations')->where('completion_status', 0)->get();
if (count($stock_reconciliations) < 1) {
flash()->error("There is no ongoing physical sundries count");
return redirect('stores');
} else {
return view('stores::stores.resume_sundries_physical_stock_count', compact('stock_reconciliations'));
}
}
/* handle a resumed sundries physical stock count */
public function complete_resumed_sundries_stock_count(Request $request)
{
$reconciliation_ids_array = $request->reconciliation_record_ids;
$sundries_ids_array = $request->sundry_id;
$system_stock_array = $request->system_stock;
$physical_stock_array = $request->physical_stock;
$difference_array = $request->difference;
$shrinkage_array = $request->shrinkage;
$markup_array = $request->mark_up;
$reason_for_difference_array = $request->reason_for_difference;
for ($x = 0; $x < count($reconciliation_ids_array); $x++) {
$physical_stock = SundryStoreStockReconciliation::find($reconciliation_ids_array[$x]);
$physical_stock->sundry_id = $sundries_ids_array[$x];
$physical_stock->system_stock = $system_stock_array[$x];
$physical_stock->physical_stock = $physical_stock_array[$x];
$physical_stock->difference = $difference_array[$x];
$physical_stock->shrinkage = $shrinkage_array[$x];
$physical_stock->mark_up = $markup_array[$x];
$physical_stock->reason_for_difference = $reason_for_difference_array[$x];
$physical_stock->completion_status = isset($request->reconcile_stock) ? 1 : 0;
if (isset($request->reconcile_stock_top)) {
$physical_stock->completion_status = 1;
}
if ($physical_stock->update()) {
//update the system stock levels with the newly counted physical stock
//update only those with new physical value
if (isset($sundries_ids_array[$x]) && !is_null($sundries_ids_array[$x]) && $sundries_ids_array[$x] != "") {
$sundry = Sundry::withTrashed()->find($sundries_ids_array[$x]);
$sundry->store_stock = $physical_stock_array[$x];
$sundry->updated_by = Auth::id();
$reconcile_drug_store_stock = $sundry->update();
}
}
}
flash('Stock levels details have been updated')->success();
return redirect('stores');
}
/* sundries stock reconciliation report */
public function sundries_stock_reconciliation_report(Request $request)
{
$filters=[];
if (!empty($request->dates)) {
switch ($request->dates) {
case 'today':
$today = Carbon::today()->startOfDay()->toDateString();
$end = Carbon::parse($today)->endOfDay()->toDateTimeString();
array_push($filters, [$today, $end]);
break;
case 'yesterday':
$yesterday = Carbon::yesterday()->startOfDay()->toDateString();
$end = Carbon::parse($yesterday)->endOfDay()->toDateTimeString();
array_push($filters, [$yesterday, $end]);
break;
case 'custom_date':
$start = Carbon::parse($request->start_date)->startOfDay()->toDateTimeString();
$end = Carbon::parse($request->start_date)->endOfDay()->toDateTimeString();
array_push($filters, [$start, $end]);
break;
case 'custom_date_range':
$start = Carbon::parse($request->start_date)->startOfDay()->toDateTimeString();
$end = Carbon::parse($request->end_date)->endOfDay()->toDateTimeString();
array_push($filters, [$start, $end]);
break;
default:
# code...
break;
}
} else{
$today = Carbon::today()->startOfDay()->toDateString();
$end = Carbon::parse($today)->endOfDay()->toDateTimeString();
array_push($filters, [$today, $end]);
}
$reconciled_stocks = SundryStoreStockReconciliation::groupBy("stock_count_identifier")->whereBetween('created_at', $filters)->orderBy('stock_count_identifier', 'desc')->get();
$route='stores.sundries_stock_reconciliation_report_details';
$title='stores.sundries_stock_reconciliation_report';
$route_filter='stores.sundries_stock_reconciliation_report';
return view('stores::stores.sundries_stock_reconciliation_report', compact('reconciled_stocks','route','route_filter','title'));
}
/* stock reconciliation report details */
public function sundries_stock_reconciliation_report_details(Request $request)
{
$sundries_reconciled = SundryStoreStockReconciliation::where(['stock_count_identifier' => $request->stock_count_identifier])->get();
return view('stores::stores.sundries_stock_reconciliation_report_details', compact('sundries_reconciled'));
}
//GENERAL ITEMS
/* update stock sheet */
public function update_general_items_stock_sheet(Request $request)
{
$general_items_ids = $request->general_item_id;
$quantity = $request->quantity;
$expired_dates = $request->expiry_date;
for ($x = 0; $x < count($general_items_ids); $x++) :
$general_item = GeneralItem::find($general_items_ids[$x]);
$general_item->store_stock = $quantity[$x];
$general_item->expiry_date = $expired_dates[$x];
$update_store_stock = $general_item->update();
endfor;
if ($update_store_stock) :
flash('General Items Store Stock Levels Updated')->success();
return redirect('general_items_stock_sheet');
endif;
flash('Sorry, unable to update stock')->error();
return redirect()->back();
}
public function general_items_physical_stock_count()
{
//check if there is a physical count that wasn't completed and alert the user otherwise allow the user go ahead with create new count
$ongoing_physical_count = GeneralItemStoreStockReconciliation::where('completion_status', 0)->get();
if (count($ongoing_physical_count) > 0) {
flash('There is an ongoing physical count. You can not start a new count, please resume previous count')->error();
return redirect()->back();
}
$general_items = DB::table('general_items')->whereNull('deleted_at')->orderBy('name', 'asc')->get();
if (count($general_items) < 1) {
flash()->error("There is no general items in stock");
return redirect('general_items');
} else {
$chart_of_accounts = ChartOfAccount::orderBy('name', 'asc')->pluck('name', 'id')->toArray();
$chart_of_accounts = ['' => '- select -'] + $chart_of_accounts;
$general_items_dropdown = DB::table('general_items')->whereNull('deleted_at')->orderBy('name', 'asc')->pluck('name','id')->prepend('All drugs', 'all_items')->toArray();
return view('stores::stores.general_items_physical_stock_count', compact('general_items', 'chart_of_accounts', 'general_items_dropdown'));
}
}
/* handle updating general items physical stock count */
public function update_general_items_physical_stock_count(Request $request)
{
$batch_quotation_ids_array = $request->batch_quotation_id;
$batch_general_item_ids_array = (isset($request->batch_general_item_id) && is_array($request->batch_general_item_id)) ? $request->batch_general_item_id : [];
$unique_sundry_ids_with_batches_array = array_unique($batch_general_item_ids_array);
$batch_numbers_array = $request->batch_number;
$batch_unit_cost_array = $request->batch_unit_cost;
$batch_quantity_balances_array = $request->batch_quantity_balance;
$batch_expiry_dates_array = $request->expiry_date;
$batch_db_record_ids_array = $request->batch_db_record_id;
$general_items_ids_array = $request->general_item_id;
$system_stock_array = $request->system_stock;
$physical_stock_array = $request->physical_stock;
$cost_price_array = $request->cost_price;
$difference_array = $request->difference;
$shrinkage_array = $request->shrinkage;
$markup_array = $request->mark_up;
$reason_for_difference_array = $request->reason_for_difference;
//get the max identifier
$stock_adjustment_chart_of_account = ChartOfAccount::where('slug', 'stock_adjustment')->first();
$affected_account_id = $stock_adjustment_chart_of_account->id;
$opening_inventory_chart_of_account = ChartOfAccount::where('slug', 'opening_inventory')->first();
$general_items_with_initial_stock_array = is_null($request->is_initial_stock) ? [] : $request->is_initial_stock;
$affected_account_id = $request->account_id;
$reconcile_drug_store_stock = true;
$max_stock_count_identifier = DB::table('general_item_store_stock_reconciliations')->max('stock_count_identifier');
//update batch tracking tables with reconciliations
for ($i=0; $i < count($batch_numbers_array) ; $i++) {
if (!is_null($batch_numbers_array[$i]) && !is_null($batch_quantity_balances_array[$i])) {
//enforce double entry per batch
if (in_array($batch_general_item_ids_array[$i], $general_items_with_initial_stock_array)) {
$affected_account_id = $opening_inventory_chart_of_account->id;//overide adjustment a/c to be opening_inv
} else{
$affected_account_id = $stock_adjustment_chart_of_account->id;
}
account_for_batch_reconciliations_difference($item_type = 6, $batch_general_item_ids_array[$i], $affected_account_id, $batch_numbers_array[$i], $batch_quantity_balances_array[$i], $request->reconciliation_date, "store", $ward_id = null);
reconcile_batches($item_type = 6, $batch_general_item_ids_array[$i], $batch_numbers_array[$i], $batch_quantity_balances_array[$i], $batch_expiry_dates_array[$i], "store", $batch_unit_cost_array[$i]??0, $batch_db_record_ids_array[$i]??0, $ward_id=null);
}
}
if (isset($request->reconcile_stock)) {
for ($x = 0; $x < count($general_items_ids_array); $x++) :
/* check if the difference value is not null and then update the drug */
if (!is_null($difference_array[$x])) {
$physical_stock = new GeneralItemStoreStockReconciliation;
$physical_stock->general_item_id = $general_items_ids_array[$x];
$physical_stock->system_stock = $system_stock_array[$x];
$physical_stock->physical_stock = $physical_stock_array[$x];
$physical_stock->difference = $difference_array[$x];
//$physical_stock->shrinkage = $shrinkage_array[$x];
$physical_stock->mark_up = $markup_array[$x];
$physical_stock->reason_for_difference = $reason_for_difference_array[$x];
$physical_stock->completion_status = 1;
$physical_stock->affected_account_id = $affected_account_id;
$physical_stock->reconciliation_date = $request->reconciliation_date;
$physical_stock->created_by = Auth::id();
$physical_stock->save();
//add the stock_count_identifier of the newly counted stock
$physical_stock_record_to_update = GeneralItemStoreStockReconciliation::find($physical_stock->id);
$physical_stock_record_to_update->stock_count_identifier = $max_stock_count_identifier + 1; //increase ID by 1 for new
$physical_stock_record_to_update->update();
//update the system stock levels with the newly counted physical stock
//update only those with new physical value
$general_item = GeneralItem::find($general_items_ids_array[$x]);
$general_item->store_stock = $physical_stock_array[$x];
if (in_array($general_item->id, $general_items_with_initial_stock_array)) {
$general_item->opening_stock = $physical_stock_array[$x];
$general_item->opening_cost_price = $cost_price_array[$x];
}
$general_item->updated_by = Auth::id();
$reconcile_drug_store_stock = $general_item->update();
}
endfor;
/*==== do this to cater for the newer introduced editing batch number ======*/
if (track_items_using_batches()) :
for ($i = 0; $i < count($batch_general_item_ids_array); $i++) :
if (!is_null($batch_general_item_ids_array[$i]) && $batch_general_item_ids_array[$i] != "") {
if ($batch_quotation_ids_array[$i] != '0') {
$quotation_record = Quotation::where(['drug_id' => $batch_general_item_ids_array[$i], 'batch_number' => $batch_numbers_array[$i], 'quotation_type_id' => 6])->first();
if (!is_null($quotation_record)) {
$quotation_record->batch_balance = $batch_quantity_balances_array[$i];
$quotation_record->update();
}
} elseif ($batch_quantity_balances_array[$i] != null && $batch_numbers_array[$i] != null && $batch_quotation_ids_array[$i] == '0') {
//assume that this batch doesnt have a corresponding quotation so make one
$new_quotation = new Quotation;
$new_quotation->quotation_type_id = 6;
$new_quotation->drug_id = $batch_general_item_ids_array[$i];
$new_quotation->quantity = $batch_quantity_balances_array[$i];
$new_quotation->expected_date = date('Y-m-d');
$new_quotation->quotation_user = Auth::id();
$new_quotation->quotation_date = date('Y-m-d');
$new_quotation->billing_date = Carbon::now();
$new_quotation->billing_user = Auth::id();
$new_quotation->approval_date = Carbon::now();
$new_quotation->approval_status = 1;
$new_quotation->approval_user = Auth::id();
$new_quotation->receive_user = Auth::id();
$new_quotation->receive_date = date('Y-m-d');
$new_quotation->receive_status = 1;
$new_quotation->expiry_date = $batch_expiry_dates_array[$i];
$new_quotation->batch_number = $batch_numbers_array[$i];
$new_quotation->batch_balance = $batch_quantity_balances_array[$i];
$new_quotation->directly_received_items = 1;
$new_quotation->created_by = Auth::id();
$new_quotation->save();
}
}
endfor;
foreach ($unique_sundry_ids_with_batches_array as $batch_sundry) {
$all_batch_balances_for_general_item = Quotation::where(['drug_id' => $batch_sundry, 'quotation_type_id' => 6])->where('batch_balance', '>', 0)->sum('batch_balance');
if ($all_batch_balances_for_general_item > 0) {
$general_item_record = GeneralItem::withTrashed()->find($batch_sundry);
$general_item_record->store_stock = $all_batch_balances_for_general_item;
$general_item_record->update();
}
}
endif;
/*=========== end the catering for the newer introduced batch number ===========*/
if ($reconcile_drug_store_stock) :
flash('Stock levels have been reconciled')->success();
return redirect('general_items_stock_sheet');
endif;
} else if (isset($request->save_stock)) {
//save these for editing later on
for ($x = 0; $x < count($general_items_ids_array); $x++) :
$physical_stock = new GeneralItemStoreStockReconciliation;
$physical_stock->sundry_id = $general_items_ids_array[$x];
$physical_stock->system_stock = $system_stock_array[$x];
$physical_stock->physical_stock = $physical_stock_array[$x];
$physical_stock->difference = $difference_array[$x];
//$physical_stock->shrinkage = $shrinkage_array[$x];
$physical_stock->mark_up = $markup_array[$x];
$physical_stock->reason_for_difference = $reason_for_difference_array[$x];
$physical_stock->completion_status = 0;
$physical_stock->created_by = Auth::id();
$saved_physical_stock = $physical_stock->save();
//add stock_count_identifier that will be used in resuming edit
$physical_stock_record_to_that_will_be_updated = GeneralItemStoreStockReconciliation::find($physical_stock->id);
$physical_stock_record_to_that_will_be_updated->stock_count_identifier = $max_stock_count_identifier + 1; //increase ID by 1 for new
$physical_stock_record_to_that_will_be_updated->update();
endfor;
if ($saved_physical_stock) :
flash('Physical stock has been saved. You can resume later')->success();
return redirect('stores');
endif;
}
flash('Sorry, unable to update stock')->error();
return redirect()->back();
}
/* handle to resume general items physical stock count */
public function resume_general_items_physical_stock_count()
{
//check if there is a physical count that wasn't completed and alert the user otherwise allow the user go ahead with create new count
$stock_reconciliations = DB::table('general_item_store_stock_reconciliations')->where('completion_status', 0)->get();
if (count($stock_reconciliations) < 1) {
flash()->error("There is no ongoing physical sundries count");
return redirect('stores');
} else {
return view('stores::stores.resume_general_items_physical_stock_count', compact('stock_reconciliations'));
}
}
/* handle a resumed general items physical stock count */
public function complete_resumed_general_items_stock_count(Request $request)
{
$reconciliation_ids_array = $request->reconciliation_record_ids;
$general_items_ids_array = $request->sundry_id;
$system_stock_array = $request->system_stock;
$physical_stock_array = $request->physical_stock;
$difference_array = $request->difference;
$shrinkage_array = $request->shrinkage;
$markup_array = $request->mark_up;
$reason_for_difference_array = $request->reason_for_difference;
for ($x = 0; $x < count($reconciliation_ids_array); $x++) {
$physical_stock = SundryStoreStockReconciliation::find($reconciliation_ids_array[$x]);
$physical_stock->sundry_id = $general_items_ids_array[$x];
$physical_stock->system_stock = $system_stock_array[$x];
$physical_stock->physical_stock = $physical_stock_array[$x];
$physical_stock->difference = $difference_array[$x];
$physical_stock->shrinkage = $shrinkage_array[$x];
$physical_stock->mark_up = $markup_array[$x];
$physical_stock->reason_for_difference = $reason_for_difference_array[$x];
$physical_stock->completion_status = isset($request->reconcile_stock) ? 1 : 0;
if (isset($request->reconcile_stock_top)) {
$physical_stock->completion_status = 1;
}
if ($physical_stock->update()) {
//update the system stock levels with the newly counted physical stock
//update only those with new physical value
if (isset($general_items_ids_array[$x]) && !is_null($general_items_ids_array[$x]) && $general_items_ids_array[$x] != "") {
$general_item = GeneralItem::withTrashed()->find($general_items_ids_array[$x]);
$general_item->store_stock = $physical_stock_array[$x];
$general_item->updated_by = Auth::id();
$reconcile_drug_store_stock = $general_item->update();
}
}
}
flash('Stock levels details have been updated')->success();
return redirect('stores');
}
/* general_items stock reconciliation report */
public function general_items_stock_reconciliation_report(Request $request)
{
$reconciled_stocks = GeneralItemStoreStockReconciliation::groupBy("stock_count_identifier")->get();
return view('stores::stores.general_items_stock_reconciliation_report', compact('reconciled_stocks'));
}
/* general_items reconciliation report details */
public function general_items_stock_reconciliation_report_details(Request $request)
{
$var=false;
$general_items_reconciled = GeneralItemStoreStockReconciliation::where(['stock_count_identifier' => $request->stock_count_identifier])->get();
return view('stores::stores.general_items_stock_reconciliation_report_details', compact('general_items_reconciled','var'));
}
//END GENERAL ITEMS
public function select_receive_items_option(Request $request)
{
$quotation_type_options = DB::table('quotation_types')->pluck('name', 'id')->toArray();
$quotation_type_options = ['' => '- Select Quotation type -'] + $quotation_type_options;
$results = null;
return view('stores::stores.select_receive_items_option', compact('quotation_type_options'));
}
public function receive_items_directly(Request $request)
{
$package_units = DB::table('package_units')->whereNull('deleted_at')->orderBy('name')->pluck('name', 'id')->toArray();
$package_units = ['' => '- select -'] + $package_units;
$quotation_type_options = DB::table('quotation_types')->pluck('name', 'id')->toArray();
$quotation_type_options = ['' => '- Select Quotation type -'] + $quotation_type_options;
$results = null;
$filters = [];
$quotation_type = $request->quotation_type;
$items = null;
$suppliers = DB::table('suppliers')->where('available', 1)->whereNull('deleted_at')->orderBy('name')->pluck('name', 'id')->toArray();
$suppliers = ['' => '- select -'] + $suppliers;
$quotation_types_array = DB::table('quotation_types')->pluck('name', 'id')->toArray();
//1-drug 2-sundry 3-dental 4-radiology 5-Lab
if ($quotation_type == 1) {
$items = Drug::where('available', 1)->orderby('name', 'asc')->paginate(50);
} elseif ($quotation_type == 2) {
$items = Sundry::whereNull('deleted_at')->orderBy('name', 'asc')->paginate(50);
} elseif ($quotation_type == 3) {
$items = Dental::whereNull('deleted_at')->orderBy('name', 'asc')->paginate(50);
} elseif ($quotation_type == 4) {
$items = Radiology::whereNull('deleted_at')->orderBy('name', 'asc')->paginate(50);
} elseif ($quotation_type == 5) {
$items = Lab::whereNull('deleted_at')->orderBy('name', 'asc')->paginate(50);
} elseif ($quotation_type == 6) {
$items = GeneralItem::whereNull('deleted_at')->orderBy('name', 'asc')->paginate(50);
} elseif ($quotation_type == 7) {
$items = EyeGlasses::whereNull('deleted_at')->orderBy('name', 'asc')->paginate(50);
}
$drugs = Drug::where('available', 1)->orderby('name')->pluck('name', 'id');
$sundries = Sundry::where('available', 1)->orderby('name')->pluck('name', 'id');
$dentals = Dental::orderBy('name')->pluck('name', 'id');
$radiologies = Radiology::orderBy('name')->pluck('name', 'id');
$labs = Lab::orderBy('name')->pluck('name', 'id');
$general_items = GeneralItem::orderBy('name')->pluck('name', 'id');
$optical_items = EyeGlasses::orderBy('name')->pluck('name', 'id');
return view('stores::stores.receive_items_directly', compact('items', 'quotation_type', 'suppliers', 'quotation_types_array', 'drugs', 'sundries', 'dentals', 'radiologies', 'labs', 'package_units', 'general_items', 'optical_items'));
}
public function store_received_items_directly(Request $request)
{
$validator = Validator::make($request->all(), [
'received_on_date' => 'required',
'supplier' => 'required'
]);
if ($validator->fails()) {
$string = "";
foreach ($validator->errors()->getMessages() as $item) {
$string .= "{$item[0]}<br>";
}
flash('please ensure you have filled in the received date and batch number')->error();
return redirect('receive_items_directly');
} else {
/* =============== */
//check if the items have required values to complete double entry before proceeding
if ($request->item_type == 3 || $request->item_type == 4 || $request->item_type == 5) {
for ($i=0; $i < count($request->item_id) ; $i++) {
if (($request->item_type == 3) && get_name($request->item_id[$i], "id", "expenses_account_id", "dentals") == null) {
flash("Please make sure that all dentals have expense accounts e.g ".get_name($request->item_id[$i], "id", "name", "dentals"))->error();
return redirect('select_receive_items_option');
}
if (($request->item_type == 4) && get_name($request->item_id[$i], "id", "expenses_account_id", "radiologies") == null) {
flash("Please make sure that all radiologies have expense accounts e.g ".get_name($request->item_id[$i], "id", "name", "radiologies"))->error();
return redirect('select_receive_items_option');
}
if (($request->item_type == 5) && get_name($request->item_id[$i], "id", "expenses_account_id", "labs") == null) {
flash("Please make sure that all labs have expense accountse.g ".get_name($request->item_id[$i], "id", "name", "labs"))->error();
return redirect('select_receive_items_option');
}
if (($request->item_type == 6) && get_name($request->item_id[$i], "id", "expenses_account_id", "general_items") == null) {
flash("Please make sure that all general items have expense accountse.g ".get_name($request->item_id[$i], "id", "name", "general_items"))->error();
return redirect('select_receive_items_option');
}
}
}
/* =============== */
$package_unit_array = $request->package_unit;
$number_of_package_units_array = $request->number_of_package_units;
$quantity_per_package_unit_array = $request->quantity_per_package_unit;
$bill_per_package_unit_array = $request->bill_per_package_unit;
$item_id_array = $request->item_id;
$quantity_array = $request->quantity;
$expected_date = date('Y-m-d');
$supplier_id = $request->supplier;
$user_id = Auth::id();
$item_type = $request->item_type;
$quotation_date = Carbon::now();
$bill_array = $request->bill;
$receive_date = Carbon::createFromFormat('d/m/Y', $request->received_on_date)->toDateString();
$expiry_date = $request->expiry_date;
$batch_numbers_array = $request->batch_number;
$total_price = 0;
$results = DB::select("select max(quotation_number) quotation_number from quotations limit 1");
$current_quotation_number = 0;
foreach ($results as $result) {
$current_quotation_number = $result->quotation_number + 1;
}
//get next grn_number
$new_grn_number = Quotation::where('quotation_number', $current_quotation_number)->max('grn_number');
if (is_null($new_grn_number)) {
$new_grn_number = (float)$current_quotation_number +0.1;
} else {
$new_grn_number = (float)$new_grn_number + 0.1;
}
//$non_zero_count = count(array_filter($quantity_array, "nonzero")); generating an error for but to be reviewed
$non_zero_count = count($quantity_array);
$expected_last_quotation_number = $current_quotation_number + $non_zero_count;
$old_quantity = 0;
$new_quantity = 0;
for ($x = 0; $x < count($item_id_array); $x++) :
//Expiry date of the drugs
$expiry_date_for_each = isset($expiry_date[$x]) ? Carbon::createFromFormat('d/m/Y', $expiry_date[$x])->toDateString() : "";
// Updating the total price incase it has changed
//$total_price = $bill_array[$x] * $quantity_array[$x];
$total_price = $number_of_package_units_array[$x] * $bill_per_package_unit_array[$x];
$eloquent_model = new Quotation;
$eloquent_model->quotation_type_id = $item_type;
$eloquent_model->drug_id = $item_id_array[$x];
$eloquent_model->package_unit = $package_unit_array[$x];
$eloquent_model->number_of_package_units = $number_of_package_units_array[$x];
$eloquent_model->quantity_per_package_unit = $quantity_per_package_unit_array[$x];
$eloquent_model->bill_per_package_unit = $bill_per_package_unit_array[$x];
$eloquent_model->quantity = $quantity_array[$x];
$eloquent_model->expected_date = $expected_date;
$eloquent_model->quotation_user = $user_id;
$eloquent_model->quotation_number = $current_quotation_number;
$eloquent_model->quotation_date = $quotation_date;
$eloquent_model->supplier_id = $supplier_id;
$eloquent_model->bill = $bill_array[$x];
$eloquent_model->billing_date = Carbon::now();
$eloquent_model->billing_user = Auth::id();
$eloquent_model->approval_date = Carbon::now();
$eloquent_model->approval_status = 1;
$eloquent_model->approval_user = Auth::id();
$eloquent_model->receive_user = Auth::id();
$eloquent_model->receive_date = $receive_date;
$eloquent_model->receive_status = 1;
$eloquent_model->grn_number=$new_grn_number;
$eloquent_model->receive_number_of_package_units = $number_of_package_units_array[$x];
$eloquent_model->receive_quantity_per_package_unit = $quantity_per_package_unit_array[$x];
$eloquent_model->receive_bill_per_package_unit = $bill_per_package_unit_array[$x];
$eloquent_model->receive_quantity = $quantity_array[$x];
$eloquent_model->receive_bill = $bill_array[$x];
$eloquent_model->receiver_comment = $request->receiver_comment;
$eloquent_model->total_price = $total_price;
$eloquent_model->expiry_date = $expiry_date_for_each;
$eloquent_model->batch_number = $batch_numbers_array[$x];
$eloquent_model->batch_balance = $quantity_array[$x];
$eloquent_model->directly_received_items = 1;
if ($request->has('store_submit_button')) {
$eloquent_model->destination = 'store';
create_batch_watcher_record($item_id_array[$x], $item_type, $bill_array[$x],$batch_numbers_array[$x], $quantity_array[$x], $pharmacy_stock = 0,$lab_stock=0, $expiry_date_for_each);
} else if ($request->has('pharmacy_submit_button')) {
$eloquent_model->destination = 'pharmacy';
create_batch_watcher_record($item_id_array[$x], $item_type, $bill_array[$x],$batch_numbers_array[$x], $store_stock = 0, $quantity_array[$x],$lab_stock=0, $expiry_date_for_each);
} elseif ($request->has('lab_submit_button')) {
$eloquent_model->destination = 'lab';
create_batch_watcher_record($item_id_array[$x], $item_type, $bill_array[$x],$batch_numbers_array[$x],$store_stock=0 , $pharmacy_stock = 0,$quantity_array[$x], $expiry_date_for_each);
}elseif ($request->has('radiology_submit_button'))
{
$eloquent_model->destination = 'Imaging';
create_batch_watcher_record($item_id_array[$x], $item_type, $bill_array[$x], $batch_numbers_array[$x], $store_stock=0, $pharmacy_stock = 0, $quantity_array[$x], $expiry_date_for_each);
}
$eloquent_model->created_by = Auth::id();
if ($eloquent_model->save()) {
// Increasing the stock level in necessary inventory tables i.e //1-drug,2-sundry,3-dental,4-radiology 5-Lab
//check for the quotation_type_id then know what table to use in getting $old_quantity
$store_item = null;
$drug_id = $item_id_array[$x];
$quantity_to_add = $quantity_array[$x];
//do the necessary stock additions depending on which button has been clicked on the form
if ($request->has('store_submit_button')) {
if ($item_type == 1) {
$old_quantity = get_name($drug_id, "id", "store_stock", "drugs");
if ($old_quantity == "N/A") {
$old_quantity = 0;
};
$new_quantity = $old_quantity + (int)$quantity_to_add;
$store_item = Drug::find($drug_id);
if (!is_null($store_item)) {
$store_item->store_stock = $new_quantity;
$store_item->expiry_date = $expiry_date_for_each;
save_new_cost_of_good($drug_id, $item_type, $bill_array[$x]);
}
} elseif ($item_type == 2) {
$old_quantity = get_name($drug_id, "id", "store_stock", "sundries");
$new_quantity = $old_quantity + (int)$quantity_to_add;
$store_item = Sundry::find($drug_id);
if (!is_null($store_item)) {
$store_item->store_stock = $new_quantity;
$store_item->expiry_date = $expiry_date_for_each;
save_new_cost_of_good($drug_id, $item_type, $bill_array[$x]);
}
} elseif ($item_type == 3) {
$old_quantity = get_name($drug_id, "id", "store_stock", "dentals");
$new_quantity = $old_quantity + (int)$quantity_to_add;
$store_item = Dental::find($drug_id);
if (!is_null($store_item)) {
$store_item->store_stock = $new_quantity;
$store_item->expiry_date = $expiry_date_for_each;
save_new_cost_of_good($drug_id, $item_type, $bill_array[$x]);
}
} elseif ($item_type == 4) {
$old_quantity = get_name($drug_id, "id", "store_stock", "radiologies");
$new_quantity = $old_quantity + (int)$quantity_to_add;
$store_item = Radiology::find($drug_id);
if (!is_null($store_item)) {
$store_item->store_stock = $new_quantity;
$store_item->expiry_date = $expiry_date_for_each;
save_new_cost_of_good($drug_id, $item_type, $bill_array[$x]);
}
} elseif ($item_type == 5) {
$old_quantity = get_name($drug_id, "id", "store_stock", "labs");
$new_quantity = $old_quantity + (int)$quantity_to_add;
$store_item = Lab::find($drug_id);
if (!is_null($store_item)) {
$store_item->store_stock = $new_quantity;
$store_item->expiry_date = $expiry_date_for_each;
save_new_cost_of_good($drug_id, $item_type, $bill_array[$x]);
}
} elseif ($item_type == 6) {
$old_quantity = get_name($drug_id, "id", "store_stock", "general_items");
$new_quantity = $old_quantity + (int)$quantity_to_add;
$store_item = GeneralItem::find($drug_id);
if (!is_null($store_item)) {
$store_item->store_stock = $new_quantity;
$store_item->expiry_date = $expiry_date_for_each;
save_new_cost_of_good($drug_id, $item_type, $bill_array[$x]);
}
} elseif ($item_type == 7) {
$old_quantity = get_name($drug_id, "id", "store_stock", "eye_glasses");
$new_quantity = $old_quantity + (int)$quantity_to_add;
$store_item = EyeGlasses::find($drug_id);
if (!is_null($store_item)) {
$store_item->store_stock = $new_quantity;
$store_item->expiry_date = $expiry_date_for_each;
save_new_cost_of_good($drug_id, $item_type, $bill_array[$x]);
}
}
} else if ($request->has('pharmacy_submit_button')) {
if ($item_type == 1) {
$old_quantity = get_name($drug_id, "id", "pharmacy_stock", "drugs");
if ($old_quantity == "N/A") {
$old_quantity = 0;
};
$new_quantity = $old_quantity + (int)$quantity_to_add;
$store_item = Drug::find($drug_id);
if (!is_null($store_item)) {
$store_item->pharmacy_stock = $new_quantity;
$store_item->expiry_date = $expiry_date_for_each;
save_new_cost_of_good($drug_id, $item_type, $bill_array[$x]);
}
} elseif ($item_type == 2) {
$old_quantity = get_name($drug_id, "id", "pharmacy_stock", "sundries");
$new_quantity = $old_quantity + (int)$quantity_to_add;
$store_item = Sundry::find($drug_id);
if (!is_null($store_item)) {
$store_item->pharmacy_stock = $new_quantity;
$store_item->expiry_date = $expiry_date_for_each;
save_new_cost_of_good($drug_id, $item_type, $bill_array[$x]);
}
} elseif ($item_type == 3) {
$old_quantity = get_name($drug_id, "id", "pharmacy_stock", "dentals");
$new_quantity = $old_quantity + (int)$quantity_to_add;
$store_item = Dental::find($drug_id);
if (!is_null($store_item)) {
$store_item->pharmacy_stock = $new_quantity;
$store_item->expiry_date = $expiry_date_for_each;
save_new_cost_of_good($drug_id, $item_type, $bill_array[$x]);
}
} elseif ($item_type == 4) {
$old_quantity = get_name($drug_id, "id", "pharmacy_stock", "radiologies");
$new_quantity = $old_quantity + (int)$quantity_to_add;
$store_item = Radiology::find($drug_id);
if (!is_null($store_item)) {
$store_item->pharmacy_stock = $new_quantity;
$store_item->expiry_date = $expiry_date_for_each;
save_new_cost_of_good($drug_id, $item_type, $bill_array[$x]);
}
} elseif ($item_type == 5) {
$old_quantity = get_name($drug_id, "id", "pharmacy_stock", "labs");
$new_quantity = $old_quantity + (int)$quantity_to_add;
$store_item = Lab::find($drug_id);
if (!is_null($store_item)) {
$store_item->pharmacy_stock = $new_quantity;
$store_item->expiry_date = $expiry_date_for_each;
save_new_cost_of_good($drug_id, $item_type, $bill_array[$x]);
}
} elseif ($item_type == 6) {
$old_quantity = get_name($drug_id, "id", "pharmacy_stock", "general_items");
$new_quantity = $old_quantity + (int)$quantity_to_add;
$store_item = GeneralItem::find($drug_id);
if (!is_null($store_item)) {
$store_item->pharmacy_stock = $new_quantity;
$store_item->expiry_date = $expiry_date_for_each;
save_new_cost_of_good($drug_id, $item_type, $bill_array[$x]);
}
} elseif ($item_type == 7) {
$old_quantity = get_name($drug_id, "id", "pharmacy_stock", "eye_glasses");
$new_quantity = $old_quantity + (int)$quantity_to_add;
$store_item = EyeGlasses::find($drug_id);
if (!is_null($store_item)) {
$store_item->pharmacy_stock = $new_quantity;
$store_item->expiry_date = $expiry_date_for_each;
save_new_cost_of_good($drug_id, $item_type, $bill_array[$x]);
}
}
} elseif ($request->has('lab_submit_button')) {
if ($item_type == 5) {
$old_quantity = get_name($drug_id, "id", "laboratory_stock", "labs");
$new_quantity = $old_quantity + (int)$quantity_to_add;
$store_item = Lab::find($drug_id);
if (!is_null($store_item)) {
$store_item->laboratory_stock = $new_quantity;
$store_item->expiry_date = $expiry_date_for_each;
save_new_cost_of_good($drug_id, $item_type, $bill_array[$x]);
}
}
}
if (!is_null($store_item)) {
$store_item->updated_at = Carbon::now();
$store_item->updated_by = Auth::id();
$store_item->update();
}
if ($old_quantity <= 0 && $new_quantity > 0) {
$query_stock_dates_results = DB::select("SELECT id FROM inventory_stock_dates WHERE item_id = $drug_id AND quotation_type_id = $item_type ORDER BY id DESC LIMIT 1");
$stock_id = isset($query_stock_dates_results[0]) ? $query_stock_dates_results[0]->id : 0;
if (count($query_stock_dates_results) != 0) {
$inventory_stock_date_model = InventoryStockDate::find($stock_id);
$inventory_stock_date_model->restock_date = $receive_date;
$inventory_stock_date_model->update();
}
}
}
endfor;
//immediately create inventory bill for the received items to enforce double entry
$this->auto_create_inventory_bill_or_expense($request, $current_quotation_number);
$last_quotation_id = $eloquent_model->id;
$new_quotation_number = get_name($last_quotation_id, "id", "quotation_number", "quotations");
flash('Stock Levels Updated ')->success();
return redirect('goods_received_note/' . $new_grn_number);
}
}
public function goods_received_note($quotation_number)
{
$hospital_details = HospitalInformation::first();
$quotation_items = Quotation::where(['grn_number' => $quotation_number])->get();
$quotations = Quotation::where(['grn_number' => $quotation_number])->first();
return view('stores::stores.goods_received_note', compact('hospital_details', 'quotation_items', 'quotations'));
}
public function goods_received_note_print($quotation_number)
{
$hospital_details = HospitalInformation::first();
$quotation_items = Quotation::where(['grn_number' => $quotation_number])->get();
$quotations = Quotation::where(['grn_number' => $quotation_number])->first();
$data = [
'hospitalInfo' => $hospital_details,
'quotation_items' => $quotation_items,
'quotations' => $quotations,
];
$pdf = SnappyPDF::loadView('stores::stores/goods_received_note_print', $data)
->setOrientation('portrait')
->setOption('margin-bottom', 7)
->setOption('margin-top', 5)
->setOption('footer-html', '<i>Stre@mline</i> '.streamline_date(date('Y-m-d')).' Printed By: '.get_full_name(Auth::id(), "id", "first_name", "last_name", "users").' '.streamline_date_time(date('Y-m-d H:m:i')));
return $pdf->inline('Goods Recieved Note' . date(" d-m-y h:ia") . '.pdf');
}
public function receive_items_directly_search(Request $request)
{
$package_units = DB::table('package_units')->whereNull('deleted_at')->orderBy('name')->pluck('name', 'id')->toArray();
$package_units = ['' => '- select -'] + $package_units;
$quotation_type = $request->quotation_type;
$item_ids_array = $request->items_ids;
$quotation_type_options = DB::table('quotation_types')->pluck('name', 'id')->toArray();
$quotation_type_options = ['' => '- Select Quotation type -'] + $quotation_type_options;
$results = null;
$filters = [];
$items = null;
$suppliers = DB::table('suppliers')->where('available', 1)->whereNull('deleted_at')->orderBy('name')->pluck('name', 'id')->toArray();
$suppliers = ['' => '- select -'] + $suppliers;
$quotation_types_array = DB::table('quotation_types')->pluck('name', 'id')->toArray();
//1-drug 2-sundry 3-dental 4-radiology 5-Lab
if ($quotation_type == 1) {
$items = Drug::whereIn('id', $item_ids_array)->orderBy('name', 'asc')->get();
} elseif ($quotation_type == 2) {
$items = Sundry::whereIn('id', $item_ids_array)->whereNull('deleted_at')->orderBy('name', 'asc')->get();
} elseif ($quotation_type == 3) {
$items = Dental::whereIn('id', $item_ids_array)->orderBy('name', 'asc')->get();
} elseif ($quotation_type == 4) {
$items = Radiology::whereIn('id', $item_ids_array)->orderBy('name', 'asc')->get();
} elseif ($quotation_type == 5) {
$items = Lab::whereIn('id', $item_ids_array)->orderBy('name', 'asc')->get();
} elseif ($quotation_type == 6) {
$items = GeneralItem::whereIn('id', $item_ids_array)->orderBy('name', 'asc')->get();
} elseif ($quotation_type == 7) {
$items = EyeGlasses::whereIn('id', $item_ids_array)->orderBy('name', 'asc')->get();
}
$drugs = Drug::where('available', 1)->orderby('name')->pluck('name', 'id');
$sundries = Sundry::where('available', 1)->orderby('name')->pluck('name', 'id');
$dentals = Dental::orderBy('name')->pluck('name', 'id');
$radiologies = Radiology::orderBy('name')->pluck('name', 'id');
$labs = Lab::orderBy('name')->pluck('name', 'id');
$general_items = GeneralItem::orderBy('name')->pluck('name', 'id');
$optical_items = EyeGlasses::orderBy('name')->pluck('name', 'id');
return view('stores::stores.receive_items_directly', compact('items', 'quotation_type', 'suppliers', 'quotation_types_array', 'drugs', 'sundries', 'dentals', 'radiologies', 'labs', 'package_units', 'general_items', 'optical_items'));
}
/* labs stock sheet */
public function labs_stock_sheet(Request $request)
{
$labs = DB::table('labs')->whereNull('deleted_at')->orderBy('name', 'asc')->get();
// getting the lab store stock batches
$labs= calculate_stock_value($labs,5,'store_stock');
$total_cost_value = 0;
foreach($labs as $key => $lab){
$total_cost_value += $lab->item_cost_value;
}
if (count($labs) < 1) {
flash()->error("There is no out of stock labs");
return redirect('/labs/');
} else {
return view('stores::stores.labs_stock_sheet', compact('labs','total_cost_value'));
}
}
/*radiology stock sheet */
public function radiology_stock_sheet(Request $request){
$radiologies = DB::table('radiologies')->whereNull('deleted_at')->orderBy('name', 'asc')->get();
// getting the radiology stock batches
$radiologies= calculate_stock_value($radiologies,4,'store_stock');
$total_cost_value = 0;
foreach($radiologies as $key => $radiology){
$total_cost_value += $radiology->item_cost_value;
}
if (count($radiologies) < 1) {
flash()->error("There is no out of stock radiologies");
return redirect('/radiology/');
} else {
return view('stores::stores.radiology_stock_sheet', compact('radiologies','total_cost_value'));
}
}
/* general items stock sheet*/
/* general items stock sheet */
public function general_items_stock_sheet()
{
$general_items = DB::table('general_items')->whereNull('deleted_at')->orderBy('name', 'asc')->get();
if (count($general_items) < 1) {
flash()->error("There is no out of stock sundries");
return redirect('/general_items/');
} else {
return view('stores::stores.general_items_stock_sheet', compact('general_items'));
}
}
public function request_a_quotation_search(Request $request)
{
$quotation_type = $request->quotation_type;
$item_ids_array = $request->items_ids;
$is_all_items = in_array("all_items", $item_ids_array);
$amc_period = $request->amc_period;
$quotation_type_options = DB::table('quotation_types')->pluck('name', 'id')->toArray();
$quotation_type_options = ['' => '- Select Quotation type -'] + $quotation_type_options;
$results = null;
$filters = [];
$items = null;
$suppliers = DB::table('suppliers')->where('available', 1)->whereNull('deleted_at')->orderBy('name')->pluck('name', 'id')->toArray();
$suppliers = ['' => '- select -'] + $suppliers;
$quotation_types_array = DB::table('quotation_types')->pluck('name', 'id')->toArray();
//1-drug 2-sundry 3-dental 4-radiology 5-Lab
if ($quotation_type == 1) {
if ($is_all_items) {
$items = Drug::where('available', 1)->orderby('name', 'asc')->get();
} else{
$items = Drug::whereIn('id', $item_ids_array)->orderBy('name', 'asc')->get();
}
} elseif ($quotation_type == 2) {
if ($is_all_items) {
$items = Sundry::where('available', 1)->orderby('name', 'asc')->get();
} else{
$items = Sundry::whereIn('id', $item_ids_array)->orderBy('name', 'asc')->get();
}
} elseif ($quotation_type == 3) {
if ($is_all_items) {
$items = Dental::orderBy('name', 'asc')->get();
} else {
$items = Dental::whereIn('id', $item_ids_array)->orderBy('name', 'asc')->get();
}
} elseif ($quotation_type == 4) {
if ($is_all_items) {
$items = Radiology::orderBy('name', 'asc')->get();
} else{
$items = Radiology::whereIn('id', $item_ids_array)->orderBy('name', 'asc')->get();
}
} elseif ($quotation_type == 5) {
if ($is_all_items) {
$items = Lab::orderBy('name', 'asc')->get();
} else {
$items = Lab::whereIn('id', $item_ids_array)->orderBy('name', 'asc')->get();
}
} elseif ($quotation_type == 6) {
if ($is_all_items) {
$items = GeneralItem::orderBy('name', 'asc')->get();
} else {
$items = GeneralItem::whereIn('id', $item_ids_array)->orderBy('name', 'asc')->get();
}
} elseif ($quotation_type == 7) {
if ($is_all_items) {
$items = EyeGlasses::whereNull('deleted_at')->orderBy('name', 'asc')->get();
} else {
$items = EyeGlasses::whereIn('id', $item_ids_array)->whereNull('deleted_at')->orderBy('name', 'asc')->get();
}
}
$drugs = Drug::where('available', 1)->orderby('name')->pluck('name', 'id');
$sundries = Sundry::where('available', 1)->orderby('name')->pluck('name', 'id');
$dentals = Dental::orderBy('name')->pluck('name', 'id');
$radiologies = Radiology::orderBy('name')->pluck('name', 'id');
$labs = Lab::orderBy('name')->pluck('name', 'id');
$general_items = GeneralItem::orderBy('name')->pluck('name', 'id');
$opticals = EyeGlasses::orderBy('name')->pluck('name', 'id');
$suppliers = DB::table('suppliers')->where('available', 1)->whereNull('deleted_at')->orderBy('name')->pluck('name', 'id')->toArray();
$quotation_types_array = DB::table('quotation_types')->pluck('name', 'id')->toArray();
$package_units = DB::table('package_units')->whereNull('deleted_at')->orderBy('name')->pluck('name', 'id')->toArray();
$package_units = ['' => '- select -'] + $package_units;
return view('stores::stores.request_quotation', compact('items', 'quotation_type', 'suppliers', 'quotation_types_array', 'package_units', 'drugs', 'sundries', 'dentals', 'radiologies', 'labs', 'general_items', 'amc_period', 'opticals'));
}
public function lab_requisition_for_sundries(Request $request)
{
$quotation_type_options = DB::table('quotation_types')->pluck('name', 'id')->toArray();
$quotation_type_options = ['' => '- Select Requisition type -'] + $quotation_type_options;
$names_array = [];
$item_type = 2; //1-drug 2-sundry 3-dental 4-radiology 5-Lab
$item_ids_array = $request->item_name;
if (is_null($item_ids_array)) {
$item_ids_array = [];
}
if ($item_type == 1) {
$results = Drug::whereIn('id', $item_ids_array)->orderBy('name', 'asc')->get();
$names_array = Drug::where('available', 1)->orderby('name')->distinct()->pluck('name', 'id');
} elseif ($item_type == 2) {
$results = Sundry::whereIn('id', $item_ids_array)->orderBy('name', 'asc')->get();
$names_array = Sundry::where('available', 1)->orderby('name')->distinct()->pluck('name', 'id');
} elseif ($item_type == 3) {
$results = Dental::whereIn('id', $item_ids_array)->whereIn('id', $item_ids_array)->orderBy('name', 'asc')->get();
$names_array = Dental::orderBy('name')->distinct()->pluck('name', 'id');
} elseif ($item_type == 4) {
$results = Radiology::whereIn('id', $item_ids_array)->orderBy('name', 'asc')->get();
$names_array = Radiology::orderBy('name')->distinct()->pluck('name', 'id');
} elseif ($item_type == 5) {
$results = Lab::whereIn('id', $item_ids_array)->orderBy('name', 'asc')->get();
$names_array = Lab::orderBy('name')->distinct()->pluck('name', 'id');
} elseif ($item_type == 6) {
$results = GeneralItem::whereIn('id', $item_ids_array)->orderBy('name', 'asc')->get();
$names_array = GeneralItem::orderBy('name')->distinct()->pluck('name', 'id');
}
return view('stores::stores.labs_sundries_requisition', compact('quotation_type_options', 'results', 'item_type', 'names_array'));
}
public function radiology_requisition_for_sundries(Request $request){
$quotation_type_options = DB::table('quotation_types')->pluck('name', 'id')->toArray();
$quotation_type_options = ['' => '- Select Requisition type -'] + $quotation_type_options;
$names_array = [];
$item_type = 2; //1-drug 2-sundry 3-dental 4-radiology 5-Lab
$item_ids_array = $request->item_name;
if (is_null($item_ids_array)) {
$item_ids_array = [];
}
if ($item_type == 2) {
$results = Sundry::whereIn('id', $item_ids_array)->orderBy('name', 'asc')->get();
$names_array = Sundry::where('available', 1)->orderby('name')->distinct()->pluck('name', 'id');
}
return view('stores::stores.radiology_sundries_requisition', compact('quotation_type_options', 'results', 'item_type', 'names_array'));
}
public function store_radiology_requisition_for_sundries(Request $request){
$item_id_array = $request->item_id;
$quantity_array = $request->quantity;
$item_type = $request->item_type;
$user_id = Auth::id();
/* return back if no quantity has been filled */
if (array_sum($quantity_array) < 1) {
flash('Please insert some values!')->error();
return redirect()->back();
}
$filtered_items_array = [];
$filtered_quantities_array = [];
$associative_requested_items_array = [];
for ($i = 0; $i < count($item_id_array); $i++) {
if ($quantity_array[$i] != "") {
$associative_requested_items_array[$item_id_array[$i]] = $quantity_array[$i];
$filtered_items_array[] = $item_id_array[$i];
$filtered_quantities_array[] = $quantity_array[$i];
}
}
$new_requisition = new Requisition;
$new_requisition->quotation_type_id = $item_type;
$new_requisition->drug_id = implode(',', $filtered_items_array);
$new_requisition->quantity_requested = implode(',', $filtered_quantities_array);
$new_requisition->requisition_origin = 3; //1-pharmacy, 2-lab ,3 radiologies
$new_requisition->created_by = $user_id;
$new_requisition->save();
flash('Requisition number ' . $new_requisition->id . ' made successfully')->success();
return redirect('/print_requisition_receipt/' . $new_requisition->id);
}
public function store_lab_requisition_for_sundries(Request $request)
{
$item_id_array = $request->item_id;
$quantity_array = $request->quantity;
$item_type = $request->item_type;
$user_id = Auth::id();
/* return back if no quantity has been filled */
if (array_sum($quantity_array) < 1) {
flash('Please insert some values!')->error();
return redirect()->back();
}
$filtered_items_array = [];
$filtered_quantities_array = [];
$associative_requested_items_array = [];
for ($i = 0; $i < count($item_id_array); $i++) {
if ($quantity_array[$i] != "") {
$associative_requested_items_array[$item_id_array[$i]] = $quantity_array[$i];
$filtered_items_array[] = $item_id_array[$i];
$filtered_quantities_array[] = $quantity_array[$i];
}
}
$new_requisition = new Requisition;
$new_requisition->quotation_type_id = $item_type;
$new_requisition->drug_id = implode(',', $filtered_items_array);
$new_requisition->quantity_requested = implode(',', $filtered_quantities_array);
$new_requisition->requisition_origin = 2; //1-pharmacy, 2-lab ,3 radiologies
$new_requisition->created_by = $user_id;
$new_requisition->save();
flash('Requisition number ' . $new_requisition->id . ' made successfully')->success();
return redirect('/print_requisition_receipt/' . $new_requisition->id);
}
// Labs Sundries stock sheet
public function lab_sundries_stock_sheet(Request $request)
{
$sundries = DB::table('sundries')->whereNull('deleted_at')->orderBy('name', 'asc')->paginate(500);
if (empty($sundries)) {
flash()->error("There is out of stock of sundries");
return redirect('/sundries/');
} else {
return view('stores::stores.labs_sundries_stock_sheet', compact('sundries'));
}
}
//radiology sundries stock sheet
public function radiology_sundries_stock_sheet(Request $request){
$sundries = DB::table('sundries')->whereNull('deleted_at')->orderBy('name', 'asc')->paginate(500);
if (empty($sundries)) {
flash()->error("There is out of stock of sundries");
return redirect('/sundries/');
} else {
return view('stores::stores.radiology_sundries_stock_sheet', compact('sundries'));
}
}
public function delete_received_items($quotation_number)
{
$quotation_items = DB::table('quotations')
->where('quotation_number', $quotation_number)
->get(['drug_id', 'quantity', 'destination', 'quotation_type_id', 'batch_number']);
// reduce the amount from pharmacy or stores
foreach ($quotation_items as $item) {
if ($item->quotation_type_id == 1) {
$store_item = Drug::find($item->drug_id);
if ($store_item) {
if ($item->destination == "store") {
$store_item->store_stock = $store_item->store_stock - $item->quantity;
} else {
$store_item->pharmacy_stock = $store_item->pharmacy_stock - $item->quantity;
}
$store_item->save();
}
$item_batch_watcher = ItemBatchWatcher::where(['item_type'=>1, 'item_id'=>$item->drug_id, 'batch_number' => $item->batch_number])->delete();
} elseif ($item->quotation_type_id == 2) {
$store_item = Sundry::find($item->drug_id);
if ($store_item) {
if ($item->destination == "store") {
$store_item->store_stock = $store_item->store_stock - $item->quantity;
} else {
$store_item->pharmacy_stock = $store_item->pharmacy_stock - $item->quantity;
}
$store_item->save();
}
$item_batch_watcher = ItemBatchWatcher::where(['item_type'=>2, 'item_id'=>$item->drug_id, 'batch_number' => $item->batch_number])->delete();
} elseif ($item->quotation_type_id == 3) {
$store_item = Dental::find($item->drug_id);
if ($store_item) {
if ($item->destination == "store") {
$store_item->store_stock = $store_item->store_stock - $item->quantity;
} else {
$store_item->pharmacy_stock = $store_item->pharmacy_stock - $item->quantity;
}
$store_item->save();
}
} elseif ($item->quotation_type_id == 4) {
$store_item = Radiology::find($item->drug_id);
if ($store_item) {
if ($item->destination == "store") {
$store_item->store_stock = $store_item->store_stock - $item->quantity;
} else {
$store_item->pharmacy_stock = $store_item->pharmacy_stock - $item->quantity;
}
$store_item->save();
}
$item_batch_watcher = ItemBatchWatcher::where(['item_type'=>4, 'item_id'=>$item->drug_id, 'batch_number' => $item->batch_number])->delete();
} elseif ($item->quotation_type_id == 5) {
$store_item = Lab::find($item->drug_id);
if ($store_item) {
if ($item->destination == "store") {
$store_item->store_stock = $store_item->store_stock - $item->quantity;
} else {
$store_item->pharmacy_stock = $store_item->pharmacy_stock - $item->quantity;
}
$store_item->save();
}
$item_batch_watcher = ItemBatchWatcher::where(['item_type'=>5, 'item_id'=>$item->drug_id, 'batch_number' => $item->batch_number])->delete();
} elseif ($item->quotation_type_id == 7) {
$store_item = EyeGlasses::find($item->drug_id);
if ($store_item) {
if ($item->destination == "store") {
$store_item->store_stock = $store_item->store_stock - $item->quantity;
} else {
$store_item->pharmacy_stock = $store_item->pharmacy_stock - $item->quantity;
}
$store_item->save();
}
$item_batch_watcher = ItemBatchWatcher::where(['item_type'=>7, 'item_id'=>$item->drug_id, 'batch_number' => $item->batch_number])->delete();
}
}
//delete the attached bill
$bill_id = null;
$quotation_record = Quotation::where('quotation_number', $quotation_number)->first();
if ($quotation_record) {
$bill_id = $quotation_record->bill_id;
if ($bill_id) {
$hospital_bill = HospitalBill::find($bill_id);
$hospital_bill->delete();
}
}
$update = Quotation::where('quotation_number', $quotation_number)->delete();
flash("Previously received items have been deleted")->success();
return redirect('/previously_received_items/');
}
public function check_batch_balance(Request $request)
{
$quotation = ItemBatchWatcher::where(['item_id' => $request->drug_id, 'batch_number' => $request->batch_number])->first();
if ($quotation) {
if ($quotation->batch_balance > 0) {
return true;
}
return "This batch has no balance left";
}
return "No batch of this drug found";
}
public function attach_unattached_items_to_fake_system_batches()
{
//1. get stock value, check the quotation in use
//2. check batch balances of quotation and see if they equate to store stock
//3. if they don't, attach the remaning un accounted balance to fake system batch
$drugs = Drug::where('available', 1)->orderby('name', 'desc')->get();
foreach ($drugs as $drug) {
$drug_store_stock = $drug->store_stock;
//batch details on drugs table ======= batch_number_in_use, quotation_id_of_batch_in_use, balance_of_batch_in_use
$all_quotations_of_this_drug = Quotation::where(['drug_id' => $drug->id, 'quotation_type_id' => 1])->get();
$balance_on_drug_batches = 0;
foreach ($all_quotations_of_this_drug as $quotation) {
$balance_on_drug_batches += $quotation->batch_balance;
}
if ($drug_store_stock > $balance_on_drug_batches) {
$unattached_to_quotation_balance = $drug_store_stock - $balance_on_drug_batches;
$total_price = get_name($drug->id, "id", "cost_price", "drugs") * $balance_on_drug_batches;
//create system fake quotation
$new_quotation = new Quotation;
$new_quotation->quotation_type_id = 1;
$new_quotation->drug_id = $drug->id;
$new_quotation->quantity = $unattached_to_quotation_balance;
$new_quotation->expected_date = Carbon::now();
$new_quotation->quotation_user = Auth::id();
$new_quotation->quotation_number = 0;
$new_quotation->quotation_date = Carbon::now();
$new_quotation->receive_user = Auth::id();
$new_quotation->receive_date = Carbon::now();
$new_quotation->receive_status = 1;
$new_quotation->receiver_comment = "SYSTEM CREATED QUOTATION";
$new_quotation->total_price = $total_price;
$new_quotation->expiry_date = Carbon::now()->addYear();
$new_quotation->batch_number = "SYSTEM_CREATED_QUOTATION";
$new_quotation->batch_balance = $unattached_to_quotation_balance;
$new_quotation->supplier_id = 0;
$new_quotation->created_by = Auth::id();
$new_quotation->save();
//update the drug batch details to this one
$drug->batch_number_in_use = $new_quotation->batch_number;
$drug->quotation_id_of_batch_in_use = $new_quotation->id;
$drug->balance_of_batch_in_use = $new_quotation->batch_balance;
$drug->update();
}
}
//cater for sundry quantities that don't have attached batches
$sundries = Sundry::where('available', 1)->orderby('name', 'desc')->get();
foreach ($sundries as $sundry) {
$sundry_store_stock = $sundry->store_stock;
//batch details on drugs table ======= batch_number_in_use, quotation_id_of_batch_in_use, balance_of_batch_in_use
$all_quotations_of_this_sundry = Quotation::where(['drug_id' => $sundry->id, 'quotation_type_id' => 2])->get();
$balance_on_sundries_batches = 0;
foreach ($all_quotations_of_this_sundry as $quotation) {
$balance_on_sundries_batches += $quotation->batch_balance;
}
if ($sundry_store_stock > $balance_on_sundries_batches) {
$unattached_to_quotation_balance = $sundry_store_stock - $balance_on_sundries_batches;
$total_price = get_name($sundry->id, "id", "buying_price", "sundries") * $balance_on_sundries_batches;
//create system fake quotation
$new_quotation = new Quotation;
$new_quotation->quotation_type_id = 2;
$new_quotation->drug_id = $sundry->id;
$new_quotation->quantity = $unattached_to_quotation_balance;
$new_quotation->expected_date = Carbon::now();
$new_quotation->quotation_user = Auth::id();
$new_quotation->quotation_number = 0;
$new_quotation->quotation_date = Carbon::now();
$new_quotation->receive_user = Auth::id();
$new_quotation->receive_date = Carbon::now();
$new_quotation->receive_status = 1;
$new_quotation->receiver_comment = "SYSTEM CREATED QUOTATION";
$new_quotation->total_price = $total_price;
$new_quotation->expiry_date = Carbon::now()->addYear();
$new_quotation->batch_number = "SYSTEM_CREATED_QUOTATION";
$new_quotation->batch_balance = $unattached_to_quotation_balance;
$new_quotation->supplier_id = 0;
$new_quotation->created_by = Auth::id();
$new_quotation->save();
//update the sundry batch details to this one
$sundry->batch_number_in_use = $new_quotation->batch_number;
$sundry->quotation_id_of_batch_in_use = $new_quotation->id;
$sundry->balance_of_batch_in_use = $new_quotation->batch_balance;
$sundry->update();
}
}
flash("system has attached auto created batch to items that didn't have batches")->success();
return redirect('stores_stock_sheet');
}
public function edit_temporary_quotation_search(Request $request)
{
$quotation_type = $request->item_type;
$quotation_id = $request->quotation_id;
$suppliers = DB::table('suppliers')->where('available', 1)->whereNull('deleted_at')->orderBy('name')->pluck('name', 'id')->toArray();
$suppliers = ['' => '- select -'] + $suppliers;
$quotation_results = TemporaryQuotation::where(['id' => $quotation_id, 'completion_status' => 0])->orderBy('id', 'desc')->get();
$package_units = DB::table('package_units')->whereNull('deleted_at')->orderBy('name')->pluck('name', 'id')->toArray();
$package_units = ['' => '- select -'] + $package_units;
$item_ids_array = [];
$item_ids_array = $request->items_ids;
$added_items_collection = null;
//1-drug 2-sundry 3-dental 4-radiology 5-Lab
if ($quotation_type == 1) {
$items = Drug::whereNull('deleted_at')->orderBy('name', 'asc')->get();
$added_items_collection = Drug::whereIn('id', $item_ids_array)->orderBy('name', 'asc')->get();
} elseif ($quotation_type == 2) {
$items = Sundry::whereNull('deleted_at')->orderBy('name', 'asc')->get();
$added_items_collection = Sundry::whereIn('id', $item_ids_array)->orderBy('name', 'asc')->get();
} elseif ($quotation_type == 3) {
$items = Dental::whereNull('deleted_at')->orderBy('name', 'asc')->get();
$added_items_collection = Dental::whereIn('id', $item_ids_array)->orderBy('name', 'asc')->get();
} elseif ($quotation_type == 4) {
$items = Radiology::whereNull('deleted_at')->orderBy('name', 'asc')->get();
$added_items_collection = Radiology::whereIn('id', $item_ids_array)->orderBy('name', 'asc')->get();
} elseif ($quotation_type == 5) {
$items = Lab::whereNull('deleted_at')->orderBy('name', 'asc')->get();
$added_items_collection = Lab::whereIn('id', $item_ids_array)->orderBy('name', 'asc')->get();
} elseif ($quotation_type == 6) {
$items = GeneralItem::whereNull('deleted_at')->orderBy('name', 'asc')->get();
$added_items_collection = GeneralItem::whereIn('id', $item_ids_array)->orderBy('name', 'asc')->get();
} elseif ($quotation_type == 7) {
$items = EyeGlasses::whereNull('deleted_at')->orderBy('name', 'asc')->get();
$added_items_collection = EyeGlasses::whereIn('id', $item_ids_array)->orderBy('name', 'asc')->get();
}
$drugs = Drug::where('available', 1)->orderby('name')->pluck('name', 'id')->prepend('All drugs', 'all_items');
$sundries = Sundry::where('available', 1)->orderby('name')->pluck('name', 'id')->prepend('All sundries', 'all_items');
$dentals = Dental::orderBy('name')->pluck('name', 'id')->prepend('All dentals', 'all_items');
$radiologies = Radiology::orderBy('name')->pluck('name', 'id')->prepend('All radiologies', 'all_items');
$labs = Lab::orderBy('name')->pluck('name', 'id')->prepend('All labs', 'all_items');
$general_items = GeneralItem::orderBy('name')->pluck('name', 'id')->prepend('All general items', 'all_items');
$opticals = EyeGlasses::orderBy('name')->pluck('name', 'id')->prepend('All Optical Items', 'all_items');
return view('stores::stores.edit_temporary_quotation', compact('items', 'quotation_type', 'suppliers', 'quotation_id', 'quotation_results', 'package_units', 'added_items_collection', 'drugs', 'sundries', 'dentals', 'radiologies', 'labs', 'general_items', 'opticals'));
}
public function remove_item_batch(Request $request)
{
$item_id = $request->item_id;
$batch_number = $request->batch_number;
$item_type = $request->item_type;
//1.find the batch and delete it
//2.if one happens, find the drug and reduce the stock by the batch quantity
$item_batch_watcher = ItemBatchWatcher::find($item_id);
$quotation_record = Quotation::where(['drug_id' => $item_batch_watcher->item_id, 'batch_number' => $batch_number, 'quotation_type_id' => $item_type])->first();
if ($item_batch_watcher) {
if($item_type == 1 || $item_type == 2 || $item_type== 7){
if ($item_batch_watcher->pharmacy_stock != 0) {
return 0;
}
}
if($item_type == 4 || $item_type == 5){
if ($item_batch_watcher->lab_stock != 0) {
return 0;
}
}
}
if (!is_null($quotation_record)) {
$quotaion_id = $quotation_record->id;
if ($quotation_record->delete()) {
if ($item_type == 1) {
$drug = Drug::withTrashed()->find($item_id);
$drug->store_stock = $drug->store_stock - $quotation_record->batch_balance;
//if it is the batch in use, delete the details from the drugs table
if ($drug->quotation_id_of_batch_in_use == $quotaion_id) {
$drug->batch_number_in_use = null;
$drug->quotation_id_of_batch_in_use = null;
$drug->balance_of_batch_in_use = 0;
}
$drug->update();
}
if ($item_type ==4) {
$radiology = Radiology::withTrashed()->find($item_id);
$radiology->store_stock = $radiology->store_stock - $quotation_record->batch_balance;
$radiology->update();
}
if ($item_type ==2) {
$sundry = Sundry::withTrashed()->find($item_id);
$sundry->store_stock = $sundry->store_stock - $quotation_record->batch_balance;
//if it is the batch in use, delete the details from the sundries table
if ($sundry->quotation_id_of_batch_in_use == $quotaion_id) {
$sundry->batch_number_in_use = null;
$sundry->quotation_id_of_batch_in_use = null;
$sundry->balance_of_batch_in_use = 0;
}
$sundry->update();
}
}
if ($item_batch_watcher) {
$item_batch_watcher->delete();
}
return 1;
}
return 0;
}
public function approve_requisitioned_opd_items(Request $request)
{
$quotation_results = DB::select("select * from requisitions where issue_status IS NULL and approval_status=0 and deleted_at IS NULL ORDER BY id desc");
return view('stores::stores.approve_opd_item_requisitions', compact('quotation_results'));
}
public function details_of_items_to_approve($id){
$requisition = Requisition::find($id);
$requisition_id = $id;
$drug_id_explode_array = explode(",", $requisition->drug_id);
$quantity_explode_array = explode(",", $requisition->quantity_requested);
$per_drug_explode_array = explode(",", $requisition->per_drug);
$associative_requested_drugs_array = [];
$unit_of_measure = DB::table('unit_of_measure')->pluck("name", "id")->toArray();
if ($requisition->quotation_type_id == 1) {
// do this if requisition type is drugs
for ($i = 0; $i < count($drug_id_explode_array); $i++) {
if (isset($quantity_explode_array[$i]) && $quantity_explode_array[$i] != "") {
if ($requisition->quotation_type_id == 1) {
$drug_name = get_name($drug_id_explode_array[$i], "id", "name", "drugs");
} else if ($requisition->quotation_type_id == 2) {
$drug_name = get_name($drug_id_explode_array[$i], "id", "name", "sundries");
}
$associative_requested_drugs_array[$drug_name] = $quantity_explode_array[$i];
}
}
}
if ($requisition->quotation_type_id == 2) {
// do this if the requisition type is for sundries
for ($i = 0; $i < count($drug_id_explode_array); $i++) {
if ($quantity_explode_array[$i] != "") {
$drug_name = get_name($drug_id_explode_array[$i], "id", "name", "sundries");
$associative_requested_drugs_array[$drug_name] = $quantity_explode_array[$i];
}
}
}
if ($requisition->quotation_type_id == 3) {
// do this if the requisition type is for dentals
for ($i = 0; $i < count($drug_id_explode_array); $i++) {
if ($quantity_explode_array[$i] != "") {
$drug_name = get_name($drug_id_explode_array[$i], "id", "name", "dentals");
$associative_requested_drugs_array[$drug_name] = $quantity_explode_array[$i];
}
}
}
if ($requisition->quotation_type_id == 4){
// do this if the requisition type is for radiologies
for ($i = 0; $i < count($drug_id_explode_array); $i++) {
if ($quantity_explode_array[$i] != "") {
$drug_name = get_name($drug_id_explode_array[$i], "id", "name", "radiologies");
$associative_requested_drugs_array[$drug_name] = $quantity_explode_array[$i];
}
}
}
if ($requisition->quotation_type_id == 5) {
// do this if the requisition type is for labs
for ($i = 0; $i < count($drug_id_explode_array); $i++) {
if ($quantity_explode_array[$i] != "") {
$drug_name = get_name($drug_id_explode_array[$i], "id", "name", "labs");
$associative_requested_drugs_array[$drug_name] = $quantity_explode_array[$i];
}
}
}
if ($requisition->quotation_type_id == 6) {
// do this if the requisition type is for general items
for ($i = 0; $i < count($drug_id_explode_array); $i++) {
if ($quantity_explode_array[$i] != "") {
$drug_name = get_name($drug_id_explode_array[$i], "id", "name", "general_items");
$associative_requested_drugs_array[$drug_name] = $quantity_explode_array[$i];
}
}
}
if ($requisition->quotation_type_id == 7) {
// do this if the requisition type is for opticals
for ($i = 0; $i < count($drug_id_explode_array); $i++) {
if ($quantity_explode_array[$i] != "") {
$drug_name = get_name($drug_id_explode_array[$i], "id", "name", "eye_glasses");
$associative_requested_drugs_array[$drug_name] = $quantity_explode_array[$i];
}
}
}
return view('stores::stores.opd_details_to_approve', compact('associative_requested_drugs_array', 'requisition_id', 'requisition'));
}
public function approve_requisition(Request $request)
{
$requisition_id = $request->requisition_id;
$requisition = Requisition::find($requisition_id);
if ($requisition) {
$requisition->approval_status = 1;
$requisition->approved_by = Auth::id();
$requisition->approved_date = Carbon::now();
$requisition->quantity_approved = $request->quantity_approved ? implode(",", $request->quantity_approved) : null;
$requisition->update();
}
flash("Requisition number ".sprintf('%04u', $requisition->id)." has been approved")->success();
return redirect('approve_requisitioned_opd_items');
}
public function viewing_items_to_issue_out($id)
{
$requisition = Requisition::find($id);
$requisition_id = $id;
$drug_id_explode_array = explode(",", $requisition->drug_id);
$quantity_explode_array = explode(",", $requisition->quantity_requested);
$per_drug_explode_array = explode(",", $requisition->per_drug);
$associative_requested_drugs_array = [];
$unit_of_measure = DB::table('unit_of_measure')->pluck("name", "id")->toArray();
if ($requisition->quotation_type_id == 1) {
// do this if requisition type is drugs
for ($i = 0; $i < count($drug_id_explode_array); $i++) {
if (isset($quantity_explode_array[$i]) && $quantity_explode_array[$i] != "") {
if ($requisition->quotation_type_id == 1) {
$drug_name = get_name($drug_id_explode_array[$i], "id", "name", "drugs");
} else if ($requisition->quotation_type_id == 2) {
$drug_name = get_name($drug_id_explode_array[$i], "id", "name", "sundries");
}
$associative_requested_drugs_array[$drug_name] = $quantity_explode_array[$i];
}
}
}
if ($requisition->quotation_type_id == 2) {
// do this if the requisition type is for sundries
for ($i = 0; $i < count($drug_id_explode_array); $i++) {
if ($quantity_explode_array[$i] != "") {
$drug_name = get_name($drug_id_explode_array[$i], "id", "name", "sundries");
$associative_requested_drugs_array[$drug_name] = $quantity_explode_array[$i];
}
}
}
if ($requisition->quotation_type_id == 5) {
// do this if the requisition type is for labs
for ($i = 0; $i < count($drug_id_explode_array); $i++) {
if ($quantity_explode_array[$i] != "") {
$drug_name = get_name($drug_id_explode_array[$i], "id", "name", "labs");
$associative_requested_drugs_array[$drug_name] = $quantity_explode_array[$i];
}
}
}
if ($requisition->quotation_type_id == 6) {
// do this if the requisition type is for labs
for ($i = 0; $i < count($drug_id_explode_array); $i++) {
if ($quantity_explode_array[$i] != "") {
$drug_name = get_name($drug_id_explode_array[$i], "id", "name", "general_items");
$associative_requested_drugs_array[$drug_name] = $quantity_explode_array[$i];
}
}
}
return view('stores::stores.view_opd_requisitioned_items', compact('associative_requested_drugs_array', 'requisition_id', 'requisition'));
}
public function edit_item_batch(Request $request)
{
$item_id = $request->item_id;
$original_batch_record_id = $request->original_batch_record_id;
$original_batch_number = $request->original_batch_number;
$item_type = $request->item_type;
$batch_number_edit = $request->new_batch_number_edit;
//1.find the batch
//2.check if it is the one in use using the original batch number and edit it before edit in quotations table
$existing_batch_record = Quotation::where(['drug_id' => $item_id, 'batch_number' => $batch_number_edit, 'quotation_type_id' => $item_type])->first();
if ($existing_batch_record) {
return 2;
}
if ($item_type == 1) {
$drug = Drug::withTrashed()->find($item_id);
if ($drug->batch_number_in_use == $original_batch_number) {
$drug->batch_number_in_use = $batch_number_edit;
$drug->update();
}
} elseif($item_type == 2){
$sundry = Sundry::withTrashed()->find($item_id);
if ($sundry->batch_number_in_use == $original_batch_number) {
$sundry->batch_number_in_use = $batch_number_edit;
$sundry->update();
}
}
$quotation_record = Quotation::where(['drug_id' => $item_id, 'batch_number' => $original_batch_number, 'quotation_type_id' => $item_type])->first();
if ($quotation_record) {
$quotation_record->batch_number = $batch_number_edit;
$quotation_record->update();
}
//$item_batch_record = ItemBatchWatcher::where(['item_id' => $item_id, 'batch_number' => $original_batch_number, 'item_type' => $item_type])->first();
$item_batch_record = ItemBatchWatcher::find($original_batch_record_id);
if ($item_batch_record) {
$item_batch_record->batch_number = $batch_number_edit;
if ($item_batch_record->update()) {
return 1;
}
}
return 0;
}
public function physical_stock_count_search(Request $request)
{
$item_ids_array = $request->search_items_ids;
$item_ids_array = is_array($item_ids_array) ? $item_ids_array : [];
$is_all_items = in_array("all_items", $item_ids_array);
$ongoing_physical_count = StoreStockReconciliation::where('completion_status', 0)->get();
if (count($ongoing_physical_count) > 0) {
flash('There is an ongoing physical count. You can not start a new count, please resume previous count')->error();
return redirect()->back();
}
if ($is_all_items) {
$drugs = Drug::where('available', 1)->orderby('name', 'asc')->get();
} else{
$drugs = Drug::whereIn('id', $item_ids_array)->orderBy('name', 'asc')->get();
}
if (count($drugs) < 1) {
flash()->error("There is no drugs stock");
return redirect('/drugs/');
} else {
$batch_numbers = [];
$sql = "SELECT DISTINCT batch_number FROM quotations";
$results = DB::select($sql);
foreach ($results as $result) {
$batch_numbers[$result->batch_number] = $result->batch_number;
}
$stock_adjustment_chart_of_account = ChartOfAccount::where('slug', 'stock_adjustment')->first();
$batch_numbers = ['' => '- select -'] + $batch_numbers;
$drugs_dropdown = DB::table('drugs')->where('available', 1)->whereNull('deleted_at')->orderBy('name', 'asc')->pluck('name','id')->prepend('All drugs', 'all_items')->toArray();
return view('stores::stores.physical_stock_count', compact('drugs', 'batch_numbers', 'stock_adjustment_chart_of_account', 'drugs_dropdown'));
}
}
public function sundries_physical_stock_count_search(Request $request)
{
$item_ids_array = $request->search_items_ids;
$is_all_items = in_array("all_items", $item_ids_array);
$ongoing_physical_count = SundryStoreStockReconciliation::where('completion_status', 0)->get();
if (count($ongoing_physical_count) > 0) {
flash('There is an ongoing physical count. You can not start a new count, please resume previous count')->error();
return redirect()->back();
}
$sundries = []; //DB::table('sundries')->whereNull('deleted_at')->orderBy('name', 'asc')->get();
if ($is_all_items) {
$sundries = Sundry::where('available', 1)->orderby('name', 'asc')->get();
} else{
$sundries = Sundry::whereIn('id', $item_ids_array)->orderBy('name', 'asc')->get();
}
$sundries_dropdown = DB::table('sundries')->whereNull('deleted_at')->orderBy('name', 'asc')->pluck('name','id')->prepend('All sundries', 'all_items')->toArray();
$stock_adjustment_chart_of_account = ChartOfAccount::where('slug', 'stock_adjustment')->first();
return view('stores::stores.sundries_physical_stock_count', compact('sundries', 'sundries_dropdown', 'stock_adjustment_chart_of_account'));
}
public function general_items_physical_stock_count_search(Request $request)
{
$item_ids_array = $request->search_items_ids;
$is_all_items = in_array("all_items", $item_ids_array);
$ongoing_physical_count = GeneralItemStoreStockReconciliation::where('completion_status', 0)->get();
if (count($ongoing_physical_count) > 0) {
flash('There is an ongoing physical count. You can not start a new count, please resume previous count')->error();
return redirect()->back();
}
$general_items = []; //DB::table('general_items')->whereNull('deleted_at')->orderBy('name', 'asc')->get();
if ($is_all_items) {
$general_items = GeneralItem::orderBy('name', 'asc')->get();
} else{
$general_items = GeneralItem::whereIn('id', $item_ids_array)->orderBy('name', 'asc')->get();
}
if (count($general_items) < 1) {
flash()->error("There is no general items in stock");
return redirect('general_items');
} else {
$chart_of_accounts = ChartOfAccount::orderBy('name', 'asc')->pluck('name', 'id')->toArray();
$chart_of_accounts = ['' => '- select -'] + $chart_of_accounts;
$general_items_dropdown = DB::table('general_items')->whereNull('deleted_at')->orderBy('name', 'asc')->pluck('name','id')->prepend('All drugs', 'all_items')->toArray();
return view('stores::stores.general_items_physical_stock_count', compact('general_items', 'chart_of_accounts', 'general_items_dropdown'));
}
}
public function update_labs_stock_sheet(Request $request)
{
$lab_ids_array = $request->lab_id;
$quantities_array = $request->quantity;
$non_insured_prices_array = $request->non_insured_price;
$expiry_dates_array = $request->expiry_date;
for ($i=0; $i < count($lab_ids_array) ; $i++) {
$lab = Lab::withTrashed()->find($lab_ids_array[$i]);
$lab->store_stock = $quantities_array[$i];
$lab->non_insured_price = $non_insured_prices_array[$i];
$lab->expiry_date = $expiry_dates_array[$i];
$lab->save();
}
flash('stock sheet has been updated')->success();
return redirect('labs_stock_sheet');
}
public function get_item_cost_price()
{
$category_id = $_GET['category_id'];
$item_id_array = $_GET['item_id'];
$item_id = $item_id_array[0];
$cost_price = 0;
if ($category_id == 1) {
$drug = Drug::withTrashed()->find($item_id);
if ($drug) {
$cost_price = $drug->cost_price;
}
} elseif($category_id == 2){
$sundry = Sundry::withTrashed()->find($item_id);
if ($sundry) {
$cost_price = $sundry->cost_price;
}
}
return ugandan_shillings($cost_price);
}
public function item_bill_print($quotation_number, $item_type)
{
$supplier_reference = DB::table('quotations')->where(['quotation_number' => $quotation_number])->first();
$hospital_details = HospitalInformation::first();
$quotations_results = DB::select("SELECT * FROM quotations where quotation_number = {$quotation_number}");
$approval_status = 0;
if (count($quotations_results)) {
if($quotations_results[0]->approval_status == 1){
$approval_status = 1;
}
}
$logged_user_fn = auth()->user()->first_name;
$logged_user_ln = auth()->user()->last_name;
$data = [
'hospitalInfo' => $hospital_details,
'quotations_results' => $quotations_results,
'quotation_number' => $quotation_number,
'supplier_reference' => $supplier_reference->supplier_reference,
'item_type' => $item_type,
'approval_status' => $approval_status
];
$pdf = SnappyPDF::loadView('stores::stores/item_bill_print', $data)
->setOrientation('portrait')
->setOption('margin-bottom', 10)
->setOption('margin-top', 5)
->setOption('margin-left', 2)
->setOption('margin-right', 2)
->setOption('footer-font-size', 10)
->setOption('footer-html', '<i>- Stre@mline -</i> '.$logged_user_fn." ".$logged_user_ln .' '.streamline_date_time(date('Y-m-d')).'');
return $pdf->inline('ITEMS BILL' . date(" d-m-y h:ia") . '.pdf');
}
public function items_purchase_order_print($quotation_number, $item_type)
{
$hospital_details = HospitalInformation::first();
$table_quotations = "quotations";
$quotation_results = DB::select("select * from $table_quotations where quotation_number = {$quotation_number}");
$data = [
'hospitalInfo' => $hospital_details,
'item_type' => $item_type,
'quotation_number' => $quotation_number,
'quotation_results' => $quotation_results,
'table_quotations' => $table_quotations
];
$pdf = SnappyPDF::loadView('stores::stores/items_purchase_order_print', $data)
->setOrientation('portrait')
->setOption('margin-bottom', 10)
->setOption('margin-top', 5)
->setOption('margin-left', 2)
->setOption('margin-right', 2)
->setOption('footer-font-size', 10)
->setOption('footer-html', '<i>- Stre@mline -</i> '.get_full_name(Auth::id(), "id", "first_name", "last_name", "users") .' '.streamline_date_time(date('Y-m-d')).'');
return $pdf->inline('Purchase order' . date(" d-m-y h:ia") . '.pdf');
}
public function auto_create_inventory_bill_or_expense(Request $request, $quotation_number)
{
$logged_in_user = Auth::id();
$supplier_id = $request->supplier;
$item_type = $request->item_type;
$quotation_date = Carbon::now();
$bill_array = $request->bill;
$receive_date = Carbon::createFromFormat('d/m/Y', $request->received_on_date)->toDateString();
//$bill_date = Carbon::parse($request->bill_date)->toDateString();
//$bill_due_date = Carbon::parse($request->bill_due_date)->toDateString();
$quotation_total_bill = Quotation::where(['quotation_number' => $quotation_number])->get()->sum('total_price');
$expense_account_id_array = $item_ids_array = $item_quatities_array = $item_amounts_array = [];
$quotation_items = Quotation::where(['quotation_number' => $quotation_number])->get();
foreach ($quotation_items as $quotation_record) {
//$quotation_total_bill =+ $quotation_record->total_price;
if (in_array($item_type, [1,2])) {
$expense_account_id_array[] = 14; //chart of account id for expenses
} elseif($item_type == 3){
$expense_account_id_array[] = get_name($quotation_record->drug_id, 'id', 'expenses_account_id', 'dentals');
} elseif($item_type == 4){
$expense_account_id_array[] = get_name($quotation_record->drug_id, 'id', 'expenses_account_id', 'radiologies');
} elseif($item_type == 5){
$expense_account_id_array[] = get_name($quotation_record->drug_id, 'id', 'expenses_account_id', 'labs');
} elseif($item_type == 6){
$expense_account_id_array[] = get_name($quotation_record->drug_id, 'id', 'expenses_account_id', 'general_items');
} elseif($item_type == 7){
$expense_account_id_array[] = get_name($quotation_record->drug_id, 'id', 'expenses_account_id', 'eye_glasses');
}
$item_ids_array[] = $quotation_record->drug_id;
$item_quatities_array[] = $quotation_record->receive_quantity;
$item_amounts_array[] = $quotation_record->total_price;
}
$bill = new HospitalBill;
$bill->vendor = $supplier_id;
$bill->bill_date = $receive_date;
//$bill->bill_term = $request->bill_term;
$bill->bill_memo = "UN-VERIFIED AUTO CREATED STRE@MLINE INVENTORY BILL";
$bill->bill_number = "UN-VERIFIED BILL FROM QUOTATION-".$quotation_number;
$bill->bill_due_date = $receive_date;
$bill->total_amount = $quotation_total_bill;
$bill->item_ids = implode(',', $item_ids_array);
$bill->item_accounts = implode(',', $expense_account_id_array);
$bill->item_quantities = implode(',', $item_quatities_array);
$bill->item_subtotals = implode(',', $item_amounts_array);
$bill->created_by = $logged_in_user;
$bill->balance_history = serialize(array());
$bill->receipt_history = serialize(array());
$bill->staff_incharge_history = serialize(array());
$bill->amount_paid_history = serialize(array());
$bill->date_paid_history = serialize(array());
$track_invoice = new TrackInvoice;
$track_invoice->reason = $bill->bill_memo;
$track_invoice->created_by = $logged_in_user;
switch ($item_type) {
case 1:
$bill->bill_type = 'DRU';
break;
case 2:
$bill->bill_type = 'SUN';
break;
case 3:
$bill->bill_type = 'DEN';
break;
case 4:
$bill->bill_type = 'RAD';
break;
case 5:
$bill->bill_type = 'LAB';
break;
case 6:
$bill->bill_type = 'GEN';
break;
case 7:
$bill->bill_type = 'EYE';
break;
}
if ($bill->save() && $track_invoice->save()) {
$accounts_payable_balance = ChartOfAccount::find(14); // chart of accout: Account payable
ChartOfAccount::where('id', 14)->update(['balance' => (int)$quotation_total_bill + (int)$accounts_payable_balance->balance]);
flash('Bill has successfully been saved.')->success();
} else {
flash('Failed to save Bill.')->error();
}
$update = Quotation::where('quotation_number', $quotation_number)
->update(['bill_id' => $bill->id, 'invoice_generated' => 0, 'invoice_date' => $bill->bill_date, 'invoice_number' => $bill->bill_number]);
}
public function issued_item_print($requisition_id, $item_type)
{
$requisition_model = Requisition::withTrashed()->find($requisition_id);
$data = [
'requisition_model' => $requisition_model,
'requisition_id' => $requisition_id,
'item_type' => $item_type,
'isDom' => true,
];
$pdf_card = new DomPDF();
$html = view('stores::stores/issued_item_print',$data)->render();
$pdf_card = DomPDF::loadHtml($html);
$options = [
'dpi' => 100,
'isPhpEnabled' => true,
'isHtml5ParserEnabled' => true,
'isJavascriptEnabled' => true,
'isRemoteEnabled' => true,
'footer-html'=>'<i>- Stre@mline -</i> '. get_full_name(Auth::id(), "id", "first_name", "last_name", "users") .' '.streamline_date_time(date('Y-m-d')).''
];
DomPDF::setOptions($options);
$pdf_card->setPaper('A4', 'potrait');
$pdf_card->render();
return $pdf_card->stream('ITEMS BILL' . date(" d-m-y h:ia") . '.pdf', array('Attachment' => false));
}
public function print_previous_issued_items_details($requisition_id, $item_type)
{
$results = DB::select("select * from requisitions where id = {$requisition_id} AND issue_status = 1 ORDER BY id desc");
$hospital_details = HospitalInformation::first();
$data = [
'hospitalInfo' => $hospital_details,
'results' => $results,
'requisition_id' => $requisition_id,
'item_type' => $item_type
];
$pdf = SnappyPDF::loadView('stores::stores/print_previously_issued_items_details', $data)
->setOrientation('portrait')
->setOption('margin-bottom', 10)
->setOption('margin-top', 5)
->setOption('margin-left', 2)
->setOption('margin-right', 2)
->setOption('footer-font-size', 10)
->setOption('footer-html', '<i>- Stre@mline -</i> ' . get_full_name(Auth::id(), "id", "first_name", "last_name", "users") . ' ' . streamline_date_time(date('Y-m-d')) . '');
return $pdf->inline('ISSUED ITEMS' . date(" d-m-y h:ia") . '.pdf');
}
public function optical_items_stock_sheet() {
$opticals = DB::table('eye_glasses')->whereNull('deleted_at')->orderBy('name', 'asc')->get();
// getting the lab store stock batches
$opticals= calculate_stock_value($opticals,7,'store_stock');
$total_cost_value = 0;
foreach($opticals as $key => $lab){
$total_cost_value += $lab->item_cost_value;
}
if (count($opticals) < 1) {
flash()->error("There are no registered opticals");
return redirect('/opticals/');
} else {
return view('stores::stores.optical_items_stock_sheet', compact('opticals','total_cost_value'));
}
}
public function clean_opening_stock_balance() {
$drugs = Drug::where('available', 1)->orderby('name', 'asc')->get();
foreach ($drugs as $drug ) {
if (!is_null($drug->pharmacy_opening_stock) || !is_null($drug->store_opening_stock)) {
$store_open_stock = is_null($drug->store_opening_stock) ? 0 : $drug->store_opening_stock;
$pharm_open_stock = is_null($drug->pharmacy_opening_stock) ? 0 : $drug->pharmacy_opening_stock;
$drug->opening_stock = $store_open_stock + $pharm_open_stock;
$drug->opening_stock_date = '2022-01-01';
$drug->update();
}
if (is_null($drug->opening_stock_date) && !is_null($drug->opening_stock)) {
$drug->opening_stock_date = '2022-01-01';
$drug->update();
}
}
echo('done with clean');
}
public function optical_physical_stock_count(Request $request) {
if (isset($request->search_items_ids)) {
$item_ids_array = $request->search_items_ids;
$is_all_items = in_array("all_items", $item_ids_array);
if ($is_all_items) {
$eye_glasses = EyeGlasses::orderBy('name', 'asc')->get();
} else{
$eye_glasses = EyeGlasses::whereIn('id', $item_ids_array)->orderBy('name', 'asc')->get();
}
} else {
$eye_glasses = [];
}
$optical_dropdown = EyeGlasses::whereNull('deleted_at')->orderBy('name')->pluck('name','id')->prepend('All Optical Items', 'all_items')->toArray();
$stock_adjustment_chart_of_account = ChartOfAccount::where('slug', 'stock_adjustment')->first();
$reasons = $this->itemsStockService->getAllReconciliationReasonsArray();
return view('stores::stores.optical_physical_stock_count', compact('eye_glasses','reasons', 'stock_adjustment_chart_of_account', 'optical_dropdown'));
}
public function update_optical_physical_stock_count(Request $request)
{
$batch_quotation_ids_array = $request->batch_quotation_id;
$batch_drug_ids_array = (isset($request->batch_drug_id) && is_array($request->batch_drug_id)) ? $request->batch_drug_id : [];
$unique_drug_ids_with_batches_array = array_unique($batch_drug_ids_array);
$batch_numbers_array = $request->batch_number;
$batch_unit_cost_array = $request->batch_unit_cost;
$batch_quantity_balances_array = $request->batch_quantity_balance;
$batch_expiry_dates_array = $request->expiry_date;
$batch_db_record_ids_array = $request->item_batch_watcher_id;
$difference_in_cost_value_array=$request->difference_in_cost_value;
$drugs_ids_array = $request->drug_id;
$system_stock_array = $request->system_stock;
$physical_stock_array = $request->physical_stock;
$cost_price_array = $request->cost_price;
$difference_array = $request->difference;
$shrinkage_array = $request->shrinkage;
$markup_array = $request->mark_up;
$reason_for_difference_array = $request->reason_for_difference;
$batch_reason_array = $request->reconcile_reason;
$drugs_with_initial_stock_array = is_null($request->is_initial_stock) ? [] : $request->is_initial_stock;
$stock_adjustment_chart_of_account = ChartOfAccount::where('slug', 'stock_adjustment')->first();
$affected_account_id = $stock_adjustment_chart_of_account->id;
$opening_inventory_chart_of_account = ChartOfAccount::where('slug', 'opening_inventory')->first();
//get the max identifier
$max_stock_count_identifier = OpticalStockReconciliation::max('stock_count_identifier');
$reconcile_optical_store_stock = true;
$batches =[];
for ($i=0; $i < count($batch_numbers_array) ; $i++) {
if (!is_null($batch_numbers_array[$i]) && !is_null($batch_quantity_balances_array[$i])) {
//enforce double entry per batch
if (in_array($batch_drug_ids_array[$i], $drugs_with_initial_stock_array)) {
$affected_account_id = $opening_inventory_chart_of_account->id;//override adjustment a/c to be opening_inv
} else{
$affected_account_id = $stock_adjustment_chart_of_account->id;
}
account_for_batch_reconciliations_difference($item_type = 7, $batch_drug_ids_array[$i], $affected_account_id, $batch_numbers_array[$i], $batch_quantity_balances_array[$i], $request->reconciliation_date, "store", $ward_id = null);
$batches=$this->itemsStockService->reconcileBatches($batches,$batch_reason_array[$i],0,$item_type = 7, $batch_drug_ids_array[$i], $batch_numbers_array[$i], $batch_quantity_balances_array[$i], $batch_expiry_dates_array[$i], "store", $batch_unit_cost_array[$i]??0, $batch_db_record_ids_array[$i]??0, $ward_id=null);
}
}
if (isset($request->reconcile_stock)) {
for ($x = 0; $x < count($drugs_ids_array); $x++) :
/* check if the difference value is not null and then update the optical */
if (!is_null($difference_array[$x])) {
$this->itemsStockService->createOpticalReconciliation(0,$batches,$difference_in_cost_value_array[$x],$drugs_ids_array[$x],$physical_stock_array[$x],$difference_array[$x], $system_stock_array[$x],1,$affected_account_id,$request->reconciliation_date,$request->general_comment,$max_stock_count_identifier);
//update the system stock levels with the newly counted physical stock
$eye = EyeGlasses::find($drugs_ids_array[$x]);
$eye->store_stock = $physical_stock_array[$x];
if (in_array($eye->id, $drugs_with_initial_stock_array)) {
$existing_opening_stock = is_null($eye->opening_stock) ? 0 : $eye->opening_stock;
$eye->opening_stock = $existing_opening_stock + $physical_stock_array[$x];
$eye->opening_cost_price = $cost_price_array[$x];
$eye->opening_stock_date = $request->reconciliation_date;
$eye->store_opening_stock = $physical_stock_array[$x];
}
$eye->updated_by = Auth::id();
$reconcile_optical_store_stock = $eye->update();
}
endfor;
/*==== do this to cater for the newer introduced editing batch number ======*/
if (track_items_using_batches()) :
for ($i = 0; $i < count($batch_numbers_array); $i++) :
if (!is_null($batch_numbers_array[$i]) && $batch_drug_ids_array[$i] != "") {
if ($batch_quotation_ids_array[$i] != '0') {
$quotation_record = Quotation::where(['drug_id' => $batch_drug_ids_array[$i], 'batch_number' => $batch_numbers_array[$i]])->first();
if (!is_null($quotation_record)) {
$quotation_record->batch_balance = $batch_quantity_balances_array[$i];
$quotation_record->update();
}
} elseif ($batch_quantity_balances_array[$i] != null && $batch_numbers_array[$i] != null && $batch_quotation_ids_array[$i] == '0') {
//assume that this batch doesnt have a corresponding quotation so make one
$new_quotation = new Quotation;
$new_quotation->quotation_type_id = 7;
$new_quotation->drug_id = $batch_drug_ids_array[$i];
$new_quotation->quantity = $batch_quantity_balances_array[$i];
$new_quotation->expected_date = date('Y-m-d');
$new_quotation->quotation_user = Auth::id();
$new_quotation->quotation_date = date('Y-m-d');
$new_quotation->billing_date = Carbon::now();
$new_quotation->billing_user = Auth::id();
$new_quotation->approval_date = Carbon::now();
$new_quotation->approval_status = 1;
$new_quotation->approval_user = Auth::id();
$new_quotation->receive_user = Auth::id();
$new_quotation->receive_date = date('Y-m-d');
$new_quotation->receive_status = 1;
$new_quotation->expiry_date = $batch_expiry_dates_array[$i];
$new_quotation->batch_number = $batch_numbers_array[$i];
$new_quotation->batch_balance = $batch_quantity_balances_array[$i];
$new_quotation->directly_received_items = 1;
$new_quotation->created_by = Auth::id();
$new_quotation->save();
}
}
endfor;
foreach ($unique_drug_ids_with_batches_array as $batch_drug) {
$all_batch_balances_for_drug = Quotation::where(['drug_id' => $batch_drug, 'quotation_type_id' => 1])->where('batch_balance', '>', 0)->sum('batch_balance');
if ($all_batch_balances_for_drug > 0) {
$drug_record = EyeGlasses::withTrashed()->find($batch_drug);
$drug_record->store_stock = $all_batch_balances_for_drug;
$drug_record->update();
}
}
endif;
/*=========== end the catering for the newer introduced batch number ===========*/
if ($reconcile_optical_store_stock) :
flash('Stock levels have been reconciled')->success();
return redirect('optical_items_stock_sheet');
endif;
flash('Unable to complete stock reconciliation')->success();
return redirect()->back();
}
}
public function optical_stock_reconciliation_report(Request $request)
{
if (!empty($request->dates)) {
if ($request->dates == "today") {
$today = Carbon::today()->startOfDay()->toDateTimeString();
$end = Carbon::parse($today)->endOfDay()->toDateTimeString();
$reconciled_stocks = OpticalStockReconciliation::select('stock_count_identifier', 'created_by', 'created_at', 'general_comment', DB::raw('SUM(variance) as total'))->groupBy('stock_count_identifier', 'created_by', 'created_at', 'general_comment')->where('type',0)->whereBetween('created_at', [$today, $end])->orderBy('stock_count_identifier', 'desc')->get();
} else if ($request->dates == "yesterday") {
$yesterday = Carbon::yesterday()->startOfDay()->toDateTimeString();
$end = Carbon::parse($yesterday)->endOfDay()->toDateTimeString();
$reconciled_stocks = OpticalStockReconciliation::select('stock_count_identifier', 'created_by', 'created_at', 'general_comment', DB::raw('SUM(variance) as total'))->groupBy('stock_count_identifier', 'created_by', 'created_at', 'general_comment')->where('type',0)->whereBetween('created_at', [$yesterday, $end])->orderBy('stock_count_identifier', 'desc')->get();
} else if ($request->dates == "custom_date") {
$start = Carbon::parse($request->start_date)->startOfDay()->toDateTimeString();
$end = Carbon::parse($request->start_date)->endOfDay()->toDateTimeString();
$reconciled_stocks = OpticalStockReconciliation::select('stock_count_identifier', 'created_by', 'created_at', 'general_comment', DB::raw('SUM(variance) as total'))->groupBy('stock_count_identifier', 'created_by', 'created_at', 'general_comment')->where('type',0)->whereBetween('created_at', [$start, $end])->orderBy('stock_count_identifier', 'desc')->get();
} else if ($request->dates == "custom_date_range") {
$start = Carbon::parse($request->start_date)->startOfDay()->toDateTimeString();
$end = Carbon::parse($request->end_date)->endOfDay()->toDateTimeString();
$reconciled_stocks = OpticalStockReconciliation::select('stock_count_identifier', 'created_by', 'created_at', 'general_comment', DB::raw('SUM(variance) as total'))->groupBy('stock_count_identifier', 'created_by', 'created_at', 'general_comment')->where('type',0)->whereBetween('created_at', [$start, $end])->orderBy('stock_count_identifier', 'desc')->get();
}
} else $reconciled_stocks = OpticalStockReconciliation::select('stock_count_identifier', 'created_by', 'created_at', 'general_comment', DB::raw('SUM(variance) as total'))->where('type',0)->groupBy('stock_count_identifier', 'created_by', 'created_at', 'general_comment')->orderBy('stock_count_identifier', 'desc')->get();
return view('stores::stores.optical_stock_reconciliation_report', compact('reconciled_stocks'));
}
public function optical_stock_reconciliation_report_details(Request $request)
{
$table_name='eye_glasses';
$active='stores.optical_stock_reconciliation_report_details';
$route = 'stores.optical_stock_reconciliation_report';
$route_title ='stores.optical_stock_reconciliation_report';
$items_reconciled = OpticalStockReconciliation::where('stock_count_identifier', $request->stock_count_identifier)->get();
$items_reconciled = $this->itemsStockService->processReconcileItems($items_reconciled);
$var=true;
return view('stores::stores.items_stock_reconciliation_report_details', compact('items_reconciled','var','route_title','table_name','active','route'));
}
public function issued_items_history(Request $request){
$item_options = [];
$quotation_type_options = DB::table('quotation_types')->pluck('name', 'id')->toArray();
$quotation_type_options = ['' => '- Select Quotation type -'] + $quotation_type_options;
$item_options['drugs'] = DB::table('drugs')->where('available', 1)->whereNull('deleted_at')->pluck('name', 'id')->prepend('All drugs', 'all_items')->toArray() + ['' => '-- select --'];
$item_options['sundries'] = DB::table('sundries')->whereNull('deleted_at')->pluck('name', 'id')->prepend('All sundries', 'all_items')->toArray() + ['' => '-- select --'];
$item_options['dentals'] = DB::table('dentals')->whereNull('deleted_at')->pluck('name', 'id')->prepend('All dentals', 'all_items')->toArray() + ['' => '-- select --'];
$item_options['labs'] = DB::table('labs')->whereNull('deleted_at')->pluck('name', 'id')->prepend('All labs', 'all_items')->toArray() + ['' => '-- select --'];
$item_options['radiologies'] = DB::table('radiologies')->whereNull('deleted_at')->pluck('name', 'id')->prepend('All radiologies', 'all_items')->toArray() + ['' => '-- select --'];
$item_options['general_items'] = DB::table('general_items')->whereNull('deleted_at')->pluck('name', 'id')->prepend('All general items', 'all_items')->toArray() + ['' => '-- select --'];
$item_options['eye_glasses'] = DB::table('eye_glasses')->whereNull('deleted_at')->pluck('name', 'id')->prepend('All eye glasses', 'all_items')->toArray() + ['' => '-- select --'];
$item_type = 0;
$item_id = 0;
$quotation_type_id = 0;
$item_name = "N/A";
$search_all_items = false;
$start_date_raw = $request->start_date;
$end_date_raw = $request->end_date;
if (isset($request->start_date) && isset($request->end_date)) {
$start_date = Carbon::createFromFormat('d/m/Y', $request->start_date)->toDateTimeString();
$end_date = Carbon::createFromFormat('d/m/Y', $request->end_date)->toDateTimeString();
} else {
$start_date = Carbon::now()->toDateTimeString();
$end_date = Carbon::now()->toDateTimeString();
}
if (isset($request->selected_drugs) && $request->quotation_type == 1) {
//Drugs
$item_id = $request->selected_drugs;
$quotation_type_id = $request->quotation_type;
$item_id == "all_items" ?: $item_name = DB::table('drugs')->find($request->selected_drugs)->name;
} elseif(isset($request->selected_sundries) && $request->quotation_type == 2) {
//Sundries
$item_id = $request->selected_sundries;
$quotation_type_id = $request->quotation_type;
$item_id == "all_items" ?: $item_name = DB::table('sundries')->find($request->selected_sundries)->name;
} elseif(isset($request->selected_dentals) && $request->quotation_type == 3) {
//Dentals
$item_id = $request->selected_dentals;
$quotation_type_id = $request->quotation_type;
$item_id == "all_items" ?: $item_name = DB::table('dentals')->find($request->selected_dentals)->name;
} elseif(isset($request->selected_radiologies) && $request->quotation_type == 4) {
//Radiologies
$item_id = $request->selected_radiologies;
$quotation_type_id = $request->quotation_type;
$item_id == "all_items" ?: $item_name = DB::table('radiologies')->find($request->selected_radiologies)->name;
} elseif(isset($request->selected_labs) && $request->quotation_type == 5) {
//Labs
$item_id = $request->selected_labs;
$quotation_type_id = $request->quotation_type;
$item_id == "all_items" ?: $item_name = DB::table('labs')->find($request->selected_labs)->name;
} elseif(isset($request->selected_general_items) && $request->quotation_type == 6) {
//General Items
$item_id = $request->selected_general_items;
$quotation_type_id = $request->quotation_type;
$item_id == "all_items" ?: $item_name = DB::table('general_items')->find($request->selected_general_items)->name;
} elseif(isset($request->selected_eye_glasses) && $request->quotation_type == 7) {
//Eye Glasses
$item_id = $request->selected_eye_glasses;
$quotation_type_id = $request->quotation_type;
$item_id == "all_items" ?: $item_name = DB::table('eye_glasses')->find($request->selected_eye_glasses)->name;
}
$display = "Records for " . $item_name . " between " . streamline_date($start_date) . " and " . streamline_date($end_date);
$all_items_results = $ward_results = [];
if ($item_id == "all_items") {
$search_all_items = true;
$results = DB::table('requisitions')
->select('*')->whereNull('deleted_at')
->where('quotation_type_id', $quotation_type_id)
->whereBetween('created_at', [$start_date, $end_date])
->get();
$ward_results = DB::table('ward_item_requests')
->select('*')->whereNull('deleted_at')
->where(['item_type' => $quotation_type_id, 'issued_from' => 'store'])
->whereBetween('created_at', [$start_date, $end_date])
->get();
if(count($results) > 0):
foreach($results as $result):
$item_type = $request->quotation_type;
$requested_item_ids_explode = explode(",", $result->drug_id);
$quantity_requested_explode = explode(",", $result->quantity_requested);
$item_id_explode = explode(",", $result->item_ids_issued_out);
$issued_out_explode = explode(",", $result->quantity_issued);
$cost_value_explode = explode(",", $result->cost_value);
// for($x = 0; $x < count($item_id_explode); $x++):
// $item_key = array_search($item_id_explode[$x], $requested_item_ids_explode);
// $qty_requested = $quantity_requested_explode[$item_key];
// $duplicate_checker[] = $item_id_explode[$x];
// //$cost_value = $cost_value_explode[$item_key];
// $cost_value = $cost_value_explode[$x];
// if(array_key_exists($item_id_explode[$x],$all_items_results)):
// $all_items_results[$item_id_explode[$x]]["quantity_requested"] += in_array($item_id_explode[$x], $duplicate_checker) ? 0 : (int)$qty_requested ?? 0;
// $all_items_results[$item_id_explode[$x]]["quantity_issued"] += (int)$issued_out_explode[$x] ?? 0;
// $all_items_results[$item_id_explode[$x]]["cost_value"] += (int)$cost_value ?? 0;
// else:
// $all_items_results[$item_id_explode[$x]]["quantity_requested"] = (int)$qty_requested ?? 0;
// $all_items_results[$item_id_explode[$x]]["quantity_issued"] = (int)$issued_out_explode[$x] ?? 0;
// $all_items_results[$item_id_explode[$x]]["cost_value"] = (int)$cost_value ?? 0;
// endif;
// endfor;
for($x = 0; $x < count($item_id_explode); $x++):
$cost_value = isset($cost_value_explode[$x]) ? (int)$cost_value_explode[$x] : 0;
$qty_requested = isset($quantity_requested_explode[$x]) ? (int)$quantity_requested_explode[$x] : 0;
$issued_qty = isset($issued_out_explode[$x]) ? (int)$issued_out_explode[$x] : 0;
if(array_key_exists($item_id_explode[$x],$all_items_results)):
$all_items_results[$item_id_explode[$x]]["quantity_requested"] += $qty_requested;
$all_items_results[$item_id_explode[$x]]["quantity_issued"] += $issued_qty;
$all_items_results[$item_id_explode[$x]]["cost_value"] += $cost_value;
else:
$all_items_results[$item_id_explode[$x]]["quantity_requested"] = $qty_requested;
$all_items_results[$item_id_explode[$x]]["quantity_issued"] = $issued_qty;
$all_items_results[$item_id_explode[$x]]["cost_value"] = $cost_value;
endif;
endfor;
endforeach;
endif;
if(count($ward_results) > 0):
foreach($ward_results as $ward_result):
$item_type = $request->quotation_type;
$requested_item_ids_explode = explode(",", $ward_result->item_ids);
$quantity_requested_explode = explode(",", $ward_result->item_quantities);
$item_id_explode = explode(",", $ward_result->item_ids_issued_out);
$issued_out_explode = explode(",", $ward_result->quantity_issued_out);
// $cost_value_explode = explode(",", $ward_result->cost_value);
for($x = 0; $x < count($item_id_explode); $x++):
$cost_value = 0;
$qty_requested = 0;
$issued_qty = isset($issued_out_explode[$x]) ? (int)$issued_out_explode[$x] : 0;
if(array_key_exists($item_id_explode[$x],$all_items_results)):
$all_items_results[$item_id_explode[$x]]["quantity_requested"] += $qty_requested;
$all_items_results[$item_id_explode[$x]]["quantity_issued"] += $issued_qty;
$all_items_results[$item_id_explode[$x]]["cost_value"] += $cost_value;
else:
$all_items_results[$item_id_explode[$x]]["quantity_requested"] = $qty_requested;
$all_items_results[$item_id_explode[$x]]["quantity_issued"] = $issued_qty;
$all_items_results[$item_id_explode[$x]]["cost_value"] = $cost_value;
endif;
endfor;
endforeach;
endif;
} else{
$results = DB::table('requisitions')
->select('*')->whereNull('deleted_at')
->where('quotation_type_id', $quotation_type_id)
->whereRaw('FIND_IN_SET(' . $item_id . ',drug_id)')
->whereBetween('created_at', [$start_date, $end_date])
->get();
$ward_results = DB::table('ward_item_requests')
->select('*')->whereNull('deleted_at')
->where(['item_type' => $quotation_type_id, 'issued_from' => 'store'])
->whereRaw('FIND_IN_SET(' . $item_id . ',item_ids_issued_out)')
->whereBetween('created_at', [$start_date, $end_date])
->get();
}
return view('stores::stores.issued_items_history', compact('item_options', 'quotation_type_options', 'item_type', 'results', 'display', 'item_id', 'search_all_items', 'all_items_results', 'start_date_raw', 'end_date_raw', 'ward_results'));
}
public function electronic_stock_card(Request $request){
$item_options = [];
$quotation_type_options = DB::table('quotation_types')->pluck('name', 'id')->toArray();
$quotation_type_options = ['' => '- Select Item type -'] + $quotation_type_options;
$item_options['drugs'] = ['all_items' => 'All Drugs'] + DB::table('drugs')->where('available', 1)->orderBy('name','asc')->whereNull('deleted_at')->pluck('name', 'id')->toArray();
$item_options['sundries'] = ['all_items' => 'All Sundries'] + DB::table('sundries')->whereNull('deleted_at')->orderBy('name','asc')->pluck('name', 'id')->toArray() ;
$item_options['dentals'] =['all_items' => 'All Dentals'] + DB::table('dentals')->whereNull('deleted_at')->orderBy('name','asc')->pluck('name', 'id')->toArray() ;
$item_options['labs'] =['all_items' => 'All Labs'] + DB::table('labs')->whereNull('deleted_at')->orderBy('name','asc')->pluck('name', 'id')->toArray() ;
$item_options['radiologies'] =['all_items' => 'All Radiologies'] + DB::table('radiologies')->whereNull('deleted_at')->orderBy('name','asc')->pluck('name', 'id')->toArray() ;
$item_options['general_items'] =['all_items' => 'All General Items'] + DB::table('general_items')->whereNull('deleted_at')->orderBy('name','asc')->pluck('name', 'id')->toArray() ;
$item_options['eye_glasses'] = ['all_items' => 'All Opticals'] + DB::table('eye_glasses')->whereNull('deleted_at')->orderBy('name','asc')->pluck('name', 'id')->toArray();
$item_type = 0;
$item_id =$filters=$reconciled_stocks= [];
$item_type_name='';
$quotation_type_id = 0;
$selling_price=$units=[];
$item_name = "N/A";
$search_all_items = false;
$start_date_raw = $request->start_date;
$end_date_raw = $request->end_date;
if (isset($request->start_date) && isset($request->end_date)) {
$start_date = Carbon::createFromFormat('d/m/Y', $request->start_date)->startOfDay()->toDateTimeString();
$end_date=$closing_stock_date = Carbon::createFromFormat('d/m/Y', $request->end_date)->endOfDay()->toDateTimeString();
$opening_stock_date = Carbon::createFromFormat('d/m/Y', $request->start_date)->subDay()->toDateTimeString();
} else {
$start_date = Carbon::now()->startOfDay()->toDateTimeString();
$end_date=$closing_stock_date = Carbon::now()->endOfDay()->toDateTimeString();
$opening_stock_date = Carbon::now()->subDay()->toDateTimeString();
}
if (isset($request->selected_drugs) && $request->quotation_type == 1) {
//Drugs
$item_type_name="Drugs";
if (in_array('all_items', $request->selected_drugs)) {
$item_id = Drug::where('available', 1)->pluck('id')->toArray();
}else $item_id = $request->selected_drugs;
$quotation_type_id =$item_type= $request->quotation_type;
$selling_price = Drug::select()->whereIn('id', $item_id)->pluck('non_insured_price')->toArray();
$table_name = 'drugs';
$table_col_name='name';
} elseif(isset($request->selected_sundries) && $request->quotation_type == 2) {
//Sundries
$item_type_name="Sundries";
if (in_array('all_items', $request->selected_sundries)){
$item_id = Sundry::pluck('id')->toArray();
}else $item_id = $request->selected_sundries;
$quotation_type_id=$item_type = $request->quotation_type;
$selling_price = Sundry::select()->whereIn('id', $item_id)->pluck('non_insured_price')->toArray();
$table_name = 'sundries';
$table_col_name='name';
} elseif(isset($request->selected_dentals) && $request->quotation_type == 3) {
//Dentals
$item_type_name='Dentals';
$item_id = $request->selected_dentals;
$quotation_type_id =$item_type= $request->quotation_type;
$selling_price = Dental::select()->whereIn('id', $item_id)->pluck('non_insured_price')->toArray();
$table_name = 'dentals';
$table_col_name='name';
} elseif(isset($request->selected_radiologies) && $request->quotation_type == 4) {
//Radiologies
$item_type_name='Radiologies';
if (in_array('all_items', $request->selected_radiologies)){
$item_id = Radiology::pluck('id')->toArray();
} else $item_id = $request->selected_radiologies;
$quotation_type_id =$item_type= $request->quotation_type;
$table_name = 'radiologies';
$table_col_name='name';
} elseif(isset($request->selected_labs) && $request->quotation_type == 5) {
//Labs
$item_type_name='Labs';
if (in_array('all_items',$request->selected_labs)){
$item_id = Lab::pluck('id')->toArray();
} else {$item_id = $request->selected_labs;}
$quotation_type_id =$item_type= $request->quotation_type;
$table_name = 'labs';
$table_col_name='name';
} elseif(isset($request->selected_general_items) && $request->quotation_type == 6) {
//General Items
$item_type_name='General Items';
if (in_array('all_items', $request->selected_general_items)){
$item_id = GeneralItem::pluck('id')->toArray();
}else{$item_id = $request->selected_general_items;}
$quotation_type_id =$item_type= $request->quotation_type;
$table_name = 'general_items';
$table_col_name='name';
} elseif(isset($request->selected_eye_glasses) && $request->quotation_type == 7) {
//Eye Glasses
$item_type_name='Eye Glasses';
if (in_array('all_items', $request->selected_eye_glasses)){
$item_id = EyeGlasses::pluck('id')->toArray();
}else $item_id = $request->selected_eye_glasses;
$quotation_type_id =$item_type= $request->quotation_type;
$table_name = 'eye_glasses';
$table_col_name='name';
}
$batch_stock_watcher = BatchStockWatcher::whereIn('item_id',$item_id)->where('item_type',$quotation_type_id)->whereNot('item_batch_watcher_id',0)->get();
foreach ($batch_stock_watcher as $record){
$details_arr = json_decode($record->details, true);
$details = $details_arr[$opening_stock_date] ?? $details_arr[get_closest_element_in_array(array_keys($details_arr), $opening_stock_date)]??[];
$details_closing= $details_arr[$closing_stock_date] ?? $details_arr[get_closest_element_in_array(array_keys($details_arr), $closing_stock_date)]??[];
$record->opening_stock = $details;
$record->date_opening_stock = get_closest_element_in_array(array_keys($details_arr), $opening_stock_date);
$record->closing_stock = $details_closing;
}
$display = "{$item_type_name} Stock Movement between " . streamline_date($start_date) . " and " . streamline_date($end_date);
$results = ItemBatchWatcher::select('item_id', DB::raw('SUM(store_stock) as total_store_stock'), DB::raw('SUM(cost_price) as cost_value'))
->where('item_type', $quotation_type_id)
->whereIn('item_id', $item_id)
->groupBy('item_id')
->get();
//get prev issue out
$issued_out_items = BatchIssuedTracking::whereIn('item_id',$item_id)->where('item_type',$quotation_type_id)->whereBetween('created_at', [$start_date, $end_date])
->orderBy('created_at', 'desc')->get()->toArray();
// get prev received items
$received_items = Quotation::select('quotation_type_id','drug_id','approval_status','approval_user','billing_user','receive_quantity','receive_date','receive_bill_per_package_unit','destination','receive_bill')
->where(['quotation_type_id'=>$quotation_type_id,'receive_status'=>1,'approval_status'=>1,'destination'=>'store'])
->whereBetween('receive_date', [$start_date, $end_date])->whereNotNull(['approval_user','billing_user'])
->get()->toArray();
if (in_array($quotation_type_id, [4, 5])){
$reconciled_stocks = GeneralStockReconciliation::where(['source'=>1,'item_type'=>$quotation_type_id])
->whereBetween('created_at',[$start_date, $end_date])->orderBy('stock_count_identifier', 'desc')->get()->toArray();
}
else if($quotation_type_id == 1) {
$reconciled_stocks = StoreStockReconciliation::select('drug_id as item_id','difference')->whereBetween('created_at', [$start_date, $end_date])->orderBy('stock_count_identifier', 'desc')->get()->toArray();
}
else if ($quotation_type_id == 2){
$reconciled_stocks = SundryStoreStockReconciliation::select('sundry_id as item_id','difference')->whereBetween('created_at', [$start_date, $end_date])->orderBy('stock_count_identifier', 'desc')->get()->toArray();
}
else if ($quotation_type_id == 6){
$reconciled_stocks = GeneralItemStoreStockReconciliation::select('general_item_id as item_id','difference')->whereBetween('created_at', [$start_date, $end_date])->orderBy('stock_count_identifier', 'desc')->get()->toArray();
}
// Prepare a lookup array for item_ids_issued_out
$issued_out_lookup =$batch_stocks= $received_items_lookup =$adjusted_stock= [];
foreach ($received_items as $received_item) {
foreach ($item_id as $item) {
if (!isset($received_items_lookup[$item])) {
$received_items_lookup[$item] = [];
}
if($received_item['drug_id'] == $item)
$received_items_lookup[$item][] = $received_item;
}
}
//reconclied stocks
foreach ($reconciled_stocks as $stock){
foreach ($item_id as $item) {
if (!isset($adjusted_stock[$item])) {
$adjusted_stock[$item] = [];
}
if($stock['item_id'] == $item)
$adjusted_stock[$item][] = $stock;
}
}
//issued out items
foreach ($batch_stock_watcher as $stock_value){
foreach ($item_id as $item) {
if (!isset($batch_stocks[$item])) {
$batch_stocks[$item] = [];
}
if($stock_value['item_id'] == $item)
$batch_stocks[$item][] = $stock_value;
}
}
foreach ($issued_out_items as &$issued_out) {
//get batch cost value and expiry
$batch_item_details = ItemBatchWatcher::where('item_id', $issued_out['item_id'])
->where('batch_number', $issued_out['batch_number'])
->where('item_type', $quotation_type_id)->first();
$issued_out['unit_cost'] = $batch_item_details->cost_price??0;
if (!isset($issued_out_lookup[$issued_out['item_id']])) {
$issued_out_lookup[$issued_out['item_id']] = [];
}
$issued_out_lookup[$issued_out['item_id']][] = $issued_out;
}
// Process results
$counter=0;
$totals=[
'total_store_stock'=>0,
'total_received_stock'=>0,
'total_received_cost_value'=>0,
'total_received_sale_value'=>0,
'total_issued_out_stock'=>0,
'total_issued_out_cost_value'=>0,
'total_issued_out_sale_value'=>0,
'total_adjusted_stock'=>0,
'total_cost_value'=>0,
'total_sale_value'=>0,
'total_opening_stock'=>0,
'total_closing_stock'=>0,
'total_closing_cost_value'=>0,
'total_closing_sale_value'=>0,
];
foreach ($results as $result) {
$itemId = $result->item_id;
$result->item_name = get_name($itemId,'id','name',"{$table_name}");
$unit_name=$this->itemsStockService->get_item_form_name($itemId,$request->quotation_type);
$result->unit_name = $unit_name;
$result->selling_price = $selling_price[$counter] ?? 0;
$counter++;
$issuedOutItems = $result->issued_out_items ?? [ // Initialize or reuse
'quantity' => 0,
'cost_value' => 0,
'sale_value'=>0,
];
if (isset($issued_out_lookup[$itemId])) {
foreach ($issued_out_lookup[$itemId] as $issuedOut) {
$issuedOutItems['quantity'] += (int)$issuedOut['quantity_moved'];
$issuedOutItems['cost_value'] += (int)$issuedOut['quantity_moved'] * (int)$issuedOut['unit_cost'];
$issuedOutItems['sale_value'] += (int)$issuedOut['quantity_moved'] * (int)$result->selling_price;
}
}
// Update object property after loop
$result->issued_out_items = $issuedOutItems;
$receivedItems = $result->received_items ?? [ // Initialize or reuse
'quantity' => 0,
'cost_value' => 0,
'sale_value' => 0
];
if(isset($received_items_lookup[$itemId])){
foreach ($received_items_lookup[$itemId] as $receivedItem) {
$receivedItems['quantity'] += (int)$receivedItem['receive_quantity'];
$receivedItems['cost_value'] += (int)$receivedItem['receive_quantity'] * (int)$receivedItem['receive_bill'];
}
}
// Update object property after loop
$result->received_items = $receivedItems;
if(isset($adjusted_stock[$itemId])){
$adjustedStock = $result->adjusted_stock ?? [ // Initialize or reuse
'quantity' => 0,
];
foreach ($adjusted_stock[$itemId] as $stock) {
$adjustedStock['quantity'] += (int)$stock['difference'];
}
// Update object property after loop
$result->adjusted_stock = $adjustedStock;
}
$batchStock = $result->batch_stock ?? [ // Initialize or reuse
'opening_stock' => 0,
'closing_stock' => 0,
'opening_cost_value' => 0,
'opening_sale_value' => 0,
'closing_cost_value'=>0,
'closing_sale_value'=>0
];
if (isset($batch_stocks[$itemId])) {
foreach ($batch_stocks[$itemId] as $stock) {
//filter out opening stock value that are after the date
if($stock->date_opening_stock <= $opening_stock_date){
$batchStock['opening_stock'] += (count($stock->opening_stock) > 0) ??(int)$stock->opening_stock['store_stock'];
$batchStock['opening_cost_value'] += ((count($stock->opening_stock) > 0) ??(int)$stock->opening_stock['store_stock']*(int)$stock->opening_stock['buying_price']);
$batchStock['opening_sale_value'] += ((count($stock->opening_stock) > 0) ??(int)$stock->opening_stock['store_stock']*(int)$stock->opening_stock['selling_price']);
}
$batchStock['closing_stock'] += (count($stock->closing_stock) > 0) ??(int)$stock->closing_stock['store_stock']??0;
$batchStock['closing_cost_value'] += ((count($stock->closing_stock) > 0) ??(int)$stock->closing_stock['store_stock']??0*(int)$stock->closing_stock['buying_price']);
$batchStock['closing_sale_value'] += ((count($stock->closing_stock) > 0) ??(int)$stock->closing_stock['store_stock']??0*(int)$stock->closing_stock['selling_price']);
}
// Update object property after loop
$result->batch_stock = $batchStock;
}
$totals['total_store_stock'] += $result->total_store_stock;
$totals['total_received_stock'] += $result->received_items['quantity'] ?? 0;
$totals['total_received_cost_value'] += $result->received_items['cost_value'] ?? 0;
$totals['total_received_sale_value'] += $result->received_items['sale_value'] ?? 0;
$totals['total_issued_out_stock'] += $result->issued_out_items['quantity'] ?? 0;
$totals['total_issued_out_cost_value'] += $result->issued_out_items['cost_value'] ?? 0;
$totals['total_issued_out_sale_value'] += $result->issued_out_items['sale_value'] ?? 0;
$totals['total_adjusted_stock'] += $result->adjusted_stock['quantity'] ?? 0;
$totals['total_cost_value'] += $result->batch_stock['opening_cost_value'];
$totals['total_sale_value'] += $result->batch_stock['opening_sale_value'];
$totals['total_opening_stock'] +=$result->batch_stock['opening_stock'];
$totals['total_closing_stock'] +=$result->batch_stock['closing_stock'];
$totals['total_closing_cost_value'] +=$result->batch_stock['closing_cost_value'];
$totals['total_closing_sale_value'] +=$result->batch_stock['closing_sale_value'];
}
return view('stores::stores.electronic_stock_card', compact('item_options','totals','start_date','end_date','opening_stock_date', 'quotation_type_options', 'item_type', 'results', 'display', 'item_id'));
}
public function electronic_stock_card_details(Request $request)
{
$item_id = $request->item_id;
$item_type = $request->item_type;
$start_date = $request->start_date;
$request_type=$request->request_type;
$opening_stock_date=$request->opening_stock_date;
$end_date =$closing_stock_date= $request->end_date;
$display=$stock_reorder=$table_unit_name=$item_name='';
$amc=0;
if ($item_type == 1) {
//Drugs
$amc=get_item_average_monthly_consumption($item_type,$item_id,30);
$selling_price = Drug::select()->where('id', $item_id)->pluck('non_insured_price')->toArray();
$units = Drug::select()->where('id', $item_id)->pluck('unit_id')->toArray();
$table_unit_name='drug_forms';
$table_name = 'drugs';
$table_col_name='name';
$table_reorder_name='reorder_level';
} elseif($item_type == 2) {
//Sundries
$amc=get_item_average_monthly_consumption($item_type,$item_id,30);
$selling_price = Sundry::select()->where('id', $item_id)->pluck('non_insured_price')->toArray();
$table_name = 'sundries';
$table_col_name='name';
$units= Sundry::select('form_id')->where('id', $item_id)->first()['form_id'];
$table_unit_name='general_forms';
$table_reorder_name='re_order_level';
} elseif($item_type == 3) {
//Dentals
$selling_price = Dental::select()->where('id', $item_id)->pluck('non_insured_price')->toArray();
$table_name = 'dentals';
$table_col_name='name';
$table_reorder_name='re_order_level';
} elseif($item_type == 4) {
//Radiologies
$table_name = 'radiologies';
$table_unit_name='general_forms';
$table_col_name='name';
$table_reorder_name='reorder_level';
} elseif($item_type == 5) {
//Labs
$units= Lab::select()->where('id', $item_id)->pluck('form_id')->toArray();
$table_name = 'labs';
$table_unit_name='lab_forms';
$table_col_name='name';
$table_reorder_name='reorder_level';
} elseif($item_type == 6) {
//General Items
$table_name = 'general_items';
$table_col_name='name';
$table_reorder_name='reorder_level';
} elseif($item_type == 7) {
//Eye Glasses
$table_name = 'eye_glasses';
$table_col_name='name';
$table_reorder_name='reorder_level';
}
$item_name=get_name($item_id, 'id', 'name', "{$table_name}");
($table_unit_name!='')? $unit_name=get_name($item_id, 'id', 'name', "{$table_unit_name}"):$unit_name='';
$unit_name=($unit_name == 'N/A')?'':$unit_name;
$stock_reorder=get_name($item_id, 'id', "{$table_reorder_name}", "{$table_name}");
$batch_stock_watcher = BatchStockWatcher::where('item_id',$item_id)->where('item_type',$item_type)->whereNot('item_batch_watcher_id',0)->get();
foreach ($batch_stock_watcher as $record){
$details_arr = json_decode($record->details, true);
$details = $details_arr[$opening_stock_date] ?? $details_arr[get_closest_element_in_array(array_keys($details_arr), $opening_stock_date)];
$details_closing= $details_arr[$closing_stock_date] ?? $details_arr[get_closest_element_in_array(array_keys($details_arr), $closing_stock_date)];
$record->opening_stock = $details;
$record->date_opening_stock = get_closest_element_in_array(array_keys($details_arr), $opening_stock_date);
$record->closing_stock = $details_closing;
}
//get prev issue out
$issued_out_items =BatchIssuedTracking::where('item_id',$item_id)->where('item_type',$item_type)->whereBetween('created_at', [$start_date, $end_date])
->orderBy('created_at', 'desc')->get()->toArray();
// get prev received items
$received_items = Quotation::select('id','quotation_type_id','drug_id','directly_received_items','batch_number','expiry_date','supplier_id','approval_user','billing_user','receive_quantity','receive_date','receive_bill_per_package_unit','destination','receive_bill')
->where(['quotation_type_id'=>$item_type,'drug_id'=>$item_id,'receive_status'=>1,'approval_status'=>1,'destination'=>'store'])
->whereBetween('receive_date', [$start_date, $end_date])->whereNotNull(['approval_user','billing_user'])
->get()->toArray();
if (in_array($item_type, [4, 5])){
$reconciled_stocks = GeneralStockReconciliation::where(['source'=>1,'item_type'=>$item_type,'item_id'=>$item_id])
->whereBetween('created_at',[$start_date, $end_date])->orderBy('stock_count_identifier', 'desc')->get()->toArray();
}
else if($item_type == 1) {
$reconciled_stocks = StoreStockReconciliation::select('drug_id as item_id','difference','reconciliation_date','id')->where('drug_id',$item_id)->whereBetween('created_at', [$start_date, $end_date])->orderBy('stock_count_identifier', 'desc')->get()->toArray();
}
else if ($item_type == 2){
$reconciled_stocks = SundryStoreStockReconciliation::select('sundry_id as item_id','difference','reconciliation_date','id')->where('sundry_id',$item_id)->whereBetween('created_at', [$start_date, $end_date])->orderBy('stock_count_identifier', 'desc')->get()->toArray();
}
else if ($item_type == 6){
$reconciled_stocks = GeneralItemStoreStockReconciliation::select('general_item_id as item_id','difference','id','created_at as reconciliation_date')->where('general_item_id',$item_id)->whereBetween('created_at', [$start_date, $end_date])->orderBy('stock_count_identifier', 'desc')->get()->toArray();
}
$display = "Stock Movement Details for " . $item_name . " between " . streamline_date($start_date) . " and " . streamline_date($end_date);
$data_array=combineByDate($issued_out_items,$received_items,$batch_stock_watcher,$reconciled_stocks,$item_id,$opening_stock_date);
$opening_stock=$data_array['opening_stock'];
$closing_stock=$data_array['closing_stock'];
$data=$data_array['data'];
if ($request_type=='2') {
$data_details = [
'data' => $data,
'unit_name' => $unit_name,
'amc' => $amc,
'opening_stock' => $opening_stock,
'closing_stock' => $closing_stock,
'stock_reorder' => $stock_reorder,
'start_date'=>$start_date,
'end_date'=>$end_date,
'display'=>$display,
];
//print view
$pdf = SnappyPDF::loadView('stores::stores/electronic_stock_card_details_print', $data_details)
->setOrientation('portrait')
->setOption('margin-bottom', 7)
->setOption('margin-top', 5)
->setOption('footer-html', '<i>Stre@mline</i> '.streamline_date(date('Y-m-d')).' Printed By: '.get_full_name(Auth::id(), "id", "first_name", "last_name", "users").' '.streamline_date_time(date('Y-m-d H:m:i')));
return $pdf->inline('Stock Card Details' . date(" d-m-y h:ia") . '.pdf');
}
return view('stores::stores.electronic_stock_card_details', compact('data','unit_name','amc','start_date','end_date','opening_stock_date','item_type','item_id','opening_stock','closing_stock','stock_reorder', 'display'));
}
public function electronic_stock_card_receive_items_drill_down(Request $request){
$item_id = $request->item_id;
$item_type = $request->item_type;
$start_date =$opening_stock_date= $request->start_date;
$end_date =$closing_stock_date= $request->end_date;
$display=$unit_name=$item_name='';
$selling_price=0;
$units=$table_unit_name='';
$request_type = $request->request_type;
if ($item_type == 1) {
//Drugs
$selling_price = Drug::select('non_insured_price')->where('id', $item_id)->first()['non_insured_price'];
$units = Drug::select('form_id')->where('id', $item_id)->first()['form_id'];
$table_unit_name='drug_forms';
$table_name = 'drugs';
$table_col_name='name';
} elseif($item_type == 2) {
//Sundries
$amc=get_item_average_monthly_consumption($item_type,$item_id,30);
$selling_price = Sundry::select('non_insured_price')->where('id', $item_id)->first()['non_insured_price'];
$table_name = 'sundries';
$units= Sundry::select('form_id')->where('id', $item_id)->first()['form_id'];
$table_unit_name='general_forms';
$table_col_name='name';
} elseif($item_type == 3) {
//Dentals
$selling_price = Dental::select('non_insured_price')->where('id', $item_id)->first()['non_insured_price'];
$table_name = 'dentals';
$table_col_name='name';
} elseif($item_type == 4) {
//Radiologies
$table_unit_name='general_forms';
$units = Radiology::select()->where('id', $item_id)->first()['form_id'];
$table_name = 'radiologies';
$table_col_name='name';
} elseif($item_type == 5) {
//Labs
$units= Lab::select()->where('id', $item_id)->first()['form_id'];
$table_name = 'labs';
$table_unit_name='lab_forms';
$table_col_name='name';
} elseif($item_type == 6) {
//General Items
$table_name = 'general_items';
$table_col_name='name';
} elseif($item_type == 7) {
//Eye Glasses
$table_name = 'eye_glasses';
$table_col_name='name';
}
$item_name=get_name($item_id, 'id', 'name', "{$table_name}");
($units != '') ? $unit_name=get_name($units, 'id', 'name', "{$table_unit_name}"): $unit_name='';
$data_items = Quotation::select('id','quotation_type_id','quotation_number','grn_number','drug_id','directly_received_items','batch_number','expiry_date','supplier_id','approval_user','billing_user','receive_quantity as quantity','receive_date as date','receive_bill_per_package_unit','destination','receive_bill as unit_cost')
->where(['quotation_type_id'=>$item_type,'drug_id'=>$item_id,'receive_status'=>1,'approval_status'=>1,'destination'=>'store'])
->whereBetween('receive_date', [$start_date, $end_date])->whereNotNull(['approval_user','billing_user','supplier_id','receive_quantity'])
->get()->toArray();
$display = "Received Stock Details for " . $item_name . " between " . streamline_date($start_date) . " and " . streamline_date($end_date);
$summary=[];
foreach ($data_items as &$record){
$supplier_name = get_name($record['supplier_id'],'id','name','suppliers');
if (!isset($supplier[$supplier_name])){
$summary[$supplier_name]=$record['quantity'];
}
else{
$summary[$supplier_name]+=$record['quantity'];
}
$record['name']=$supplier_name;
$record['cost_value']= (int) $record['quantity'] * (int) $record['unit_cost'];
$record['sale_value'] = (int) $record['quantity'] * (int) $selling_price;
}
$type=1;
$route='stores.received_items_drill_down';
if ($request_type == '2'){
$data_details = [
'data_items' => $data_items,
'unit_name' => $unit_name,
'start_date'=>$start_date,
'end_date'=>$end_date,
'type'=>$type,
'item_type'=>$item_type,
'summary'=>$summary,
'display'=>$display,
];
//print view
$pdf = SnappyPDF::loadView('stores::stores/electronic_stock_card_drill_details_print', $data_details)
->setOrientation('portrait')
->setOption('margin-bottom', 7)
->setOption('margin-top', 5)
->setOption('footer-html', '<i>Stre@mline</i> '.streamline_date(date('Y-m-d')).' Printed By: '.get_full_name(Auth::id(), "id", "first_name", "last_name", "users").' '.streamline_date_time(date('Y-m-d H:m:i')));
return $pdf->inline('Received Stock Card Details' . date(" d-m-y h:ia") . '.pdf');
}
return view('stores::stores.electronic_stock_card_drill_details', compact('data_items','item_type','route','item_id','start_date','end_date', 'summary', 'display','unit_name','type'));
}
public function electronic_stock_card_issued_items_drill_down(Request $request){
$item_id = $request->item_id;
$item_type = $request->item_type;
$start_date =$opening_stock_date= $request->start_date;
$end_date =$closing_stock_date= $request->end_date;
$display=$unit_name=$item_name='';
$selling_price=0;
$units=$table_unit_name='';
$request_type = $request->request_type;
if ($item_type == 1) {
//Drugs
$selling_price = Drug::select('non_insured_price')->where('id', $item_id)->first()['non_insured_price'];
$units = Drug::select('form_id')->where('id', $item_id)->first()['form_id'];
$table_unit_name='drug_forms';
$table_name = 'drugs';
$table_col_name='name';
} elseif($item_type == 2) {
//Sundries
$amc=get_item_average_monthly_consumption($item_type,$item_id,30);
$selling_price = Sundry::select('non_insured_price')->where('id', $item_id)->first()['non_insured_price'];
$table_name = 'sundries';
$units = Sundry::select('form_id')->where('id', $item_id)->first()['form_id'];
$table_unit_name='general_forms';
$table_col_name='name';
} elseif($item_type == 3) {
//Dentals
$selling_price = Dental::select('non_insured_price')->where('id', $item_id)->first()['non_insured_price'];
$table_name = 'dentals';
$table_col_name='name';
} elseif($item_type == 4) {
//Radiologies
$table_unit_name='general_forms';
$units = Radiology::select('form_id')->where('id', $item_id)->first()['form_id'];
$table_name = 'radiologies';
$table_col_name='name';
} elseif($item_type == 5) {
//Labs
$units= Lab::select('form_id')->where('id', $item_id)->first()['form_id'];
$table_name = 'labs';
$table_unit_name='lab_forms';
$table_col_name='name';
} elseif($item_type == 6) {
//General Items
$table_name = 'general_items';
$table_col_name='name';
} elseif($item_type == 7) {
//Eye Glasses
$table_name = 'eye_glasses';
$table_col_name='name';
}
$item_name=get_name($item_id, 'id', 'name', "{$table_name}");
($units != '') ? $unit_name=get_name($units, 'id', 'name', "{$table_unit_name}"): $unit_name='';
//get prev issue out
$issued_out_items = BatchIssuedTracking::select('requisition_id','id','batch_number','quantity_moved as quantity','moved_to','created_at','item_id')->where(['item_id'=>$item_id,'item_type'=>$item_type])->whereBetween('created_at', [$start_date, $end_date])
->orderBy('created_at', 'desc')->get()->toArray();
$display = "Issued Out Stock Details for " . $item_name . " between " . streamline_date($start_date) . " and " . streamline_date($end_date);
// Add issued data
$data_items=$summary=[];
foreach ($issued_out_items as &$item) {
$batch_item_details = ItemBatchWatcher::where(['item_id'=> $item['item_id'],'batch_number'=>$item['batch_number'],'item_type'=>$item_type])->first();
if ($item['moved_to']== 'ward'){
//get ward name
$ward_id = get_name($item['requisition_id'],'id','ward_id','ward_item_requests');
$item['name'] = get_name($ward_id, 'id', 'name', 'wards');
$item['name_title']='IPD';
} else $item['name_title']=$item['name']=$item['moved_to'];
$item['date']= explode('T',$item['created_at'])[0];
if (!isset($summary[$item['name_title']])){
$summary[$item['name_title']]=$item['quantity'];
}else $summary[$item['name_title']]+=$item['quantity'];
$item['cost_value']= (int) $item['quantity'] * (int) $batch_item_details->cost_price??0;
$item['sale_value'] = (int) $item['quantity'] * (int) $selling_price;
$item['expiry_date'] = $batch_item_details->expiry_date;
$item['unit_cost']= $batch_item_details->cost_price??0;
$item['quotation_number']=$item['requisition_id'];
$data_items[]=$item;
}
$type=2;
$route='stores.issued_items_drill_down';
if ($request_type == '2'){
$data_details = [
'data_items' => $data_items,
'unit_name' => $unit_name,
'start_date'=>$start_date,
'end_date'=>$end_date,
'type'=>$type,
'item_type'=>$item_type,
'summary'=>$summary,
'display'=>$display,
];
//print view
$pdf = SnappyPDF::loadView('stores::stores/electronic_stock_card_drill_details_print', $data_details)
->setOrientation('portrait')
->setOption('margin-bottom', 7)
->setOption('margin-top', 5)
->setOption('footer-html', '<i>Stre@mline</i> '.streamline_date(date('Y-m-d')).' Printed By: '.get_full_name(Auth::id(), "id", "first_name", "last_name", "users").' '.streamline_date_time(date('Y-m-d H:m:i')));
return $pdf->inline('Issued Out Stock Card Details' . date(" d-m-y h:ia") . '.pdf');
}
return view('stores::stores.electronic_stock_card_drill_details', compact('data_items','route', 'summary','item_id','start_date','end_date','item_type', 'display','unit_name','type'));
}
public function electronic_stock_card_adjustment_drill_down(Request $request){
$item_id = $request->item_id;
$item_type = $request->item_type;
$start_date =$opening_stock_date= $request->start_date;
$end_date =$closing_stock_date= $request->end_date;
$display=$unit_name=$item_name='';
$selling_price=0;
$units=$table_unit_name='';
$request_type = $request->request_type;
if ($item_type == 1) {
//Drugs
$selling_price = Drug::select('non_insured_price')->where('id', $item_id)->first()['non_insured_price'];
$units = Drug::select('form_id')->where('id', $item_id)->first()['form_id'];
$table_unit_name='drug_forms';
$table_name = 'drugs';
$table_col_name='name';
} elseif($item_type == 2) {
//Sundries
$amc=get_item_average_monthly_consumption($item_type,$item_id,30);
$selling_price = Sundry::select('non_insured_price')->where('id', $item_id)->first()['non_insured_price'];
$table_name = 'sundries';
$units = Sundry::select('form_id')->where('id', $item_id)->first()['form_id'];
$table_unit_name='general_forms';
$table_col_name='name';
} elseif($item_type == 3) {
//Dentals
$selling_price = Dental::select('non_insured_price')->where('id', $item_id)->first()['non_insured_price'];
$table_name = 'dentals';
$table_col_name='name';
} elseif($item_type == 4) {
//Radiologies
$units = Radiology::select('form_id')->where('id', $item_id)->first()['form_id'];
$table_unit_name='general_forms';
$table_name = 'radiologies';
$table_col_name='name';
} elseif($item_type == 5) {
//Labs
$units= Lab::select('form_id')->where('id', $item_id)->first()['form_id'];
$table_name = 'labs';
$table_unit_name='lab_forms';
$table_col_name='name';
} elseif($item_type == 6) {
//General Items
$table_name = 'general_items';
$table_col_name='name';
} elseif($item_type == 7) {
//Eye Glasses
$table_name = 'eye_glasses';
$table_col_name='name';
}
$item_name=get_name($item_id, 'id', 'name', "{$table_name}");
($units != '') ? $unit_name=get_name($units, 'id', 'name', "{$table_unit_name}"): $unit_name='';
if (in_array($item_type, [4, 5])){
if ($item_type == 4){
$route='stores.radiologies_stock_reconciliation_report_details';
}
if ($item_type == 5){
$route='stores.labs_stock_reconciliation_report_details';
}
$reconciled_stocks = GeneralStockReconciliation::where(['source'=>1,'item_type'=>$item_type,'item_id'=>$item_id])
->whereBetween('created_at',[$start_date, $end_date])->orderBy('stock_count_identifier', 'desc')->get()->toArray();
}
else if($item_type == 1) {
$route='stores.stock_reconciliation_report_details';
$reconciled_stocks = StoreStockReconciliation::select('drug_id as item_id','difference','stock_count_identifier','reconciliation_date','id','created_by','system_stock','physical_stock')->where('drug_id',$item_id)->whereBetween('created_at', [$start_date, $end_date])->orderBy('stock_count_identifier', 'desc')->get()->toArray();
}
else if ($item_type == 2){
$route='stores.sundries_stock_reconciliation_report_details';
$reconciled_stocks = SundryStoreStockReconciliation::select('sundry_id as item_id','difference','stock_count_identifier','reconciliation_date','id','created_by','system_stock','physical_stock')->where('sundry_id',$item_id)->whereBetween('created_at', [$start_date, $end_date])->orderBy('stock_count_identifier', 'desc')->get()->toArray();
}
else if ($item_type == 6){
$route='stores.general_items_stock_reconciliation_report_details';
$reconciled_stocks = GeneralItemStoreStockReconciliation::select('general_item_id as item_id','difference','stock_count_identifier','reconciliation_date','id','created_by','system_stock','physical_stock')->where('general_item_id',$item_id)->whereBetween('created_at', [$start_date, $end_date])->orderBy('stock_count_identifier', 'desc')->get()->toArray();
}
foreach($reconciled_stocks as &$stock){
$stock['name']=get_full_name($stock['created_by'], 'id', 'first_name','last_name', 'users');
$stock['date']= explode('T', $stock['reconciliation_date'])[0];
}
$display = "Adjusted Stock Card Details for " . $item_name . " between " . streamline_date($start_date) . " and " . streamline_date($end_date);
if ($request_type == '2'){
$data_details = [
'reconciled_stocks' => $reconciled_stocks,
'unit_name' => $unit_name,
'start_date'=>$start_date,
'end_date'=>$end_date,
'display'=>$display,
];
//print view
$pdf = SnappyPDF::loadView('stores::stores/electronic_adjusted_stock_card_drill_details_print', $data_details)
->setOrientation('portrait')
->setOption('margin-bottom', 7)
->setOption('margin-top', 5)
->setOption('footer-html', '<i>Stre@mline</i> '.streamline_date(date('Y-m-d')).' Printed By: '.get_full_name(Auth::id(), "id", "first_name", "last_name", "users").' '.streamline_date_time(date('Y-m-d H:m:i')));
return $pdf->inline('Adjusted Stock Card Details' . date(" d-m-y h:ia") . '.pdf');
}
return view('stores::stores.electronic_adjusted_stock_card_drill_details', compact('display','item_id','start_date','end_date','item_type','route', 'unit_name','reconciled_stocks'));
}
public function clean_labs_with_no_expense_accounts()
{
$labs_bills = HospitalBill::where('bill_type','LAB')->get();
$items_accounts_new_array = [];
foreach ($labs_bills as $bill) {
$expense_account_id = null;
$items_ids_array = explode(",", $bill->item_ids);
$items_expense_accounts_array = explode(",", $bill->item_accounts);
$items_accounts_new_array = [];
for ($i=0; $i < count($items_ids_array) ; $i++) {
$expense_account_id = get_name($items_ids_array[$i], 'id', 'expenses_account_id', 'labs');
if (is_null($expense_account_id) || $expense_account_id == "N/A" || $expense_account_id == "") {
$expense_account_id = get_name('labs_expense_account', 'slug', 'id', 'chart_of_accounts');
if ($expense_account_id == "N/A") {
$expense_account_id = 14; //default to payable account if needed accounts are not found
}
}
$items_accounts_new_array[] = $expense_account_id;
}
//update the bills record with new accounts
$bill->item_accounts = implode(",", $items_accounts_new_array);
$bill->update();
}
return "Lab bills with no expenses accounts have been cleaned";
}
public function get_item_batch_watcher_details(Request $request)
{
$batch_record = ItemBatchWatcher::find($request->batch_number);
if ($batch_record) {
return $batch_record;
}
return false;
}
public function clean_stock_watcher_to_remove_deleted(Request $request){
$all_batches_array = ItemBatchWatcher::where('item_type', 1)->pluck('id')->toArray();
$batch_stock_watcher = BatchStockWatcher::where('item_type', 1)->whereNotIn('item_batch_watcher_id', $all_batches_array)->delete();
$all_batch_stock_watcher = BatchStockWatcher::where('item_type', 1)->get();
$associative_doubles_array = [];
$duplicate_records = [];
foreach ($all_batch_stock_watcher as $one_batch_row) {
if (array_key_exists($one_batch_row->item_batch_watcher_id, $associative_doubles_array)) {
$associative_doubles_array[$one_batch_row->item_batch_watcher_id] = $one_batch_row->id;
$duplicate_records[$one_batch_row->item_batch_watcher_id] = $one_batch_row->id;
} else{
$associative_doubles_array[$one_batch_row->item_batch_watcher_id] = $one_batch_row->id;
}
}
//delete the duplicate
foreach ($duplicate_records as $item_batch_watcher_id => $stocker_watcher_id) {
$stock_watcher_records = BatchStockWatcher::where(['item_batch_watcher_id' => $item_batch_watcher_id, 'item_type' => 1])->first();
$stock_watcher_records->delete();
}
return "removed drugs with deleted batches";
}
public function issued_items_history_cost_centres(Request $request){
$item_options = [];
$quotation_type_options = DB::table('quotation_types')->pluck('name', 'id')->toArray();
$quotation_type_options = ['' => '- Select Quotation type -'] + $quotation_type_options;
$item_options['drugs'] = DB::table('drugs')->where('available', 1)->whereNull('deleted_at')->pluck('name', 'id')->prepend('All drugs', 'all_items')->toArray() + ['' => '-- select --'];
$item_options['sundries'] = DB::table('sundries')->whereNull('deleted_at')->pluck('name', 'id')->prepend('All sundries', 'all_items')->toArray() + ['' => '-- select --'];
$item_options['dentals'] = DB::table('dentals')->whereNull('deleted_at')->pluck('name', 'id')->prepend('All dentals', 'all_items')->toArray() + ['' => '-- select --'];
$item_options['labs'] = DB::table('labs')->whereNull('deleted_at')->pluck('name', 'id')->prepend('All labs', 'all_items')->toArray() + ['' => '-- select --'];
$item_options['radiologies'] = DB::table('radiologies')->whereNull('deleted_at')->pluck('name', 'id')->prepend('All radiologies', 'all_items')->toArray() + ['' => '-- select --'];
$item_options['general_items'] = DB::table('general_items')->whereNull('deleted_at')->pluck('name', 'id')->prepend('All general items', 'all_items')->toArray() + ['' => '-- select --'];
$item_options['eye_glasses'] = DB::table('eye_glasses')->whereNull('deleted_at')->pluck('name', 'id')->prepend('All eye glasses', 'all_items')->toArray() + ['' => '-- select --'];
$item_type = 0;
$item_id = 0;
$quotation_type_id = 0;
$item_name = "N/A";
$search_all_items = false;
$start_date_raw = $request->start_date;
$end_date_raw = $request->end_date;
if (isset($request->start_date) && isset($request->end_date)) {
$start_date = Carbon::createFromFormat('d/m/Y', $request->start_date)->toDateTimeString();
$end_date = Carbon::createFromFormat('d/m/Y', $request->end_date)->toDateTimeString();
} else {
$start_date = Carbon::now()->toDateTimeString();
$end_date = Carbon::now()->toDateTimeString();
}
if (isset($request->selected_drugs) && $request->quotation_type == 1) {
//Drugs
$item_id = $request->selected_drugs;
$quotation_type_id = $request->quotation_type;
$item_id == "all_items" ?: $item_name = DB::table('drugs')->find($request->selected_drugs)->name;
} elseif(isset($request->selected_sundries) && $request->quotation_type == 2) {
//Sundries
$item_id = $request->selected_sundries;
$quotation_type_id = $request->quotation_type;
$item_id == "all_items" ?: $item_name = DB::table('sundries')->find($request->selected_sundries)->name;
} elseif(isset($request->selected_dentals) && $request->quotation_type == 3) {
//Dentals
$item_id = $request->selected_dentals;
$quotation_type_id = $request->quotation_type;
$item_id == "all_items" ?: $item_name = DB::table('dentals')->find($request->selected_dentals)->name;
} elseif(isset($request->selected_radiologies) && $request->quotation_type == 4) {
//Radiologies
$item_id = $request->selected_radiologies;
$quotation_type_id = $request->quotation_type;
$item_id == "all_items" ?: $item_name = DB::table('radiologies')->find($request->selected_radiologies)->name;
} elseif(isset($request->selected_labs) && $request->quotation_type == 5) {
//Labs
$item_id = $request->selected_labs;
$quotation_type_id = $request->quotation_type;
$item_id == "all_items" ?: $item_name = DB::table('labs')->find($request->selected_labs)->name;
} elseif(isset($request->selected_general_items) && $request->quotation_type == 6) {
//General Items
$item_id = $request->selected_general_items;
$quotation_type_id = $request->quotation_type;
$item_id == "all_items" ?: $item_name = DB::table('general_items')->find($request->selected_general_items)->name;
} elseif(isset($request->selected_eye_glasses) && $request->quotation_type == 7) {
//Eye Glasses
$item_id = $request->selected_eye_glasses;
$quotation_type_id = $request->quotation_type;
$item_id == "all_items" ?: $item_name = DB::table('eye_glasses')->find($request->selected_eye_glasses)->name;
}
$display = "Records for " . $item_name . " between " . streamline_date($start_date) . " and " . streamline_date($end_date);
$all_items_results = $ward_results = [];
$results = DB::table('requisitions')
->select('*')->whereNull('deleted_at')
->where('quotation_type_id', $quotation_type_id)
->whereRaw('FIND_IN_SET(' . $item_id . ',drug_id)')
->whereBetween('created_at', [$start_date, $end_date])
->get();
if(count($results) > 0):
foreach($results as $result):
$item_type = $request->quotation_type;
$requested_item_ids_explode = explode(",", $result->drug_id);
$quantity_requested_explode = explode(",", $result->quantity_requested);
$item_id_explode = explode(",", $result->item_ids_issued_out);
$issued_out_explode = explode(",", $result->quantity_issued);
$cost_value_explode = explode(",", $result->cost_value);
for($x = 0; $x < count($item_id_explode); $x++):
if ($item_id == $item_id_explode[$x]) {
$cost_value = isset($cost_value_explode[$x]) ? (int)$cost_value_explode[$x] : 0;
$qty_requested = $quantity_requested_explode[$x] ? (int)$quantity_requested_explode[$x] : 0;
$issued_qty = isset($issued_out_explode[$x]) ? (int)$issued_out_explode[$x] : 0;
if(array_key_exists($item_id_explode[$x],$all_items_results)):
$all_items_results[$item_id_explode[$x]]["quantity_requested"] += $qty_requested;
$all_items_results[$item_id_explode[$x]]["quantity_issued"] += $issued_qty;
$all_items_results[$item_id_explode[$x]]["cost_value"] += $cost_value;
else:
$all_items_results[$item_id_explode[$x]]["quantity_requested"] = $qty_requested;
$all_items_results[$item_id_explode[$x]]["quantity_issued"] = $issued_qty;
$all_items_results[$item_id_explode[$x]]["cost_value"] = $cost_value;
endif;
}
endfor;
endforeach;
endif;
$ward_results = DB::table('ward_item_requests')
->select('*')->whereNull('deleted_at')
->where(['item_type' => $quotation_type_id, 'issued_from' => 'store'])
->whereRaw('FIND_IN_SET(' . $item_id . ',item_ids_issued_out)')
->whereBetween('created_at', [$start_date, $end_date])
->get();
$ward_quantities_array = [];
if (count($ward_results)) {
foreach ($ward_results as $single_record) {
$ward_id = $single_record->ward_id;
$requested_item_ids_explode = explode(",", $single_record->item_ids);
$quantity_requested_explode = explode(",", $single_record->item_quantities);
$item_id_explode = explode(",", $single_record->item_ids_issued_out);
$issued_out_explode = explode(",", $single_record->quantity_issued_out);
for($x = 0; $x < count($item_id_explode); $x++){
if ($item_id == $item_id_explode[$x]) {
if(array_key_exists($ward_id,$ward_quantities_array)):
$ward_quantities_array[$ward_id] += $issued_out_explode[$x];
else:
$ward_quantities_array[$ward_id] = $issued_out_explode[$x];
endif;
}
}
}
}
return view('stores::stores.issued_items_history_cost_centres', compact('item_options', 'quotation_type_options', 'item_type', 'results', 'display', 'item_id', 'search_all_items', 'all_items_results', 'start_date_raw', 'end_date_raw', 'ward_quantities_array'));
}
}