I have a billing application, where I have a table for billings a table for billing numbering because the user can have more than one billing numbering and each numbering has its own consecutive, so when the user is going to create a billing he chooses the numbering, at the frontend the system shows the possible consecutive with which the billing will be created, is "possible" because if another user creates a billing before him, he will assign the consecutive. So the consecutive is finally assigned in the backend with this code:
...
$numbering = BillingNumbering::find($request->billing_numbering);
$number = $numbering->current_number + 1;
$billing->number = $number;
$numbering->current_number = $number;
$numbering->used = true;
$numbering->save();
$billing->save();
Where first I get the billing numbering, get the current number and increase in one and immediately update the table for future requests.
The problem is that some cases when multiples users are working and save a billing almost at the same time the billing take the same billing number generating duplicates in billing consecutives.
How can I achieve this without number duplication?
you can make the billing number unique. If I assume this is your real code. why you are saving 'numbering' first not 'billing'.
Related
I have a small billing software written in php CodeIgniter. This is how i save values when i submit a payment
<?php
public function addPayment() {
$id = $this->input->post('id');
$client_id = $this->input->post('client_id');
$date = strtotime($this->input->post('date_from_addpayment'));
$description = $this->input->post('description');
$cash_pending = $this->input->post('cash_pending');
$cash_recevied = $this->input->post('cash_recevied');
$balance = $cash_pending - $cash_recevied;
?>
When each transaction occur I want to sum all the due of the client at that time and save it in balance table in MySQL.
My PHPMySQL structure of payment column is as follow:
https://i.stack.imgur.com/ELJrL.png
I just want when user ADD THE PAYMENT then balance due at that time display in this column.
Screenshot: https://i.imgur.com/raboF4M.png
To my understanding, balance, due, cash_pending - all 3 field relates - refers to the same figure - the amount that is pending. What i believe is you need to restructure the code for a bit.
You need to have a table maintaining clients balance (like current one you have). Just u can remove cash_pending / due fields.
You then need to have another table that will record in transactions of all the cash received. And as and when the cash is received, you can just substract that amount from the balance for the client.
In case any excess amount needs to be added for something like cash given or so - that you can add to the clients balance field back. So all the time - you have a proper balance figure for the client and also have a record of all the cash received from the user.
First of all before ending the php tag close your function's curly bracket.
In your table id is auto increment so do not need to take id as a input to store in database.
put all required fields as your table structure like this.
$data = array('client_id'=>$client_id, 'date'=>$date,
'description'=>$description, 'cash_recevied'=>$cash_recevied, 'cash_pending'=>$cash_pending,
'due'=>$due );
$this->load->model('Your-model-name');
$this->your-model-name->function-name($data);
Now call your model. and then in your model do this
function FunctionName($data){
return $this->db->insert('tablename', $data);
}
Working on a lightweight invoicing system and I'm trying to update my 'items' table correctly without fully succeeding.
Once an invoice is saved, I need to mark the items as paid that were purchased so far that day for that buyer.
Right now this is my query:
$markitemspaidquery = "UPDATE solditems SET paidstatus='paid', paidtime='$date' WHERE buyerid='$buyer_id'";
This updates the records for the buyer correctly, but the problem is it will mark EVERY item in the table for that buyer 'paid'; even if it is from 3 days ago.
How can I use a query kind of like this one or achieve this affect?
$markitemspaidquery = "UPDATE solditems SET paidstatus='paid', paidtime='$date' WHERE buyerid='$buyer_id' AND DATE(timesold)=CURDATE() AND paidstatus='unpaid'";
In all reality, everything should be paid by the end of the day anyway because of the way the company works, but I would like to know for future reference since it's just using up unnecessary resources to update every item for the buyer.
Here is an example with order by and limit
update questions
set prepStatus=1,status_bef_change=status,cv_bef_change=closeVotes,max_cv_reached=greatest(max_cv_reached,closeVotes)
where status='O' and prepStatus = 0
order by qId desc
limit 900;
There is a flaw in your datamodel. You have items sold and invoices but no connection between them.
So you muddle your way through be saying: when there is an invoice on a day for a customer it must be an invoice exactly covering all items on that very day bought by that customer. This is a rule you are kind of making up - the database doesn't tell you this.
So have a reference in your sold items table to the invoice table. Once an invoice is entered in the system it must be linked to all items sold it includes. Thus the update is easy, or better not necessary, as it is not the sigle item sold which is paid, but the invoice. So the sold items shouldn't have columns paidstatus and paidtime, but the invoice should.
UPDATE: Here is an example for a working data model. Each item has an invoice number which is null at first. Once the customer checks out an invoice is written and all the customer's items without an invoice number get this new invoice number. The invoice's total amount is the sum of its items. I.e. you don't store the sum redundantly.
auction_item
auction_item_no - primary key
customer_no - not null
description - not null
price - not null
invoice_no - nullalble (null as long as not checked out)
invoice
invoice_no - composite primary key part 1
customer_no - composite primary key part 2
date_time - not null
I'm very new to PHP. I'm building a companion webservice for an iPhone application I'm creating.
I have the following DB table that i've created which is filled with triggers.
The basic concept is that for a given currency when the price hits the trigger price I'm going to send a push notification.
Before I can generate the push notification I need an elegant way to validate each entry in this table against the current market price.
On initial thought I was thinking to select each trigger price and each currency and compare against the current market price I have in another variable.
Could anyone tell me the most elegant way to achieve what I'm trying to do? (compare the whole table against market price for various currencies)
Also if you have any php snippets that would be great,
Thanks,
John
Well if the app has a user logged in then you only need to check for the rows for that user, which isn't that bad.
However I would implement the database differently, have a separate currencies table like this:
id SERIAL
currency_name VARCHAR(10)
market_price FLOAT
Then change your main table so that target_price is a FLOAT as well (you could use int if you store the number of cents -- or equivalent -- instead of a dollar value, so 103 instead of 1.03). Finally change currency to be an int that references the other table
currency_id INTEGER
Then you probably want to add a foreign key constraint to the table:
FOREIGN KEY (currency_id)
REFERENCES currencies(id)
Now you can update the currencies table as the market_price changes then use SQL to get a list of the rows that need triggered:
SELECT u.id
FROM users u, currencies c
WHERE u.currency_id = c.id
AND u.trigger_price <= c.market_price
;
That's probably the best way, in my opinion.
If you really need to do it in PHP then I'd create an associative array of the market prices where prices['currency_name'] = market price for that currency. And currency name matches the string in the table. Then you're just going to have to go through the whole table and check each match, assuming you've already fetched the table into $result and checked for errors:
while ($row = $result->fetch_assoc()) {
if (isset($prices[$row->currency) // Sanity check on the prices array
&& ($row->trigger_price <= $prices[$row->currency]))
{
// Matching row, do something with it ...
}
}
If you trust the database to only contain stuff in the currency array you can skip the sanity check. If you only want to check certain currencies you could only select rows that match currencies you have updates for.
I'm also assuming your condition is the trigger price being lower than the current price, you may need to do different logic depending on exactly what you want to do.
Horrible title I know, I couldn't find a better way to articulate my problem.
I searched through SO without success, but if the answer's already out there, feel free to link it and I will read it thoroughly.
I'm building a book ordering system. People will order books throughout the month, and one large order arrives at the end of every month.
Orders get recorded into an Order table with the following fields:
order_id, book_id, quantity, language, person_ordering, timestamp, month, year
When orders arrive, they are inputted into an Received table with the following fields:
book_id, quantity, language
Now suppose one person orders (2) copies of book 1. And another person orders (3). And another (5). For a grand total of (10).
Then the order arrives and it only has 7 copies.
I'm trying to write a script/function that will find out:
Which persons will receive their copies of the book (it's first come first serve, so the people that ordered it first will have their order fulfilled first.
If a person can only have their order partially fulfilled, to update the Order table (or possible a new Pending Orders table is needed?) to reflect that they have X amount still waiting to be fulfilled. Then the following month, their orders would be fulfilled first, again, based on date ordered.
I thought about pulling the information from the Orders table based on time-stamp of when the order was made and sorting through it, then pulling the information out of the Received table and somehow comparing the two arrays and updating a third array?
Or perhaps there's a simpler solution that I'm missing.
If more information is needed, I will gladly provide.
I've been pulling my hair out over this problem for 2 days straight.
Any help would be appreciated.
Thanks!
To me, it sounds like you could do away with your timestamp, month, and year variables to be replace with a single datetime stamp.
Also, add a column in your Received table for the datetime stamp of collection.
Finally, make another table to keep track of fulfilled orders.
Do a select * on the month needed ordered by the datetime stamp descending for your "orders" data.
In a separate query get your "received" data for programmatic comparison using the correct month.
Put the "received" quantity of each "received" book_id into separate variables (probably a key/value array).
For each "received" book_id, compare and compute the "ordered" quantity needed from each order in a sub-loop, updating the "received" quantity value. At the end of each iteration of your sub-loop, if your "ordered" quantity does not equal 0, then you need to add another entry for the next month with the remaining quantity, also enter all fulfilled orders into your new table.
* You **will not** want to modify any existing records, as you will almost certainly need this untouched in the future.
Clear as mud? :P
* Database tip - Every entry of every record should **always** have a datetime stamp and when possible, a "who did it".
You can try with adding an extra field in Received table.
when the order is coming you can calculate the number of copies that we can provide at that time.
book_id, quantity,qty_available, language
1. B1 2 2 EN
2. B1 3 3 EN
3. B1 5 2 EN
Assuming that the Received table is for current stock, and that orders are only shipped when the entire order can be shipped, here's a suggestion for what you can do:
Add a field to Order for whether the Order has been fulfilled.
Select from Order who have ordered the book, ordered by date. You can limit by quantity of Received.
Start fulfilling the Orders and marking them as such until quantity from Received is reached.
If what is left of Received quantity is not enough to fulfill an Order, leave it and leave the remaining quantity in Received for next time.
Hope it makes sense.
when i submit an edited order in which the reward points awarded is negative (because the new processed order is less than the original), in the reward history one of the entries is pushed forward 12 hours ahead of the most recent entry
this isn't causing any bad effects to the total reward points as the value is being calculated correctly
there's really nothing my edit order module could be doing that does this, to edit the order the module just does the exact same thing as what Reorder does but it also creates a new session which stores the previous order's item's, their qty, the date the order was made and it's increment id, how the points are calculated is that when they are normally calculated, there's a check for this session, if it's exists it gets the Base Grand Total, puts that though $this->getReward()->getRateToPoints()->calculateToPoints() and subtracts that from the points delta
when we process the order in the checkout, it just creates a new order but the transaction id is the same as the previous order, since internet sales looks at this transaction id they'll know which order to edit, the old order will be canceled during the next run of the synchronization scripts
given all of that, at no time do i ever do anything with the reward history and it's not always the order your editing who's reward history entry i pushed up, i went and edited order 100000040 but 100000042 was pushed up
NOTE: i should also point out that the orders are not storing the same transaction id at this time as i am waiting on sample xml to compare to the request/response xml from the payment gateway, so there is no way that an order once process is tied to another order in any way
The following code is taken from Enterprise_Reward_Model_Action_OrderExtra::getPoints, it is places between $pointsDelta = $this->getReward()->getRateToPoints()->calculateToPoints((float)$monetaryAmount); and return $pointsDelta;
$editOrder = Mage::getModel('core/session')->getData('editorder');
if(!is_null($editOrder))
{
$readConnection = Mage::getSingleton('core/resource')->getConnection('core_read');
$result = $readConnection->fetchAll("
SELECT sfo.entity_id FROM sales_flat_order AS sfo
WHERE sfo.increment_id = ?
LIMIT 1
",$editOrder['original_order']);
$order = Mage::getModel('sales/order')->load($result[0]['entity_id']);
$orderData = $order->getData();
$previousOrderMonetaryAmount = (($orderData['base_grand_total'] - $orderData['base_shipping_amount']) - $orderData['base_tax_amount']);
$pointsDelta = $pointsDelta - $this->getReward()->getRateToPoints()->calculateToPoints((float)$previousOrderMonetaryAmount);
}
above is a snapshot of what's happening, the top shows what the reward history was before en order was edited and processed, the bottom is what happens after (for #100000049 nothing happened so i had to do it again yo get the glitch showing up)
the items in #100000044 are completely different to order #100000048, order #100000046 is missing cause when the points delta is 0 (meaning no points will be added/subtracted) it doesn't show (which is good)
all the order with a negative values are processed edited orders of those which had positive values but had some items removed during the edit reducing the cart total (in the gateway, this would then refund the customer so it makes sense that they should not be allowed to have the points that they was refunded for)
The problem is to do with magento itself, by forcing a clean build of magento to always have a negative amount in the order using $pointsDelta = $pointsDelta - 100000 results in the exact same problem, no idea if Magento will consider it a bug though since the only way to have discovered it is via customization of Magento but i'll report it nun the less