I am creating an intranet for a vehicle hire company
I set the default price as such:
$dayRate = '90.00';
I have created a field on my table to store a discount day rate if needed, called disc_day_rate which defaults to 0.
I pull the discount price as such
$discDayRate = $hire['disc_day_rate'];
I wish to find the lowest of these two numbers, but I think the default disc_day_rate of 0 is causing issues
I have tried using min(); and if ($discDayrate == "0") methods but after finding many answers on stackoverflow without having to post my own It's time to ask for help with an elegant solution
This ensures the 0.00 will never cause you a problem.
if ($discDayRate == 0.00) { ## don't use quotes here; it should be saved as a DECIMAL or INT in the database
$the_rate = $dayRate; ## back to the default
}
else {
if ($discDayRate < $dayRate) {
$the_rate = $diskDayRate;
}
else {
$the_rate = $dayRate;
}
}
$the_rate has your desired rate.
Related
I have a website that everything is working well except lowest price. I mean all prices will be changed based on selected currency but not lowest price.
Lowest Price is showing correctly just based on US dollar not other currencies, I mean If we will change currency to Euro, still lowest price is showing on US dollar which is default currency.
In my Sql Database I have a table pt_currencie and Column rate
and on my room page, lowest price is showing with following PHP code:
<?php echo $lowestPrice; ?>
and in the controller, the code is:
$this->data['lowestPrice'] = $this->hotels_lib->bestPrice($this->data['hotel']->id);
and here is setting for userdata and change currency
function changeCurrency($id){
$this->db->where('id',$id);
$rs = $this->db->get('pt_currencies')->result();
$this->session->set_userdata('currencycode', $rs[0]->code);
$this->session->set_userdata('currencysymbol', $rs[0]->symbol);
$this->session->set_userdata('currencyname', $rs[0]->name);
$this->session->set_userdata('currencyrate', $rs[0]->rate);
}
}
How can I show $lowestPrice based on selected currency (rate) ?
what formula should I add into above code that lowest price show based on selected currency?
Ok if I'm understanding your question correctly, you will have to take the currency rates out of the db into a php array and then determine the lowest price using php with something like this:
$query = "SELECT rate FROM pt_currencie";
$result = mysqli_query($db_conn, $query);
$rate_arr = mysqli_fetch_fields($result);
$currLowestPrice = $lowestPrice;
foreach ($rate_arr as $rate) {
$tmpLowestPrice = $lowestPrice * $rate;
if($currlowestPrice > $tmpLowestPrice)
$currLowestPrice = $tmpLowestPrice;
}
So this should atleast give you the lowest price in $currLowestPrice for adjusted to currency rates by the end of the for loop (the code above will probably have to be adjusted a bit for your program)
I need to create promo codes which should be short in length (~ 6 characters). The promo codes have to be unique, so I need to check their uniqueness in database as well. They need to be generated in batches of thousands, so a check in db with every coupon generation is not feasible. I have created a method which first generates the required number of coupons and then check for duplicates using where in(). Having duplicate count of greater than zero, makes it generate the count again.
public function generateCoupons($count, $length = 6)
{
$coupons = [];
while(count($coupons) < $count) {
do {
$coupon = strtoupper(str_random($length));
} while (in_array($coupon, $coupons));
$coupons[] = $coupon;
}
$existing = Offer::whereIn('coupon', $coupons)->count();
if ($existing > 0)
$coupons += $this->generateCoupons($existing, $length);
return (count($coupons) == 1) ? $coupons[0] : $coupons;
}
Need suggestions how to improve upon this? Or if I can have some other way to achieve the same.
Make sure the promo code is indexed in your DB. This will speed up the search for existing promo codes.
Otherwise, your method is good! you want to check as many codes as possible at once (which you do with the whereIn/count) and only re-generate the codes that were not unique.
Build a table new_codes with 1000 candidates. PRIMARY KEY(code).
DELETE new_codes
FROM new_codes
LEFT JOIN existing_codes ON existing_codes.code = new_codes.code
WHERE existing_codes.code IS NOT NULL;
That (if I did it right) will very quickly delete the dups. Now you will have not-quite-1000 'good' codes.
For several days now I am trying to cope with the algorithm implementation at the online shop which I am writing in PHP. I do not know whether the problem is only the implementation, or perhaps bad algorithm design. Hovewer, for me it seems fine. I only haven`t checked its complexity of it, but it's such a problem.
After a long deliberation on the same algorithm, without thinking on implementation I came up with the use of binary search tree (bst) with additional data inserted into list consist of user defined info (later about it). The whole orders list would be displayed, or returned using inorder method.
I write it like that:
If the input object date is greater than current object go right
If the input object date is less than current object go left
If the dates are the same stay at place
If the field is blank check if the product is in stock
If it is put into place and finish
If there is not do nothing and exit
If the field is full
{Check if on the list is this user id
If yes than check order priority
If no do nothing and exit
Check if there is product on stock
If yes replace record and exit
If no do nothing and exit
}
{If there is not user id on the list check if product is on stock
If yes then put element on the end
If no do nothing and exit
}
Maybe it looks a little bad, but I was not able to do indentation.
Data is transferred into algorithm in a loop until the end of orders list. The list is unordered.
This is my implementation:
class BinaryTree {
private $predescor = array(
'd'=>array('data'=>0),
'p'=>null,
'r'=>null,
'l'=>null
);
private $ancestor = array(
'd'=>array('data'=>0),
'p'=>null,
'r'=>null,
'l'=>null
);
private $i = 0;
public function insertIntoTree(&$root,$element)
{
$this->predescor = $root;
$this->predescor;
while($this->predescor)
{
if($element['d']['data']==$this->predescor['d']['data'])
{
$this->inertIntoList($element,$this->predescor['d']);
return true;
}
$this->predescor = $this->predescor;
if($element['d']['data']<$this->predescor['d']['data'])
{
$this->predescor = $this->predescor['l'];
}
else
{
$this->predescor = $this->predescor['r'];
}
}
$element['p'] = $this->predescor;
if(!$this->predescor)
{
$root = $element;
}
else if($element['d']['data']<$this->predescor['d']['data'])
{
$this->predescor['l'] = $element;
}
else
{
$this->predescor['r'] = $element;
}
return true;
}
public function putList(&$list,$root)
{
if($root!=null)
{
$this->putList($list, $root['l']);
$lista[$this->i] = $root;
$this->i++;
$this->putList($list, $root['r']);
}
return;
}
private function insertIntoList($element,&$position)
{
if($position == null)
{
$position = $element;
return true;
}
foreach($position['user'] as &$key)
{
if($key == $element['d']['user'])
{
if($key['priority']<$element['d']['user']['priority'])
{
return false;
}
else if($key['priority']==$element['d']['user']['priority'])
{
return false;
}
else
{
if(Orders::checkOrder($element['d']['user']['order']))
{
$key['order'] = $element['d']['user']['order'];
return true;
}
else
{
return false;
}
}
}
}
//#todo add at the end
return true;
}
}
I would like to advise whether there is a simpler way than using bst consisting of a quite complex arrays, which would also be easier to implement? Because now I can not inplement it in PHP.
Thank you in advance.
I wouldn't start by coding this in php at all.
I'd start by building this into the database. ("Orders" implies a database.) I'd start by clarifying a couple of points. Assuming that one order can have many line items . . .
The number of days since the last order seems to clearly apply to the order,
not to individual products.
The user can have "only one request carried at a time". Request for
what? Doesn't seem to make sense for this to apply either to an
order or to an order's line item.
The order priority seems to clearly apply to the order, not to line
items. But a line-item priority might make more sense. (What products does the customer need first?)
Whether the product is in stock seems to apply to the line items, not
to the order as a whole.
I'd start by creating two views. (Not because you'll eventually need two views, but because some things are still unclear.)
One view, which has to do with "ranking" as applied to an order, would calculate or display three things.
Number of days since the last order.
Is this order the "one request carried at a time"?
The order priority.
If the numbers assigned to these three things are consistent in scale, you can just sort on those three columns. But that's not likely. You'll probably need to weight each factor, possibly by multiplying by a "weighting" factor. A calculation on the result should let you put these in a useful order. It's not yet clear whether the calculation is best done in the view or in a stored procedure.
The other view would have to do with whether a line item is in stock. It's not clear whether one line item out of stock means the whole order is incomplete, or whether one line item out of stock changes the calculation of a weighted number that scales along with the others above. (You can make a good argument for each of those approaches.)
I have a matrix of inputs boxes which contain prices for dates. If there is no price in the database for a particular date the input box displays 0. I have the following code which saves into the database the prices typed into the input boxes. It does not save all the 0 values only the new prices.
Which is fine. However I have now discovered an issue. If one of the inputs dislays a value from the database, say $10 and I want to set it now to 0, the code will not do it.
It will only save if the values and above 0. I have not been able to do this final check.
The conditions for saving are
1. If the value is numeric
2. If it is 0 and already has an entry in the database then save
3. If it has no value in the database and is greater than 0
4. If it is 0 and has no value in the database then do not save
if (isset($this->data['Rate'])){
// for each rate
foreach($this->data['Rate'] as $rate_id => $room){
// for each room type
foreach($room as $room_id => $room){
$price_for_today = isset($room['Price'][$key]) ? $room['Price'][$key] : 0;
// get existing availabilities is num (get this from previous date loop)
$today = ''.$date.' 00:00:00';
$conditions = array('Availability.date' => $today,'Availability.room_id'=>$room_id);
$this->Availability->contain();
$result = $this->Availability->find('all',array('order'=>'Availability.room_id ASC', 'conditions'=>$conditions));
$avail_id = $result[0]['Availability']['id'];
// check prices
$check_prices = "SELECT * FROM prices
WHERE rate_id = '".$rate_id."' AND availability_id = '".$avail_id."'";
$prices_result = $this->Availability->query($check_prices);
// if new prices > 0.00
if($price_for_today>0 && is_numeric($price_for_today)){
// better checking needed!
if($prices_result){
$setprices = "UPDATE prices SET price = '".$price_for_today."'
WHERE rate_id = '".$rate_id."' AND availability_id = '".$avail_id."'";
$update = $this->Availability->query($setprices);
} else {
$setprices = "INSERT INTO prices (price, availability_id, rate_id)
VALUES ('".$price_for_today."', '".$avail_id."', '".$rate_id."')";
$insert = $this->Availability->query($setprices);
}
}
//$errors[] = $setprices;
} // end rooms loop
} // end Rates loop
Your problem is in
> // if new prices > 0.00
> if($price_for_today>0 &&
> is_numeric($price_for_today)){
here you specify that $prices_for_today have to be >0, so if you had a price and want to put it 0 today then you will not do anything... You should use
if(($price_for_today>0 && is_numeric($price_for_today)) || (!empty($prices_result) && $price_for_today==0 && is_numeric($price_for_today))){
if you change it it will now enter in the if and do the change.
I sugest that you do NOT use the query function unless is extremely necesary. you should create a model for price (if you haven't done that already) and then use the associations (hasMany, HasOne, HABTM) or load the model directly in the controller with $this->loadModel('Price'). Then use a find 'all' as always with conditions and fields. This recomendation is to use cake as it was intended, not indispensable. Also the save, updatefield, read can be done if you do this... leaving the checks and everything to cake.
In our order proces it is possible to send an invoice for a partial order. So when a couple of order lines are being shipped, an invoice have to be send also.
To make this possible I use this code:
$invoice = Mage::getModel('sales/service_order', $order)->prepareInvoice($items);
if (!$invoice->getTotalQty()) {
Mage::throwException(Mage::helper('core')->__('Cannot create an invoice without products.'));
}
$invoice->setRequestedCaptureCase(Mage_Sales_Model_Order_Invoice::CAPTURE_ONLINE);
$invoice->register();
$transactionSave = Mage::getModel('core/resource_transaction')
->addObject($invoice)
->addObject($invoice->getOrder());
$transactionSave->save();
$invoice->sendEmail();
$invoice->setEmailSent(true);
$invoice->save();
Where the $items variable is an array containing the order ids and the amount of products to be invoiced.
The created invoice shows the correct products to be invoiced, but somehow the totals aren't updated. The totals still are the totals of the complete order, instead of the partial invoice.
I probably have to update or recalculate the totals but can't find the right code to force the update.
Anyone around who can put me in the right direction?
Well, it seems I have found the problem. The functionality as described above works manually executing it in the administrator interface. The code as enclosed above I only got to work by changing a core file of Magento.
If you change line 103 of Mage_Sales_Model_Service_Order from continue; to $qty = 0; the functionality works.
In short, this is what happens. With continue the second row item isn't added to the invoice which the invoice makes thinks the curren item is the last item of the whole order and therefore needs to invoice the complete outstanding amount. In my case the invoice I did want to invoice and the row I didn't want to invoice.
I've submitted it as issue on the Magento issue list.
Today I faced with exactly this problem, but I found a more elegant way to solve it without editing the core. The solution is to pass the products that we don't want to invoice, with 0 quantity.
In this way, the code you changed in core will act exactly like in your solution :)
As an example if I have 2 products in my order:
array(
1234 => 1,
1235 => 2
)
passing this array:
$qtys = array(
1234 => 1,
1235 => 0
)
will force this code:
// Mage_Sales_Model_Service_Order: lines 97-103
if (isset($qtys[$orderItem->getId()])) { // here's the magic
$qty = (float) $qtys[$orderItem->getId()];
} elseif (!count($qtys)) {
$qty = $orderItem->getQtyToInvoice();
} else {
continue; // the line to edit according to previous solution
}
to act exactly like in your solution, so you don't have to edit core code.
Hope it helps :)
OK - took me a bit, but now I see how to correctly create the array.
foreach ($items as $itemId => $item) {
$itemQtyToShip = $item->getQtyToShip()*1;
if ($itemQtyToShip>0) {
$itemQtyOnHand = $stockItem->getQty()*1;
if ($itemQtyOnHand>0) {
//use the order item id as key
//set the amount to invoice for as the value
$toShip[$item->getId()] = $itemQtyToShip;
} else {
//if not shipping the item set the qty to 0
$toShip[$item->getId()] = 0;
}
}
$invoice = Mage::getModel('sales/service_order', $order)->prepareInvoice($toShip);
This creates a proper invoice.