Adding days to a date excluding weekends in Shopify - shopify

I'm trying to write some code to estimate a shipping date in Shopify. I've been learning liquid but am having trouble writing some logic in Ruby. I'm not sure if Shopify templates use Ruby or Ruby on Rails.
I want to get todays date and add either 3 or 5 days based on a input variable, excusing weekends. Heres how I'd do it in PHP:
$orderDate = date('Y-m-d');
$personalized = true;
$orderDays = ($personalized ? 4 : 2);
(date('H') > 12 ? $orderDays++ : $false);
$d = new DateTime( $orderDate );
$t = $d->getTimestamp();
// loop for X days
for($i=0; $i<$orderDays; $i++){
// add 1 day to timestamp
$addDay = 86400;
// get what day it is next day
$nextDay = date('w', ($t+$addDay));
// if it's Saturday or Sunday get $i-1
if($nextDay == 0 || $nextDay == 6) {
$i--;
}
// modify timestamp, add 1 day
$t = $t+$addDay;
}
$d->setTimestamp($t);
echo $d->format( 'Y-m-d' ). "\n";
Whats the best way to write this for Shopify liquid?

Use the date filter in Liquid.
The date format you are using in Ruby is equivalent to:
{{ "now" | date: "%Y, %m, %-d" }}
A day is 86400 seconds. Example to add 3 days from now and format:
{% assign days = 3 | times: 86400 %}
{{ "now" | date: "%s" | plus: days | date: "%Y, %m, %-d" }}
Note: You need the date: "%s" filter applied first to "now" for Liquid to understand that you are using the current timestamp and not the string "now".
A way to check if an order is made on a weekend would be:
{% assign wday = order.created_at | date: "%a" %}
{% if wday == 'Sat' or wday == 'Sun' %}
el Weekendo
{% endif %}

Related

How to indicate "New" sign for fresh product on liquid

I'm using liquid on Shopify. And new to liquid.
Now, I'm trying to indicate "new" sign for products within 7 days.
{% assign today_date = 'now' | date: '%s' %}
{% assign create_date = product.created_at | date: '%s' %}
{% assign dif = today_date - create_date %}
<div>Time diff is {{ dif }}</div>
{% if dif < 30000 %}
<div>New</div>
{% endif %}
It shows errors like this.
Time diff is 1607714358
Liquid error: comparison of String with 30000 failed
What should I do?
Thanks in advance.
All liquid operations (+,-,/,*/%) are done via filters.
So this one here {% assign dif = today_date - create_date %} is incorrect.
It should be like so {% assign dif = today_date | minus: create_date %}.
This is your only mistake in the code.
Final code should be:
{% assign today_date = 'now' | date: '%s' %}
{% assign create_date = product.created_at | date: '%s' %}
{% assign dif = today_date | minus: create_date %}
<div>Time diff is {{ dif }}</div>
{% if dif < 30000 %}
<div>New</div>
{% endif %}

Symfony 5 :Key "DATE" for array with keys "NumberProjects, date" does not exist

hi guys right now im working in small project and i feel like im stacked, so basically im trying to write a new query to select a specific data from my db, im trying to get projects that create at the same year and month.
this is my query and it work fine in MySql :
SELECT COUNT(id) AS NumberProjects, DATE AS date FROM projects
GROUP BY EXTRACT(year FROM DATE),
EXTRACT(month FROM DATE) ;
but when it comes to symfony this is will not work of course and i do not know whats the problem
this is my function
/**
* #return Projects[] Returns an array of Projects objects
*/
public function findAllArchive():array
{
{
$conn = $this->getEntityManager()->getConnection();
$sql = 'SELECT COUNT(id) AS NumberProjects, DATE AS date FROM projects
GROUP BY EXTRACT(year FROM DATE),
EXTRACT(month FROM DATE) ';
$stmt = $conn->prepare($sql);
$stmt->execute();
return $stmt->fetchAll();
}
}
this is my twig
<div class="sidebar-box ftco-animate">
<h3>Archives</h3>
<ul class="categories">
{% for archive in archive %}
{{ dump(archive.DATE) }}
<li>{{ archive.DATE|date("F Y", "Europe/Paris") }}<span>{{ archive.total }}</span></li>
{% endfor %}
</ul>
</div>
update
i tryed with this one and i got this error : [Semantical Error] line 0, col 80 near 'EXTRACT(year': Error: Cannot group by undefined identification or result variable
public function findAllArchive():array
{
{
$qb=$this->createQueryBuilder('p');
$qb->select('p.date AS DATE','COUNT(p.id) AS total')
->groupBy('EXTRACT(year FROM DATE)');
}
return $qb->getQuery()->getResult();
}
any help pls !
so i figure it out guys,the doctrine do not know EXTRACT function so i tried this and it work fine
public function findAllArchive():array
{
{
$entityManeger=$this->getEntityManager();
$query=$entityManeger->createQueryBuilder('p')
->select('YEAR(p.date) AS gbYear,MONTH(p.date) AS gbMonth, COUNT(p.id) AS total ')
->from('App:Projects','p')
->groupBy('gbYear')
->addGroupBy('gbMonth')
;
}
return $query->getQuery()->execute() ;
}

Shopify - How to update product price on update

I have been trying to figure out the best way to add a free product to the cart in Shopify, but can't find what I am looking for in their documentation.
What I need to do is to add a product to the cart if the cart value is £10 or more. I have managed to get the product added, but how can I change the price to zero? Also, how can I ensure that if the user selects a higher quantity of the product, they do not get multiple free items and only get one free item? Hope that makes sense.
Here is what I have so far which works really well to add the product. But not change the price.
*EDIT: I realise if I can't change the price of an item then can I apply a fixed discount code at the cart page level?
**EDIT: Come to think of it, a discount code wouldn't work anyway because the user can easily remove the free product and still get the discount. Perhaps I need to either create some kind of hidden product that can not be searched for on the store, add that to the cart and disable the quantity selector.
There must be a way to do this because there are apps that can do it.
**I do not want to use an app
<script>
$(".cart__qty-input").blur(function() {
location.reload();
})(jQuery);
</script>
{% assign product = all_products['free-gift'] %}
{% unless cart.item_count == 0 or product.empty? or product.variants.first.available == false %}
{% if cart.total_price >= 1000 %}
{% assign variant_id = product.variants.first.id %}
<script>
(function($) {
var cartItems = {{ cart.items | json }},
qtyInTheCart = 0,
cartUpdates = {};
for (var i=0; i<cartItems.length; i++) {
if ( cartItems[i].id === {{ variant_id }} ) {
qtyInTheCart = cartItems[i].quantity;
break;
}
}
if ( ( cartItems.length === 1 ) && ( qtyInTheCart > 0 ) ) {
cartUpdates = { {{ variant_id }}: 0 }
}
else if ( ( cartItems.length >= 1 ) && ( qtyInTheCart !== 1 ) ) {
cartUpdates = { {{ variant_id }}: 1 }
}
else {
return;
}
var params = {
type: 'POST',
url: '/cart/update.js',
data: { updates: cartUpdates },
dataType: 'json',
success: function(stuff) {
window.location.href = '/cart';
}
};
$.ajax(params);
})(jQuery);
</script>
{% endif %}
{% endunless %}
You can achieve that by using standard Shopify functionality.
Create a collection that contains all product except the gift one.
Create an automatic discount using the following configuration:
Type: Buy X get Y
Customer spends: Minimum purchase amount
Amount: £10
Any items for: Specific collections
Search and add the collection you created in the 1st step
Customer gets:
Quantity: 1
Any items from: Specific products
Search and add the product you want to use as a gift (the one that doesn't belong to the collection created in the 1st step)
At a discounted value: Free
Set a maximum number of uses per order: enable it and set the value to 1
The above must suit your specification.
Then you can still use the scripts you've already created to automatically add/remove the gift product to the cart based on cart total (if that's necessary). If a customer will change the quantity of the gift product to 2 or more he will get it by the standard price specified in Shopify. Only one gift item will be discounted if the cart meets the criteria.

Shopify slice function returns '<'

I need to extract currency symbol in Shopify template. So far I've written:
{% assign symbol = product.price | money %} //creates a variable which holds price with currency symbol
{% assign symbol = symbol | slice: 0 %} //should return first char out of a string
{{ symbol }} //prints the variable
Unfortunately last line returns the < char.
Right now I'm out of ideas how to make this work. I know that Shopify can display currency by {{ shop.currency }} method, but it returns currency name instead of currency symbol.
Check the money format which is set in the Store Settings
Settings > General > Standards and formats > Currency > Change formatting
there are:
"HTML with currency"
"HTML without currency"
By default they are ${{amount}} USD and ${{amount}}, but they are wrapped them in span.money because you are using currency switcher.
<span class="money" >${{amount}} USD<span>
Easly you can use the filter strip_html to remove the span.money.
{% assign symbol = symbol | strip_html | slice: 0 %}

Extracting string and comparing with date

I have a string "products_2016-05-09" where 2016-05-09 is date appended in the string. I want to extract this date. If the date is minus 1 day I want to display string "products". How can I do this in liquid syntax?
To extract the date from the string, use the remove and split filters:
{% assign pdate = string | remove: "products_" %}
{% assign pdate = pdate | split: '-' %}
To check if that product date (pdate) is within 24 hours (86400 seconds) back, use something like this:
{% assign today = "now" | date: "%s" %}
{% assign yesterday = today | minus: 86400 %}
{% if pdate[0] == yesterday | date: "%Y" and pdate[1] == yesterday | date: "%m" and pdate[2] == yesterday | date: "%d" %}
Display string "products"
{% endif %}
Note: This only check if the product date is yesterday (24 hours ago from now) for a more accurate time verification, you need to do more arithmetics. You could also do all of this on the front-end using JavaScript.
The below code worked for me:
{% assign var =  {{custom_attribute.${producttype}}} %}
{% assign words = var | split: '_' %}
{% assign yestDate = 'now' | date: "%s" | minus: 86400 | date: "%F" %}
{% assign varDate = words[1] %}
{% if varDate | convert: "date"  == yestDate %}
Dynamic String {{words[0]}}
{% else %}
sorry!
{% endif %}