Browse Source

Refactoring services #885

refactoring
Guillaume 1 year ago
parent
commit
32b0a64835
42 changed files with 240 additions and 225 deletions
  1. +1
    -1
      backend/controllers/AccessController.php
  2. +1
    -1
      backend/controllers/CommunicateController.php
  3. +2
    -2
      backend/controllers/CronController.php
  4. +1
    -1
      backend/controllers/DeliveryNoteController.php
  5. +1
    -1
      backend/controllers/DevelopmentController.php
  6. +0
    -2
      backend/controllers/DistributionController.php
  7. +1
    -1
      backend/controllers/DocumentController.php
  8. +6
    -6
      backend/controllers/OrderController.php
  9. +1
    -1
      backend/controllers/PointSaleController.php
  10. +1
    -1
      backend/controllers/ProducerController.php
  11. +1
    -1
      backend/controllers/ProductCategoryController.php
  12. +1
    -1
      backend/controllers/ProductController.php
  13. +1
    -1
      backend/controllers/QuotationController.php
  14. +1
    -1
      backend/controllers/ReportController.php
  15. +1
    -1
      backend/controllers/SiteController.php
  16. +1
    -1
      backend/controllers/StatsController.php
  17. +1
    -1
      backend/controllers/SubscriptionController.php
  18. +1
    -1
      backend/controllers/UserGroupController.php
  19. +2
    -2
      backend/models/CreditForm.php
  20. +1
    -1
      backend/views/development/development.php
  21. +1
    -1
      backend/views/document/download.php
  22. +9
    -9
      backend/views/user/credit.php
  23. +1
    -1
      common/components/ActiveRecordCommon.php
  24. +2
    -0
      common/components/View.php
  25. +2
    -2
      common/controllers/CommonController.php
  26. +4
    -4
      common/logic/Order/Order/OrderBuilder.php
  27. +5
    -0
      common/logic/Product/Product/ProductRepository.php
  28. +1
    -1
      common/logic/Product/Product/ProductSolver.php
  29. +1
    -1
      common/logic/Product/ProductCategory/ProductCategoryRepository.php
  30. +3
    -2
      common/logic/Subscription/Subscription/SubscriptionSearch.php
  31. +2
    -1
      common/logic/User/CreditHistory/CreditHistorySearch.php
  32. +2
    -2
      producer/controllers/CreditController.php
  33. +137
    -139
      producer/controllers/OrderController.php
  34. +6
    -6
      producer/controllers/SiteController.php
  35. +4
    -1
      producer/views/credit/add.php
  36. +15
    -15
      producer/views/credit/history.php
  37. +3
    -3
      producer/views/layouts/main.php
  38. +2
    -1
      producer/views/order/confirm.php
  39. +3
    -3
      producer/views/order/order.php
  40. +3
    -3
      producer/views/site/index.php
  41. +3
    -1
      producer/views/subscription/_form.php
  42. +5
    -1
      producer/views/subscription/index.php

+ 1
- 1
backend/controllers/AccessController.php View File

'allow' => true, 'allow' => true,
'roles' => ['@'], 'roles' => ['@'],
'matchCallback' => function ($rule, $action) { 'matchCallback' => function ($rule, $action) {
return $this->getLogic()->getUserContainer()->getSolver()->hasAccessBackend();
return $this->getUserManager()->hasAccessBackend();
} }
] ]
], ],

+ 1
- 1
backend/controllers/CommunicateController.php View File

'allow' => true, 'allow' => true,
'roles' => ['@'], 'roles' => ['@'],
'matchCallback' => function ($rule, $action) { 'matchCallback' => function ($rule, $action) {
return $this->getLogic()->getUserContainer()->getSolver()->hasAccessBackend();
return $this->getUserManager()->hasAccessBackend();
} }
] ]
], ],

+ 2
- 2
backend/controllers/CronController.php View File

public function actionInitDemo($key = '') public function actionInitDemo($key = '')
{ {
if ($key == '45432df6e842ac71aa0b5bb6b9f25d44') { if ($key == '45432df6e842ac71aa0b5bb6b9f25d44') {
$producerRepository = $this->getLogic()->getProducerContainer()->getRepository();
$producer = $producerRepository->getOneDemoAccount();
$producerManager = $this->getProducerManager();
$producer = $producerManager->findOneProducerDemoAccount();


if ($producer) { if ($producer) {
// initialisation de la distribution à J+7 // initialisation de la distribution à J+7

+ 1
- 1
backend/controllers/DeliveryNoteController.php View File

'allow' => true, 'allow' => true,
'roles' => ['@'], 'roles' => ['@'],
'matchCallback' => function ($rule, $action) { 'matchCallback' => function ($rule, $action) {
return $this->getLogic()->getUserContainer()->getSolver()->hasAccessBackend();
return $this->getUserManager()->hasAccessBackend();
} }
] ]
], ],

+ 1
- 1
backend/controllers/DevelopmentController.php View File

'allow' => true, 'allow' => true,
'roles' => ['@'], 'roles' => ['@'],
'matchCallback' => function ($rule, $action) { 'matchCallback' => function ($rule, $action) {
return $this->getLogic()->getUserContainer()->getSolver()->hasAccessBackend();
return $this->getUserManager()->hasAccessBackend();
} }
] ]
], ],

+ 0
- 2
backend/controllers/DistributionController.php View File

{ {
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;


$creditHistoryService = \Yii::$app->logic->getCreditHistoryContainer()->getService();

$json = [ $json = [
'distribution' => [], 'distribution' => [],
'products' => [] 'products' => []

+ 1
- 1
backend/controllers/DocumentController.php View File

'allow' => true, 'allow' => true,
'roles' => ['@'], 'roles' => ['@'],
'matchCallback' => function ($rule, $action) { 'matchCallback' => function ($rule, $action) {
return $this->getLogic()->getUserContainer()->getSolver()->hasAccessBackend();
return $this->getUserManager()->hasAccessBackend();
} }
] ]
], ],

+ 6
- 6
backend/controllers/OrderController.php View File

*/ */
public function actionPaymentStatus($idOrder) public function actionPaymentStatus($idOrder)
{ {
$creditHistoryService = \Yii::$app->logic->getCreditHistoryContainer()->getService();
$creditHistoryManager = $this->getCreditHistoryManager();
$order = Order::searchOne(['id' => $idOrder]); $order = Order::searchOne(['id' => $idOrder]);


if ($order) { if ($order) {
if ($history && is_array($history) && count($history)) { if ($history && is_array($history) && count($history)) {
foreach ($history as $creditHistory) { foreach ($history as $creditHistory) {
$html .= '<tr>' $html .= '<tr>'
. '<td>' . date('d/m/Y H:i:s', strtotime($creditHistoryService->getDate($creditHistory))) . '</td>'
. '<td>' . Html::encode($creditHistoryService->getStrUserAction($creditHistory)) . '</td>'
. '<td>' . $creditHistoryService->getStrWording($creditHistory) . '</td>'
. '<td>' . ($creditHistoryService->isTypeDebit($creditHistory) ? '- ' . $creditHistoryService->getAmountWithTax($creditHistory, Order::AMOUNT_TOTAL, true) : '') . '</td>'
. '<td>' . ($creditHistoryService->isTypeCredit($creditHistory) ? '+ ' . $creditHistoryService->getAmountWithTax($creditHistory, Order::AMOUNT_TOTAL, true) : '') . '</td>'
. '<td>' . date('d/m/Y H:i:s', strtotime($creditHistoryManager->getDate($creditHistory))) . '</td>'
. '<td>' . Html::encode($creditHistoryManager->getStrUserAction($creditHistory)) . '</td>'
. '<td>' . $creditHistoryManager->getStrWording($creditHistory) . '</td>'
. '<td>' . ($creditHistoryManager->isTypeDebit($creditHistory) ? '- ' . $creditHistoryManager->getAmountWithTax($creditHistory, Order::AMOUNT_TOTAL, true) : '') . '</td>'
. '<td>' . ($creditHistoryManager->isTypeCredit($creditHistory) ? '+ ' . $creditHistoryManager->getAmountWithTax($creditHistory, Order::AMOUNT_TOTAL, true) : '') . '</td>'
. '</tr>'; . '</tr>';
} }
} else { } else {

+ 1
- 1
backend/controllers/PointSaleController.php View File

'allow' => true, 'allow' => true,
'roles' => ['@'], 'roles' => ['@'],
'matchCallback' => function ($rule, $action) { 'matchCallback' => function ($rule, $action) {
return $this->getLogic()->getUserContainer()->getSolver()->hasAccessBackend();
return $this->getUserManager()->hasAccessBackend();
} }
], ],
], ],

+ 1
- 1
backend/controllers/ProducerController.php View File

'allow' => true, 'allow' => true,
'roles' => ['@'], 'roles' => ['@'],
'matchCallback' => function ($rule, $action) { 'matchCallback' => function ($rule, $action) {
return $this->getLogic()->getUserContainer()->getSolver()->hasAccessBackend();
return $this->getUserManager()->hasAccessBackend();
} }
] ]
], ],

+ 1
- 1
backend/controllers/ProductCategoryController.php View File

'allow' => true, 'allow' => true,
'roles' => ['@'], 'roles' => ['@'],
'matchCallback' => function ($rule, $action) { 'matchCallback' => function ($rule, $action) {
return $this->getLogic()->getUserContainer()->getSolver()->hasAccessBackend();
return $this->getUserManager()->hasAccessBackend();
} }
], ],
], ],

+ 1
- 1
backend/controllers/ProductController.php View File

'allow' => true, 'allow' => true,
'roles' => ['@'], 'roles' => ['@'],
'matchCallback' => function ($rule, $action) { 'matchCallback' => function ($rule, $action) {
return $this->getLogic()->getUserContainer()->getSolver()->hasAccessBackend();
return $this->getUserManager()->hasAccessBackend();
} }
] ]
], ],

+ 1
- 1
backend/controllers/QuotationController.php View File

'allow' => true, 'allow' => true,
'roles' => ['@'], 'roles' => ['@'],
'matchCallback' => function ($rule, $action) { 'matchCallback' => function ($rule, $action) {
return $this->getLogic()->getUserContainer()->getSolver()->hasAccessBackend();
return $this->getUserManager()->hasAccessBackend();
} }
] ]
], ],

+ 1
- 1
backend/controllers/ReportController.php View File

'allow' => true, 'allow' => true,
'roles' => ['@'], 'roles' => ['@'],
'matchCallback' => function ($rule, $action) { 'matchCallback' => function ($rule, $action) {
return $this->getLogic()->getUserContainer()->getSolver()->hasAccessBackend();
return $this->getUserManager()->hasAccessBackend();
} }
] ]
], ],

+ 1
- 1
backend/controllers/SiteController.php View File

'allow' => true, 'allow' => true,
'roles' => ['@'], 'roles' => ['@'],
'matchCallback' => function ($rule, $action) { 'matchCallback' => function ($rule, $action) {
return $this->getLogic()->getUserContainer()->getSolver()->hasAccessBackend();
return $this->getUserManager()->hasAccessBackend();
} }
], ],
[ [

+ 1
- 1
backend/controllers/StatsController.php View File

'allow' => true, 'allow' => true,
'roles' => ['@'], 'roles' => ['@'],
'matchCallback' => function ($rule, $action) { 'matchCallback' => function ($rule, $action) {
return $this->getLogic()->getUserContainer()->getSolver()->hasAccessBackend();
return $this->getUserManager()->hasAccessBackend();
} }
] ]
], ],

+ 1
- 1
backend/controllers/SubscriptionController.php View File

'allow' => true, 'allow' => true,
'roles' => ['@'], 'roles' => ['@'],
'matchCallback' => function ($rule, $action) { 'matchCallback' => function ($rule, $action) {
return $this->getLogic()->getUserContainer()->getSolver()->hasAccessBackend();
return $this->getUserManager()->hasAccessBackend();
} }
] ]
], ],

+ 1
- 1
backend/controllers/UserGroupController.php View File

'allow' => true, 'allow' => true,
'roles' => ['@'], 'roles' => ['@'],
'matchCallback' => function ($rule, $action) { 'matchCallback' => function ($rule, $action) {
return $this->getLogic()->getUserContainer()->getSolver()->hasAccessBackend();
return $this->getUserManager()->hasAccessBackend();
} }
], ],
], ],

+ 2
- 2
backend/models/CreditForm.php View File

*/ */
public function save() public function save()
{ {
$creditHistoryService = Yii::$app->logic->getCreditHistoryContainer()->getService();
$creditHistoryManager = $this->getCreditHistoryManager();


if ($this->validate()) { if ($this->validate()) {
$creditHistory = new CreditHistory; $creditHistory = new CreditHistory;
$creditHistory->amount = $this->amount ; $creditHistory->amount = $this->amount ;
$creditHistory->mean_payment = $this->mean_payment ; $creditHistory->mean_payment = $this->mean_payment ;


$creditHistoryService->save($creditHistory);
$creditHistoryManager->save($creditHistory);
// on prévient l'utilisateur que son compte vient d'être crédité // on prévient l'utilisateur que son compte vient d'être crédité
if($this->send_mail) { if($this->send_mail) {

+ 1
- 1
backend/views/development/development.php View File

]; ];




if ($this->getLogic()->getUserContainer()->getSolver()->hasAccessBackend()) {
if ($this->getUserManager()->hasAccessBackend()) {


$columns[] = [ $columns[] = [
'header' => 'Priorité', 'header' => 'Priorité',

+ 1
- 1
backend/views/document/download.php View File

</tr> </tr>


<?php <?php
$taxRateArray = $this->getLogic()->getTaxRateContainer()->getRepository()->getAsArray();
$taxRateArray = $this->getTaxRateManager()->findTaxRatesAsArray();
foreach ($document->getTotalVatArray($typeAmount) as $idTaxRate => $totalVat): ?> foreach ($document->getTotalVatArray($typeAmount) as $idTaxRate => $totalVat): ?>
<tr> <tr>
<td class="align-right" colspan="5"> <td class="align-right" colspan="5">

+ 9
- 9
backend/views/user/credit.php View File

use yii\widgets\ActiveForm; use yii\widgets\ActiveForm;
use common\helpers\GlobalParam; use common\helpers\GlobalParam;


$creditHistoryService = $this->getLogic()->getCreditHistoryContainer()->getService();
$creditHistoryManager = $this->getCreditHistoryManager();


$this->setTitle('Créditer <small>'.Html::encode($user->lastname.' '.$user->name).'</small>', 'Créditer '.Html::encode($user->lastname.' '.$user->name)) ; $this->setTitle('Créditer <small>'.Html::encode($user->lastname.' '.$user->name).'</small>', 'Créditer '.Html::encode($user->lastname.' '.$user->name)) ;
$this->addBreadcrumb(['label' => 'Utilisateurs', 'url' => ['index']]) ; $this->addBreadcrumb(['label' => 'Utilisateurs', 'url' => ['index']]) ;
<?php foreach($history as $creditHistory): ?> <?php foreach($history as $creditHistory): ?>


<tr> <tr>
<td><?= $creditHistoryService->getDate($creditHistory, true) ; ?></td>
<td><?= Html::encode($creditHistoryService->getStrUserAction($creditHistory)); ?></td>
<td><?= $creditHistoryService->getStrWording($creditHistory); ?></td>
<td><?= $creditHistoryManager->getDate($creditHistory, true) ; ?></td>
<td><?= Html::encode($creditHistoryManager->getStrUserAction($creditHistory)); ?></td>
<td><?= $creditHistoryManager->getStrWording($creditHistory); ?></td>
<td> <td>
<?php if($creditHistoryService->isTypeDebit($creditHistory)): ?>
- <?= $creditHistoryService->getAmount($creditHistory, true); ?>
<?php if($creditHistoryManager->isTypeDebit($creditHistory)): ?>
- <?= $creditHistoryManager->getAmount($creditHistory, true); ?>
<?php endif; ?> <?php endif; ?>
</td> </td>
<td> <td>
<?php if($creditHistoryService->isTypeCredit($creditHistory)): ?>
+ <?= $creditHistoryService->getAmount($creditHistory, true); ?>
<?php if($creditHistoryManager->isTypeCredit($creditHistory)): ?>
+ <?= $creditHistoryManager->getAmount($creditHistory, true); ?>
<?php endif; ?> <?php endif; ?>
</td> </td>
<td> <td>
<?= $creditHistoryService->getStrMeanPayment($creditHistory) ?>
<?= $creditHistoryManager->getStrMeanPayment($creditHistory) ?>
</td> </td>
<td> <td>
<?php if(strlen($creditHistory->getComment())): ?> <?php if(strlen($creditHistory->getComment())): ?>

+ 1
- 1
common/components/ActiveRecordCommon.php View File

return $records->count(); return $records->count();
} }


return false;
return null;
} }


public static function groupByPrimaryKey($class, $records) public static function groupByPrimaryKey($class, $records)

+ 2
- 0
common/components/View.php View File



class View extends \yii\web\View class View extends \yii\web\View
{ {
use BusinessLogicContainerTrait;

var $title ; var $title ;
var $page_title ; var $page_title ;
var $buttons ; var $buttons ;

+ 2
- 2
common/controllers/CommonController.php View File

public function beforeAction($event) public function beforeAction($event)
{ {
if (!Yii::$app->user->isGuest) { if (!Yii::$app->user->isGuest) {
$this->getUserContainer()->getBuilder()->updateLastConnection(Yii::$app->user->identity);
$this->getUserManager()->updateUserLastConnection(Yii::$app->user->identity);
} }


return parent::beforeAction($event); return parent::beforeAction($event);


public function isUserCurrentAdmin() public function isUserCurrentAdmin()
{ {
return $this->getUserContainer()->getSolver()->isAdmin($this->getUserCurrent());
return $this->getUserManager()->isAdmin($this->getUserCurrent());
} }


public function getRequest() public function getRequest()

+ 4
- 4
common/logic/Order/Order/OrderBuilder.php View File

$this->subscriptionSolver = $this->loadService(SubscriptionSolver::class); $this->subscriptionSolver = $this->loadService(SubscriptionSolver::class);
} }


public function instanciateOrder(Distribution $distribution): Order
public function instanciateOrder(): Order
{ {
$order = new Order(); $order = new Order();
$order->populateDistribution($distribution);
//$order->populateDistribution($distribution);
$order->date = date('Y-m-d H:i:s'); $order->date = date('Y-m-d H:i:s');
$order->status = 'tmp-order'; $order->status = 'tmp-order';


return $order; return $order;
} }


public function createOrder(Distribution $distribution): Order
public function createOrder(): Order
{ {
$order = $this->instanciateOrder($distribution);
$order = $this->instanciateOrder();


$this->createUserPointSale($order); $this->createUserPointSale($order);
$this->initOrderCommentPointSale($order); $this->initOrderCommentPointSale($order);

+ 5
- 0
common/logic/Product/Product/ProductRepository.php View File

]; ];
} }


public function findOneProductById(int $id): ?Product
{
return Product::searchOne(['id' => $id]);
}

public function findProducts(): array public function findProducts(): array
{ {
return Product::searchAll(); return Product::searchAll();

+ 1
- 1
common/logic/Product/Product/ProductSolver.php View File

$this->productPriceSolver = $this->loadService(ProductPriceSolver::class); $this->productPriceSolver = $this->loadService(ProductPriceSolver::class);
} }


public function getPrice(Product $product, array $params = []): float
public function getPrice(Product $product, array $params = []): ?float
{ {
$specificPriceArray = $product->productPrice; $specificPriceArray = $product->productPrice;



+ 1
- 1
common/logic/Product/ProductCategory/ProductCategoryRepository.php View File

'with' => [], 'with' => [],
'join_with' => [], 'join_with' => [],
'orderby' => '', 'orderby' => '',
'attribute_id_producer' => ''
'attribute_id_producer' => 'id_producer'
]; ];
} }



+ 3
- 2
common/logic/Subscription/Subscription/SubscriptionSearch.php View File

} }
public function search($params) { public function search($params) {
$optionsSearch = self::getDefaultOptionsSearch() ;

$subscriptionManager = new SubscriptionManager();
$optionsSearch = $subscriptionManager->getDefaultOptionsSearch() ;
$query = Subscription::find() $query = Subscription::find()
->with($optionsSearch['with']) ->with($optionsSearch['with'])

+ 2
- 1
common/logic/User/CreditHistory/CreditHistorySearch.php View File

public function search($params) public function search($params)
{ {
$optionsSearch = CreditHistoryRepository::getDefaultOptionsSearch() ;
$creditHistoryManager = new CreditHistoryManager();
$optionsSearch = $creditHistoryManager->getDefaultOptionsSearch() ;
$query = CreditHistory::find() $query = CreditHistory::find()
->with($optionsSearch['with']) ->with($optionsSearch['with'])

+ 2
- 2
producer/controllers/CreditController.php View File

$idProducer = $paymentIntentMetadata->producer_id; $idProducer = $paymentIntentMetadata->producer_id;


if (isset($paymentIntentMetadata->order_id)) { if (isset($paymentIntentMetadata->order_id)) {
$order = $this->getOrderManager()->findOneById($paymentIntentMetadata->order_id);
$order = $this->getOrderManager()->findOneOrderById($paymentIntentMetadata->order_id);
$pointSale = $this->getPointSaleManager()->findOnePointSaleById($order->id_point_sale); $pointSale = $this->getPointSaleManager()->findOnePointSaleById($order->id_point_sale);
$distribution = $this->getDistributionManager()->getOneById($order->id_distribution);
$distribution = $this->getDistributionManager()->findOneDistributionById($order->id_distribution);
} }


// Handle the event // Handle the event

+ 137
- 139
producer/controllers/OrderController.php View File



use common\helpers\GlobalParam; use common\helpers\GlobalParam;
use common\helpers\Mailjet; use common\helpers\Mailjet;
use common\helpers\Password;
use common\logic\Distribution\Distribution\Distribution; use common\logic\Distribution\Distribution\Distribution;
use common\logic\Order\Order\Order; use common\logic\Order\Order\Order;
use common\logic\Order\ProductOrder\ProductOrder;
use common\logic\PointSale\PointSale\PointSale; use common\logic\PointSale\PointSale\PointSale;
use common\logic\Producer\Producer\Producer; use common\logic\Producer\Producer\Producer;
use common\logic\Product\Product\Product;
use common\logic\User\CreditHistory\CreditHistory; use common\logic\User\CreditHistory\CreditHistory;
use common\logic\User\User\User; use common\logic\User\User\User;
use common\logic\User\UserProducer\UserProducer; use common\logic\User\UserProducer\UserProducer;
); );
} }


$order = $this->getOrderManager()->findOneById($id);
$order = $this->getOrderManager()->findOneOrderById($id);
if ($order && $this->getOrderManager()->isOrderStateOpen($order)) { if ($order && $this->getOrderManager()->isOrderStateOpen($order)) {
$params['order'] = $order; $params['order'] = $order;
} }
public function actionHistory($type = 'incoming') public function actionHistory($type = 'incoming')
{ {
$queryHistoryArray = $this->getOrderManager() $queryHistoryArray = $this->getOrderManager()
->queryHistory($this->getProducer(), $this->getUserCurrent(), $type);
->queryOrdersHistory($this->getProducer(), $this->getUserCurrent(), $type);
$queryHistoryIncoming = $queryHistoryArray['incoming']; $queryHistoryIncoming = $queryHistoryArray['incoming'];
$queryHistoryPassed = $queryHistoryArray['passed']; $queryHistoryPassed = $queryHistoryArray['passed'];


]); ]);
} }


/**
* Supprime un producteur.
*/
public function actionRemoveProducer(int $id = 0) public function actionRemoveProducer(int $id = 0)
{ {
$producer = $this->getProducerContainer()->getRepository()->getOneById($id);
$producer = $this->getProducerManager()->findOneProducerById($id);


$this->getUserProducerContainer()->getBuilder()->updateActive(
$this->getUserProducerManager()->updateActive(
$this->getUserCurrent(), $this->getUserCurrent(),
$producer, $producer,
false false
public function actionAjaxProcess() public function actionAjaxProcess()
{ {
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
$posts = \Yii::$app->request->post();

$orderManager = $this->getOrderManager();
$producerManager = $this->getProducerManager();
$redirect = null; $redirect = null;
$order = new Order;
$producer = $this->getProducer(); $producer = $this->getProducer();
$idProducer = $producer->id; $idProducer = $producer->id;

$posts = \Yii::$app->request->post();
$order = $orderManager->instanciateOrder();


if ($idProducer) { if ($idProducer) {
$this->_verifyProducerActive($idProducer); $this->_verifyProducerActive($idProducer);
} }


$order = new Order; $order = new Order;
$order->load(Yii::$app->request->post());
$order->load(\Yii::$app->request->post());
$order->id_user = $user ? $user->id : null; $order->id_user = $user ? $user->id : null;
$order->status = 'tmp-order'; $order->status = 'tmp-order';
$order->date = date('Y-m-d H:i:s'); $order->date = date('Y-m-d H:i:s');
return ['status' => 'error', 'errors' => $errors]; return ['status' => 'error', 'errors' => $errors];
} }


if ($producer->isOnlinePaymentActiveAndTypeOrder()) {
$order = Order::searchOne([
'id' => $order->id
]);

if ($producerManager->isOnlinePaymentActiveAndTypeOrder($producer)) {
$order = $orderManager->findOneOrderById($order->id);
\Stripe\Stripe::setApiKey( \Stripe\Stripe::setApiKey(
$producer->getPrivateKeyApiStripe()
$producerManager->getPrivateKeyApiStripe($producer)
); );


$lineItems = []; $lineItems = [];
'price_data' => [ 'price_data' => [
'currency' => 'eur', 'currency' => 'eur',
'product_data' => [ 'product_data' => [
'name' => $product->name . ' (' . $productOrder->quantity . ' ' . Product::strUnit(
'name' => $product->name . ' (' . $productOrder->quantity . ' ' . $this->getProductManager()->strUnit(
$product->unit, $product->unit,
'wording_short', 'wording_short',
true true
'order_id' => $order->id 'order_id' => $order->id
], ],
], ],
'success_url' => \Yii::$app->urlManagerProducer->createAbsoluteUrl(
'success_url' => $this->getUrlManagerProducer()->createAbsoluteUrl(
[ [
'order/confirm', 'order/confirm',
'idOrder' => $order->id, 'idOrder' => $order->id,
'returnPayment' => 'success' 'returnPayment' => 'success'
] ]
), ),
'cancel_url' => \Yii::$app->urlManagerProducer->createAbsoluteUrl(
'cancel_url' => $this->getUrlManagerProducer()->createAbsoluteUrl(
[ [
'order/confirm', 'order/confirm',
'idOrder' => $order->id, 'idOrder' => $order->id,
*/ */
public function _verifyProducerActive($idProducer) public function _verifyProducerActive($idProducer)
{ {
$producer = Producer::findOne($idProducer);
$producer = $this->getProducerManager()->findOneProducerById($idProducer);
if ($producer && !$producer->active) { if ($producer && !$producer->active) {
throw new NotFoundHttpException('Ce producteur est actuellement hors ligne.'); throw new NotFoundHttpException('Ce producteur est actuellement hors ligne.');
} }
*/ */
public function processForm($order, $user) public function processForm($order, $user)
{ {
$productManager = $this->getProductManager();
$distributionManager = $this->getDistributionManager();
$pointSaleDistributionManager = $this->getPointSaleDistributionManager();
$pointSaleManager = $this->getPointSaleManager();
$userPointSaleManager = $this->getUserPointSaleManager();
$userProducerManager = $this->getUserProducerManager();
$orderManager = $this->getOrderManager();
$producerManager = $this->getProducerManager();
$productOrderManager = $this->getProductOrderManager();
$userManager = $this->getUserManager();
$creditHistoryManager = $this->getCreditHistoryManager();

$posts = \Yii::$app->request->post(); $posts = \Yii::$app->request->post();
$productsArray = []; $productsArray = [];
$totalQuantity = 0; $totalQuantity = 0;
} }


foreach ($posts['products'] as $key => $quantity) { foreach ($posts['products'] as $key => $quantity) {
$product = Product::find()->where(['id' => (int)$key])->one();
$product = $productManager->findOneProductById((int)$key);

$totalQuantity += $quantity; $totalQuantity += $quantity;
if ($product && $quantity) { if ($product && $quantity) {
$productsArray[] = $product; $productsArray[] = $product;
} }
} }


// date
$errorDate = false; $errorDate = false;
if (isset($order->id_distribution)) { if (isset($order->id_distribution)) {
// date de commande
$distribution = DistributionModel::find()->where(['id' => $order->id_distribution])->one();

$distribution = $distributionManager->findOneDistributionById($order->id_distribution);
if ($order->getState() != Order::STATE_OPEN) { if ($order->getState() != Order::STATE_OPEN) {
$errorDate = true; $errorDate = true;
} }
} }


// point de vente
$errorPointSale = false; $errorPointSale = false;
if (isset($distribution) && $distribution) { if (isset($distribution) && $distribution) {
$pointSaleDistribution = PointSaleDistributionModel::searchOne([
'id_distribution' => $distribution->id,
'id_point_sale' => $posts['Order']['id_point_sale']
]);
$pointSale = $pointSaleManager->findOnePointSaleById($posts['Order']['id_point_sale']);
$pointSaleDistribution = $pointSaleDistributionManager->findOnePointSaleDistribution($distribution, $pointSale);


if (!$pointSaleDistribution || !$pointSaleDistribution->delivery) { if (!$pointSaleDistribution || !$pointSaleDistribution->delivery) {
$errorPointSale = true; $errorPointSale = true;
} }


$pointSale = PointSale::findOne($posts['Order']['id_point_sale']);

if ($pointSale) { if ($pointSale) {
if (strlen($pointSale->code) && !$pointSale->validateCode($posts['code_point_sale'])) {
if (strlen($pointSale->code) && !$pointSaleManager->validateCode($pointSale, $posts['code_point_sale'])) {
$errorPointSale = true; $errorPointSale = true;
} }
} else { } else {
$errorPointSale = true; $errorPointSale = true;
} }


$userPointSale = UserPointSale::searchOne([
'id_user' => GlobalParam::getCurrentUserId(),
'id_point_sale' => $pointSale->id
]);

$userPointSale = $userPointSaleManager->findOneUserPointSale(GlobalParam::getCurrentUser(), $pointSale);
if ($pointSale->restricted_access && !$userPointSale) { if ($pointSale->restricted_access && !$userPointSale) {
$errorPointSale = true; $errorPointSale = true;
} }
$errors = []; $errors = [];


if ($order->validate() && count($productsArray) && !$errorDate && !$errorPointSale) { if ($order->validate() && count($productsArray) && !$errorDate && !$errorPointSale) {
$userProducer = UserProducer::searchOne([
'id_producer' => $order->distribution->id_producer,
'id_user' => $user->id
]);

// gestion point de vente
$pointSale = PointSale::searchOne([
'id' => $order->id_point_sale
]);
$userProducer = $userProducerManager->findOneUserProducer($user, $producer);
$pointSale = $pointSaleManager->findOnePointSaleById($order->id_point_sale);


// commentaire point de vente // commentaire point de vente
$order->comment_point_sale = ($pointSale && strlen($pointSale->getComment())) ? $order->comment_point_sale = ($pointSale && strlen($pointSale->getComment())) ?
// sauvegarde de la commande // sauvegarde de la commande
$order->save(); $order->save();


$order->initReference();

$order->changeOrderStatus('new-order', 'user');

// ajout de l'utilisateur à l'établissement
Producer::addUser($user->id, $distribution->id_producer);
$orderManager->generateOrderReference($order);
$orderManager->changeOrderStatus($order, 'new-order', 'user');
$producerManager->addUser($user, $producer);


// suppression de tous les enregistrements ProductOrder // suppression de tous les enregistrements ProductOrder
if (!is_null($order)) { if (!is_null($order)) {
ProductOrder::deleteAll(['id_order' => $order->id]);
$productOrderManager->deleteProductOrdersByOrder($order);


$stepsArray = [];
if (isset($order->productOrder)) { if (isset($order->productOrder)) {
foreach ($order->productOrder as $productOrder) { foreach ($order->productOrder as $productOrder) {
$unitsArray[$productOrder->id_product] = $productOrder->unit; $unitsArray[$productOrder->id_product] = $productOrder->unit;
} }
} }


// produits dispos
$availableProducts = ProductDistributionModel::searchByDistribution($distribution->id);

// sauvegarde des produits
$availableProducts = $productManager->findProductsByDistribution($distribution);
foreach ($productsArray as $product) { foreach ($productsArray as $product) {
if (isset($availableProducts[$product->id])) { if (isset($availableProducts[$product->id])) {
$productOrder = new ProductOrder(); $productOrder = new ProductOrder();
} }
$productOrder->quantity = $quantity; $productOrder->quantity = $quantity;
$productOrder->price = $product->getPrice([ $productOrder->price = $product->getPrice([
'user' => User::getCurrent(),
'user' => GlobalParam::getCurrentUser(),
'user_producer' => $userProducer, 'user_producer' => $userProducer,
'point_sale' => $pointSale, 'point_sale' => $pointSale,
'quantity' => $quantity 'quantity' => $quantity
} }


// lien utilisateur / point de vente // lien utilisateur / point de vente
$pointSale->linkUser($user->id);
$pointSaleManager->addUser($user, $pointSale);


// credit // credit
$credit = Producer::getConfig('credit');
$creditLimit = Producer::getConfig('credit_limit');
$creditFunctioning = $pointSale->getCreditFunctioning();
$creditUser = $user->getCredit($distribution->id_producer);
$order = Order::searchOne([
'id' => $order->id
]);
$amountPaid = $order->getAmount(Order::AMOUNT_PAID);
$amountRemaining = $order->getAmount(Order::AMOUNT_REMAINING);
$credit = $producerManager->getConfig('credit');
$creditLimit = $producerManager->getConfig('credit_limit');
$creditFunctioning = $pointSaleManager->getPointSaleCreditFunctioning($pointSale);
$creditUser = $userManager->getCredit($user, $producer);
$order = $orderManager->findOneOrderById($order->id);
$amountRemaining = $orderManager->getAmount($order, Order::AMOUNT_REMAINING);


if ($credit && $pointSale->credit && if ($credit && $pointSale->credit &&
(($creditFunctioning == Producer::CREDIT_FUNCTIONING_OPTIONAL && $posts['use_credit']) || (($creditFunctioning == Producer::CREDIT_FUNCTIONING_OPTIONAL && $posts['use_credit']) ||
$creditFunctioning == Producer::CREDIT_FUNCTIONING_MANDATORY || $creditFunctioning == Producer::CREDIT_FUNCTIONING_MANDATORY ||
($creditFunctioning == Producer::CREDIT_FUNCTIONING_USER && $userProducer->credit_active) ($creditFunctioning == Producer::CREDIT_FUNCTIONING_USER && $userProducer->credit_active)
)) { )) {
$order->changeOrderStatus('waiting-paiement-by-credit', 'user');
$orderManager->changeOrderStatus($order, 'waiting-paiement-by-credit', 'user');


// à payer // à payer
if ($order->getPaymentStatus() == Order::PAYMENT_UNPAID) {
if ($orderManager->getPaymentStatus($order) == Order::PAYMENT_UNPAID) {
if (!is_null($creditLimit) && $amountRemaining > $creditUser - $creditLimit) { if (!is_null($creditLimit) && $amountRemaining > $creditUser - $creditLimit) {
$amountRemaining = $creditUser - $creditLimit; $amountRemaining = $creditUser - $creditLimit;
} }


if ($amountRemaining > 0) { if ($amountRemaining > 0) {
$order->saveCreditHistory(
$creditHistoryManager->createCreditHistory(
CreditHistory::TYPE_PAYMENT, CreditHistory::TYPE_PAYMENT,
$amountRemaining, $amountRemaining,
$distribution->id_producer,
GlobalParam::getCurrentUserId(),
GlobalParam::getCurrentUserId()
$producer,
GlobalParam::getCurrentUser(),
GlobalParam::getCurrentUser()
); );
$order->changeOrderStatus('paid-by-credit', 'user');
$orderManager->changeOrderStatus($order, 'paid-by-credit', 'user');
} else { } else {
$order->changeOrderStatus('waiting-paiement-on-delivery', 'user');
$orderManager->changeOrderStatus($order, 'waiting-paiement-on-delivery', 'user');
} }
} // surplus à rembourser } // surplus à rembourser
elseif ($order->getPaymentStatus() == Order::PAYMENT_SURPLUS) { elseif ($order->getPaymentStatus() == Order::PAYMENT_SURPLUS) {
$amountSurplus = $order->getAmount(Order::AMOUNT_SURPLUS);
$order->saveCreditHistory(
$amountSurplus = $orderManager->getAmount($order, Order::AMOUNT_SURPLUS);
$creditHistoryManager->createCreditHistory(
CreditHistory::TYPE_REFUND, CreditHistory::TYPE_REFUND,
$amountSurplus, $amountSurplus,
$distribution->id_producer,
GlobalParam::getCurrentUserId(),
GlobalParam::getCurrentUserId()
$producer,
GlobalParam::getCurrentUser(),
GlobalParam::getCurrentUser()
); );
} }
} else { } else {
$order->changeOrderStatus('waiting-paiement-on-delivery', 'user');
$orderManager->changeOrderStatus($order, 'waiting-paiement-on-delivery', 'user');
} }


$paramsEmail = [ $paramsEmail = [
'from_email' => $producer->getEmailOpendistrib(),
'from_email' => $producerManager->getEmailOpendistrib($producer),
'from_name' => $producer->name, 'from_name' => $producer->name,
'to_email' => $user->email, 'to_email' => $user->email,
'to_name' => $user->getUsername(),
'to_name' => $userManager->getUsername($user),
'subject' => '[' . $producer->name . '] Confirmation de commande', 'subject' => '[' . $producer->name . '] Confirmation de commande',
'content_view_text' => '@common/mail/orderConfirm-text.php', 'content_view_text' => '@common/mail/orderConfirm-text.php',
'content_view_html' => '@common/mail/orderConfirm-html.php', 'content_view_html' => '@common/mail/orderConfirm-html.php',
*/ */
if ($isNewOrder) { if ($isNewOrder) {
// au client // au client
if (Producer::getConfig('option_email_confirm')) {
if ($producerManager->getConfig('option_email_confirm')) {
Mailjet::sendMail($paramsEmail); Mailjet::sendMail($paramsEmail);
} }


// au producteur // au producteur
$contactProducer = $producer->getMainContact();
if (Producer::getConfig('option_email_confirm_producer') && $contactProducer && strlen(
$contactProducer = $producerManager->getMainContact($producer);
if ($producerManager->getConfig('option_email_confirm_producer') && $contactProducer && strlen(
$contactProducer->email $contactProducer->email
)) { )) {
$paramsEmail['to_email'] = $contactProducer->email; $paramsEmail['to_email'] = $contactProducer->email;
} }
} }


$order->setTillerSynchronization();
$orderManager->setTillerSynchronization($order);
} }




*/ */
public function actionCancel(int $id) public function actionCancel(int $id)
{ {
$order = $this->getOrderManager()->findOneById($id);
$orderManager = $this->getOrderManager();
$order = $this->getOrderManager()->findOneOrderById($id);


if (!$order) { if (!$order) {
throw new \yii\web\NotFoundHttpException('Commande introuvable'); throw new \yii\web\NotFoundHttpException('Commande introuvable');
} }


if ($this->getOrderManager()->isOrderStateOpen($order)) {
if ($orderManager->isOrderStateOpen($order)) {
throw new UserException('Vous ne pouvez plus annuler cette commande.'); throw new UserException('Vous ne pouvez plus annuler cette commande.');
} }


if ($this->getOrderManager()->isOrderbelongsToUser($order, GlobalParam::getCurrentUser())) {
$orderContainer->getBuilder()->delete($order);
\Yii::$app->session->setFlash('success', 'Votre commande a bien été annulée.');
if ($orderManager->isOrderbelongsToUser($order, GlobalParam::getCurrentUser())) {
$orderManager->deleteOrder($order);
$this->setFlash('success', 'Votre commande a bien été annulée.');
} }


$this->redirect(\Yii::$app->urlManager->createUrl(['order/history']));
return $this->redirect($this->getUrlManagerProducer()->createUrl(['order/history']));
} }


/** /**
*/ */
public function actionConfirm(int $idOrder, string $returnPayment = '') public function actionConfirm(int $idOrder, string $returnPayment = '')
{ {
$order = $this->getOrderManager()->findOneById($idOrder);
$orderManager = $this->getOrderManager();
$order = $orderManager->findOneOrderById($idOrder);
$producer = $this->getProducer(); $producer = $this->getProducer();


if (!$order || (!$this->getOrderManager()->isOrderBelongsToUser($order, GlobalParam::getCurrentUser()) && !$producer->option_allow_order_guest)) {
if (!$order || (!$orderManager->isOrderBelongsToUser($order, GlobalParam::getCurrentUser()) && !$producer->option_allow_order_guest)) {
throw new \yii\base\UserException('Commande introuvable.'); throw new \yii\base\UserException('Commande introuvable.');
} }


public function actionAjaxValidateCodePointSale(int $idPointSale, string $code) public function actionAjaxValidateCodePointSale(int $idPointSale, string $code)
{ {
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
$pointSaleContainer = $this->getPointSaleContainer();
$pointSale = $pointSaleContainer->getRepository()->getOneById($idPointSale);
$pointSaleManager = $this->getPointSaleManager();
$pointSale = $pointSaleManager->findOnePointSaleById($idPointSale);


if ($pointSale && $pointSaleContainer->getSolver()->validateCode($pointSale, $code)) {
if ($pointSale && $pointSaleManager->validateCode($pointSale, $code)) {
return 1; return 1;
} }


\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
$user = GlobalParam::getCurrentUser(); $user = GlobalParam::getCurrentUser();
$producer = $this->getProducer(); $producer = $this->getProducer();
$pointSale = $this->getPointSaleContainer()->getRepository()->getOneById($pointSaleId);
$pointSale = $this->getPointSaleManager()->findOnePointSaleById($pointSaleId);
$order = $this->getOrderUser($date, $pointSale); $order = $this->getOrderUser($date, $pointSale);


return $this->buildJsonAjaxInfos($date, $producer, $pointSale, $user, $order); return $this->buildJsonAjaxInfos($date, $producer, $pointSale, $user, $order);


public function ajaxInfosDistributions(Producer $producer, PointSale $pointSaleCurrent = null) public function ajaxInfosDistributions(Producer $producer, PointSale $pointSaleCurrent = null)
{ {
$distributionManager = $this->getDistributionManager();
$dateMini = date('Y-m-d'); $dateMini = date('Y-m-d');


$distributionsArray = DistributionModel::searchAll([
$distributionsArray = Distribution::searchAll([
'active' => 1, 'active' => 1,
'id_producer' => $producer->id 'id_producer' => $producer->id
], [ ], [
'params' => [':date' => $dateMini], 'params' => [':date' => $dateMini],
'join_with' => ['pointSaleDistribution'], 'join_with' => ['pointSaleDistribution'],
]); ]);
$distributionsArray = DistributionModel::filterDistributionsByDateDelay($distributionsArray);
$distributionsArray = $distributionManager->filterDistributionsByDateDelay($distributionsArray);


// Filtre par point de vente // Filtre par point de vente
if ($pointSaleId && $producer->option_order_entry_point == Producer::ORDER_ENTRY_POINT_POINT_SALE) {
if ($pointSaleCurrent && $producer->option_order_entry_point == Producer::ORDER_ENTRY_POINT_POINT_SALE) {
$distributionsArrayFilterPointSale = []; $distributionsArrayFilterPointSale = [];
for ($i = 0; $i < count($distributionsArray); $i++) { for ($i = 0; $i < count($distributionsArray); $i++) {
$distribution = $distributionsArray[$i]; $distribution = $distributionsArray[$i];
if (Distribution::isPointSaleActive($distribution, $pointSaleId)) {
$countOrders = (int)Order::searchCount([
if ($distributionManager->isPointSaleActive($distribution, $pointSaleCurrent)) {
$countOrders = Order::searchCount([
'id_distribution' => $distribution->id, 'id_distribution' => $distribution->id,
'id_point_sale' => $pointSaleId
'id_point_sale' => $pointSaleCurrent->id
]); ]);
$orderUserPointSale = $this->_getOrderUser($distribution->date, $pointSaleId); $orderUserPointSale = $this->_getOrderUser($distribution->date, $pointSaleId);


} }
} }


public function ajaxInfosOrders(Producer $producer): array
public function ajaxInfosOrders(Producer $producer, PointSale $pointSaleCurrent = null): array
{ {
$producerManager = $this->getProducerManager();
$orderManager = $this->getOrderManager();

$dateMini = date('Y-m-d');
$ordersUserArray = []; $ordersUserArray = [];
if (GlobalParam::getCurrentUserId() && !$producer->isOnlinePaymentActiveAndTypeOrder()) {
if (GlobalParam::getCurrentUserId() && !$producerManager->isOnlinePaymentActiveAndTypeOrder($producer)) {
$conditionsOrdersUser = [ $conditionsOrdersUser = [
'distribution.date > :date' 'distribution.date > :date'
]; ];
':date' => $dateMini ':date' => $dateMini
]; ];


if ($pointSaleId && $producer->option_order_entry_point == Producer::ORDER_ENTRY_POINT_POINT_SALE) {
if ($pointSaleCurrent && $producer->option_order_entry_point == Producer::ORDER_ENTRY_POINT_POINT_SALE) {
$conditionsOrdersUser[] = 'order.id_point_sale = :id_point_sale'; $conditionsOrdersUser[] = 'order.id_point_sale = :id_point_sale';
$paramsOrdersUser[':id_point_sale'] = $pointSaleId;
$paramsOrdersUser[':id_point_sale'] = $pointSaleCurrent->id;
} }


$ordersUserArray = Order::searchAll([ $ordersUserArray = Order::searchAll([
if (is_array($ordersUserArray) && count($ordersUserArray)) { if (is_array($ordersUserArray) && count($ordersUserArray)) {
foreach ($ordersUserArray as &$order) { foreach ($ordersUserArray as &$order) {
$order = array_merge($order->getAttributes(), [ $order = array_merge($order->getAttributes(), [
'amount_total' => $order->getAmountWithTax(Order::AMOUNT_TOTAL),
'amount_total' => $orderManager->getAmountWithTax($order, Order::AMOUNT_TOTAL),
'date_distribution' => $order->distribution->date, 'date_distribution' => $order->distribution->date,
'pointSale' => $order->pointSale->getAttributes() 'pointSale' => $order->pointSale->getAttributes()
]); ]);


public function ajaxInfosUser(Producer $producer) public function ajaxInfosUser(Producer $producer)
{ {
$userProducer = UserProducer::searchOne([
'id_producer' => $producer->id,
'id_user' => GlobalParam::getCurrentUserId()
]);
$userProducerManager = $this->getUserProducerManager();
$producerManager = $this->getProducerManager();

$user = GlobalParam::getCurrentUser();
$userProducer = $userProducerManager->findOneUserProducer($user, $producer);


if ($user && !$userProducer) { if ($user && !$userProducer) {
$userProducer = Producer::addUser($user->id, $producer->id);
$userProducer = $producerManager->addUser($user, $producer);
} }


$jsonUser = false; $jsonUser = false;


private function ajaxInfosPointsSale($idProducer, $distribution = false) private function ajaxInfosPointsSale($idProducer, $distribution = false)
{ {
$userManager = $this->getUserManager();
$producerManager = $this->getProducerManager();

$user = GlobalParam::getCurrentUser();
$pointsSaleArray = PointSale::find(); $pointsSaleArray = PointSale::find();


if ($distribution) { if ($distribution) {
->orderBy('code ASC, restricted_access ASC, is_bread_box ASC, `default` DESC, name ASC') ->orderBy('code ASC, restricted_access ASC, is_bread_box ASC, `default` DESC, name ASC')
->all(); ->all();


$creditFunctioningProducer = Producer::getConfig('credit_functioning');
$creditFunctioningProducer = $producerManager->getConfig('credit_functioning');
$position = 0; $position = 0;


foreach ($pointsSaleArray as &$pointSale) { foreach ($pointsSaleArray as &$pointSale) {
} }


$favoritePointSale = false; $favoritePointSale = false;
if (User::getCurrent()) {
$favoritePointSale = User::getCurrent()->getFavoritePointSale();
if ($user) {
$favoritePointSale = $userManager->getUserFavoritePointSale($user);
} }


if ($favoritePointSale) { if ($favoritePointSale) {


public function ajaxInfosProductCategories(Producer $producer) public function ajaxInfosProductCategories(Producer $producer)
{ {
$categoriesArray = $this->getProductCategoryContainer()->getRepository()
->getAsArray();
$countProductsWithoutCategory = $this->getProductContainer()->getRepository()
->countProductsWithoutCategory($producer);
$categoriesArray = $this->getProductCategoryManager()->findProductCategoriesAsArray();
$countProductsWithoutCategory = $this->getProductManager()->countProductsWithoutCategory($producer);


if ($countProductsWithoutCategory) { if ($countProductsWithoutCategory) {
array_unshift($categoriesArray, ['id' => null, 'name' => 'Catégorie par défaut']); array_unshift($categoriesArray, ['id' => null, 'name' => 'Catégorie par défaut']);
Order $order = null Order $order = null
) )
{ {
$ordersArray = $this->getOrderManager()->findByDistribution($distribution);
$productManager = $this->getProductManager();
$orderManager = $this->getOrderManager();
$ordersArray = $this->getOrderManager()->findOrdersByDistribution($distribution);


$productsArray = Product::find() $productsArray = Product::find()
->where([ ->where([


// filtre sur les points de vente // filtre sur les points de vente
foreach ($productsArray as $product) { foreach ($productsArray as $product) {
if ($product->isAvailableOnPointSale($pointSale)) {
if ($productManager->isAvailableOnPointSale($product, $pointSale)) {
$productsArrayFilter[] = $product; $productsArrayFilter[] = $product;
} }
} }


$indexProduct = 0; $indexProduct = 0;
foreach ($productsArrayFilter as $key => &$product) { foreach ($productsArrayFilter as $key => &$product) {
$productObject = $product;
$product = array_merge( $product = array_merge(
$product->getAttributes(), $product->getAttributes(),
[ [
'unit_coefficient' => Product::$unitsArray[$product->unit]['coefficient'], 'unit_coefficient' => Product::$unitsArray[$product->unit]['coefficient'],
'prices' => $product->getPriceArray($user, $pointSale),
'prices' => $productManager->getPriceArray($product, $user, $pointSale),
'productDistribution' => $product['productDistribution'], 'productDistribution' => $product['productDistribution'],
'productPointSale' => $product['productPointSale'], 'productPointSale' => $product['productPointSale'],
] ]
} }


$product['quantity_max'] = $product['productDistribution'][0]['quantity_max']; $product['quantity_max'] = $product['productDistribution'][0]['quantity_max'];
$quantityOrder = Order::getProductQuantity($product['id'], $ordersArray);
$quantityOrder = $orderManager->getProductQuantity($productObject, $ordersArray);
$product['quantity_ordered'] = $quantityOrder; $product['quantity_ordered'] = $quantityOrder;
$product['quantity_remaining'] = $product['quantity_max'] - $quantityOrder; $product['quantity_remaining'] = $product['quantity_max'] - $quantityOrder;
$product['wording_unit'] = Product::strUnit($product['unit'], 'wording_unit', true);
$product['wording_unit_ref'] = Product::strUnit($product['unit'], 'wording_short', true);
$product['wording_unit'] = $productManager->strUnit($product['unit'], 'wording_unit', true);
$product['wording_unit_ref'] = $productManager->strUnit($product['unit'], 'wording_short', true);


if ($order) { if ($order) {
$quantityOrderUser = Order::getProductQuantity($product['id'], [$order], true);
$quantityOrderUser = $orderManager->getProductQuantity($productObject, [$order], true);
$product['quantity_ordered'] = $quantityOrder; $product['quantity_ordered'] = $quantityOrder;
$product['quantity_remaining'] = $product['quantity_max'] - $quantityOrder + $quantityOrderUser; $product['quantity_remaining'] = $product['quantity_max'] - $quantityOrder + $quantityOrderUser;
$product['quantity_form'] = $quantityOrderUser * $coefficient_unit; $product['quantity_form'] = $quantityOrderUser * $coefficient_unit;
foreach ($order->productOrder as $productOrder) { foreach ($order->productOrder as $productOrder) {
if ($productOrder->id_product == $product['id']) { if ($productOrder->id_product == $product['id']) {
$product['wording_unit'] = Product::strUnit($productOrder->unit, 'wording_unit', true);
$product['wording_unit'] = $productManager->strUnit($productOrder->unit, 'wording_unit', true);
$product['step'] = $productOrder->step; $product['step'] = $productOrder->step;
} }
} }
} else { } else {
$product['quantity_form'] = 0; $product['quantity_form'] = 0;
$product['wording_unit'] = Product::strUnit($product['unit'], 'wording_unit', true);
$product['wording_unit'] = $productManager->strUnit($product['unit'], 'wording_unit', true);
} }
$product['coefficient_unit'] = $coefficient_unit; $product['coefficient_unit'] = $coefficient_unit;




private function getOrderUser(string $date, PointSale $pointSale = null) private function getOrderUser(string $date, PointSale $pointSale = null)
{ {
$orderManager = $this->getOrderManager();

$orderUser = false; $orderUser = false;
if (GlobalParam::getCurrentUserId()) { if (GlobalParam::getCurrentUserId()) {
$conditionOrderUser = [ $conditionOrderUser = [
'id_user' => GlobalParam::getCurrentUserId(), 'id_user' => GlobalParam::getCurrentUserId(),
]; ];


if ($pointSaleId) {
$conditionOrderUser['id_point_sale'] = $pointSaleId;
if ($pointSale) {
$conditionOrderUser['id_point_sale'] = $pointSale;
} }


$orderUser = Order::searchOne($conditionOrderUser); $orderUser = Order::searchOne($conditionOrderUser);


if ($orderUser) { if ($orderUser) {
$json['order'] = array_merge($orderUser->getAttributes(), [ $json['order'] = array_merge($orderUser->getAttributes(), [
'amount_total' => $orderUser->getAmountWithTax(Order::AMOUNT_TOTAL),
'amount_paid' => $orderUser->getAmount(Order::AMOUNT_PAID),
'amount_total' => $orderManager->getAmountWithTax($orderUser, Order::AMOUNT_TOTAL),
'amount_paid' => $orderManager->getAmount($orderUser, Order::AMOUNT_PAID),
]); ]);
} }



+ 6
- 6
producer/controllers/SiteController.php View File

public function actionIndex() public function actionIndex()
{ {
$dataProviderPointsSale = new ActiveDataProvider([ $dataProviderPointsSale = new ActiveDataProvider([
'query' => $this->getPointSaleContainer()->getRepostory()->queryPublic($this->getProducer()),
'query' => $this->getPointSaleManager()->queryPointSalesPublic($this->getProducer()),
'pagination' => [ 'pagination' => [
'pageSize' => 50, 'pageSize' => 50,
], ],
'sort' => false, 'sort' => false,
]); ]);


$productCategoryArray = $this->getProductCategoryContainer()->getRepository()->get();
$productCategoryArray = $this->getProductCategoryManager()->findProductCategories();
$dataProviderProductsByCategories = []; $dataProviderProductsByCategories = [];
foreach ($productCategoryArray as $productCategory) { foreach ($productCategoryArray as $productCategory) {
$dataProviderProductsByCategories[$productCategory->id] = new ActiveDataProvider([ $dataProviderProductsByCategories[$productCategory->id] = new ActiveDataProvider([
'query' => $this->getProductContainer()->getRepository()->queryByProductCategory($productCategory),
'query' => $this->getProductManager()->queryProductsByProductCategory($productCategory),
'pagination' => [ 'pagination' => [
'pageSize' => 500, 'pageSize' => 500,
], ],
if ($model->load(\Yii::$app->request->post()) && $model->validate()) { if ($model->load(\Yii::$app->request->post()) && $model->validate()) {
$isSent = false; $isSent = false;
if (is_array($producer->contact)) { if (is_array($producer->contact)) {
$email = $this->getLogic()->getProducerContainer()->getSolver()->getMainContactEmail($producer);
$email = $this->getProducerManager()->getMainContactEmail($producer);
if (strlen($email) && $model->sendEmail($email)) { if (strlen($email) && $model->sendEmail($email)) {
$isSent = true; $isSent = true;
} }
public function actionBookmarks(string $action) public function actionBookmarks(string $action)
{ {
$producer = $this->getProducer(); $producer = $this->getProducer();
$userProducer = $this->getLogic()->getUserProducerContainer()
->getBuilder()->createIfNotExist(GlobalParam::getCurrentUser(), $producer);
$userProducer = $this->getUserProducerManager()
->createUserProducerIfNotExist(GlobalParam::getCurrentUser(), $producer);


if ($action == 'add') { if ($action == 'add') {
$userProducer->bookmark = 1; $userProducer->bookmark = 1;

+ 4
- 1
producer/views/credit/add.php View File

use yii\widgets\ActiveForm; use yii\widgets\ActiveForm;
use common\logic\Producer\Producer\Producer; use common\logic\Producer\Producer\Producer;


$producerManager = $this->getProducerManager();
$producer = $this->context->getProducer();

$this->setTitle('Créditer mon compte'); $this->setTitle('Créditer mon compte');
$this->setPageTitle('Crédit mon compte'); $this->setPageTitle('Crédit mon compte');


'template' => '{label}<div class="input-group input-group-lg">{input}<span class="input-group-addon"><span class="glyphicon glyphicon-euro"></span></span></div>{hint}', 'template' => '{label}<div class="input-group input-group-lg">{input}<span class="input-group-addon"><span class="glyphicon glyphicon-euro"></span></span></div>{hint}',
]) ])
->label('Quel montant souhaitez-vous créditer ?') ->label('Quel montant souhaitez-vous créditer ?')
->hint('Montant minimum : '.Producer::getOnlinePaymentMinimumAmount().' €'); ?>
->hint('Montant minimum : '.$producerManager->getOnlinePaymentMinimumAmount($producer).' €'); ?>


<div class="form-group"> <div class="form-group">
<?= Html::submitButton('<span class="glyphicon glyphicon-lock"></span> Payer', ['class' => 'btn btn-primary'] <?= Html::submitButton('<span class="glyphicon glyphicon-lock"></span> Payer', ['class' => 'btn btn-primary']

+ 15
- 15
producer/views/credit/history.php View File



use yii\grid\GridView; use yii\grid\GridView;


$creditHistorySolver = \Yii::$app->logic->getCreditHistoryContainer()->getSolver();
$creditHistoryManager = $this->getCreditHistoryManager();
$producer = $this->context->getProducer(); $producer = $this->context->getProducer();
$this->setTitle('Crédit : <span id="credit-user">' . number_format($creditUser, 2) . ' €</span>'); $this->setTitle('Crédit : <span id="credit-user">' . number_format($creditUser, 2) . ' €</span>');
$this->setPageTitle('Crédit'); $this->setPageTitle('Crédit');
'columns' => [ 'columns' => [
[ [
'attribute' => 'date', 'attribute' => 'date',
'value' => function ($model) use ($creditHistorySolver) {
return $creditHistorySolver->getDate($model, true);
'value' => function ($model) use ($creditHistoryManager) {
return $creditHistoryManager->getDate($model, true);
} }
], ],
[ [
'attribute' => 'id_user_action', 'attribute' => 'id_user_action',
'value' => function ($model) use ($creditHistorySolver) {
return $creditHistorySolver->getStrUserAction($model);
'value' => function ($model) use ($creditHistoryManager) {
return $creditHistoryManager->getStrUserAction($model);
} }
], ],
[ [
'label' => 'Type', 'label' => 'Type',
'format' => 'raw', 'format' => 'raw',
'value' => function ($model) use ($creditHistorySolver) {
return $creditHistorySolver->getStrWording($model);
'value' => function ($model) use ($creditHistoryManager) {
return $creditHistoryManager->getStrWording($model);
} }
], ],
[ [
'attribute' => 'mean_payment', 'attribute' => 'mean_payment',
'value' => function ($model) use ($creditHistorySolver) {
return $creditHistorySolver->getStrMeanPayment($model);
'value' => function ($model) use ($creditHistoryManager) {
return $creditHistoryManager->getStrMeanPayment($model);
} }
], ],
[ [
'label' => '- Débit', 'label' => '- Débit',
'format' => 'raw', 'format' => 'raw',
'value' => function ($model) use ($creditHistorySolver) {
if ($creditHistorySolver->isTypeDebit($model)) {
return '-&nbsp;' . $creditHistorySolver->getAmount($model, true);
'value' => function ($model) use ($creditHistoryManager) {
if ($creditHistoryManager->isTypeDebit($model)) {
return '-&nbsp;' . $creditHistoryManager->getAmount($model, true);
} }
return ''; return '';
} }
[ [
'label' => '+ Crédit', 'label' => '+ Crédit',
'format' => 'raw', 'format' => 'raw',
'value' => function ($model) use ($creditHistorySolver) {
if ($creditHistorySolver->isTypeCredit($model)) {
return '+&nbsp;' . $creditHistorySolver->getAmount($model, true);
'value' => function ($model) use ($creditHistoryManager) {
if ($creditHistoryManager->isTypeCredit($model)) {
return '+&nbsp;' . $creditHistoryManager->getAmount($model, true);
} }
return ''; return '';
} }

+ 3
- 3
producer/views/layouts/main.php View File

$credit = ' <span class="label label-' . $labelType . '">' . number_format($userProducer->credit, 2) . ' €</span>'; $credit = ' <span class="label label-' . $labelType . '">' . number_format($userProducer->credit, 2) . ' €</span>';
} }


$countSubcriptions = $this->getLogic()->getSubscriptionContainer()->getRepository()->count(
$countSubcriptions = $this->getSubscriptionManager()->countSubscriptionsByUser(
GlobalParam::getCurrentUser(), GlobalParam::getCurrentUser(),
GlobalParam::getCurrentProducer() GlobalParam::getCurrentProducer()
); );
[ [
'label' => '<span class="glyphicon glyphicon-cog"></span> Administration', 'label' => '<span class="glyphicon glyphicon-cog"></span> Administration',
'url' => $this->getUrlManagerBackend()->createAbsoluteUrl(['site/index']), 'url' => $this->getUrlManagerBackend()->createAbsoluteUrl(['site/index']),
'visible' => isset(Yii::$app->user->identity) && $this->getLogic()->getUserContainer()->getSolver()->isProducer(\Yii::$app->user->identity),
'visible' => isset(Yii::$app->user->identity) && $this->getUserManager()->isProducer(\Yii::$app->user->identity),
'options' => ['id' => 'btn-administration'] 'options' => ['id' => 'btn-administration']
], ],
], ],
</div> </div>
<?php endif; ?> <?php endif; ?>
<div id="infos-producer"> <div id="infos-producer">
<?php if(!$this->getLogic()->getProducerContainer()->getSolver()->hasSpecificDelays($producer) && $producer->order_deadline && $producer->order_delay): ?>
<?php if(!$this->getProducerManager()->hasSpecificDelays($producer) && $producer->order_deadline && $producer->order_delay): ?>
<span data-toggle="tooltip" data-placement="bottom" title="Heure limite de commande"> <span data-toggle="tooltip" data-placement="bottom" title="Heure limite de commande">
<span class="glyphicon glyphicon-time"></span> Commande avant <span class="glyphicon glyphicon-time"></span> Commande avant
<strong><?php echo Html::encode($producer->order_deadline) ?> h</strong></span>, <strong><?php echo Html::encode($producer->order_deadline) ?> h</strong></span>,

+ 2
- 1
producer/views/order/confirm.php View File



$this->setTitle('Confirmation de commande') ; $this->setTitle('Confirmation de commande') ;
$producer = GlobalParam::getCurrentProducer() ; $producer = GlobalParam::getCurrentProducer() ;
$producerManager = $this->getProducerManager();


?> ?>


<div id="order-success"> <div id="order-success">




<?php if($producer->isOnlinePaymentActiveAndTypeOrder() && $returnPayment != 'success'): ?>
<?php if($producerManager->isOnlinePaymentActiveAndTypeOrder($producer) && $returnPayment != 'success'): ?>
<div class="alert alert-danger"> <div class="alert alert-danger">
<h5>Le paiement en ligne a échoué.</h5> <h5>Le paiement en ligne a échoué.</h5>
<strong>Attention</strong>, votre commande ne sera effective qu'à la réception du paiement.<br /> <strong>Attention</strong>, votre commande ne sera effective qu'à la réception du paiement.<br />

+ 3
- 3
producer/views/order/order.php View File

\producer\assets\VuejsOrderOrderAsset::register($this); \producer\assets\VuejsOrderOrderAsset::register($this);


$this->setTitle('Commander') ; $this->setTitle('Commander') ;

$producer = $this->context->getProducer(); $producer = $this->context->getProducer();
$producerManager = $this->getProducerManager();


?> ?>


</div> </div>
<div v-else> <div v-else>
<span class="glyphicon glyphicon-chevron-right"></span> <span class="glyphicon glyphicon-chevron-right"></span>
<?php if($producer->isOnlinePaymentActiveAndTypeOrder()): ?>
<?php if($producerManager->isOnlinePaymentActiveAndTypeOrder($producer)): ?>
La commande est à payer en ligne lors de l'étape suivante. La commande est à payer en ligne lors de l'étape suivante.
<?php elseif($producer->option_payment_info && strlen($producer->option_payment_info) > 0): ?> <?php elseif($producer->option_payment_info && strlen($producer->option_payment_info) > 0): ?>
Confirmez votre commande et retrouvez les informations liées au paiement sur la page suivante. Confirmez votre commande et retrouvez les informations liées au paiement sur la page suivante.


<?php <?php
$producer = GlobalParam::getCurrentProducer() ; $producer = GlobalParam::getCurrentProducer() ;
if($producer->hasSpecificDelays()): ?>
if($producerManager->hasSpecificDelays($producer)): ?>
<div id="specific-delays" class="panel panel-default"> <div id="specific-delays" class="panel panel-default">
<div class="panel-heading"> <div class="panel-heading">
Délais de commande spécifiques Délais de commande spécifiques

+ 3
- 3
producer/views/site/index.php View File

use common\helpers\Price; use common\helpers\Price;


$producer = $this->context->getProducer() ; $producer = $this->context->getProducer() ;
$productSolver = $this->getLogic()->getProductContainer()->getSolver();
$productManager = $this->getProductManager();
$this->setTitle('Accueil'); $this->setTitle('Accueil');
$this->setPageTitle(Html::encode($producer->type.' à '.$producer->city)) ; $this->setPageTitle(Html::encode($producer->type.' à '.$producer->city)) ;




$columnsProducts[] = [ $columnsProducts[] = [
'attribute' => 'price', 'attribute' => 'price',
'value' => function($model) use ($productSolver) {
'value' => function($model) use ($productManager) {
if($model->price) { if($model->price) {
return Price::format($productSolver->getPriceWithTax($model)).' ('. $productSolver->strUnit($model->unit, 'wording_unit', true).')' ;
return Price::format($productManager->getPriceWithTax($model)).' ('. $productManager->strUnit($model->unit, 'wording_unit', true).')' ;
} }
return '' ; return '' ;
} }

+ 3
- 1
producer/views/subscription/_form.php View File



\producer\assets\VuejsSubscriptionFormAsset::register($this) ; \producer\assets\VuejsSubscriptionFormAsset::register($this) ;


$producerManager = $this->getProducerManager();

?> ?>


<div class="subscription-form" id="app-subscription-form" :class="{'loaded': !loading}"> <div class="subscription-form" id="app-subscription-form" :class="{'loaded': !loading}">
<h3><span>Paiement</span></h3> <h3><span>Paiement</span></h3>


<?php if(Producer::getConfig('credit')): ?>
<?php if($producerManager->getConfig('credit')): ?>
<div class="form-group field-subscriptionform-auto_payment"> <div class="form-group field-subscriptionform-auto_payment">
<label><input type="checkbox" id="subscriptionform-auto_payment" name="SubscriptionForm[auto_payment]" v-model="autoPayment"> Paiement automatique</label> <label><input type="checkbox" id="subscriptionform-auto_payment" name="SubscriptionForm[auto_payment]" v-model="autoPayment"> Paiement automatique</label>
<div class="hint-block">Cochez cette case si vous souhaitez que votre Crédit soit automatiquement débité.</div> <div class="hint-block">Cochez cette case si vous souhaitez que votre Crédit soit automatiquement débité.</div>

+ 5
- 1
producer/views/subscription/index.php View File

use yii\grid\GridView; use yii\grid\GridView;
use common\helpers\GlobalParam; use common\helpers\GlobalParam;
use common\logic\Producer\Producer\Producer; use common\logic\Producer\Producer\Producer;
use yii\helpers\ArrayHelper;
use common\logic\PointSale\PointSale\PointSale;

$producerManager = $this->getProducerManager();


$this->setTitle('Abonnements') ; $this->setTitle('Abonnements') ;
$this->addButton(['label' => '<span class="glyphicon glyphicon-plus"></span> Ajouter', 'url' => 'subscription/form', 'class' => 'btn btn-primary']) ; $this->addButton(['label' => '<span class="glyphicon glyphicon-plus"></span> Ajouter', 'url' => 'subscription/form', 'class' => 'btn btn-primary']) ;
], ],
] ; ] ;
if(Producer::getConfig('credit')) {
if($producerManager->getConfig('credit')) {
$columns[] = [ $columns[] = [
'format' => 'raw', 'format' => 'raw',
'label' => 'Paiement automatique', 'label' => 'Paiement automatique',

Loading…
Cancel
Save