I have a food ordering script which I want to add If delivery time is between 8:00:00PM - 7:59:59AM to add an extra fee of $5 and if it is between 8:00:00 AM and 7:59:59 PM to keep delivery as is in the script.
This is my code that calculates the delivery fee that returns the delivery fee we already have set in our dashboard.
We want to add this as a fix to add a fee for our night deliveries.
Day deliveries = Normal delivery Fee
Night Delivery = Normal delivery fee + 5
Thank you and I hope someone can guide me.
public static function verifyLocation($merchant_id=0, $lat=0, $lng=0,$order_subtotal=0)
{
$resp = Yii::app()->db->createCommand()
->select('merchant_id,latitude,lontitude,minimum_order')
->from('{{merchant}}')
->where("merchant_id=:merchant_id",array(
':merchant_id'=>(integer)$merchant_id,
))
->limit(1)
->queryRow();
if($resp){
$provider = FunctionsV3::getMapProvider();
MapsWrapper::init($provider);
$unit = FunctionsV3::getMerchantDistanceType($merchant_id);
$mode = isset($provider['mode'])?$provider['mode']:'driving';
$merchant_delivery_distance = getOption($merchant_id,'merchant_delivery_miles');
/*GET DELIVERY FEE*/
$delivery_fee = getOption($merchant_id,'merchant_delivery_charges');
$resp_distance = array();
if($merchant_delivery_distance>0){
$resp_distance = MapsWrapper::getDistance($resp['latitude'],$resp['lontitude'],$lat,$lng,$unit,$mode);
$distance = $resp_distance['distance'];
if($merchant_delivery_distance>0){
if($distance>$merchant_delivery_distance){
$pretty_distance = Yii::t("default","[distance] [unit]",array(
'[distance]'=>$merchant_delivery_distance,
'[unit]'=>MapsWrapper::prettyUnit($unit)
));
$error = Yii::t("default","Sorry but this merchant delivers only with in [distance] your current distance is [current_distance]",array(
'[distance]'=>$pretty_distance,
'[current_distance]'=>$resp_distance['pretty_distance']
));
throw new Exception( $error );
}
}
/*MINIMUM ORDER TABLE*/
$min_tables_enabled = getOption($merchant_id,'min_tables_enabled');
if($min_tables_enabled==1){
$min_order = self::getMinimumOrderTable(
$merchant_id,$resp_distance['distance'],$resp_distance['unit'],$resp['minimum_order']
);
if($min_order>$order_subtotal){
$error = Yii::t("default","Sorry but minimum order is [min_order] for distance [distance]",array(
'[min_order]'=>FunctionsV3::prettyPrice($min_order),
'[distance]'=>$resp_distance['pretty_distance']
));
throw new Exception( $error );
}
}
/*SHIPPING FEE*/
$shipping_enabled = getOption($merchant_id,'shipping_enabled');
if($shipping_enabled==2){
$delivery_fee = self::getShippingFee($merchant_id,$resp_distance['distance'],$resp_distance['unit'],$delivery_fee);
}
}
return array_merge((array)$resp_distance, array('delivery_fee'=>$delivery_fee));
} else throw new Exception( t("Merchant not found") );
}
You could achieve that by using php date to get time between desired time so you can increase the fee accordingly
*Note : PHP gets date from server ,if you were to set the price based on the individual user timezone.Javascript should be used to integrate with PHP
<?php
date_default_timezone_set('Africa/Johannesburg'); //Set your timezone here get php timezone from
https://www.php.net/manual/en/timezones.php
$normalfee = "500"; //The variable containing the normal fee
$tax = "5"; //The added tax for after 8pm fee increase
$getdate = date("Hi"); //Get some time from the server
echo $getdate."Debug : The current time now<br>"; //For debug purposes
if(($getdate > "759") && ($getdate < "2000")){
$finalfee = $normalfee;
echo $finalfee."Debug : Still the same fee<br>"; //The fee should remain normal starting at 8:00am till 7:59:59pm
} else {
$finalfee = $normalfee + $tax;
echo $finalfee."Night time fee added<br>"; //The fee will increase by 5 starting from 8:00pm till 7:59:59am
}
echo "Debug variable passed out of condition the dollar sign can now be added $".$finalfee."<br>";
//Again Debugging this is to show you can then use the $finalfee variable outside the conditions
?>
The script cleaned up...
<?php
date_default_timezone_set('Africa/Johannesburg');
$normalfee = "500";
$tax = "5";
$getdate = date("Hi");
if(($getdate > "759") && ($getdate < "2000")){
$finalfee = $normalfee;
} else {
$finalfee = $normalfee + $tax;
}
$display = "Final price $".$finalfee;
?>
Related
This question is based on Get selected variation price in jQuery on Woocommerce Variable products.
I have some code that works on the single product page to display a calculated price based on user input. The problem is that the calculated price also applies to the related products on the bottom of the page. Their price is set to be the same as the product being viewed.
I think the problem lies in the line $('.price').html(total_pris+',-'); where '.price' applies to the related products also. How do I fix this?
My code:
add_action( 'woocommerce_before_add_to_cart_quantity', 'func_option_valgt'
);
function func_option_valgt() {
global $product;
if (has_term('endene','product_cat')){
$variations_data =[]; // Initializing
// Loop through variations data
foreach($product->get_available_variations() as $variation ) {
// Set for each variation ID the corresponding price in the data array (to be used in jQuery)
$variations_data[$variation['variation_id']] = $variation['display_price'];
}
?>
<script>
jQuery(function($) {
var jsonData = <?php echo json_encode($variations_data); ?>,
inputVID = 'input.variation_id';
$('input , #id_dropdown_one_end, #id_dropdown_other_end').change( function(){
if( '' != $(inputVID).val() ) {
var vid = $(inputVID).val(), // VARIATION ID
length = $('#rope_length').val(), // LENGTH
diameter = $('#diameter').val(), // DIAMETER
ene_enden = $('#id_dropdown_one_end').find('option:selected').attr("value_one_end"),
andre_enden = $('#id_dropdown_other_end').find('option:selected').attr("value_other_end"),
vprice = ''; // Initilizing
// Loop through variation IDs / Prices pairs
$.each( jsonData, function( index, price ) {
if( index == $(inputVID).val() ) {
vprice = price; // The right variation price
var ene_enden_conv = Number(ene_enden);
var andre_enden_conv = Number(andre_enden);
var rope_price = (length*vprice) + ene_enden_conv + andre_enden_conv;
var total_pris = rope_price;
if (rope_price != 0){
$('.price').html(total_pris+',-');
}
}
});
}
});
});
</script>
<?php
}
}
To avoid updating related product prices too, you just need to make a little change replacing:
$('.price').html(total_pris+',-');
by:
$('.woocommerce-variation-price > .price').html(total_pris+',-');
This should solve your problem.
The below script is for displaying countdown timing
Used code is here with a combination of php,javascript
Tried many ways but no use
<script>
function countdown(endT,callback,val) {
var val,days,hours,minutes,sec,timer;
end = new Date(endT);
end = end.getTime(); //Get initial Date in Milliseconds,
if (isNaN(end)) {
alert('# countdown.js # "Invalid Date", valid format- mm/dd/yyyy hh:mm:ss TT ');
return;
}
timer = setInterval(calculate,1000);//Timer to calculate remaining time
function calculate(){
var current = new Date();
var remaining = parseInt((end - current.getTime())/1000);//remaining seconds,
if (remaining <= 0){
clearInterval(timer);
days=0;
hours=0;
minutes=0;
sec=0;
display(days,hours,minutes,sec);
if (typeof callback === 'function' ) {
callback();
}
}else{
days = parseInt(remaining/86400);
remaining = (remaining%86400);
hours = parseInt(remaining/3600);
remaining = (remaining%3600);
minutes = parseInt(remaining/60);
remaining = (remaining%60);
sec = parseInt(remaining);
display(days,hours,minutes,sec);
}
}
//Function For displaying Results in HTML page with specific ID's
function display(days,hours,minutes,sec) {
var dl = days.toString().length;
if (dl == "1") {
sl = 2;
}else{
if (isNaN(dl)) {
sl = 3;
}
sl = dl;
}
d1="days";
d2=val;
d=d1.concat(d2);
h1="hours";
h2=val;
h=h1.concat(h2);
m1="minutes";
m2=val;
m=m1.concat(m2);
s1="seconds";
s2=val;
s=s1.concat(s2);
document.getElementById(d).innerHTML = ("00"+days).slice(-sl);
document.getElementById(h).innerHTML = ("0"+hours).slice(-2);
document.getElementById(m).innerHTML = ("0"+minutes).slice(-2);
document.getElementById(s).innerHTML = ("0"+sec).slice(-2);
}
}
</script>
<?php
for ($i = 6; $i <9; $i++)
{
$dates="2019-03-0$i 12:45:01";
?>
<script>
countdown('<?php echo $dates;?>',callback,'<?php echo $i;?>');
function callback(){
//alert('Your Id is Expired');
};
</script>
<div class="countDown" align="center">
<span id="days<?php echo $i; ?>">00</span> <!-- Remaining Days,id="days"-->
<span id="hours<?php echo $i; ?>">00</span> <!-- Remaining hours ,id="hours"-->
<span id="minutes<?php echo $i; ?>">00</span> <!-- Remaining minutes,id="minutes"-->
<span id="seconds<?php echo $i; ?>">00</span> <!-- Remaining secounds,id="secounds"-->
</div>
<?php
}
?>
First iterated value only assigned to all other loop ids...Instead of unique values
Loop have 3 iterations
First iteration value assigned first id
The first iteration value assigned to next two iterations..
Kindly help me to fix the issue..
Combination of php and javascript always confusing. It can be used in combination when creating dynamic elements on page load but not after page load.So you have to code in javascript for countdown. If there is need to access server variable (i.e php variable ) then you need Ajax request to access this variable.
I am the new administrator of a website I did not created (professionnals did, I'm just an IT student beginning with JavaScript). I wanted to add a timer on the homepage of the website with the following working code I founded on the Internet:
<script language="JavaScript1.2">
//##################################################
// Author: ricocheting.com
// For: public release (freeware)
// Date: 4/24/2003 (update: 6/26/2009)
// Description: displays the amount of time until the "dateFuture" entered below.
// NOTE: the month entered must be one less than current month. ie; 0=January, 11=December
// NOTE: the hour is in 24 hour format. 0=12am, 15=3pm etc
// format: dateFuture = new Date(year,month-1,day,hour,min,sec)
// example: dateFuture = new Date(2003,03,26,14,15,00) = April 26, 2003 - 2:15:00 pm
dateFuture = new Date(2014,10,25,20,00,00);
// TESTING: comment out the line below to print out the "dateFuture" for testing purposes
//document.write(dateFuture +"<br />");
//###################################
//nothing beyond this point
function GetCount(){
dateNow = new Date(); //grab current date
amount = dateFuture.getTime() - dateNow.getTime(); //calc milliseconds between dates
delete dateNow;
adversaire = "Saastal";
// time is already past
if(amount < 0){
document.getElementById('countbox').innerHTML="Le match Sion - " + adversaire + " a débuté !";
}
// date is still good
else{
days=0;hours=0;mins=0;secs=0;out="";
amount = Math.floor(amount/1000);//kill the "milliseconds" so just secs
days=Math.floor(amount/86400);//days
amount=amount%86400;
hours=Math.floor(amount/3600);//hours
amount=amount%3600;
mins=Math.floor(amount/60);//minutes
amount=amount%60;
secs=Math.floor(amount);//seconds
if(days != 0){out += days +" jour"+((days!=1)?"s":"")+", ";}
if(days != 0 || hours != 0){out += hours +" heure"+((hours!=1)?"s":"")+", ";}
if(days != 0 || hours != 0 || mins != 0){out += mins +" minute"+((mins!=1)?"s":"")+", ";}
out += secs +" seconde"+((secs!=1)?"s":"");
document.getElementById('countbox').innerHTML="Temps restant avant Sion - " + adversaire + " : " + out;
setTimeout("GetCount()", 1000);
}
}
window.onload=GetCount;//call when everything has loaded
</script>
<div id="countbox"></div>
The only problem is that when I add this code (which works), then another JavaScript code already on the page (scrolling text) doesn't work anymore. Here is the code of the scrolling text but what is important is that I founded it with "Right click/view page source" and I cannot change it, except for the text part (in the admin page, I have a textbox in which I write the text that is going to scroll and according to the following code, this text is just a variable part of the JavaScript function) :
<h3 class="replace">Agenda</h3>
<script language="JavaScript1.2">
// Distributed by http://www.hypergurl.com
// Scrollers width here (in pixels)
var scrollerwidth="180px";
// Scrollers height here
var scrollerheight="100px";
// Scrollers speed here (larger is faster 1-10)
var scrollerspeed=1;
/* Scrollers content goes here! Keep all of the message on the same line!
* var scrollercontent='<font face="Arial" color="green" size="5">
* <b>Place your content here.<br>
* vous pouvez inclure des balises HTML, des hyperliens
* Script distributed by Hypergurl.com.
* The scrolling massage will now pause on mouseover.<br>
* Thanks David for the update!</b></font>'
* le texte de la marquee doit être inclu dans une balise <div> ... </div>
* ATTENTION: les aphostrophes doivent impérativement être échappés!!!!
*/
var txt = ' '
+ 'HERE IS THE TEXT I CAN WRITE'
var scrollercontent = ''
+ txt
+ '';
var pauseit=1;
// Change nothing below!
scrollerspeed=(document.all)? scrollerspeed : Math.max(1, scrollerspeed-1) //slow speed down by 1 for NS
var copyspeed=scrollerspeed
var iedom=document.all||document.getElementById
var actualheight=''
var cross_scroller, ns_scroller
var pausespeed=(pauseit==0)? copyspeed: 0
function populate(){
if (iedom){
cross_scroller=document.getElementById? document.getElementById("iescroller") : document.all.iescroller
cross_scroller.style.top=parseInt(scrollerheight)+8+"px"
cross_scroller.innerHTML=scrollercontent
actualheight=cross_scroller.offsetHeight
}
else if (document.layers){
ns_scroller=document.ns_scroller.document.ns_scroller2
ns_scroller.top=parseInt(scrollerheight)+8
ns_scroller.document.write(scrollercontent)
ns_scroller.document.close()
actualheight=ns_scroller.document.height
}
lefttime=setInterval("scrollscroller()",50)
}
window.onload=populate
function scrollscroller(){
if (iedom){
if (parseInt(cross_scroller.style.top)>(actualheight*(-1)+8))
cross_scroller.style.top=parseInt(cross_scroller.style.top)-copyspeed+"px"
else
cross_scroller.style.top=parseInt(scrollerheight)+8+"px"
}
else if (document.layers){
if (ns_scroller.top>(actualheight*(-1)+8))
ns_scroller.top-=copyspeed
else
ns_scroller.top=parseInt(scrollerheight)+8
}
}
if (iedom||document.layers){
with (document){
if (iedom){
write('<div style="position:relative;width:'+scrollerwidth+';height:'+scrollerheight+';overflow:hidden" onMouseover="copyspeed=pausespeed" onMouseout="copyspeed=scrollerspeed">')
write('<div id="iescroller" style="position:absolute;left:0px;top:0px;width:100%;">')
write('</div></div>')
}
else if (document.layers){
write('<ilayer width='+scrollerwidth+' height='+scrollerheight+' name="ns_scroller">')
write('<layer name="ns_scroller2" width='+scrollerwidth+' height='+scrollerheight+' left=0 top=0 onMouseover="copyspeed=pausespeed" onMouseout="copyspeed=scrollerspeed"></layer>')
write('</ilayer>')
}
}
}
So my question is: do you know a way to let these two JavaScript functions work on the same page? I just want to have my timer either on the homepage, either in the scrolling text (which is also on the homepage, in the right column)...
Thank you in advance for you help.
Kinds regards,
user3507737
It looks like you're overwriting the first script's window.onload call by including the second script, which has its own .onload call.
I would remove the two lines that begin with window.onload from the scripts included above, and add a third <script> tag in your page that does the following:
window.onload = function () {
GetCount();
populate();
};
This should get both your scripts running.
You assign an action to the window.onload event twice. In the first block of javascript you have window.onload=GetCount; and in the second you have window.onload=populate (which needs a semicolon at the end, by the way).
You can only assign one function to the onload event, so it would be best to make a function that calls both GetCount and populate and assign this new function to your window.onload. See more in this answer.
You need to remove the current code that binds to onload and replace it with something like:
window.onload = function () {
populate();
GetCount();
};
I am basing this code off of this jsfiddle:
http://jsfiddle.net/vxupE/
I would love to implement these price levels into my code so that when a person puts in $501 they are charged 20% but if they put in $500 they are charged 25%
if $price =< 101 then *.30
if $price > 100 and < 501 then *.25
if $price > 500 and < 1501 then *.20
if $price > 1500 then *.15
I'm at a loss when is comes to javascript. I think this could help others though. Would definitely help me! :)
Try this:
$('#sub_tot').change(function(){
var value = $(this).val();
var charge = 0;
if ( value >= 501 ) {
charge = .25;
}
else if ( value >= 100 ) {
charge = .20;
}
$('#tax').val( (value * charge).toFixed(2) );
}).change()
There are two ways I would consider.
switch statements, there are plenty of tutorials on line to look through. The other option is is using if and else if To find the correct additional charge.
if($price =< 101){
charge=0.3;
}else if($price>=100){
charge=0.25;
}else if($price>=500){
charge=0.2;
}else if($price>=1500){
charge=0.15;
where charge can then be used to calculate the final cost.
UPDATE
your code is checking if your sub total value is equal to your zip code. change
$('#sub_tot').change(function(){ to $('#zip').change(function(){ to
How do I modify PrestaShop 1.5 to display product prices in two currencies at the same time (ie. base currenct and visitor's currency on products listed in product & categories pages):
I think I should be modifying ProductController.php and product.tpl. Is this correct?
Below is one solution for the product page that I find on a forum, but it is for PrestaShop 1.4x:
Override ProductController.php in /controllers/ProductController.php
<?php
class ProductController extends ProductControllerCore{
public function displayContent() {
global $currency;
$second_currency = 'USD';
$productPriceWithTax = Product::getPriceStatic($this->product->id, true, NULL, 6);
if (Product::$_taxCalculationMethod == PS_TAX_INC) {
$productPriceWithTax = Tools::ps_round($productPriceWithTax, 2);
}
$productPriceWithoutEcoTax = (float)($productPriceWithTax - $this->product->ecotax);
$current_currency = $currency->iso_code;
$default_currency = Currency::getDefaultCurrency()->iso_code;
$currency_array = Currency::getCurrencies($object = false, $active = 1);
if ($current_currency == $default_currency) {
foreach ($currency_array as $arr) {
if ((string)$arr['iso_code'] == $second_currency) {
$second_currency_price = Tools::ps_round($productPriceWithoutEcoTax * (float)$arr['conversion_rate'], 2);
}
}
}
self::$smarty->assign('second_currency_price', $second_currency_price . ' ' . $second_currency);
parent::displayContent();
}
}
Modify product.tpl:
{if $priceDisplay >= 0 && $priceDisplay <= 2}
<span id="our_price_display">{convertPrice price=$productPrice}</span>
to
{if $priceDisplay >= 0 && $priceDisplay <= 2}
{$second_currency_price} /
<span id="our_price_display">{convertPrice price=$productPrice}</span>
In above example USD is the second currency ($second_currency='USD'). I was wondering if it would be possible to modify this code for PrestaShop 1.5, which has changed significantly since 1.4x.
You have to loop this array which contains all the currencies you manage: {$currencies}
{foreach from=$currencies item=c}{$c.name}{/foreach}
The default currency is in: {$id_currency_cookie}
If I remember, you have to write this in product.tpl.
I don't know how to display the correct price for your currency. Tell us if you find.