Total Invoices - Receipts not adding up - php

I have the next issue - I have a table invoices and a table with receipts. An invoice is created by an agent and I want to get the sold for each agent but the numbers are wrong.
Here is what I've tried:
$agents = Agent::get();
$invoices_receipts_agent = array();
foreach ($agents as $agent) {
$payment_invoice = 0;
$payment_recepit = 0;
$id_agent = $agent->id_agent;
$invoices = Invoice::whereAgent_id($id_agent)->get();
foreach ($invoices as $invoice) {
$payment_invoice = $payment_invoice + $invoice->total_pay;
$recepits = Recepit::whereInvoice_id($invoice->id_invoice)->get();
if (count($recepits) > 0) {
foreach ($recepits as $recepit) {
$payment_recepit = $payment_recepit + $recepit->amount_payd;
}
}
}
$total = $payment_invoice - $payment_recepit;
$total_agents = ['name' => $agent->name, 'total' => $total];
array_push($invoices_receipts_agent, $total_agents);
}
I made a test and created two invoices for the agent with ID 5
First invoice: 10
Second invoice : 20
Total invoices: 30
Then I did a recepit for the second invoice and found the expected total:
Total: 10 + 20 - 20 = 10 (correct total)
And that's great, but I have an agent with 3600 invoices and something is wrong the total. The total (total = invoices - recepits) is too big, but I can't figure out why.
Extra detail: the fields for the numbers are float.

First of all, you have an easier way to handle this issue using Eloquent Relationships.
In this case, can define One-to-Many relationship between Agent and Invoice as:
class Agent {
...
function invoices(){
return $this->hasMany('App-Namespace\Invoice')
}
}
...and define the inverse relationship on Invoice.
Then, you must do same between Invoice and Receipt models, since an Invoice can have one to many receipts.
So, if Agents table primary key is id you could say:
$agent = Agent::find($agent_id)->invoices->get();
...to get an agent invoices; or:
$invoice = Invoice::find($invoice_id)->receipts->get();
...to get all receipts for a specific invoice.
And finally implement your code:
$agents = Agent::all();
$invoices_receipts_agent = array();
foreach ($agents as $agent) {
$payment_invoice = 0;
$invoices = $agent->invoices->get();
foreach ($invoices as $invoice){
$payment_invoice += $invoice->total_pay;
$payment_receipt += $invoice->receipts->sum('amount_paid');
}
$total = $payment_invoice + $payment_receipt;
$invoices_receipts_agent[] = ['name' => $agent->name, 'total' => $total];
}
Note: I have used sum collection function to get sum of values of column amount_paid of a particular receipt. You could do same to get sum of total_pay column of an invoice like:
$total_paid = $agent->invoices()->sum('total_pay');

Can you confirm it this current version of your code?
I see some typos like in:
$recepits = Recepit::whereInvoice_id($invoice->id_invoice)->get();
if (count($receipts) > 0) {
Here we have issues:
Variable is named $recepits, but then called in next line with other name ($receipts).
$receipts should be a collection (result of Eloquent query) not an array. So to get count you have to say: $receipts->count()
If this is your final code, those are definitly error which are affecting your result.

Related

Laravel get rows from table using timestamp column

In my table, I have 2 columns:
1-count_of_h 2- updated_at
Now I want select rows which is past the updated_at, count_of_h hours.
A code like this:
$rows = Model::where('updated_at', '<', Carbon::now()->subHours($row->count_of_h))->get();
But I don't know how can I do it.
My code is kinda dirty ( but it works )
$arrayOfData = [];
Model::chunk(100, function($model) {
foreach($model as $m) {
if($m->updated_at < Carbon::now()->subHours($m->count_of_h)) {
$arrayOfData[] = $m;
}
}
});
First is make an array. After that, it will take every 100 rows then check if its past count_of_h hours

insert the last inserted record id into an array in another table using Codeigniter

so I got two tables one called patients and another called tests , the tests table has the patient id , i have a page called add patient which have fields for adding new patient information and other fields for adding their test info and upload all the data into the two tables in one query ,tests fields could be duplicated by ajax to i could add more than one test to the same patient , now i wanna add more than one test at the same time into the tests table and i managed to do so but the case is i can't add the patient_id into tests table, i wanna add the same patient_id more than one time to all the tests i have added while adding a new patient in that page, i'm new to Codeigniter!
this is the adding page
the patient fields and the test fields
<input type="text" name="patientname" />
<input type="text" name="address" />
<input type="text" name="testname[]"/>
<input type="text" name="price[]" />
and this is my controller
public function testbby
{
$this->load->model("khmodel", "Khmodel");
// patient main info
$patient_input_data = array();
$patient_input_data['patientname'] = $this->input->post('patientname');
$patient_input_data['address'] = $this->input->post('address');
//test data
$testname = $this->input->post('testname[]');
$price = $this->input->post('price[]');
$test_input_data = array();
for ($i = 0; $i < count($testname); $i ++ )
{
$test_input_data[$i] = array(
'testname' => $testname[$i],
'price' => $price[$i],
);
}
$this->Khmodel->insert_bby($patient_input_data, $test_input_data);
redirect('main/dashboard');
}
and this is my model
public function insert_bby($patient, $test)
{
$this->db->insert('patients', $patient);
$patient_id = $this->db->insert_id();
// i used this and it worked but only while adding one test , s
//once it's gonna be an array i dunno what to do with the id !
//$test['refpatient']=$patient_id;
$this->db->insert_batch('tests', $test);
return $insert_id = $this->db->insert_id();
}
To start with, you don't need this.
$patient_input_data = array();
Because when you make the call
$patient_input_data['patientname'] = $this->input->post('patientname');
The array, $patient_input_data, will be created. There are times when you might want to make sure you have an array even if it's empty. But this isn't one of them.
For the array input values, ie testname[], get the data by leaving off the brackets at the end of the name. Like this.
//test data
$testname = $this->input->post('testname'); //instead of post('testname[]')
$price = $this->input->post('price');
The vars $testname and $price will be arrays with an item for each field on the form.
Seems to me that those two inputs are required so you should add code to check that is the case. The Form Validation class is excellent for that purpose.
The array $test_input_data is a case where you will want the array to exist - even if it's empty. You don't have to explicitly set the index value when adding items to the array, i.e. $test_input_data[$i] = array(... because $test_input_data[] = array(... will work just fine, but there's no harm either way.
On to the model. The first part is good. For the second you need to create arrays that include the patient id you got from the first insert and add that value to each of the sub-arrays in the $tests argument. The model then becomes this.
public function insert_bby($patient, $tests)
{
$this->db->insert('patients', $patient);
$patient_id = $this->db->insert_id();
// add the patient id key/value to each sub-array in $tests
foreach ($tests as $test)
{
$test['patient id'] = $patient_id;
}
// will return the number of rows inserted or FALSE on failure
return $this->db->insert_batch('tests', $tests);
}
the value i mean , i dont know but your code seems to be so right and logical
but i have tried this code and it worked so well , i didn't even use the model/
public function testbby
{
$this->load->model("khmodel", "Khmodel");
// patient main info
$patient_input_data = array();
$patient_input_data['patientname'] = $this->input->post('patientname');
$patient_input_data['address'] = $this->input->post('address');
//test data
$testname = $this->input->post('testname[]');
$price = $this->input->post('price[]');
$this->db->reset_query();
$this->db->insert('patients', $patient_input_data);
$patient_id=$this->db->insert_id();
$test_input_data = array();
for ($i = 0; $i < count($testname); $i ++ )
{
$test_input_data[] = array(
'testname' => $testname[$i],
'price' => $price[$i],
'patient_id'=>$patient_id
);
}
$this->db->reset_query();
$this->db->insert_batch('tbl_tests',$test_input_data);
redirect('main/dashboard');
}

Laravel - Simple foreach inside foreach - not updating the model with firstOrNew

Very simple task. Getting multiple data (invoices) from an API.
foreach($items->data as $item) {
$invoice = Invoice::firstOrNew(array('invoice_number' => $item->DocumentNo));
$invoice->total = $item->GrandTotal;
$invoice->save();
$m = 0;
foreach ($item->lines as $product) {
$productModel = Product::find(1)->where('unique_id', '=', $product->Product)->first();
if(isset($productModel)) {
$productToInvoice = ProductToInvoice::firstOrNew(array('product_id' => $productModel->product_id, 'invoice_id' => $invoice->id));
$productToInvoice->total = $product->LineNetAmt;
$productToInvoice->quantity = $product->QtyEntered;
$productToInvoice->price = $product->PriceEntered;
$productToInvoice->save();
}
$m++;
}
}
$item->lines are the products inside the invoice. Data coming from the API. I connect this data to my Product model with this line:
$productModel = Product::find(1)->where('unique_id', '=', $product->Product)->first();
When the invoice doesn't exist, everything seems to be ok. Product lines are added correctly.
When the invoice exists (and also the product lines): it updates the lines but total, quantity and price are the same for all lines.
EDIT: If you var_dump($m) inside the loop - it will print 0, 1 (for 2 lines) but if you save, for example productToInvoice->price = $m it will save 1 for each entry / line.
What exactly am I doing wrong here?
You should try this:
$productToInvoice->total = $productModel->LineNetAmt; // $productModel insted of $product
$productToInvoice->quantity = $productModel->QtyEntered; // $productModel insted of $product
$productToInvoice->price = $productModel->PriceEntered; // $productModel insted of $product
I think it's this line
Product::find(1)
you are finding Product with id 1 every time.
that line should be
$productModel = Product::where('unique_id', '=', $product->Product)->first();

Sum of Foreach Loop

I'm trying to total a bill balance with a program I'm working on in PHP.
The code I use to pull the pricing is as such.
public function PackagePricing($arg) {
$query = <<<SQL
SELECT packageID
FROM customer_packages
WHERE active = :true
AND customerID = :arg
SQL;
$resource = $this->db->db->prepare( $query );
$resource->execute( array (
":true" => 1,
":arg" => 1,
));
foreach($resource as $row) {
self::GetPricing($row['packageID']);
}
}
public function GetPricing($arg) {
$query = <<<SQL
SELECT price
FROM products
WHERE id = :arg
SQL;
$resource = $this->db->db->prepare( $query );
$resource->execute( array (
":arg" => $arg,
));
$totalBill = 0;
foreach($resource as $row) {
$totalBill+= $row['price'];
}
echo $totalBill;
}
Now by my understanding this should work, but what I'm getting in turn is:
On the right you can see the billing total and rather than totaling out it's giving me each individually.
The error seems quite obvious. Here's your sequence in different words :
Get all packages ID.
Foreach package ID, get the price of the item (only one result is returned)
For that single result, add up all the prices (you only get one). Print it and go back to 2.
What you see is not 2 prices that have been added as strings in some sort of way. You simply prints subsequently 2 different prices. 10 & 30
GetPricing should return a price, and the foreach loop that calls it should make the sum.
$total = 0;
foreach($resource as $row)
{
$total += self::GetPricing($row['packageID']);
}
Hope this helps.

Compare array values from one array PHP

NOTE:
I'm new to php and mysql.
Background info:
I have +/- 30,000 products and they are from 7 different supplier and they have a lot of the same products
let's say i have 1 product and three of the suppliers have the it, i need to publish the product with the lowest price and the other two product stay unpublished
that is the basic idea and this must run through the 30,000 products and check and see if there are any matches and run the publishing function
SQL setup:
There are two tables xxxx_virtuemart_product and xxxx_virtuemart_product_prices
There are three rows in xxxx_virtuemart_product ▬▬▬ product_id,product_sku,published ▬▬▬
There are two rows in xxxx_virtuemart_product_prices ▬▬▬ product_id,product_price ▬▬▬
My little bit of code:
I have this little code because i'm stuck, how can i make a check to see if there are any matches and then run a query to change the published value of the product with the lowest price?
i know there is a way to use the query to check for matches, but do not understand how to do is
$query = "SELECT `product_sku` FROM `xxxx_virtuemart_product`";
$query_run = mysql_query($query) or die (mysql_error());
while($row = mysql_fetch_assoc($query_run)){
foreach ($row as $key => $ps){
}
}
The below code is to check the price (not query optimize just a rough draft)
$z = //products price;
$x = //products price;
$c = //products price;
if ($z >= $x && $c >= $x) {
//the this products published value to 1
}else if ($x >= $z && $c >= $z) {
//the this products published value to 1
}else if ($z >= $c && $x >= $c) {
//the this products published value to 1
}
Can anyone please help me with this?
Thanks for reading
any questions are welcome.
Your problem is not about to compare arrays but more algorithm.
I will try this way.
1)SQL query to retrieve all the products : sql_products
2)construct a hashmap those key is product SKU (see : PHP Array)
To construct PHP hashmap : use arrays of arrays.
Example :
product_map[] = array();
foreach sql_product of sql_products :
- product_map[sql_product[SKU]][] = array(sql_product[supplier], sql_product[price], sql_product[information])
end of loop
Then loop again over the map of products constructed and sort each product record by price : that means you have to write a function to sort array (supplier, price, information).
Now you have a map of product : SKU => array(of array (supplier, price, information))

Categories