<?php
/**
* Pimcore
*
* This source file is available under two different licenses:
* - GNU General Public License version 3 (GPLv3)
* - Pimcore Enterprise License (PEL)
* Full copyright and license information is available in
* LICENSE.md which is distributed with this source code.
*
* @copyright Copyright (c) Pimcore GmbH (http://www.pimcore.org)
* @license http://www.pimcore.org/license GPLv3 and PEL
*/
namespace App\Twig\Extension;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
use Pimcore\Model\DataObject;
use Pimcore\Bundle\EcommerceFrameworkBundle\Factory;
use Symfony\Component\Security\Core\User\UserInterface;
use App\Model\Utility;
class CartExtension extends AbstractExtension
{
const DEFAULT_CART_NAME = 'cart';
const DEFAULT_CART_NAME_B2C = 'cart_b2c';
/**
* @var Factory
*/
protected $factory;
public function __construct(Factory $factory)
{
$this->factory = $factory;
}
public function getFunctions()
{
return [
new TwigFunction('app_cart_items_count', [$this, 'getCartItems']),
new TwigFunction('app_cart_items_count_b2c', [$this, 'getCartItemsB2C']),
new TwigFunction('truncate_name', [$this, 'truncateName']),
new TwigFunction('app_wish_list_count', [$this, 'getWishlistItems']),
new TwigFunction('app_get_order_status', [$this, 'getOrderStatus']),
new TwigFunction('app_get_quote_status', [$this, 'getQuoteStatus']),
new TwigFunction('app_get_quote_order', [$this, 'getQuoteOrder']),
new TwigFunction('app_get_draft_status', [$this, 'getDraftStatus']),
new TwigFunction('app_get_booking_status', [$this, 'getBookingStatus']),
new TwigFunction('app_get_booking_days', [$this, 'getBookingDays']),
new TwigFunction('app_get_product_check_stock', [$this, 'getProductCheckStock']),
new TwigFunction('app_get_all_categories', [$this, 'getCategories']),
new TwigFunction('app_get_params', [$this, 'getAllParams']),
new TwigFunction('italian_date', [$this, 'getItalianDate']),
new TwigFunction('italian_datetime', [$this, 'getItalianDatetime']),
new TwigFunction('asset_path', [$this, 'getAssetPath']),
new TwigFunction('calculate_bytes', [$this, 'readableBytes']),
new TwigFunction('european_price', [$this, 'getEuropeanPrice']),
new TwigFunction('european_count', [$this, 'getEuropeanCount']),
new TwigFunction('unserializedata', [$this, 'unserializedata'])
];
}
public function getProductCheckStock($product){
$stock = 0;
$color = 'orange';
$isAvailable = false;
$stock = (int) $product->getStockAvailability();
if($stock>=THRESHOLD_QTY)
{
$isAvailable = true;
$color = 'green';
}else if($stock<=0){
$isAvailable = false;
$color = 'red';
}
return ['isAvailable'=>$isAvailable,'stock'=>$stock,'color'=>$color];
}
public function getOrderStatus($order){
$result = '<font style="vertical-align: inherit;">IN LAVORAZIONE</font>';
$color = "";
$invoice = 0;
if($order instanceof \Pimcore\Model\DataObject\OnlineShopOrder){
if(strtolower($order->getWorkflowState()) == "delivered"){
$result = '<font style="vertical-align: inherit;">Consegnato</font>';
$color = "green";
$invoice = 1;
}
else if(strtolower($order->getWorkflowState()) == "dispatched"){
$result = '<font style="vertical-align: inherit;">SPEDITO</font>';
$color = "green";
$invoice = 1;
}
else if(strtolower($order->getWorkflowState()) == "confirmed"){
$result = '<font style="vertical-align: inherit;">IN LAVORAZIONE</font>';
$color = "";
$invoice = 1;
}
else if(strtolower($order->getWorkflowState()) == "partially_shipped"){
$result = '<font style="vertical-align: inherit;">PARZIALMENTE SPEDITO</font><br/>';
$color = "orange";
$invoice = 1;
}else if(strtolower($order->getWorkflowState()) == "cancelled"){
$result = '<font style="vertical-align: inherit;"><strike>ANNULLATO</strike></font>';
$color = "red";
$invoice = 0;
}
}
return ['color'=>$color,'result'=>$result,'invoice'=>$invoice];
}
public function getBookingStatus($order){
$result = '<font style="vertical-align: inherit;">'.BOOKING_EXPIRY_DAYS.' GIORNI ALLA SCADENZA</font>';
$color ='green';
$days = 0;
$cancelled = false;
if($order instanceof \Pimcore\Model\DataObject\PurchaseOrder){
$cancelled = $order->getIsCancelled();
$expired = $order->getIsExpired();
if($expired){
$color = "red";
$result = '<font style="vertical-align: inherit;">'.strtoupper('Prenotazione scaduta').'</font>';
}else if($cancelled){
$color = "red";
$result = '<font style="vertical-align: inherit;"><strike>ANNULLATA</strike></font>';
}else{
$fromDate = $order->getFromDate();
$toDate = $order->getDueDate();
// p_r($fromDate->getTimeStamp());
$days = $this->secondsToTime($fromDate->getTimeStamp(),strtotime('now'));
//p_r($days);p_r(BOOKING_EXPIRY_DAYS);
if($days <= BOOKING_EXPIRY_DAYS){
$color = "green";
$result = '<font style="vertical-align: inherit;">'.(BOOKING_EXPIRY_DAYS-$days).' GIORNI ALLA SCADENZA</font>';
}else if($days<=3 && $days>1){
$color = "orange";
$result = '<font style="vertical-align: inherit;">'.(BOOKING_EXPIRY_DAYS-$days).' GIORNI ALLA SCADENZA</font>';
}else if($days >= BOOKING_EXPIRY_DAYS){
$color = "red";
$order->setIsExpired(TRUE);
$order->save();
$result = '<font style="vertical-align: inherit;">'.strtoupper('prenotazione scaduta').'</font>';
}
}
}
return ['color'=>$color,'result'=>$result,'isCancelled'=>$cancelled];
}
public function getBookingDays($orderId){
$result = '<font style="vertical-align: inherit;">'.BOOKING_EXPIRY_DAYS.'</font>';
$color ='green';
$days = 5;
$cancelled = false;
$order = \Pimcore\Model\DataObject::getById($orderId);
if($order instanceof \Pimcore\Model\DataObject\PurchaseOrder){
$cancelled = $order->getIsCancelled();
$expired = $order->getIsExpired();
if($expired){
$days = 0;
$color = "red";
$result = '<font style="vertical-align: inherit;">0</font>';
}else if($cancelled){
$color = "red";
$days = 0;
$result = '<font style="vertical-align: inherit;">0</font>';
}else{
$fromDate = $order->getFromDate();
$toDate = $order->getDueDate();
// p_r($fromDate->getTimeStamp());
$days = $this->secondsToTime($fromDate->getTimeStamp(),strtotime('now'));
//p_r($days);p_r(BOOKING_EXPIRY_DAYS);
if($days <= BOOKING_EXPIRY_DAYS){
$color = "green";
$result = '<font style="vertical-align: inherit;">'.$days.'</font>';
}else if($days<=3 && $days>1){
$color = "orange";
$result = '<font style="vertical-align: inherit;">'.$days.'</font>';
}else if($days >= BOOKING_EXPIRY_DAYS){
$color = "red";
$order->setIsExpired(TRUE);
$order->save();
$result = '<font style="vertical-align: inherit;">'.$days.'</font>';
}
}
}
return ['color'=>$color,'result'=>$result,'isCancelled'=>$cancelled,'days'=>$days];
}
function secondsToTime($from,$seconds) {
$dtF = new \DateTime("@$from");
$dtT = new \DateTime("@$seconds");
return $dtF->diff($dtT)->format('%a');
}
/**
* @return CartInterface
*/
public function getWishlistItems()
{
$totalCount = 0;
$user = \Pimcore::getContainer()->get('security.token_storage')->getToken()->getUser();
if($user instanceof \Pimcore\Model\DataObject){
$wishList = new DataObject\Wishlist\Listing();
$wishList->setCondition('user__id = ?',[$user->getId()]);
$list = $wishList->getCount();
$totalCount = !empty($list)?$list:0;
}
return $totalCount;
}
/**
* @return CartInterface
*/
protected function getCart()
{
$cartManager = $this->factory->getCartManager();
return $cartManager->getOrCreateCartByName(self::DEFAULT_CART_NAME);
}
public function getCartItems()
{
$cart = $this->getCart();
return count($cart->getItems());
}
/**
* @return CartInterface
*/
protected function getCartB2C()
{
$cartManager = $this->factory->getCartManager();
return $cartManager->getOrCreateCartByName(self::DEFAULT_CART_NAME_B2C);
}
public function getCartItemsB2C()
{
$cart = $this->getCartB2C();
return count($cart->getItems());
}
public function truncateName($string){
$string = (strlen($string) > 120) ? substr($string,0,120).'...' : $string;
return $string;
}
public function getCategories(){
$utility = new Utility();
$categories = $utility->getCategories();
$category = new DataObject\Category\Listing();
$category->setCondition('o_id IN (?)',[$categories[0]['cat']]);
$category->setOrder('name ASC');
$categoryList = $category->load();
return $categoryList;
}
public function getAllParams(){
return $_GET;
}
public function getItalianDate($date){
if(method_exists($date,"getTimestamp")){
$months = array(
'01' => 'Gennaio',
'02' => 'Febbraio',
'03' => 'Marzo',
'04' => 'Aprile',
'05' => 'Maggio',
'06' => 'Giugno',
'07' => 'Luglio',
'08' => 'Agosto',
'09' => 'Settembre',
'10' => 'Ottobre',
'11' => 'Novembre',
'12' => 'Dicembre');
list($day, $month, $year) = explode('-',date('d-m-Y',$date->getTimestamp()));
return $day . ' ' . $months[$month] . ' ' . $year;
}else{
return date('Y-m-d H:i:s');
}
}
public function getItalianDateTime($date){
//if(method_exists($date,"getTimestamp")){
$months = array(
'01' => 'Gennaio',
'02' => 'Febbraio',
'03' => 'Marzo',
'04' => 'Aprile',
'05' => 'Maggio',
'06' => 'Giugno',
'07' => 'Luglio',
'08' => 'Agosto',
'09' => 'Settembre',
'10' => 'Ottobre',
'11' => 'Novembre',
'12' => 'Dicembre');
list($day, $month, $year) = explode('-',date('d-m-Y',$date));
return $day . ' ' . $months[$month] . ' ' . $year.' ore '.date('h:i A',$date);
}
function readableBytes($bytes) {
$i = floor(log($bytes) / log(1024));
$sizes = array('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
$totalSize = (pow(1024, $i) > 0)?sprintf('%.02F', $bytes / pow(1024, $i)) * 1 :'';
$fmt = new \NumberFormatter( 'it_IT', \NumberFormatter::DECIMAL );
$totalSize = $fmt->format((float)$totalSize);
return (pow(1024, $i) > 0)?$totalSize. ' ' . $sizes[$i]:0;
}
/**
* @return int|string
*/
public static function getEuropeanPrice($price,$product=false): ?string
{
if($product)
{
preg_match('/([0-9]+\.[0-9]+)/', $price->getNetAmount()->__toString(), $matches);
$number = (float) $matches[1]; // 55.35
$formatter = new \NumberFormatter("it-IT", \NumberFormatter::CURRENCY);
$formatter->setAttribute( $formatter::FRACTION_DIGITS, 2 );
return $formatter->formatCurrency($number, 'EUR');
}else
{
if(is_numeric($price)){
$matches[1] = $price;
}else{
preg_match('/([0-9]+\.[0-9]+)/', $price, $matches);
}
$number = (!empty($matches[1]))?(float) $matches[1]:00.00; // 55.35
$formatter = new \NumberFormatter("it-IT", \NumberFormatter::CURRENCY);
$formatter->setAttribute( $formatter::FRACTION_DIGITS, 2 );
return $formatter->formatCurrency($number, 'EUR');
}
}
/**
* @return int|string
*/
public static function getEuropeanCount($qty): ?string
{
$fmt = new \NumberFormatter( 'it_IT', \NumberFormatter::DECIMAL );
return $fmt->format($qty);
}
public function unserializedata($data){
return unserialize($data);
}
public function getAssetPath($path){
return BASE_URL.$path;
}
public function getQuoteStatus($quote){
if(!$quote->getWorkflowState()){
$quote->setWorkflowState('not_processed');
}
//return $quote->getWorkflowState();
$result = '<font style="vertical-align: inherit; padding:2px; color:'.QUOTE_STATUS[$quote->getWorkflowState()]['color'].'">'.strtoupper(QUOTE_STATUS[$quote->getWorkflowState()]['title']).'</font>';
return $result;
}
public function getQuoteOrder($searchable,$column,$order){
if($searchable == $column){
if($order == 'desc'){
return '<i class="ml-2 uparrow quote_order_by" column="'.$searchable.'" orderby="asc"></i>';
}else{
return '<i class="ml-2 downarrow quote_order_by" column="'.$searchable.'" orderby="desc"></i>';
}
}else{
return '<i class="ml-2 downarrow quote_order_by" column="'.$searchable.'" orderby="'.$order.'"></i>';
}
}
}