Browse Source

Amélioration page commandes backoffice

feature/export_comptable
Fab 4 years ago
parent
commit
a9f7e59aaf
13 changed files with 289 additions and 226 deletions
  1. +3
    -2
      ShopBundle/Controller/Backend/AdminController.php
  2. +11
    -4
      ShopBundle/Repository/ReminderRepository.php
  3. +1
    -1
      ShopBundle/Resources/public/css/backend/custom.css
  4. +1
    -1
      ShopBundle/Resources/public/sass/backend/custom.scss
  5. +2
    -0
      ShopBundle/Resources/views/backend/default/block/list_reminders.html.twig
  6. +39
    -16
      ShopBundle/Resources/views/backend/order/macros.html.twig
  7. +3
    -1
      ShopBundle/Services/Order/OrderUtils.php
  8. +15
    -6
      ShopBundle/Services/Order/OrderUtilsPaymentTrait.php
  9. +1
    -1
      ShopBundle/Services/Price/OrderProductPriceUtils.php
  10. +81
    -77
      ShopBundle/Services/Price/OrderShopPriceUtils.php
  11. +117
    -76
      ShopBundle/Services/Utils.php
  12. +8
    -0
      ShopBundle/Twig/BridgeTwigExtension.php
  13. +7
    -41
      ShopBundle/Twig/FrontendTwigExtension.php

+ 3
- 2
ShopBundle/Controller/Backend/AdminController.php View File

$id = null; $id = null;
if ($easyadmin['item']) $id = $easyadmin['item']->getId(); if ($easyadmin['item']) $id = $easyadmin['item']->getId();


$reminders = array('reminders' => $reminderRepo->findByEasyAdminConfig($actionName, $entityName, $id));
$user = $this->security->getUser();


$reminders = array('reminders' => $reminderRepo->findByEasyAdminConfigAndUser($actionName, $entityName, $user, $id));
if ($actionName == 'list') { if ($actionName == 'list') {
if ($this->filtersForm === null) { if ($this->filtersForm === null) {
$options['fields'] = $parameters['fields']; $options['fields'] = $parameters['fields'];
}*/ }*/


public function duplicateAction(){ public function duplicateAction(){
$id = $this->request->query->get('id'); $id = $this->request->query->get('id');
$refererUrl = $this->request->query->get('referer', ''); $refererUrl = $this->request->query->get('referer', '');



+ 11
- 4
ShopBundle/Repository/ReminderRepository.php View File

} }




public function findByUser($user){
public function findByUser($user)
{
$qb = $this->findByMerchantQuery() $qb = $this->findByMerchantQuery()
->leftJoin('e.users','u')
->leftJoin('e.users', 'u')
->having('COUNT(u.id) = 0') ->having('COUNT(u.id) = 0')
->orHaving(':user MEMBER OF e.users') ->orHaving(':user MEMBER OF e.users')
->andWhere('e.done = 0') ->andWhere('e.done = 0')
return $qb->getQuery()->getResult(); return $qb->getQuery()->getResult();
} }


public function findByEasyAdminConfig($action, $entity, $id = null){
public function findByEasyAdminConfigAndUser($action, $entity, $user, $id = null)
{
$qb = $this->findByMerchantQuery(); $qb = $this->findByMerchantQuery();
$qb->leftJoin('e.users', 'u');
$qb->having('COUNT(u.id) = 0');
$qb->orHaving(':user MEMBER OF e.users');
$qb->andWhere('e.done = 0'); $qb->andWhere('e.done = 0');
$qb->andWhere('e.entityAction LIKE :action'); $qb->andWhere('e.entityAction LIKE :action');
$qb->andWhere('e.entityName LIKE :entity'); $qb->andWhere('e.entityName LIKE :entity');
$qb->setParameter('entity', $entity); $qb->setParameter('entity', $entity);
$qb->setParameter('action', $action); $qb->setParameter('action', $action);
if($id) {
$qb->setParameter('user', $user);
if ($id) {
$qb->andWhere('e.entityId LIKE :id'); $qb->andWhere('e.entityId LIKE :id');
$qb->setParameter('id', $id); $qb->setParameter('id', $id);
} }
$qb->orderBy('e.dateReminder', 'ASC'); $qb->orderBy('e.dateReminder', 'ASC');
$qb->groupBy('e.id');
return $qb->getQuery()->getResult(); return $qb->getQuery()->getResult();
} }



+ 1
- 1
ShopBundle/Resources/public/css/backend/custom.css View File



/* line 76, ../../sass/backend/custom.scss */ /* line 76, ../../sass/backend/custom.scss */
table th input { table th input {
width: auto;
width: 100%;
} }


/* line 77, ../../sass/backend/custom.scss */ /* line 77, ../../sass/backend/custom.scss */

+ 1
- 1
ShopBundle/Resources/public/sass/backend/custom.scss View File

.delivery-field .form-group{display: inline-block; margin-bottom: 0px; margin-right: 15px;} .delivery-field .form-group{display: inline-block; margin-bottom: 0px; margin-right: 15px;}
.delivery-field .form-group .form-control{width: 150px;} .delivery-field .form-group .form-control{width: 150px;}


table th input{width: auto}
table th input{width: 100%;}
table th .select2-container--default .select2-selection--single{padding:0.3rem 0.4rem; } table th .select2-container--default .select2-selection--single{padding:0.3rem 0.4rem; }


/************************ LOGIN PAGE *********************/ /************************ LOGIN PAGE *********************/

+ 2
- 0
ShopBundle/Resources/views/backend/default/block/list_reminders.html.twig View File

{% include '@LcShop/backend/default/modal/show_reminder.twig' %} {% include '@LcShop/backend/default/modal/show_reminder.twig' %}
</li> </li>


{% else %}
<li>Aucun élement</li>
{% endfor %} {% endfor %}


</ul> </ul>

+ 39
- 16
ShopBundle/Resources/views/backend/order/macros.html.twig View File

<th colspan="2"> <th colspan="2">
<span>Produits / Producteurs</span> <span>Produits / Producteurs</span>
</th> </th>
<th v-if="order.countComplementaryOrderShops > 0">Compléments</th>

<th> <th>
<span>Prix HT à l'unité</span> <span>Prix HT à l'unité</span>
</th> </th>
<input type="checkbox" :value="orderProduct.id" class="order-product-checkbox" /> <input type="checkbox" :value="orderProduct.id" class="order-product-checkbox" />
</td> </td>
<td colspan="2"> <td colspan="2">
<a :href="orderProduct.editLink" target="_blank">
<img :src="orderProduct.image" :alt="orderProduct.title" />
{% verbatim %}{{orderProduct.title}}{% endverbatim %} {% verbatim %}{{orderProduct.title}}{% endverbatim %}
<span v-show="orderProduct.hasRedelivery"> <span v-show="orderProduct.hasRedelivery">
- <i class="fa fa-undo" data-toggle="tooltip" :title="orderProduct.redeliveryOrderShop" ></i> - <i class="fa fa-undo" data-toggle="tooltip" :title="orderProduct.redeliveryOrderShop" ></i>
<span v-show="orderProduct.isRedelivery"> <span v-show="orderProduct.isRedelivery">
- <i class="fa fa-undo" data-toggle="tooltip" title="Ce produit est une relivraison" ></i> - <i class="fa fa-undo" data-toggle="tooltip" title="Ce produit est une relivraison" ></i>
</span> </span>

</a>
</td>
<td>
<span v-if="orderProduct.complementaryReference"> {% verbatim %}{{orderProduct.complementaryReference}}{% endverbatim %}</span>
</td> </td>
<td> <td>
{% verbatim %}{{orderProduct.price}}{% endverbatim %}€ {% verbatim %}{{orderProduct.price}}{% endverbatim %}€
<th>Total produits après réductions TTC</th> <th>Total produits après réductions TTC</th>
<td>${order.totalOrderProductsWithTaxAndReductions}€</td> <td>${order.totalOrderProductsWithTaxAndReductions}€</td>
</tr> </tr>
<tr>
<th>Total marge produits</th>
<td>${order.totalMargin}€ <br /> ${order.totalMarginPercent}%</td>
</tr>


<tr> <tr>
<th>Frais de livraisons TTC</th> <th>Frais de livraisons TTC</th>
<td>${order.deliveryPriceWithTaxAndReduction}€</td> <td>${order.deliveryPriceWithTaxAndReduction}€</td>
</tr> </tr>

{# <tr>
<th>Total Taxes </th>
<td>${order.totalWithTax}€</td>
</tr>
#}
<tr> <tr>
<th>Total TTC</th> <th>Total TTC</th>
<td>${order.totalWithTax}€</td> <td>${order.totalWithTax}€</td>


{% macro box_user_info() %} {% macro box_user_info() %}
{% import '@LcShop/backend/default/block/macros.html.twig' as macros %} {% import '@LcShop/backend/default/block/macros.html.twig' as macros %}
{% set value = ' <span v-if="order.user" v-html="order.user"></span>
{% set value = ' <a v-if="order.user" :href="order.userLink" target="_blank" v-html="order.user"></a>
<span v-else v-html="order.visitor"></span>' %} <span v-else v-html="order.visitor"></span>' %}
{{ macros.box_info('bg-info', 'user',"field.default.user"|trans({}, 'lcshop'), value) }} {{ macros.box_info('bg-info', 'user',"field.default.user"|trans({}, 'lcshop'), value) }}






{% macro box_reference() %} {% macro box_reference() %}
{% import '@LcShop/backend/default/block/macros.html.twig' as macros %}

{{ macros.box_info('bg-info', 'credit-card',"field.OrderShop.reference"|trans({}, 'lcshop'), ' ${order.reference}') }}
{% embed '@LcShop/backend/default/block/embed_box.twig' %}
{% import '@LcShop/backend/order/macros.html.twig' as order_macros %}
{% trans_default_domain 'lcshop' %}
{% block class %}bg-info{% endblock %}
{% block icon %}credit-card{% endblock %}
{% block label %}{{ "field.OrderShop.reference"|trans({}, 'lcshop')}}{% endblock %}
{% block value %}
${order.reference}<br />
<span v-if="order.countComplementaryOrderShops > 0">
${order.countComplementaryOrderShops} commande(s) complémentaire(s)
</span>
{% endblock %}
{% block button %}
{{ order_macros.order_modal_button('#modal-order-delivery-address') }}
{% endblock %}
{% endembed %}
{% endmacro %} {% endmacro %}




{% block icon %}map-marked-alt{% endblock %} {% block icon %}map-marked-alt{% endblock %}
{% block label %}{{ "field.default.deliveryAddress"|trans({}, 'lcshop')}}{% endblock %} {% block label %}{{ "field.default.deliveryAddress"|trans({}, 'lcshop')}}{% endblock %}
{% block value %} {% block value %}
<div v-if="order.deliveryType == 'home'">
<div v-if="order.deliveryAddress">
<address v-html="order.deliveryAddress"> <address v-html="order.deliveryAddress">
</address> </address>
</div> </div>
<div v-else-if="order.deliveryType == 'point-sale'">
<address v-html="order.deliveryPointSale">
</address>
</div>
<div v-else> <div v-else>
Aucun lieu de livraison défini. Aucun lieu de livraison défini.
</div> </div>
<tbody> <tbody>
<thead> <thead>
<tr> <tr>
<th v-if="order.countComplementaryOrderShops > 0">Référence</th>
<th>Mode de règlement</th> <th>Mode de règlement</th>
<th>Date</th> <th>Date</th>
<th>Montant</th> <th>Montant</th>
<tbody> <tbody>
<template v-for="(orderPayment, i) in order.orderPayments"> <template v-for="(orderPayment, i) in order.orderPayments">
<tr> <tr>
<td v-if="order.countComplementaryOrderShops > 0">
${orderPayment.orderReference}
</td>
<td>${orderPayment.meanPaymentText}</td> <td>${orderPayment.meanPaymentText}</td>
<td>${orderPayment.paidAtText}</td> <td>${orderPayment.paidAtText}</td>
<td>${orderPayment.amount}</td> <td>${orderPayment.amount}</td>

<td> <td>
<button v-show="orderPayment.editable && editionMode && modalExist('#modal-delete-order-payment')" class="btn-sm btn-info" type="button" @click="editOrderPayment(orderPayment.id)"> <button v-show="orderPayment.editable && editionMode && modalExist('#modal-delete-order-payment')" class="btn-sm btn-info" type="button" @click="editOrderPayment(orderPayment.id)">
<i class="fa fa-pen"></i> <i class="fa fa-pen"></i>
<tbody> <tbody>
<thead> <thead>
<tr> <tr>
<th v-if="order.countComplementaryOrderShops > 0">Référence</th>
<th>Date</th> <th>Date</th>
<th>Type</th> <th>Type</th>
<th>Numéro</th> <th>Numéro</th>
<tbody> <tbody>
<template v-for="(orderDocument, i) in order.orderDocuments"> <template v-for="(orderDocument, i) in order.orderDocuments">
<tr> <tr>
<td v-if="order.countComplementaryOrderShops > 0">
${orderDocument.orderReference}
</td>
<td>${orderDocument.date}</td> <td>${orderDocument.date}</td>
<td>Facture</td> <td>Facture</td>
<td>${orderDocument.reference}</td> <td>${orderDocument.reference}</td>

+ 3
- 1
ShopBundle/Services/Order/OrderUtils.php View File

{ {
$data['id'] = $order->getId(); $data['id'] = $order->getId();
$data['user'] = $order->getUser()->getSummary(); $data['user'] = $order->getUser()->getSummary();
$data['orderStatus'] = $order->getOrderStatus()->__tosString();
$data['orderStatus'] = $order->getOrderStatus()->__toString();
$data['deliveryAddress'] = $order->getDeliveryAddress()->getSummary(); $data['deliveryAddress'] = $order->getDeliveryAddress()->getSummary();
$data['invoiceAddress'] = $order->getInvoiceAddress()->getSummary(); $data['invoiceAddress'] = $order->getInvoiceAddress()->getSummary();
$data['total'] = $this->priceUtils->getTotal($order); $data['total'] = $this->priceUtils->getTotal($order);
{ {


} }


} }

+ 15
- 6
ShopBundle/Services/Order/OrderUtilsPaymentTrait.php View File

$orderPayment->setReference($reference); $orderPayment->setReference($reference);
$orderPayment->setComment($comment); $orderPayment->setComment($comment);
$orderPayment->setEditable(false); $orderPayment->setEditable(false);
$orderPayment->setCreatedBy($orderShop->getUser()) ;
$orderPayment->setUpdatedBy($orderShop->getUser()) ;
$orderPayment->setCreatedBy($orderShop->getUser());
$orderPayment->setUpdatedBy($orderShop->getUser());


if ($paidAt) { if ($paidAt) {
$orderPayment->setPaidAt($paidAt); $orderPayment->setPaidAt($paidAt);
$this->em->persist($orderPayment); $this->em->persist($orderPayment);
$this->em->flush(); $this->em->flush();


return $orderPayment ;
return $orderPayment;
} }


public function isOrderPaid($order)
public function isOrderPaid($order, $mergeComplementaryOrderShop = false)
{ {


if ($this->getTotalOrderPayments($order) >= $this->priceUtils->getTotalWithTax($order) && $this->priceUtils->getTotalWithTax($order)>0) {
if ($this->getTotalOrderPayments($order, $mergeComplementaryOrderShop) >= $this->priceUtils->getTotalWithTax($order) && $this->priceUtils->getTotalWithTax($order) > 0) {
return true; return true;
} else { } else {
return false; return false;
} }


} }


public function getTotalOrderPayments($order): float
public function getTotalOrderPayments($order, $mergeComplementaryOrderShop = false): float
{ {
$totalAmount = floatval(0); $totalAmount = floatval(0);
foreach ($order->getOrderPayments() as $orderPayment) { foreach ($order->getOrderPayments() as $orderPayment) {
$totalAmount = $orderPayment->getAmount() + $totalAmount; $totalAmount = $orderPayment->getAmount() + $totalAmount;
} }
if($mergeComplementaryOrderShop) {
foreach ($order->getComplementaryOrderShops() as $complementaryOrderShop) {
foreach ($complementaryOrderShop->getOrderPayments() as $orderPayment) {
$totalAmount = $orderPayment->getAmount() + $totalAmount;
}
}
}
return $totalAmount; return $totalAmount;
} }



+ 1
- 1
ShopBundle/Services/Price/OrderProductPriceUtils.php View File

public function getMarginPercent(OrderProductInterface $orderProduct) public function getMarginPercent(OrderProductInterface $orderProduct)
{ {
if($this->getBuyingPrice($orderProduct)) { if($this->getBuyingPrice($orderProduct)) {
return ($this->getMargin($orderProduct) / $this->getBuyingPrice($orderProduct)) * 100;
return $this->round(($this->getMargin($orderProduct) / $this->getPriceWithReduction($orderProduct)) * 100);
}else{ }else{
return 0; return 0;
} }

+ 81
- 77
ShopBundle/Services/Price/OrderShopPriceUtils.php View File



class OrderShopPriceUtils implements OrderShopPriceUtilsInterface class OrderShopPriceUtils implements OrderShopPriceUtilsInterface
{ {
use PriceUtilsTrait ;
use PriceUtilsTrait;


protected $orderProductPriceUtils ;
protected $orderProductPriceUtils;


public function __construct(OrderProductPriceUtils $orderProductPriceUtils) public function __construct(OrderProductPriceUtils $orderProductPriceUtils)
{ {
$this->orderProductPriceUtils = $orderProductPriceUtils ;
$this->orderProductPriceUtils = $orderProductPriceUtils;
} }


//Inclus les ReductionCatalog des OrderProducts //Inclus les ReductionCatalog des OrderProducts
public function getTotalOrderProducts(OrderShopInterface $orderShop):float
public function getTotalOrderProducts(OrderShopInterface $orderShop): float
{ {
// A tester calculer ce montant en faisant TotalOrderWithTax - TotalOrderTaxes // A tester calculer ce montant en faisant TotalOrderWithTax - TotalOrderTaxes






//Inclus les ReductionCatalog des OrderProducts //Inclus les ReductionCatalog des OrderProducts
public function getMarginOrderProducts(OrderShopInterface $orderShop):float
public function getMarginOrderProducts(OrderShopInterface $orderShop): float
{ {
// A tester calculer ce montant en faisant TotalOrderWithTax - TotalOrderTaxes

$total = 0; $total = 0;
foreach ($orderShop->getOrderProducts() as $orderProduct) { foreach ($orderShop->getOrderProducts() as $orderProduct) {
$total += $this->orderProductPriceUtils->getTotalMargin($orderProduct); $total += $this->orderProductPriceUtils->getTotalMargin($orderProduct);
return $total; return $total;
} }


public function getMarginOrderProductsPercent(OrderShopInterface $orderShop): float
{
if ($this->getTotalOrderProducts($orderShop)) {
return $this->round($this->getMarginOrderProducts($orderShop) / $this->getTotalOrderProducts($orderShop) * 100);
} else {
return 0;
}

}


public function getTotalOrderProductsWithTax(OrderShopInterface $orderShop):float

public function getTotalOrderProductsWithTax(OrderShopInterface $orderShop): float
{ {
return $this->getTotalOrderProductsWithTaxByOrderProducts($orderShop->getOrderProducts()) ;
return $this->getTotalOrderProductsWithTaxByOrderProducts($orderShop->getOrderProducts());
} }


public function getTotalBuyingPriceOrderProductsWithTax($orderProducts):float
public function getTotalBuyingPriceOrderProductsWithTax($orderProducts): float
{ {
$total = 0; $total = 0;


return $total; return $total;
} }


public function getTotalOrderProductsWithTaxByOrderProducts($orderProducts):float
public function getTotalOrderProductsWithTaxByOrderProducts($orderProducts): float
{ {
$total = 0; $total = 0;
foreach ($orderProducts as $orderProduct) { foreach ($orderProducts as $orderProduct) {
return $total; return $total;
} }


public function getTotalOrderProductsTaxes(OrderShopInterface $orderShop):float
public function getTotalOrderProductsTaxes(OrderShopInterface $orderShop): float
{ {
$total = 0 ;
$total = 0;


foreach($orderShop->getOrderProducts() as $orderProduct) {
$total += $this->orderProductPriceUtils->getTotalTaxes($orderProduct) / $this->getReductionsCoef($orderShop) ;
foreach ($orderShop->getOrderProducts() as $orderProduct) {
$total += $this->orderProductPriceUtils->getTotalTaxes($orderProduct) / $this->getReductionsCoef($orderShop);
} }


return $total ;
return $total;
} }


public function getOrderProductsTaxesAsArray(OrderShopInterface $orderShop):array
public function getOrderProductsTaxesAsArray(OrderShopInterface $orderShop): array
{ {
$orderProductsTaxes = []; $orderProductsTaxes = [];
foreach ($orderShop->getOrderProducts() as $orderProduct) { foreach ($orderShop->getOrderProducts() as $orderProduct) {


$idTaxRate = $orderProduct->getTaxRate()->getId() ;
$idTaxRate = $orderProduct->getTaxRate()->getId();


if(!isset($orderProductsTaxes[$idTaxRate])) {
if (!isset($orderProductsTaxes[$idTaxRate])) {
$orderProductsTaxes[$idTaxRate] = [ $orderProductsTaxes[$idTaxRate] = [
'label' => $orderProduct->getTaxRate()->getValue() . '%', 'label' => $orderProduct->getTaxRate()->getValue() . '%',
'totalOrderProducts' => 0, 'totalOrderProducts' => 0,
} }


$orderProductsTaxes[$idTaxRate]['totalOrderProducts'] += $this->orderProductPriceUtils->getTotalWithReduction($orderProduct) / $this->getReductionsCoef($orderShop); $orderProductsTaxes[$idTaxRate]['totalOrderProducts'] += $this->orderProductPriceUtils->getTotalWithReduction($orderProduct) / $this->getReductionsCoef($orderShop);
$orderProductsTaxes[$idTaxRate]['totalTaxes'] += $this->orderProductPriceUtils->getTotalTaxes($orderProduct) / $this->getReductionsCoef($orderShop) ;
$orderProductsTaxes[$idTaxRate]['totalTaxes'] += $this->orderProductPriceUtils->getTotalTaxes($orderProduct) / $this->getReductionsCoef($orderShop);
} }


return $orderProductsTaxes ;
return $orderProductsTaxes;
} }


private function getReductionsCoef(OrderShopInterface $orderShop) :float
private function getReductionsCoef(OrderShopInterface $orderShop): float
{ {
return $this->getTotalOrderProducts($orderShop) / $this->getTotalOrderProductsWithReductions($orderShop); return $this->getTotalOrderProducts($orderShop) / $this->getTotalOrderProductsWithReductions($orderShop);
} }


private function getTaxRateAverage(OrderShopInterface $orderShop):float
private function getTaxRateAverage(OrderShopInterface $orderShop): float
{ {
return $this->getTotalOrderProductsWithTax($orderShop) / $this->getTotalOrderProducts($orderShop); return $this->getTotalOrderProductsWithTax($orderShop) / $this->getTotalOrderProducts($orderShop);
} }


public function getTotalOrderProductsWithReductions(OrderShopInterface $orderShop) public function getTotalOrderProductsWithReductions(OrderShopInterface $orderShop)
{ {
$total = $this->getTotalOrderProducts($orderShop) ;
$total -= $this->getTotalReductionCartsAmount($orderShop) ;
$total -= $this->getTotalReductionCreditsAmount($orderShop) ;
return $total ;
$total = $this->getTotalOrderProducts($orderShop);
$total -= $this->getTotalReductionCartsAmount($orderShop);
$total -= $this->getTotalReductionCreditsAmount($orderShop);
return $total;
} }


public function getTotalOrderProductsWithReductionCarts(OrderShopInterface $orderShop) public function getTotalOrderProductsWithReductionCarts(OrderShopInterface $orderShop)
{ {
$total = $this->getTotalOrderProducts($orderShop) ;
$total -= $this->getTotalReductionCartsAmount($orderShop) ;
return $total ;
$total = $this->getTotalOrderProducts($orderShop);
$total -= $this->getTotalReductionCartsAmount($orderShop);
return $total;
} }


public function getTotalReductionCartsAmount(OrderShopInterface $orderShop) public function getTotalReductionCartsAmount(OrderShopInterface $orderShop)
{ {
$totalReductionAmount = 0 ;
$totalReductionAmount = 0;
foreach ($orderShop->getOrderReductionCarts() as $orderReductionCart) { foreach ($orderShop->getOrderReductionCarts() as $orderReductionCart) {
$totalReductionAmount += $this->getOrderProductsReductionCartAmountWithoutTax($orderShop,$orderReductionCart);
$totalReductionAmount += $this->getOrderProductsReductionCartAmountWithoutTax($orderShop, $orderReductionCart);
} }
return $totalReductionAmount ;
return $totalReductionAmount;
} }


public function getTotalReductionCreditsAmount(OrderShopInterface $orderShop) public function getTotalReductionCreditsAmount(OrderShopInterface $orderShop)
{ {
$totalReductionAmount = 0 ;
$totalReductionAmount = 0;
foreach ($orderShop->getOrderReductionCredits() as $orderReductionCredit) { foreach ($orderShop->getOrderReductionCredits() as $orderReductionCredit) {
$totalReductionAmount += $this->getOrderProductsReductionCreditAmountWithoutTax($orderShop,$orderReductionCredit);
$totalReductionAmount += $this->getOrderProductsReductionCreditAmountWithoutTax($orderShop, $orderReductionCredit);
} }
return $totalReductionAmount ;
return $totalReductionAmount;
} }


public function getTotalOrderProductsWithTaxAndReductions(OrderShopInterface $orderShop) public function getTotalOrderProductsWithTaxAndReductions(OrderShopInterface $orderShop)
{ {
$total = $this->getTotalOrderProductsWithTax($orderShop) ;
$total -= $this->getTotalReductionCartsAmountWithTax($orderShop) ;
$total -= $this->getTotalReductionCreditsAmountWithTax($orderShop) ;
return $total ;
$total = $this->getTotalOrderProductsWithTax($orderShop);
$total -= $this->getTotalReductionCartsAmountWithTax($orderShop);
$total -= $this->getTotalReductionCreditsAmountWithTax($orderShop);
return $total;
} }




public function getMarginOrderProductsWithReductions(OrderShopInterface $orderShop):float
public function getMarginOrderProductsWithReductions(OrderShopInterface $orderShop): float
{ {
$total = $this->getMarginOrderProducts($orderShop) ;
$total = $this->getMarginOrderProducts($orderShop);


$totalReductionAmount = 0 ;
$totalReductionAmount = 0;
foreach ($orderShop->getOrderReductionCarts() as $orderReductionCart) { foreach ($orderShop->getOrderReductionCarts() as $orderReductionCart) {
$totalReductionAmount += $this->getOrderProductsReductionCartAmountWithoutTax($orderShop,$orderReductionCart);
$totalReductionAmount += $this->getOrderProductsReductionCartAmountWithoutTax($orderShop, $orderReductionCart);
} }


foreach ($orderShop->getOrderReductionCredits() as $orderReductionCredit) { foreach ($orderShop->getOrderReductionCredits() as $orderReductionCredit) {
$totalReductionAmount += $this->getOrderProductsReductionCreditAmountWithoutTax($orderShop,$orderReductionCredit);
$totalReductionAmount += $this->getOrderProductsReductionCreditAmountWithoutTax($orderShop, $orderReductionCredit);
} }


$total -= $totalReductionAmount ;
$total -= $totalReductionAmount;


return $total ;
return $total;
} }




public function getTotalOrderProductsWithTaxAndReductionCarts(OrderShopInterface $orderShop) public function getTotalOrderProductsWithTaxAndReductionCarts(OrderShopInterface $orderShop)
{ {
$total = $this->getTotalOrderProductsWithTax($orderShop) ;
$total -= $this->getTotalReductionCartsAmountWithTax($orderShop) ;
return $total ;
$total = $this->getTotalOrderProductsWithTax($orderShop);
$total -= $this->getTotalReductionCartsAmountWithTax($orderShop);
return $total;
} }


public function getTotalReductionCartsAmountWithTax(OrderShopInterface $orderShop) public function getTotalReductionCartsAmountWithTax(OrderShopInterface $orderShop)
{ {
$totalReductionAmount = 0 ;
$totalReductionAmount = 0;
foreach ($orderShop->getOrderReductionCarts() as $orderReductionCart) { foreach ($orderShop->getOrderReductionCarts() as $orderReductionCart) {
$totalReductionAmount += $this->getOrderProductsReductionCartAmountWithTax($orderShop,$orderReductionCart);
$totalReductionAmount += $this->getOrderProductsReductionCartAmountWithTax($orderShop, $orderReductionCart);
} }
return $totalReductionAmount ;
return $totalReductionAmount;
} }


public function getTotalReductionCreditsAmountWithTax(OrderShopInterface $orderShop) public function getTotalReductionCreditsAmountWithTax(OrderShopInterface $orderShop)
{ {
$totalReductionAmount = 0 ;
$totalReductionAmount = 0;
foreach ($orderShop->getOrderReductionCredits() as $orderReductionCredit) { foreach ($orderShop->getOrderReductionCredits() as $orderReductionCredit) {
$totalReductionAmount += $this->getOrderProductsReductionCreditAmountWithTax($orderShop,$orderReductionCredit);
$totalReductionAmount += $this->getOrderProductsReductionCreditAmountWithTax($orderShop, $orderReductionCredit);
} }
return $totalReductionAmount ;
return $totalReductionAmount;
} }


public function getOrderProductsReductionCartAmountWithoutTax(OrderShopInterface $order, $orderReductionCart) public function getOrderProductsReductionCartAmountWithoutTax(OrderShopInterface $order, $orderReductionCart)
{ {
$amount =0;
if($orderReductionCart->getAppliedTo() === ReductionCart::APPLIED_TO_ORDER_PRODUCTS) {
$amount = 0;
if ($orderReductionCart->getAppliedTo() === ReductionCart::APPLIED_TO_ORDER_PRODUCTS) {


if ($orderReductionCart->getUnit() == 'percent') { if ($orderReductionCart->getUnit() == 'percent') {
$amount = $this->amountReductionByPercentValue( $amount = $this->amountReductionByPercentValue(
); );
} else if ($orderReductionCart->getUnit() == 'amount') { } else if ($orderReductionCart->getUnit() == 'amount') {
if ($orderReductionCart->getBehaviorTaxRate() == 'tax-excluded') { if ($orderReductionCart->getBehaviorTaxRate() == 'tax-excluded') {
$amount = $orderReductionCart->getValue();
$amount = $orderReductionCart->getValue();
} else if ($orderReductionCart->getBehaviorTaxRate() == 'tax-included') { } else if ($orderReductionCart->getBehaviorTaxRate() == 'tax-included') {
$amount = $this->round($orderReductionCart->getValue() / $this->getTaxRateAverage($order));
$amount = $this->round($orderReductionCart->getValue() / $this->getTaxRateAverage($order));
} }


} }
} }
return $amount ;
return $amount;


} }


{ {
$amount = 0; $amount = 0;


if($orderReductionCart->getAppliedTo() === ReductionCart::APPLIED_TO_ORDER_PRODUCTS) {
if ($orderReductionCart->getAppliedTo() === ReductionCart::APPLIED_TO_ORDER_PRODUCTS) {
if ($orderReductionCart->getUnit() == 'percent') { if ($orderReductionCart->getUnit() == 'percent') {
$amount = $this->amountReductionByPercentValue( $amount = $this->amountReductionByPercentValue(
$this->getTotalOrderProductsWithTax($order), $this->getTotalOrderProductsWithTax($order),
$orderReductionCart->getValue() $orderReductionCart->getValue()
); );
}
elseif ($orderReductionCart->getUnit() == 'amount') {
} elseif ($orderReductionCart->getUnit() == 'amount') {
if ($orderReductionCart->getBehaviorTaxRate() == 'tax-excluded') { if ($orderReductionCart->getBehaviorTaxRate() == 'tax-excluded') {
$amount = $this->round($orderReductionCart->getValue() * $this->getTaxRateAverage($order));
}
elseif ($orderReductionCart->getBehaviorTaxRate() == 'tax-included') {
$amount = $orderReductionCart->getValue() ;
$amount = $this->round($orderReductionCart->getValue() * $this->getTaxRateAverage($order));
} elseif ($orderReductionCart->getBehaviorTaxRate() == 'tax-included') {
$amount = $orderReductionCart->getValue();
} }


} }
} }


return $amount ;
return $amount;
} }


public function getOrderProductsReductionCreditAmountWithoutTax(OrderShopInterface $order, OrderReductionCreditInterface $orderReductionCredit) public function getOrderProductsReductionCreditAmountWithoutTax(OrderShopInterface $order, OrderReductionCreditInterface $orderReductionCredit)
{ {
$amount = 0; $amount = 0;
if ($orderReductionCredit->getBehaviorTaxRate() == 'tax-excluded') { if ($orderReductionCredit->getBehaviorTaxRate() == 'tax-excluded') {
$amount = $orderReductionCredit->getValue();
}
else if ($orderReductionCredit->getBehaviorTaxRate() == 'tax-included') {
$amount = $this->round($orderReductionCredit->getValue() / $this->getTaxRateAverage($order));
$amount = $orderReductionCredit->getValue();
} else if ($orderReductionCredit->getBehaviorTaxRate() == 'tax-included') {
$amount = $this->round($orderReductionCredit->getValue() / $this->getTaxRateAverage($order));
} }


return $amount; return $amount;
{ {
$amountWithTax = 0; $amountWithTax = 0;
if ($orderReductionCredit->getBehaviorTaxRate() == 'tax-excluded') { if ($orderReductionCredit->getBehaviorTaxRate() == 'tax-excluded') {
$amountWithTax = $this->round($orderReductionCredit->getValue() * $this->getTaxRateAverage($order));
}
elseif ($orderReductionCredit->getBehaviorTaxRate() == 'tax-included') {
$amountWithTax = $orderReductionCredit->getValue();
$amountWithTax = $this->round($orderReductionCredit->getValue() * $this->getTaxRateAverage($order));
} elseif ($orderReductionCredit->getBehaviorTaxRate() == 'tax-included') {
$amountWithTax = $orderReductionCredit->getValue();
} }


return $amountWithTax; return $amountWithTax;

+ 117
- 76
ShopBundle/Services/Utils.php View File

use Lc\ShopBundle\Context\UnitInterface; use Lc\ShopBundle\Context\UnitInterface;
use Lc\ShopBundle\Context\UserInterface; use Lc\ShopBundle\Context\UserInterface;
use Lc\ShopBundle\Context\UserPointSaleInterface; use Lc\ShopBundle\Context\UserPointSaleInterface;
use Liip\ImagineBundle\Imagine\Cache\CacheManager;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface; use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\HttpFoundation\ParameterBag; use Symfony\Component\HttpFoundation\ParameterBag;
use Symfony\Component\HttpFoundation\Session\SessionInterface; use Symfony\Component\HttpFoundation\Session\SessionInterface;


class Utils class Utils
{ {
protected $em ;
protected $parameterBag ;
protected $merchantUtils ;
protected $em;
protected $parameterBag;
protected $merchantUtils;
protected $session; protected $session;
protected $translator; protected $translator;
protected $configManager; protected $configManager;


const MEAN_PAYMENT_CREDIT_CARD = 'cb' ;
const MEAN_PAYMENT_CHEQUE = 'cheque' ;
const MEAN_PAYMENT_CREDIT = 'credit' ;
const MEAN_PAYMENT_TRANSFER = 'transfer' ;
const MEAN_PAYMENT_CASH = 'cash' ;
const MEAN_PAYMENT_CREDIT_CARD = 'cb';
const MEAN_PAYMENT_CHEQUE = 'cheque';
const MEAN_PAYMENT_CREDIT = 'credit';
const MEAN_PAYMENT_TRANSFER = 'transfer';
const MEAN_PAYMENT_CASH = 'cash';


public function __construct(EntityManagerInterface $em, ParameterBagInterface $parameterBag, SessionInterface $session, TranslatorInterface $translator, ConfigManager $configManager)
public function __construct(EntityManagerInterface $em, ParameterBagInterface $parameterBag, SessionInterface $session, TranslatorInterface $translator, ConfigManager $configManager, CacheManager $liipCacheHelper)
{ {
$this->em = $em ;
$this->parameterBag = $parameterBag ;
$this->em = $em;
$this->parameterBag = $parameterBag;
$this->session = $session; $this->session = $session;
$this->translator = $translator; $this->translator = $translator;
$this->configManager = $configManager; $this->configManager = $configManager;
$this->liipCacheHelper = $liipCacheHelper;
} }




public function getElementByDevAlias($devAlias, $class = PageInterface::class) public function getElementByDevAlias($devAlias, $class = PageInterface::class)
{ {
$class = $this->em->getClassMetadata($class)->getName(); $class = $this->em->getClassMetadata($class)->getName();
return $this->em->getRepository($class)->findOneByDevAlias($devAlias) ;
return $this->em->getRepository($class)->findOneByDevAlias($devAlias);
} }




public function isServerLocalhost() public function isServerLocalhost()
{ {
return in_array($_SERVER['REMOTE_ADDR'], ['127.0.0.1', '::1']) ;
return in_array($_SERVER['REMOTE_ADDR'], ['127.0.0.1', '::1']);
} }


public function getCookieDomain() public function getCookieDomain()
{ {
return ($this->isServerLocalhost()) ? null : $this->parameterBag->get('app.cookie_domain_distant') ;
return ($this->isServerLocalhost()) ? null : $this->parameterBag->get('app.cookie_domain_distant');
} }


public function limitText($text, $limit) {
$text = strip_tags($text) ;
public function limitText($text, $limit)
{
$text = strip_tags($text);
if (str_word_count($text, 0) > $limit) { if (str_word_count($text, 0) > $limit) {
$words = str_word_count($text, 2); $words = str_word_count($text, 2);
$pos = array_keys($words); $pos = array_keys($words);
return $text; return $text;
} }


function truncateHtml($text, $length = 100, $ending = '...', $exact = false, $considerHtml = true) {
function truncateHtml($text, $length = 100, $ending = '...', $exact = false, $considerHtml = true)
{
if ($considerHtml) { if ($considerHtml) {
// if the plain text is shorter than the maximum length, return the whole text // if the plain text is shorter than the maximum length, return the whole text
if (strlen(preg_replace('/<.*?>/', '', $text)) <= $length) { if (strlen(preg_replace('/<.*?>/', '', $text)) <= $length) {
} }
// calculate the length of the plain text part of the line; handle entities as one character // calculate the length of the plain text part of the line; handle entities as one character
$content_length = strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|[0-9a-f]{1,6};/i', ' ', $line_matchings[2])); $content_length = strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|[0-9a-f]{1,6};/i', ' ', $line_matchings[2]));
if ($total_length+$content_length> $length) {
if ($total_length + $content_length > $length) {
// the number of characters which are left // the number of characters which are left
$left = $length - $total_length; $left = $length - $total_length;
$entities_length = 0; $entities_length = 0;
if (preg_match_all('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|[0-9a-f]{1,6};/i', $line_matchings[2], $entities, PREG_OFFSET_CAPTURE)) { if (preg_match_all('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|[0-9a-f]{1,6};/i', $line_matchings[2], $entities, PREG_OFFSET_CAPTURE)) {
// calculate the real length of all entities in the legal range // calculate the real length of all entities in the legal range
foreach ($entities[0] as $entity) { foreach ($entities[0] as $entity) {
if ($entity[1]+1-$entities_length <= $left) {
if ($entity[1] + 1 - $entities_length <= $left) {
$left--; $left--;
$entities_length += strlen($entity[0]); $entities_length += strlen($entity[0]);
} else { } else {
} }
} }
} }
$truncate .= substr($line_matchings[2], 0, $left+$entities_length);
$truncate .= substr($line_matchings[2], 0, $left + $entities_length);
// maximum lenght is reached, so get off the loop // maximum lenght is reached, so get off the loop
break; break;
} else { } else {
$total_length += $content_length; $total_length += $content_length;
} }
// if the maximum length is reached, get off the loop // if the maximum length is reached, get off the loop
if($total_length>= $length) {
if ($total_length >= $length) {
break; break;
} }
} }
} }
// add the defined ending to the text // add the defined ending to the text
$truncate .= $ending; $truncate .= $ending;
if($considerHtml) {
if ($considerHtml) {
// close all unclosed html-tags // close all unclosed html-tags
foreach ($open_tags as $tag) { foreach ($open_tags as $tag) {
$truncate .= '</' . $tag . '>'; $truncate .= '</' . $tag . '>';
public function slugify($string) public function slugify($string)
{ {
$slugify = new Slugify(); $slugify = new Slugify();
return $slugify->slugify($string) ;
return $slugify->slugify($string);
} }


public function getUnitsList() public function getUnitsList()
{ {
$unitsList =array();
$unitsList = array();
$units = $this->em->getRepository(UnitInterface::class)->findAll(); $units = $this->em->getRepository(UnitInterface::class)->findAll();
foreach ($units as $unit){
foreach ($units as $unit) {
$unitsList[$unit->getId()]['unit'] = $unit->getUnit(); $unitsList[$unit->getId()]['unit'] = $unit->getUnit();
$unitsList[$unit->getId()]['wordingUnit'] = $unit->getWordingUnit(); $unitsList[$unit->getId()]['wordingUnit'] = $unit->getWordingUnit();
$unitsList[$unit->getId()]['wording'] = $unit->getWording(); $unitsList[$unit->getId()]['wording'] = $unit->getWording();


public function isUserLinkedToPointSale(UserInterface $user, PointSaleInterface $pointSale) public function isUserLinkedToPointSale(UserInterface $user, PointSaleInterface $pointSale)
{ {
foreach($user->getUserPointSales() as $userPointSale) {
if($userPointSale->getPointSale()->getId() == $pointSale->getId()) {
return true ;
foreach ($user->getUserPointSales() as $userPointSale) {
if ($userPointSale->getPointSale()->getId() == $pointSale->getId()) {
return true;
} }
} }
return false ;
return false;
} }


public function linkUserToPointSale(UserInterface $user, PointSaleInterface $pointSale) public function linkUserToPointSale(UserInterface $user, PointSaleInterface $pointSale)
{ {
if(!$this->isUserLinkedToPointSale($user, $pointSale)) {
if (!$this->isUserLinkedToPointSale($user, $pointSale)) {
$userPointSaleClass = $this->em->getClassMetadata(UserPointSaleInterface::class)->getName(); $userPointSaleClass = $this->em->getClassMetadata(UserPointSaleInterface::class)->getName();
$userPointSale = new $userPointSaleClass ;
$userPointSale = new $userPointSaleClass;


$userPointSale->setUser($user) ;
$userPointSale->setPointSale($pointSale) ;
$userPointSale->setUser($user);
$userPointSale->setPointSale($pointSale);


$this->em->persist($userPointSale); $this->em->persist($userPointSale);
$this->em->flush() ;
$this->em->flush();
} }
} }


function callCitiesApi($method, $url, $data = false) function callCitiesApi($method, $url, $data = false)
{ {
$url = 'https://geo.api.gouv.fr/'.$url ;
$url = 'https://geo.api.gouv.fr/' . $url;
$curl = curl_init(); $curl = curl_init();


switch ($method)
{
switch ($method) {
case "POST": case "POST":
curl_setopt($curl, CURLOPT_POST, 1); curl_setopt($curl, CURLOPT_POST, 1);




public function getZipByCity($city, $code = null) public function getZipByCity($city, $code = null)
{ {
$zip = null ;
$zip = null;


$paramsSearch = [ $paramsSearch = [
'nom' => $city, 'nom' => $city,
'fields' => 'nom,codesPostaux' 'fields' => 'nom,codesPostaux'
] ;
];


if($code != null && $code != 0) {
$paramsSearch['code'] = $code ;
if ($code != null && $code != 0) {
$paramsSearch['code'] = $code;
} }


$returnCitiesSearchZip = json_decode($this->callCitiesApi('get', 'communes', $paramsSearch)) ;
$returnCitiesSearchZip = json_decode($this->callCitiesApi('get', 'communes', $paramsSearch));


if($returnCitiesSearchZip) {
foreach($returnCitiesSearchZip as $citySearchZip) {
if(strtolower(trim($city)) == strtolower(trim($citySearchZip->nom))) {
$zip = $citySearchZip->codesPostaux[0] ;
if ($returnCitiesSearchZip) {
foreach ($returnCitiesSearchZip as $citySearchZip) {
if (strtolower(trim($city)) == strtolower(trim($citySearchZip->nom))) {
$zip = $citySearchZip->codesPostaux[0];
} }
} }
} }


return $zip ;
return $zip;
} }

public function date($format, $timestamp) public function date($format, $timestamp)
{ {
setlocale(LC_TIME, 'fr_FR.UTF8', 'fr.UTF8', 'fr_FR.UTF-8', 'fr.UTF-8'); setlocale(LC_TIME, 'fr_FR.UTF8', 'fr.UTF8', 'fr_FR.UTF-8', 'fr.UTF-8');
return strftime($format, $timestamp) ;
return strftime($format, $timestamp);
} }


public function getNextDay($day) public function getNextDay($day)
{ {
return new \DateTime('next '.$day) ;
return new \DateTime('next ' . $day);
} }


public function getNextDayByNumber($number) public function getNextDayByNumber($number)
{ {
return $this->getNextDay($this->getDayByNumber($number, 'en')) ;
return $this->getNextDay($this->getDayByNumber($number, 'en'));
} }


public function getDayByNumber($number, $lang = 'fr') public function getDayByNumber($number, $lang = 'fr')
{ {
if($lang == 'fr') {
if ($lang == 'fr') {
$daysArray = [ $daysArray = [
1 => 'Lundi', 1 => 'Lundi',
2 => 'Mardi', 2 => 'Mardi',
5 => 'Vendredi', 5 => 'Vendredi',
6 => 'Samedi', 6 => 'Samedi',
7 => 'Dimanche' 7 => 'Dimanche'
] ;
}
else {
];
} else {
$daysArray = [ $daysArray = [
1 => 'Monday', 1 => 'Monday',
2 => 'Tuesday', 2 => 'Tuesday',
5 => 'Friday', 5 => 'Friday',
6 => 'Saturday', 6 => 'Saturday',
7 => 'Sunday', 7 => 'Sunday',
] ;
];
} }


if(isset($daysArray[$number])) {
return $daysArray[$number] ;
if (isset($daysArray[$number])) {
return $daysArray[$number];
} }


return '' ;
return '';
} }


public function addFlash($success, $message, $extraMessages = array(), $params=array(), $domain='lcshop'){
$message = $this->translator->trans($message, $params,$domain);
public function addFlash($success, $message, $extraMessages = array(), $params = array(), $domain = 'lcshop')
{
$message = $this->translator->trans($message, $params, $domain);


if (count($extraMessages)) { if (count($extraMessages)) {
$message .= '<ul>'; $message .= '<ul>';


} }


public function getFlashMessages(){
return $this->session->getFlashBag()->all();
public function getFlashMessages()
{
return $this->session->getFlashBag()->all();
} }


function camelCase($str) {
$i = array("-","_");
function camelCase($str)
{
$i = array("-", "_");
$str = preg_replace('/([a-z])([A-Z])/', "\\1 \\2", $str); $str = preg_replace('/([a-z])([A-Z])/', "\\1 \\2", $str);
$str = preg_replace('@[^a-zA-Z0-9\-_ ]+@', '', $str); $str = preg_replace('@[^a-zA-Z0-9\-_ ]+@', '', $str);
$str = str_replace($i, ' ', $str); $str = str_replace($i, ' ', $str);
$str = str_replace(' ', '', ucwords(strtolower($str))); $str = str_replace(' ', '', ucwords(strtolower($str)));
$str = strtolower(substr($str,0,1)).substr($str,1);
$str = strtolower(substr($str, 0, 1)) . substr($str, 1);
return $str; return $str;
} }


function snakeCase($str) {
function snakeCase($str)
{
$str = preg_replace('/([a-z])([A-Z])/', "\\1_\\2", $str); $str = preg_replace('/([a-z])([A-Z])/', "\\1_\\2", $str);
$str = strtolower($str); $str = strtolower($str);
return $str; return $str;
} }


public function csvEscape($str){
public function csvEscape($str)
{
return str_replace(array("\r", "\n"), ' ', $str); return str_replace(array("\r", "\n"), ' ', $str);
} }

public function getRemindersByUser($user) public function getRemindersByUser($user)
{ {
$reminderRepo = $this->em->getRepository(ReminderInterface::class); $reminderRepo = $this->em->getRepository(ReminderInterface::class);


$entitiesRepo = array(); $entitiesRepo = array();
$entitiesConfig = array(); $entitiesConfig = array();
if(count($reminders)>0 ) {
if (count($reminders) > 0) {
foreach ($reminders as $reminder) { foreach ($reminders as $reminder) {
if($reminder->getEntityName()) {
if ($reminder->getEntityName()) {
if (!isset($entitiesConfig[$reminder->getEntityName()])) { if (!isset($entitiesConfig[$reminder->getEntityName()])) {
$entitiesConfig[$reminder->getEntityName()] = $this->configManager->getEntityConfig($reminder->getEntityName()); $entitiesConfig[$reminder->getEntityName()] = $this->configManager->getEntityConfig($reminder->getEntityName());
} }
if($reminder->getEntityAction() == 'edit' || $reminder->getEntityAction() == 'show') {
if ($reminder->getEntityAction() == 'edit' || $reminder->getEntityAction() == 'show') {
if (!isset($entitiesRepo[$reminder->getEntityName()])) { if (!isset($entitiesRepo[$reminder->getEntityName()])) {
$entitiesRepo[$reminder->getEntityName()] = $this->em->getRepository($entitiesConfig[$reminder->getEntityName()]['class']); $entitiesRepo[$reminder->getEntityName()] = $this->em->getRepository($entitiesConfig[$reminder->getEntityName()]['class']);
} }


if($reminder->getEntityId()) {
if ($reminder->getEntityId()) {
$reminder->relatedPage = $entitiesRepo[$reminder->getEntityName()]->find($reminder->getEntityId())->__toString(); $reminder->relatedPage = $entitiesRepo[$reminder->getEntityName()]->find($reminder->getEntityId())->__toString();
} }
} else { } else {
return $reminders; return $reminders;
} }


public function removeDir($dir) {
$files = array_diff(scandir($dir), array('.','..'));
public function removeDir($dir)
{
$files = array_diff(scandir($dir), array('.', '..'));
foreach ($files as $file) { foreach ($files as $file) {
(is_dir("$dir/$file")) ? $this->removeDir("$dir/$file") : unlink("$dir/$file"); (is_dir("$dir/$file")) ? $this->removeDir("$dir/$file") : unlink("$dir/$file");
} }
return rmdir($dir); return rmdir($dir);
} }


function folderToZip($folder, &$zipFile, $subfolder = null) {
function folderToZip($folder, &$zipFile, $subfolder = null)
{
if ($zipFile == null) { if ($zipFile == null) {
// no resource given, exit // no resource given, exit
return false; return false;
} }
// we check if $folder has a slash at its end, if not, we append one // we check if $folder has a slash at its end, if not, we append one
$tabFolder = str_split($folder) ;
$tabSubFolder = str_split($subfolder) ;
$tabFolder = str_split($folder);
$tabSubFolder = str_split($subfolder);
$folder .= end($tabFolder) == "/" ? "" : "/"; $folder .= end($tabFolder) == "/" ? "" : "/";
$subfolder .= end($tabSubFolder) == "/" ? "" : "/"; $subfolder .= end($tabSubFolder) == "/" ? "" : "/";
// we start by going through all files in $folder // we start by going through all files in $folder
} }
} }
} }

public function lcLiip($path, $thumb = 'tile', $default = 'default.jpg')
{
if (substr($path, 0, 1) === '/') $path = substr($path, 1);

if ($path) {
$fileManagerFolder = substr($this->getFileManagerFolder(), 1) ;

if (strpos($path, $fileManagerFolder) === false) {
$path = $fileManagerFolder . '/' . $path;
}

if (file_exists($path)) {
return $this->liipCacheHelper->getBrowserPath($path, $thumb);
}
}

return $this->liipCacheHelper->getBrowserPath($this->getFileManagerFolder() . '/' . $default, $thumb);
}

/**
* Retourne le chemin vers le dossier d'uploads de responsiveFilemanager
*
* @return string
*/
public function getFileManagerFolder()
{
return $this->parameterBag->get('app.path.images');
}

} }

+ 8
- 0
ShopBundle/Twig/BridgeTwigExtension.php View File

new TwigFunction('getDayByNumber', [$this, 'getDayByNumber']), new TwigFunction('getDayByNumber', [$this, 'getDayByNumber']),
new TwigFunction('getUnitsList', [$this, 'getUnitsList']), new TwigFunction('getUnitsList', [$this, 'getUnitsList']),
new TwigFunction('getTaxRatesList', [$this, 'getTaxRatesList']), new TwigFunction('getTaxRatesList', [$this, 'getTaxRatesList']),
new TwigFunction('lc_liip', [$this, 'lcLiip']),
new TwigFunction('getElementByDevAlias', [$this, 'getElementByDevAlias']), new TwigFunction('getElementByDevAlias', [$this, 'getElementByDevAlias']),
); );
} }
{ {
return [ return [
new TwigFilter('slugify', [$this, 'slugify']), new TwigFilter('slugify', [$this, 'slugify']),
new TwigFilter('lc_liip', [$this, 'lcLiip']),

]; ];
} }


{ {
return $this->utils->slugify($string) ; return $this->utils->slugify($string) ;
} }

public function lcLiip($path, $thumb = 'tile', $default = 'default.jpg'){

return $this->utils->lcLiip($path, $thumb, $default);
}
} }

+ 7
- 41
ShopBundle/Twig/FrontendTwigExtension.php View File

protected $kernel; protected $kernel;


public function __construct(EntityManagerInterface $em, Security $security, MerchantUtilsInterface $merchantUtils, public function __construct(EntityManagerInterface $em, Security $security, MerchantUtilsInterface $merchantUtils,
FormFactoryInterface $formFactory, RequestStack $requestStack, CacheManager $liipCacheHelper,
ParameterBagInterface $parameterBag, KernelInterface $kernel)
FormFactoryInterface $formFactory, RequestStack $requestStack, ParameterBagInterface $parameterBag, KernelInterface $kernel)
{ {
$this->em = $em; $this->em = $em;
$this->security = $security; $this->security = $security;
$this->productCategoryRepository = $this->em->getRepository($this->em->getClassMetadata(ProductCategoryInterface::class)->getName()); $this->productCategoryRepository = $this->em->getRepository($this->em->getClassMetadata(ProductCategoryInterface::class)->getName());
$this->merchantRepository = $this->em->getRepository($this->em->getClassMetadata(MerchantInterface::class)->getName()); $this->merchantRepository = $this->em->getRepository($this->em->getClassMetadata(MerchantInterface::class)->getName());
$this->productFamilyRepository = $this->em->getRepository($this->em->getClassMetadata(ProductFamilyInterface::class)->getName()); $this->productFamilyRepository = $this->em->getRepository($this->em->getClassMetadata(ProductFamilyInterface::class)->getName());
$this->liipCacheHelper = $liipCacheHelper;
$this->parameterBag = $parameterBag; $this->parameterBag = $parameterBag;
$this->kernel = $kernel; $this->kernel = $kernel;
} }
new TwigFunction('get_product_categories', [$this, 'getProductCategories']), new TwigFunction('get_product_categories', [$this, 'getProductCategories']),
new TwigFunction('get_form_newsletter', [$this, 'getFormNewsletter']), new TwigFunction('get_form_newsletter', [$this, 'getFormNewsletter']),
new TwigFunction('get_merchants', [$this, 'getMerchants']), new TwigFunction('get_merchants', [$this, 'getMerchants']),
new TwigFunction('lc_liip', [$this, 'lcLiip']),
new TwigFunction('get_file_manager_folder', [$this, 'getFileManagerFolder']), new TwigFunction('get_file_manager_folder', [$this, 'getFileManagerFolder']),
); );
} }
{ {
return [ return [
new TwigFilter('format_price', [$this, 'formatPrice']), new TwigFilter('format_price', [$this, 'formatPrice']),
new TwigFilter('lc_liip', [$this, 'lcLiip']),
new TwigFilter('lc_cache', [$this, 'lcCache']), new TwigFilter('lc_cache', [$this, 'lcCache']),
]; ];
} }


public function lcCache($file){
$cacheTime = filemtime($this->kernel->getProjectDir().'/public'.$file);
if($cacheTime){
return $file.'?c='.$cacheTime;
}else{
return $file."?c=0";
}
}


public function lcLiip($path, $thumb = 'tile', $default = 'default.jpg')
public function lcCache($file)
{ {
if (substr($path, 0, 1) === '/') $path = substr($path, 1);

if ($path) {
$fileManagerFolder = substr($this->getFileManagerFolder(), 1) ;

if (strpos($path, $fileManagerFolder) === false) {
$path = $fileManagerFolder . '/' . $path;
}

if (file_exists($path)) {
return $this->liipCacheHelper->getBrowserPath($path, $thumb);
}
$cacheTime = filemtime($this->kernel->getProjectDir() . '/public' . $file);
if ($cacheTime) {
return $file . '?c=' . $cacheTime;
} else {
return $file . "?c=0";
} }

return $this->liipCacheHelper->getBrowserPath($this->getFileManagerFolder() . '/' . $default, $thumb);
}

/**
* Retourne le chemin vers le dossier d'uploads de responsiveFilemanager
*
* @return string
*/
public function getFileManagerFolder()
{
return $this->parameterBag->get('app.path.images');
} }



public function getProductCategories() public function getProductCategories()
{ {
$categories = $this->productCategoryRepository->findAllParents(false); $categories = $this->productCategoryRepository->findAllParents(false);

Loading…
Cancel
Save