Browse Source

Refactoring services #885

refactoring
Guillaume 1 year ago
parent
commit
b49ad98310
15 changed files with 618 additions and 674 deletions
  1. +0
    -3
      backend/controllers/AccessController.php
  2. +3
    -5
      common/logic/Producer/Producer/ProducerBuilder.php
  3. +11
    -0
      common/logic/Producer/Producer/ProducerSolver.php
  4. +5
    -0
      common/logic/Subscription/Subscription/SubscriptionRepository.php
  5. +5
    -3
      common/logic/User/User/User.php
  6. +21
    -3
      common/logic/User/UserProducer/UserProducerBuilder.php
  7. +2
    -2
      common/logic/User/UserProducer/UserProducerRepository.php
  8. +1
    -1
      common/logic/User/UserUserGroup/UserUserGroup.php
  9. +25
    -61
      frontend/controllers/SiteController.php
  10. +3
    -9
      frontend/views/site/signup.php
  11. +93
    -94
      producer/controllers/CreditController.php
  12. +265
    -265
      producer/controllers/OrderController.php
  13. +1
    -2
      producer/controllers/ProducerBaseController.php
  14. +93
    -126
      producer/controllers/SiteController.php
  15. +90
    -100
      producer/controllers/SubscriptionController.php

+ 0
- 3
backend/controllers/AccessController.php View File

]); ]);
} }


/**
*
*/
public function actionDelete($idUser) public function actionDelete($idUser)
{ {
$user = User::searchOne([ $user = User::searchOne([

+ 3
- 5
common/logic/Producer/Producer/ProducerBuilder.php View File

use common\helpers\Password; use common\helpers\Password;
use common\logic\BaseService; use common\logic\BaseService;
use common\logic\BuilderInterface; use common\logic\BuilderInterface;
use common\logic\User\User\User;
use common\logic\User\UserProducer\UserProducer; use common\logic\User\UserProducer\UserProducer;
use common\logic\User\UserProducer\UserProducerBuilder; use common\logic\User\UserProducer\UserProducerBuilder;
use common\logic\User\UserProducer\UserProducerRepository; use common\logic\User\UserProducer\UserProducerRepository;
/** /**
* Lie un utilisateur à un producteur. * Lie un utilisateur à un producteur.
*/ */
public function addUser(int $idUser, int $idProducer, int $bookmark = 1): UserProducer
public function addUser(User $user, Producer $producer, int $bookmark = 1): UserProducer
{ {
$userProducer = $this->userProducerRepository->getOne($idUser, $idProducer);
if (!$userProducer) {
$userProducer = $this->userProducerBuilder->create($idUser, $idProducer, $bookmark);
}
$userProducer = $this->userProducerBuilder->createIfNotExist($user, $producer, $bookmark);


if (!$userProducer->getActive()) { if (!$userProducer->getActive()) {
$userProducer->setActive(1); $userProducer->setActive(1);

+ 11
- 0
common/logic/Producer/Producer/ProducerSolver.php View File

return null; return null;
} }


public function getMainContactEmail(Producer $producer): ?string
{
$contact = $this->getMainContact($producer);

if ($contact) {
return $contact->email;
}

return null;
}

public function isUpToDateWithOpendistribVersion(Producer $producer): bool public function isUpToDateWithOpendistribVersion(Producer $producer): bool
{ {
return $producer->latest_version_opendistrib == GlobalParam::getOpendistribVersion(); return $producer->latest_version_opendistrib == GlobalParam::getOpendistribVersion();

+ 5
- 0
common/logic/Subscription/Subscription/SubscriptionRepository.php View File

]; ];
} }


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

public function get() public function get()
{ {
return Subscription::searchAll(); return Subscription::searchAll();

+ 5
- 3
common/logic/User/User/User.php View File



namespace common\logic\User\User; namespace common\logic\User\User;


use common\logic\Order\Order\Order;
use common\logic\User\UserUserGroup\UserUserGroup;
use common\logic\User\UserProducer\UserProducer; use common\logic\User\UserProducer\UserProducer;
use yii\base\NotSupportedException; use yii\base\NotSupportedException;
use yii\behaviors\TimestampBehavior; use yii\behaviors\TimestampBehavior;


public function getUserProducer() public function getUserProducer()
{ {
return $this->hasMany(UserProducer::className(), ['id_user' => 'id']);
return $this->hasMany(UserProducer::class, ['id_user' => 'id']);
} }


public function getUserUserGroup() public function getUserUserGroup()
{ {
return $this->hasMany(UserUserGroup::className(), ['id_user' => 'id']);
return $this->hasMany(UserUserGroup::class, ['id_user' => 'id']);
} }


public function getOrder() public function getOrder()
{ {
return $this->hasMany(Order::className(), ['id_user' => 'id']);
return $this->hasMany(Order::class, ['id_user' => 'id']);
} }


public function getName(): string public function getName(): string

+ 21
- 3
common/logic/User/UserProducer/UserProducerBuilder.php View File

use common\logic\Producer\Producer\Producer; use common\logic\Producer\Producer\Producer;
use common\logic\User\CreditHistory\CreditHistory; use common\logic\User\CreditHistory\CreditHistory;
use common\logic\User\CreditHistory\CreditHistorySolver; use common\logic\User\CreditHistory\CreditHistorySolver;
use common\logic\User\User\User;


class UserProducerBuilder extends BaseService implements BuilderInterface class UserProducerBuilder extends BaseService implements BuilderInterface
{ {
$this->userProducerRepository = $this->loadService(UserProducerRepository::class); $this->userProducerRepository = $this->loadService(UserProducerRepository::class);
} }


public function instanciate(int $idUser, int $idProducer, int $bookmark = 1)
public function instanciate(User $user, Producer $producer, int $bookmark = 1)
{ {
$userProducer = new UserProducer(); $userProducer = new UserProducer();


$userProducer->setIdUser($idUser);
$userProducer->setIdProducer($idProducer);
$userProducer->populateUser($user);
$userProducer->populateproducer($producer);
$userProducer->setCredit(0); $userProducer->setCredit(0);
$userProducer->setActive(1); $userProducer->setActive(1);
$userProducer->setBookmark($bookmark); $userProducer->setBookmark($bookmark);
return $userProducer; return $userProducer;
} }


public function create(User $user, Producer $producer, int $bookmark = 1): UserProducer
{
$userProducer = $this->instanciate($user, $producer, $bookmark);
$userProducer->save();
return $userProducer;
}

public function createIfNotExist(User $user, Producer $producer, int $bookmark = 1): UserProducer
{
$userProducer = $this->userProducerRepository->getOne($user, $producer);
if (!$userProducer) {
$userProducer = $this->create($user, $producer, $bookmark);
}

return $userProducer;
}

public function updateCredit(CreditHistory $creditHistory): void public function updateCredit(CreditHistory $creditHistory): void
{ {
$userProducer = $this->userProducerRepository->getOne($creditHistory->getIdUser(), $creditHistory->getIdProducer()); $userProducer = $this->userProducerRepository->getOne($creditHistory->getIdUser(), $creditHistory->getIdProducer());

+ 2
- 2
common/logic/User/UserProducer/UserProducerRepository.php View File

]); ]);
} }


public function getBy($idUser, $active = 1, $bookmark = 1)
public function getBy(User $user, $active = 1, $bookmark = 1)
{ {
return UserProducer::find() return UserProducer::find()
->with(['producer']) ->with(['producer'])
->where([ ->where([
'id_user' => $idUser,
'id_user' => $user->id,
'active' => $active, 'active' => $active,
'bookmark' => $bookmark 'bookmark' => $bookmark
]) ])

+ 1
- 1
common/logic/User/UserUserGroup/UserUserGroup.php View File

termes. termes.
*/ */


namespace common\logic\User\UserGroup;
namespace common\logic\User\UserUserGroup;


use common\logic\PointSale\PointSale\PointSale; use common\logic\PointSale\PointSale\PointSale;
use Yii; use Yii;

+ 25
- 61
frontend/controllers/SiteController.php View File



/** /**
* Affiche la page d'accueil. * Affiche la page d'accueil.
*
* @return mixed
*/ */
public function actionIndex() public function actionIndex()
{ {
$this->getLogic()->getProducerContainer()->getBuilder();

$producerRepository = $this->getLogic()->getProducerContainer()->getRepository();

return $this->render('index', [ return $this->render('index', [
'producerDemoAccount' => $producerRepository->getOneDemoAccount(),
'producerDemoAccount' => $this->getLogic()->getProducerContainer()
->getRepository()->getOneDemoAccount(),
'dataProviderPrices' => $this->getDataProviderPrices() 'dataProviderPrices' => $this->getDataProviderPrices()
]); ]);
} }


/** /**
* Page de présentation des tarifs
*
* @return mixed
* Page de présentation des tarifs.
*/ */
public function actionPrices() public function actionPrices()
{ {


public function getDataProviderPrices() public function getDataProviderPrices()
{ {
$producerPriceRangeRepository = $this->getLogic()->getProducerPriceRangeContainer()->getRepository();

return new ActiveDataProvider([ return new ActiveDataProvider([
'query' => $producerPriceRangeRepository->query(),
'query' => $this->getLogic()->getProducerPriceRangeContainer()
->getRepository()->query(),
'pagination' => [ 'pagination' => [
'pageSize' => 100, 'pageSize' => 100,
], ],


/** /**
* Liste les producteurs utilisant la plateforme. * Liste les producteurs utilisant la plateforme.
*
* @return mixed
*/ */
public function actionProducers() public function actionProducers()
{ {
$producerRepository = $this->getLogic()->getProducerContainer()->getRepository();

$dataProviderProducers = new ActiveDataProvider([ $dataProviderProducers = new ActiveDataProvider([
'query' => $producerRepository->queryActive(),
'query' => $this->getLogic()->getProducerContainer()
->getRepository()->queryActive(),
'pagination' => [ 'pagination' => [
'pageSize' => 100, 'pageSize' => 100,
], ],


/** /**
* Affiche la page de connexion et traite le formulaire de connexion. * Affiche la page de connexion et traite le formulaire de connexion.
*
* @return mixed
*/ */
public function actionLogin() public function actionLogin()
{ {
$userProducerArray = $this->getLogic() $userProducerArray = $this->getLogic()
->getUserProducerContainer() ->getUserProducerContainer()
->getRepository() ->getRepository()
->getBy(GlobalParam::getCurrentUserId());
->getBy(GlobalParam::getCurrentUser());


if ($userProducerArray if ($userProducerArray
&& is_array($userProducerArray) && is_array($userProducerArray)
&& count($userProducerArray) == 1) { && count($userProducerArray) == 1) {


return $this->redirect($this->getUrlManagerProducer()->createAbsoluteUrl(['site/index', 'slug_producer' => $userProducerArray[0]->producer->slug]));
$urlRedirect = $this->getUrlManagerProducer()
->createAbsoluteUrl([
'site/index',
'slug_producer' => $userProducerArray[0]->producer->slug
]);

return $this->redirect($urlRedirect);
} }
else { else {
return $this->goBack(); return $this->goBack();


/** /**
* Déconnecte l'utilisateur. * Déconnecte l'utilisateur.
*
* @return mixed
*/ */
public function actionLogout() public function actionLogout()
{ {


/** /**
* Affiche la page de contact et traite le formulaire s'il est soumis. * Affiche la page de contact et traite le formulaire s'il est soumis.
*
* @return mixed
*/ */
public function actionContact() public function actionContact()
{ {


/** /**
* Affiche la page d'inscription et traite son formulaire. * Affiche la page d'inscription et traite son formulaire.
*
* @return mixed
*/ */
public function actionSignup() public function actionSignup()
{ {
/** /**
* Affiche la page de demande de nouveau mot de passe. * Affiche la page de demande de nouveau mot de passe.
* Traitement du formulaire. * Traitement du formulaire.
*
* @return mixed
*/ */
public function actionRequestPasswordReset() public function actionRequestPasswordReset()
{ {
if ($model->sendEmail()) { if ($model->sendEmail()) {
$this->setFlash('success', 'Un lien vous permettant de réinitialiser votre mot de passe $this->setFlash('success', 'Un lien vous permettant de réinitialiser votre mot de passe
vient d\'être envoyé sur votre boîte mail.'); vient d\'être envoyé sur votre boîte mail.');

return $this->goHome(); return $this->goHome();
} }
else { else {


/** /**
* Met à jour le mot de passe de l'utilisateur. * Met à jour le mot de passe de l'utilisateur.
*
* @param string $token
* @return mixed
* @throws BadRequestHttpException
*/ */
public function actionResetPassword($token) public function actionResetPassword($token)
{ {
} }


/** /**
* Affiche le formulaire de demande de code pour accéder à certains
* producteurs.
*
* @param integer $id
* @return mixed
* @throws \yii\web\HttpException
* Affiche le formulaire de demande de code pour accéder à certains producteurs.
*/ */
public function actionProducerCode($id)
public function actionProducerCode(int $id)
{ {
$producerContainer = $this->getLogic()->getProducerContainer(); $producerContainer = $this->getLogic()->getProducerContainer();
$producer = $producerContainer->getRepository()->getOneById($id); $producer = $producerContainer->getRepository()->getOneById($id);
if ($producerCodeForm->load($this->getRequest()->post()) if ($producerCodeForm->load($this->getRequest()->post())
&& $producerCodeForm->validate()) { && $producerCodeForm->validate()) {


$producerContainer->getBuilder()->addUser(GlobalParam::getCurrentUserId(), $id);
$producerContainer->getBuilder()->addUser(GlobalParam::getCurrentUser(), $producer);


$this->redirect($this->getUrlManagerProducer()->createAbsoluteUrl(['site/index', 'slug_producer' => $producer->slug])); $this->redirect($this->getUrlManagerProducer()->createAbsoluteUrl(['site/index', 'slug_producer' => $producer->slug]));
} }
/** /**
* Affiche la page de connexion / inscription pour accéder notamment au * Affiche la page de connexion / inscription pour accéder notamment au
* formulaire de commande des producteurs. * formulaire de commande des producteurs.
*
* @param integer $id
* @return mixed
*/ */
public function actionProducer($id)
public function actionProducer(int $id)
{ {
$loginForm = new LoginForm(); $loginForm = new LoginForm();
$signupForm = new SignupForm(); $signupForm = new SignupForm();
if ($this->getUser()->isGuest) { if ($this->getUser()->isGuest) {
if ($loginForm->load($this->getRequest()->post()) && $loginForm->login()) { if ($loginForm->load($this->getRequest()->post()) && $loginForm->login()) {
if (!strlen($producer->code)) { if (!strlen($producer->code)) {
$producerContainer->getBuilder()->addUser(GlobalParam::getCurrentUserId(), $id);
$producerContainer->getBuilder()->addUser(GlobalParam::getCurrentUser(), $producer);
} }


$this->redirect($returnUrl); $this->redirect($returnUrl);
} }


/** /**
* Indique à l'utilisateur que l'espace d'un producteur est hors ligne
*
* @param integer $id
* @return mixed
* Indique à l'utilisateur que l'espace d'un producteur est hors ligne.
*/ */
public function actionProducerOffline($id)
public function actionProducerOffline(int $id)
{ {
$producerRepository = $this->getLogic()->getProducerContainer()->getRepository();

return $this->render('producer_offline', [ return $this->render('producer_offline', [
'producer' => $producerRepository->getOneById($id),
'producer' => $this->getLogic()->getProducerContainer()
->getRepository()->getOneById($id),
]); ]);
} }


/** /**
* Affiche les mentions légales. * Affiche les mentions légales.
*
* @return mixed
*/ */
public function actionMentions() public function actionMentions()
{ {


/** /**
* Affiche les conditions générale de service. * Affiche les conditions générale de service.
*
* @return mixed
*/ */
public function actionCgv() public function actionCgv()
{ {


/** /**
* Affiche les précisions concernant l'utilisation du crédit. * Affiche les précisions concernant l'utilisation du crédit.
*
* @return string
*/ */
public function actionCredit() public function actionCredit()
{ {

+ 3
- 9
frontend/views/site/signup.php View File



use yii\helpers\Html; use yii\helpers\Html;
use yii\bootstrap\ActiveForm; use yii\bootstrap\ActiveForm;

/* @var $this yii\web\View */
/* @var $form yii\bootstrap\ActiveForm */
/* @var $model \frontend\models\SignupForm */
use common\logic\Config\TaxRate\TaxRate;
use yii\helpers\ArrayHelper;


$this->setTitle('Inscription') ; $this->setTitle('Inscription') ;
$this->setMeta('description', 'Inscrivez-vous afin de profiter des fonctionnalités de la plateforme.'); $this->setMeta('description', 'Inscrivez-vous afin de profiter des fonctionnalités de la plateforme.');


$this->params['breadcrumbs'][] = $this->title; $this->params['breadcrumbs'][] = $this->title;

?> ?>
<div class="site-signup"> <div class="site-signup">


'prompt' => '--', 'prompt' => '--',
]) ])
->label('TVA à appliquer par défaut'); ?> ->label('TVA à appliquer par défaut'); ?>
<!-- <?//= $form->field($model, 'free_price',[
// 'inputTemplate' => '<div class="input-group">{input}<span class="input-group-addon"><span class="glyphicon glyphicon-euro"></span></span></div>',
// ])
// ->label('Prix libre HT / mois')
// ->hint('Laissez ce champs vide si vous souhaitez dans un premier temps simplement tester la plateforme. Une fois l\'outil mis en place dans votre structure, vous pourrez modifier ce coût dans la section "Mon abonnement" de votre panneau d\'administration.') ; ?>-->
<?= $form->field($model, 'cgv')->checkbox()->label('J\'accepte les <a class="btn btn-xs btn-default" data-toggle="modal" data-target="#modal-cgv" href="javascript:void(0);">conditions générales de service</a> et les <a class="btn btn-xs btn-default" data-toggle="modal" data-target="#modal-prices" href="javascript:void(0);">conditions tarifaires</a>.') ?> <?= $form->field($model, 'cgv')->checkbox()->label('J\'accepte les <a class="btn btn-xs btn-default" data-toggle="modal" data-target="#modal-cgv" href="javascript:void(0);">conditions générales de service</a> et les <a class="btn btn-xs btn-default" data-toggle="modal" data-target="#modal-prices" href="javascript:void(0);">conditions tarifaires</a>.') ?>
</div> </div>
<div id="fields-user"> <div id="fields-user">

+ 93
- 94
producer/controllers/CreditController.php View File

public function behaviors() public function behaviors()
{ {
return [ return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'stripe-verification' => ['post'],
],
]
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'stripe-verification' => ['post'],
],
]
]; ];
} }


public function actions() public function actions()
{ {
return [ return [
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
],
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
],
]; ];
} }


{ {
$producer = $this->getProducer(); $producer = $this->getProducer();


if(\Yii::$app->user->isGuest) {
return $this->redirect(Yii::$app->urlManagerFrontend->createAbsoluteUrl(['site/producer','id' => $producer->id])) ;
if (\Yii::$app->user->isGuest) {
return $this->redirect($this->getUrlManagerFrontend()->createAbsoluteUrl(['site/producer', 'id' => $producer->id]));
} }


$searchModel = new CreditHistorySearch(); $searchModel = new CreditHistorySearch();
$dataProvider = $searchModel->search(\Yii::$app->request->queryParams); $dataProvider = $searchModel->search(\Yii::$app->request->queryParams);


$userProducer = UserProducer::searchOne([ $userProducer = UserProducer::searchOne([
'id_producer' => $producer->id,
'id_user' => GlobalParam::getCurrentUserId()
]);
'id_producer' => $producer->id,
'id_user' => GlobalParam::getCurrentUserId()
]);


if (strlen($returnPayment)) { if (strlen($returnPayment)) {
if ($returnPayment == 'success') { if ($returnPayment == 'success') {
} }


return $this->render('history', [ return $this->render('history', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
'creditUser' => $userProducer->credit
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
'creditUser' => $userProducer->credit
]); ]);
} }


{ {
$producer = $this->getProducer(); $producer = $this->getProducer();


if(\Yii::$app->user->isGuest) {
return $this->redirect(\Yii::$app->urlManagerFrontend->createAbsoluteUrl(['site/producer','id' => $producer->id])) ;
if (\Yii::$app->user->isGuest) {
return $this->redirect(\Yii::$app->urlManagerFrontend->createAbsoluteUrl(['site/producer', 'id' => $producer->id]));
} }


if ($producer->online_payment || $producer->option_stripe_mode_test) { if ($producer->online_payment || $producer->option_stripe_mode_test) {
$creditForm = new CreditForm; $creditForm = new CreditForm;


if ($creditForm->load(\Yii::$app->request->post()) && $creditForm->validate()) { if ($creditForm->load(\Yii::$app->request->post()) && $creditForm->validate()) {
$user = User::getCurrent();
$user = GlobalParam::getCurrentUser();


\Stripe\Stripe::setApiKey( \Stripe\Stripe::setApiKey(
$producer->getPrivateKeyApiStripe()
$producer->getPrivateKeyApiStripe()
); );


$checkout_session = \Stripe\Checkout\Session::create([ $checkout_session = \Stripe\Checkout\Session::create([
'line_items' => [
[
'price_data' => [
'currency' => 'eur',
'product_data' => [
'name' => 'Alimentation crédit',
],
'unit_amount' => (float)$creditForm->amount * 100,
],
'quantity' => 1,
]
],
'payment_method_types' => ['card'],
'mode' => 'payment',
'customer_email' => $user->email,
'client_reference_id' => $user->id,
'payment_intent_data' => [
'metadata' => [
'user_id' => $user->id,
'producer_id' => $producer->id
],
],
'success_url' => \Yii::$app->urlManagerProducer->createAbsoluteUrl(
[
'credit/history',
'returnPayment' => 'success'
]
),
'cancel_url' => \Yii::$app->urlManagerProducer->createAbsoluteUrl(
[
'credit/history',
'returnPayment' => 'cancel'
]
),
]);
'line_items' => [
[
'price_data' => [
'currency' => 'eur',
'product_data' => [
'name' => 'Alimentation crédit',
],
'unit_amount' => (float)$creditForm->amount * 100,
],
'quantity' => 1,
]
],
'payment_method_types' => ['card'],
'mode' => 'payment',
'customer_email' => $user->email,
'client_reference_id' => $user->id,
'payment_intent_data' => [
'metadata' => [
'user_id' => $user->id,
'producer_id' => $producer->id
],
],
'success_url' => \Yii::$app->urlManagerProducer->createAbsoluteUrl(
[
'credit/history',
'returnPayment' => 'success'
]
),
'cancel_url' => \Yii::$app->urlManagerProducer->createAbsoluteUrl(
[
'credit/history',
'returnPayment' => 'cancel'
]
),
]);


header("HTTP/1.1 303 See Other"); header("HTTP/1.1 303 See Other");
header("Location: " . $checkout_session->url); header("Location: " . $checkout_session->url);
} }


return $this->render('add', [ return $this->render('add', [
'creditForm' => $creditForm
'creditForm' => $creditForm
]); ]);
} else { } else {
throw new \yii\base\UserException('Cette option est désactivée chez ce producteur.'); throw new \yii\base\UserException('Cette option est désactivée chez ce producteur.');


try { try {
$event = \Stripe\Webhook::constructEvent( $event = \Stripe\Webhook::constructEvent(
$payload,
$sig_header,
$producer->getPrivateKeyEndpointStripe()
$payload,
$sig_header,
$producer->getPrivateKeyEndpointStripe()
); );
} catch (\UnexpectedValueException $e) { } catch (\UnexpectedValueException $e) {
// Invalid payload // Invalid payload
$user = User::findOne($paymentIntentMetadata->user_id); $user = User::findOne($paymentIntentMetadata->user_id);
$idProducer = $paymentIntentMetadata->producer_id; $idProducer = $paymentIntentMetadata->producer_id;


if(isset($paymentIntentMetadata->order_id)) {
if (isset($paymentIntentMetadata->order_id)) {
$order = Order::searchOne([ $order = Order::searchOne([
'id' => $paymentIntentMetadata->order_id
]);
'id' => $paymentIntentMetadata->order_id
]);
$pointSale = PointSale::searchOne(['id' => $order->id_point_sale]); $pointSale = PointSale::searchOne(['id' => $order->id_point_sale]);
$distribution = DistributionModel::find()->where(['id' => $order->id_distribution])->one(); $distribution = DistributionModel::find()->where(['id' => $order->id_distribution])->one();
} }
] ]
]); ]);


if(!$creditHistoryExist) {
if (!$creditHistoryExist) {


// on crédite le crédit du client // on crédite le crédit du client
$creditHistory = new CreditHistory(); $creditHistory = new CreditHistory();


// client // client
Mailjet::sendMail([ Mailjet::sendMail([
'from_email' => $producer->getEmailOpendistrib(),
'from_name' => $producer->name,
'to_email' => $user->email,
'to_name' => $user->getUsername(),
'subject' => '['.$producer->name.'] Erreur de paiement',
'content_view_text' => '@common/mail/paymentError-text.php',
'content_view_html' => '@common/mail/paymentError-html.php',
'content_params' => [
'amount' => $amount,
'user' => $user,
'producer' => $producer,
]
'from_email' => $producer->getEmailOpendistrib(),
'from_name' => $producer->name,
'to_email' => $user->email,
'to_name' => $user->getUsername(),
'subject' => '[' . $producer->name . '] Erreur de paiement',
'content_view_text' => '@common/mail/paymentError-text.php',
'content_view_html' => '@common/mail/paymentError-html.php',
'content_params' => [
'amount' => $amount,
'user' => $user,
'producer' => $producer,
]
]); ]);


// producteur // producteur
if(isset($order) && $order) {
if (isset($order) && $order) {
Mailjet::sendMail([ Mailjet::sendMail([
'from_email' => $producer->getEmailOpendistrib(),
'from_name' => $producer->name,
'to_email' => $contactProducer->email,
'to_name' => $contactProducer->name,
'subject' => '[' . $producer->name . '] Erreur de paiement',
'content_view_text' => '@common/mail/paymentErrorProducer-text.php',
'content_view_html' => '@common/mail/paymentErrorProducer-html.php',
'content_params' => [
'amount' => $amount,
'user' => $user,
'producer' => $producer,
'order' => $order,
'distribution' => $distribution
]
]);
'from_email' => $producer->getEmailOpendistrib(),
'from_name' => $producer->name,
'to_email' => $contactProducer->email,
'to_name' => $contactProducer->name,
'subject' => '[' . $producer->name . '] Erreur de paiement',
'content_view_text' => '@common/mail/paymentErrorProducer-text.php',
'content_view_html' => '@common/mail/paymentErrorProducer-html.php',
'content_params' => [
'amount' => $amount,
'user' => $user,
'producer' => $producer,
'order' => $order,
'distribution' => $distribution
]
]);
} }


break; break;
http_response_code(200); http_response_code(200);
die(); die();
} }

} }

+ 265
- 265
producer/controllers/OrderController.php View File



if (\Yii::$app->user->isGuest && !$producer->option_allow_order_guest) { if (\Yii::$app->user->isGuest && !$producer->option_allow_order_guest) {
return $this->redirect( return $this->redirect(
Yii::$app->urlManagerFrontend->createAbsoluteUrl(['site/producer', 'id' => $producer->id])
Yii::$app->urlManagerFrontend->createAbsoluteUrl(['site/producer', 'id' => $producer->id])
); );
} }


if ($id) { if ($id) {
$order = Order::searchOne([ $order = Order::searchOne([
'id' => $id
]);
'id' => $id
]);
if ($order) { if ($order) {
if ($order->getState() == Order::STATE_OPEN) { if ($order->getState() == Order::STATE_OPEN) {
$params['order'] = $order; $params['order'] = $order;


if (strlen($date)) { if (strlen($date)) {
$distribution = DistributionModel::searchOne([ $distribution = DistributionModel::searchOne([
'date' => $date,
'id_producer' => $producer->id
]);
'date' => $date,
'id_producer' => $producer->id
]);


if ($distribution) { if ($distribution) {
$distributionsArray = DistributionModel::filterDistributionsByDateDelay([$distribution]); $distributionsArray = DistributionModel::filterDistributionsByDateDelay([$distribution]);
$producer = $this->getProducer(); $producer = $this->getProducer();


$query = Order::find() $query = Order::find()
->with('productOrder', 'pointSale', 'creditHistory')
->joinWith('distribution', 'distribution.producer')
->where([
'id_user' => Yii::$app->user->id,
'distribution.id_producer' => $producer->id
])
->params([':date_today' => date('Y-m-d')]);
->with('productOrder', 'pointSale', 'creditHistory')
->joinWith('distribution', 'distribution.producer')
->where([
'id_user' => Yii::$app->user->id,
'distribution.id_producer' => $producer->id
])
->params([':date_today' => date('Y-m-d')]);


$queryIncoming = clone $query; $queryIncoming = clone $query;
$queryIncoming->andWhere('distribution.date >= :date_today')->orderBy('distribution.date ASC'); $queryIncoming->andWhere('distribution.date >= :date_today')->orderBy('distribution.date ASC');
$queryPassed->andWhere('distribution.date < :date_today')->orderBy('distribution.date DESC'); $queryPassed->andWhere('distribution.date < :date_today')->orderBy('distribution.date DESC');


$dataProviderOrders = new ActiveDataProvider([ $dataProviderOrders = new ActiveDataProvider([
'query' => ($type == 'incoming') ? $queryIncoming : $queryPassed,
'pagination' => [
'pageSize' => 10,
],
]);
'query' => ($type == 'incoming') ? $queryIncoming : $queryPassed,
'pagination' => [
'pageSize' => 10,
],
]);


return $this->render('history', [ return $this->render('history', [
'dataProviderOrders' => $dataProviderOrders,
'orderOk' => Yii::$app->getRequest()->get('orderOk', false),
'cancelOk' => Yii::$app->getRequest()->get('cancelOk', false),
'type' => $type,
'countIncoming' => $queryIncoming->count(),
'countPassed' => $queryPassed->count(),
'dataProviderOrders' => $dataProviderOrders,
'orderOk' => Yii::$app->getRequest()->get('orderOk', false),
'cancelOk' => Yii::$app->getRequest()->get('cancelOk', false),
'type' => $type,
'countIncoming' => $queryIncoming->count(),
'countPassed' => $queryPassed->count(),
]); ]);
} }


public function actionRemoveProducer($id = 0) public function actionRemoveProducer($id = 0)
{ {
$userProducer = UserProducer::find() $userProducer = UserProducer::find()
->where(['id_producer' => $id, 'id_user' => GlobalParam::getCurrentUserId()])
->one();
->where(['id_producer' => $id, 'id_user' => GlobalParam::getCurrentUserId()])
->one();


$userProducer->active = 0; $userProducer->active = 0;
$userProducer->save(); $userProducer->save();
$user = User::getCurrent(); $user = User::getCurrent();


$order = Order::find() $order = Order::find()
->where('id_distribution = :id_distribution')
->andWhere('id_user = :id_user')
->andWhere('id_point_sale = :id_point_sale')
->params([
':id_distribution' => $posts['Order']['id_distribution'],
':id_point_sale' => $posts['Order']['id_point_sale'],
':id_user' => $user ? $user->id : null
])
->one();
->where('id_distribution = :id_distribution')
->andWhere('id_user = :id_user')
->andWhere('id_point_sale = :id_point_sale')
->params([
':id_distribution' => $posts['Order']['id_distribution'],
':id_point_sale' => $posts['Order']['id_point_sale'],
':id_user' => $user ? $user->id : null
])
->one();


if ($order && !$order->online_payment_url) { if ($order && !$order->online_payment_url) {
if ($order->id_point_sale != $posts['Order']['id_point_sale']) { if ($order->id_point_sale != $posts['Order']['id_point_sale']) {
// gestion user : option_allow_order_guest // gestion user : option_allow_order_guest
if (isset($posts['user']) && $posts['user']) { if (isset($posts['user']) && $posts['user']) {
$userIndividualExist = User::searchOne([ $userIndividualExist = User::searchOne([
'email' => $posts['user']['email'],
'type' => User::TYPE_INDIVIDUAL
]);
'email' => $posts['user']['email'],
'type' => User::TYPE_INDIVIDUAL
]);


if ($userIndividualExist) { if ($userIndividualExist) {
$errorUserGuest = 'Cette adresse email est déjà utilisée, veuillez vous <a href="' . Yii::$app->urlManagerFrontend->createUrl( $errorUserGuest = 'Cette adresse email est déjà utilisée, veuillez vous <a href="' . Yii::$app->urlManagerFrontend->createUrl(
['site/producer', 'id' => $idProducer]
) . '">connecter à votre compte</a> ou en utiliser une autre.';
['site/producer', 'id' => $idProducer]
) . '">connecter à votre compte</a> ou en utiliser une autre.';
return ['status' => 'error', 'errors' => [$errorUserGuest]]; return ['status' => 'error', 'errors' => [$errorUserGuest]];
} }


$user = User::searchOne([ $user = User::searchOne([
'email' => $posts['user']['email'],
'type' => User::TYPE_GUEST
]);
'email' => $posts['user']['email'],
'type' => User::TYPE_GUEST
]);


if (!$user) { if (!$user) {
$user = new User; $user = new User;


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


\Stripe\Stripe::setApiKey( \Stripe\Stripe::setApiKey(
$producer->getPrivateKeyApiStripe()
$producer->getPrivateKeyApiStripe()
); );


$lineItems = []; $lineItems = [];
foreach ($order->productOrder as $productOrder) { foreach ($order->productOrder as $productOrder) {
$product = $productOrder->product; $product = $productOrder->product;
$lineItems[] = [ $lineItems[] = [
'price_data' => [
'currency' => 'eur',
'product_data' => [
'name' => $product->name . ' (' . $productOrder->quantity . ' ' . Product::strUnit(
$product->unit,
'wording_short',
true
) . ')',
],
'unit_amount' => $productOrder->price * 100 * $productOrder->quantity,
'price_data' => [
'currency' => 'eur',
'product_data' => [
'name' => $product->name . ' (' . $productOrder->quantity . ' ' . Product::strUnit(
$product->unit,
'wording_short',
true
) . ')',
], ],
'quantity' => 1,
'unit_amount' => $productOrder->price * 100 * $productOrder->quantity,
],
'quantity' => 1,
]; ];
} }


$checkout_session = \Stripe\Checkout\Session::create([ $checkout_session = \Stripe\Checkout\Session::create([
'line_items' => $lineItems,
'payment_method_types' => ['card'],
'mode' => 'payment',
'customer_email' => $user->email,
'client_reference_id' => $user->id,
'payment_intent_data' => [
'metadata' => [
'user_id' => $user->id,
'producer_id' => $producer->id,
'order_id' => $order->id
],
],
'success_url' => \Yii::$app->urlManagerProducer->createAbsoluteUrl(
[
'order/confirm',
'idOrder' => $order->id,
'returnPayment' => 'success'
]
),
'cancel_url' => \Yii::$app->urlManagerProducer->createAbsoluteUrl(
[
'order/confirm',
'idOrder' => $order->id,
'returnPayment' => 'cancel'
]
),
]);
'line_items' => $lineItems,
'payment_method_types' => ['card'],
'mode' => 'payment',
'customer_email' => $user->email,
'client_reference_id' => $user->id,
'payment_intent_data' => [
'metadata' => [
'user_id' => $user->id,
'producer_id' => $producer->id,
'order_id' => $order->id
],
],
'success_url' => \Yii::$app->urlManagerProducer->createAbsoluteUrl(
[
'order/confirm',
'idOrder' => $order->id,
'returnPayment' => 'success'
]
),
'cancel_url' => \Yii::$app->urlManagerProducer->createAbsoluteUrl(
[
'order/confirm',
'idOrder' => $order->id,
'returnPayment' => 'cancel'
]
),
]);
$redirect = $checkout_session->url; $redirect = $checkout_session->url;


$order->online_payment_url = $redirect; $order->online_payment_url = $redirect;
} }


foreach ($posts['products'] as $key => $quantity) { foreach ($posts['products'] as $key => $quantity) {
$product = Product::find()->where(['id' => (int)$key])->one();
$product = Product::find()->where(['id' => (int)$key])->one();
$totalQuantity += $quantity; $totalQuantity += $quantity;
if ($product && $quantity) { if ($product && $quantity) {
$productsArray[] = $product; $productsArray[] = $product;
$errorPointSale = false; $errorPointSale = false;
if (isset($distribution) && $distribution) { if (isset($distribution) && $distribution) {
$pointSaleDistribution = PointSaleDistributionModel::searchOne([ $pointSaleDistribution = PointSaleDistributionModel::searchOne([
'id_distribution' => $distribution->id,
'id_point_sale' => $posts['Order']['id_point_sale']
]);
'id_distribution' => $distribution->id,
'id_point_sale' => $posts['Order']['id_point_sale']
]);


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


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


if ($pointSale->restricted_access && !$userPointSale) { if ($pointSale->restricted_access && !$userPointSale) {
$errorPointSale = true; $errorPointSale = true;


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


// gestion point de vente // gestion point de vente
$pointSale = PointSale::searchOne([ $pointSale = PointSale::searchOne([
'id' => $order->id_point_sale
]);
'id' => $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())) ?
$pointSale->getComment() : '';
$pointSale->getComment() : '';


// la commande est automatiquement réactivée lors d'une modification // la commande est automatiquement réactivée lors d'une modification
$order->date_delete = null; $order->date_delete = null;
$productOrder->id_product = $product->id; $productOrder->id_product = $product->id;
$productOrder->id_tax_rate = $product->taxRate->id; $productOrder->id_tax_rate = $product->taxRate->id;
$unit = (!is_null( $unit = (!is_null(
$order
) && isset($unitsArray[$product->id])) ? $unitsArray[$product->id] : $product->unit;
$coefficient = Product::$unitsArray[$unit]['coefficient'];
$order
) && isset($unitsArray[$product->id])) ? $unitsArray[$product->id] : $product->unit;
$coefficient = Product::$unitsArray[$unit]['coefficient'];
$quantity = ((float)$posts['products'][$product->id]) / $coefficient; $quantity = ((float)$posts['products'][$product->id]) / $coefficient;
if ($availableProducts[$product->id]['quantity_max'] && $quantity > $availableProducts[$product->id]['quantity_remaining']) { if ($availableProducts[$product->id]['quantity_max'] && $quantity > $availableProducts[$product->id]['quantity_remaining']) {
$quantity = $availableProducts[$product->id]['quantity_remaining']; $quantity = $availableProducts[$product->id]['quantity_remaining'];
} }
$productOrder->quantity = $quantity; $productOrder->quantity = $quantity;
$productOrder->price = $product->getPrice([ $productOrder->price = $product->getPrice([
'user' => User::getCurrent(),
'user_producer' => $userProducer,
'point_sale' => $pointSale,
'quantity' => $quantity
]);
'user' => User::getCurrent(),
'user_producer' => $userProducer,
'point_sale' => $pointSale,
'quantity' => $quantity
]);
$productOrder->unit = $product->unit; $productOrder->unit = $product->unit;
$productOrder->step = $product->step; $productOrder->step = $product->step;
$productOrder->save(); $productOrder->save();
$creditFunctioning = $pointSale->getCreditFunctioning(); $creditFunctioning = $pointSale->getCreditFunctioning();
$creditUser = $user->getCredit($distribution->id_producer); $creditUser = $user->getCredit($distribution->id_producer);
$order = Order::searchOne([ $order = Order::searchOne([
'id' => $order->id
]);
'id' => $order->id
]);
$amountPaid = $order->getAmount(Order::AMOUNT_PAID); $amountPaid = $order->getAmount(Order::AMOUNT_PAID);
$amountRemaining = $order->getAmount(Order::AMOUNT_REMAINING); $amountRemaining = $order->getAmount(Order::AMOUNT_REMAINING);


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


// à payer // à payer


if ($amountRemaining > 0) { if ($amountRemaining > 0) {
$order->saveCreditHistory( $order->saveCreditHistory(
CreditHistory::TYPE_PAYMENT,
$amountRemaining,
$distribution->id_producer,
GlobalParam::getCurrentUserId(),
GlobalParam::getCurrentUserId()
CreditHistory::TYPE_PAYMENT,
$amountRemaining,
$distribution->id_producer,
GlobalParam::getCurrentUserId(),
GlobalParam::getCurrentUserId()
); );
$order->changeOrderStatus('paid-by-credit', 'user'); $order->changeOrderStatus('paid-by-credit', 'user');
} else { } else {
elseif ($order->getPaymentStatus() == Order::PAYMENT_SURPLUS) { elseif ($order->getPaymentStatus() == Order::PAYMENT_SURPLUS) {
$amountSurplus = $order->getAmount(Order::AMOUNT_SURPLUS); $amountSurplus = $order->getAmount(Order::AMOUNT_SURPLUS);
$order->saveCreditHistory( $order->saveCreditHistory(
CreditHistory::TYPE_REFUND,
$amountSurplus,
$distribution->id_producer,
GlobalParam::getCurrentUserId(),
GlobalParam::getCurrentUserId()
CreditHistory::TYPE_REFUND,
$amountSurplus,
$distribution->id_producer,
GlobalParam::getCurrentUserId(),
GlobalParam::getCurrentUserId()
); );
} }
} else { } else {
} }


$paramsEmail = [ $paramsEmail = [
'from_email' => $producer->getEmailOpendistrib(),
'from_name' => $producer->name,
'to_email' => $user->email,
'to_name' => $user->getUsername(),
'subject' => '[' . $producer->name . '] Confirmation de commande',
'content_view_text' => '@common/mail/orderConfirm-text.php',
'content_view_html' => '@common/mail/orderConfirm-html.php',
'content_params' => [
'order' => $order,
'pointSale' => $pointSale,
'distribution' => $distribution,
'user' => $user,
'producer' => $producer
]
'from_email' => $producer->getEmailOpendistrib(),
'from_name' => $producer->name,
'to_email' => $user->email,
'to_name' => $user->getUsername(),
'subject' => '[' . $producer->name . '] Confirmation de commande',
'content_view_text' => '@common/mail/orderConfirm-text.php',
'content_view_html' => '@common/mail/orderConfirm-html.php',
'content_params' => [
'order' => $order,
'pointSale' => $pointSale,
'distribution' => $distribution,
'user' => $user,
'producer' => $producer
]
]; ];


/* /*
// au producteur // au producteur
$contactProducer = $producer->getMainContact(); $contactProducer = $producer->getMainContact();
if (Producer::getConfig('option_email_confirm_producer') && $contactProducer && strlen( if (Producer::getConfig('option_email_confirm_producer') && $contactProducer && strlen(
$contactProducer->email
)) {
$contactProducer->email
)) {
$paramsEmail['to_email'] = $contactProducer->email; $paramsEmail['to_email'] = $contactProducer->email;
$paramsEmail['to_name'] = $contactProducer->name; $paramsEmail['to_name'] = $contactProducer->name;
$paramsEmail['content_view_text'] = '@common/mail/orderConfirmProducer-text.php'; $paramsEmail['content_view_text'] = '@common/mail/orderConfirmProducer-text.php';
public function actionCancel($id) public function actionCancel($id)
{ {
$order = Order::searchOne([ $order = Order::searchOne([
'id' => $id
]);
'id' => $id
]);


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


// Producteur // Producteur
$producer = Producer::searchOne([ $producer = Producer::searchOne([
'id' => $this->getProducer()->id
]);
'id' => $this->getProducer()->id
]);
$json['producer'] = [ $json['producer'] = [
'order_infos' => $producer->order_infos,
'credit' => $producer->credit,
'credit_functioning' => $producer->credit_functioning,
'use_credit_checked_default' => $producer->use_credit_checked_default,
'credit_limit' => is_numeric($producer->credit_limit) ? $producer->credit_limit : null,
'option_allow_order_guest' => $producer->option_allow_order_guest,
'option_order_entry_point' => $producer->option_order_entry_point,
'option_delivery' => $producer->option_delivery,
'online_payment' => $producer->online_payment,
'option_online_payment_type' => $producer->online_payment
'order_infos' => $producer->order_infos,
'credit' => $producer->credit,
'credit_functioning' => $producer->credit_functioning,
'use_credit_checked_default' => $producer->use_credit_checked_default,
'credit_limit' => is_numeric($producer->credit_limit) ? $producer->credit_limit : null,
'option_allow_order_guest' => $producer->option_allow_order_guest,
'option_order_entry_point' => $producer->option_order_entry_point,
'option_delivery' => $producer->option_delivery,
'online_payment' => $producer->online_payment,
'option_online_payment_type' => $producer->online_payment
]; ];


// Distributions // Distributions
$dateMini = date('Y-m-d'); $dateMini = date('Y-m-d');


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


// Filtre par point de vente // Filtre par point de vente
$distribution = $distributionsArray[$i]; $distribution = $distributionsArray[$i];
if (Distribution::isPointSaleActive($distribution, $pointSaleId)) { if (Distribution::isPointSaleActive($distribution, $pointSaleId)) {
$countOrders = (int)Order::searchCount([ $countOrders = (int)Order::searchCount([
'id_distribution' => $distribution->id,
'id_point_sale' => $pointSaleId
]);
'id_distribution' => $distribution->id,
'id_point_sale' => $pointSaleId
]);
$orderUserPointSale = $this->_getOrderUser($distribution->date, $pointSaleId); $orderUserPointSale = $this->_getOrderUser($distribution->date, $pointSaleId);


if (!$pointSaleCurrent->maximum_number_orders if (!$pointSaleCurrent->maximum_number_orders
|| ($orderUserPointSale && $orderUserPointSale->id_point_sale == $pointSaleId)
|| ($pointSaleCurrent->maximum_number_orders &&
($countOrders < $pointSaleCurrent->maximum_number_orders))) {
|| ($orderUserPointSale && $orderUserPointSale->id_point_sale == $pointSaleId)
|| ($pointSaleCurrent->maximum_number_orders &&
($countOrders < $pointSaleCurrent->maximum_number_orders))) {
$distributionsArrayFilterPointSale[] = $distribution; $distributionsArrayFilterPointSale[] = $distribution;
} }
} }
$ordersUserArray = []; $ordersUserArray = [];
if (GlobalParam::getCurrentUserId() && !$producer->isOnlinePaymentActiveAndTypeOrder()) { if (GlobalParam::getCurrentUserId() && !$producer->isOnlinePaymentActiveAndTypeOrder()) {
$conditionsOrdersUser = [ $conditionsOrdersUser = [
'distribution.date > :date'
'distribution.date > :date'
]; ];
$paramsOrdersUser = [ $paramsOrdersUser = [
':date' => $dateMini
':date' => $dateMini
]; ];


if ($pointSaleId && $producer->option_order_entry_point == Producer::ORDER_ENTRY_POINT_POINT_SALE) { if ($pointSaleId && $producer->option_order_entry_point == Producer::ORDER_ENTRY_POINT_POINT_SALE) {
} }


$ordersUserArray = Order::searchAll([ $ordersUserArray = Order::searchAll([
'id_user' => GlobalParam::getCurrentUserId()
], [
'conditions' => $conditionsOrdersUser,
'params' => $paramsOrdersUser
]);
'id_user' => GlobalParam::getCurrentUserId()
], [
'conditions' => $conditionsOrdersUser,
'params' => $paramsOrdersUser
]);
} }


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),
'date_distribution' => $order->distribution->date,
'pointSale' => $order->pointSale->getAttributes()
'amount_total' => $order->getAmountWithTax(Order::AMOUNT_TOTAL),
'date_distribution' => $order->distribution->date,
'pointSale' => $order->pointSale->getAttributes()
]); ]);
} }
$json['orders'] = $ordersUserArray; $json['orders'] = $ordersUserArray;


// User // User
$userProducer = UserProducer::searchOne([ $userProducer = UserProducer::searchOne([
'id_producer' => $producer->id,
'id_user' => GlobalParam::getCurrentUserId()
]);
'id_producer' => $producer->id,
'id_user' => GlobalParam::getCurrentUserId()
]);


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


$json['user'] = false; $json['user'] = false;
if ($user && $userProducer) { if ($user && $userProducer) {
$json['user'] = [ $json['user'] = [
'address' => $user->address,
'credit' => $userProducer->credit,
'credit_active' => $userProducer->credit_active,
'address' => $user->address,
'credit' => $userProducer->credit,
'credit_active' => $userProducer->credit_active,
]; ];
} }




// Commandes totales // Commandes totales
$ordersArray = Order::searchAll([ $ordersArray = Order::searchAll([
'distribution.date' => $date,
]);
'distribution.date' => $date,
]);


// Catégories // Catégories
$categoriesArray = ProductCategory::searchAll(
[],
[
'orderby' => 'product_category.position ASC',
'as_array' => true
]
$categoriesArray = ProductCategory::searchAll(
[],
[
'orderby' => 'product_category.position ASC',
'as_array' => true
]
); );
$countProductsWithoutCategories = Product::searchCount([
'id_producer' => $this->getProducer()->id,
'product.active' => 1,
'product.id_product_category' => null
]);
$countProductsWithoutCategories = Product::searchCount([
'id_producer' => $this->getProducer()->id,
'product.active' => 1,
'product.id_product_category' => null
]);
if ($countProductsWithoutCategories) { if ($countProductsWithoutCategories) {
array_unshift($categoriesArray, ['id' => null, 'name' => 'Catégorie par défaut']); array_unshift($categoriesArray, ['id' => null, 'name' => 'Catégorie par défaut']);
} }
$json['categories'] = $categoriesArray; $json['categories'] = $categoriesArray;


// Produits // Produits
$productsArray = Product::find()
->where([
'id_producer' => $this->getProducer()->id,
'product.active' => 1,
]);
$productsArray = Product::find()
->where([
'id_producer' => $this->getProducer()->id,
'product.active' => 1,
]);


$productsArray = $productsArray->joinWith([ $productsArray = $productsArray->joinWith([
'productDistribution' => function ($query) use (
$distribution
) {
$query->andOnCondition(
'product_distribution.id_distribution = ' . $distribution->id
);
},
/*'productPointSale' => function ($query) use ($pointSaleCurrent) {
$query->andOnCondition(
'product_point_sale.id_point_sale = ' . $pointSaleCurrent->id
);
},*/
'productPrice'
])
->orderBy('product_distribution.active DESC, order ASC')
->all();
'productDistribution' => function ($query) use (
$distribution
) {
$query->andOnCondition(
'product_distribution.id_distribution = ' . $distribution->id
);
},
/*'productPointSale' => function ($query) use ($pointSaleCurrent) {
$query->andOnCondition(
'product_point_sale.id_point_sale = ' . $pointSaleCurrent->id
);
},*/
'productPrice'
])
->orderBy('product_distribution.active DESC, order ASC')
->all();


$productsArrayFilter = []; $productsArrayFilter = [];


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


$coefficient_unit = Product::$unitsArray[$product['unit']]['coefficient'];
$coefficient_unit = Product::$unitsArray[$product['unit']]['coefficient'];


if (is_null($product['photo'])) { if (is_null($product['photo'])) {
$product['photo'] = ''; $product['photo'] = '';
$quantityOrder = Order::getProductQuantity($product['id'], $ordersArray); $quantityOrder = Order::getProductQuantity($product['id'], $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'] = Product::strUnit($product['unit'], 'wording_unit', true);
$product['wording_unit_ref'] = Product::strUnit($product['unit'], 'wording_short', true);


if ($orderUser) { if ($orderUser) {
$quantityOrderUser = Order::getProductQuantity($product['id'], [$orderUser], true); $quantityOrderUser = Order::getProductQuantity($product['id'], [$orderUser], true);
$product['quantity_form'] = $quantityOrderUser * $coefficient_unit; $product['quantity_form'] = $quantityOrderUser * $coefficient_unit;
foreach ($orderUser->productOrder as $productOrder) { foreach ($orderUser->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'] = Product::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'] = Product::strUnit($product['unit'], 'wording_unit', true);
} }
$product['coefficient_unit'] = $coefficient_unit; $product['coefficient_unit'] = $coefficient_unit;


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


if ($pointSaleId) { if ($pointSaleId) {


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' => $orderUser->getAmountWithTax(Order::AMOUNT_TOTAL),
'amount_paid' => $orderUser->getAmount(Order::AMOUNT_PAID),
]); ]);
} }




if ($distribution) { if ($distribution) {
$pointsSaleArray = $pointsSaleArray->joinWith([ $pointsSaleArray = $pointsSaleArray->joinWith([
'pointSaleDistribution' => function ($query) use (
$distribution
) {
$query->where(
[
'id_distribution' => $distribution->id,
'delivery' => 1
]
);
}
]);
'pointSaleDistribution' => function ($query) use (
$distribution
) {
$query->where(
[
'id_distribution' => $distribution->id,
'delivery' => 1
]
);
}
]);
} }


if (GlobalParam::getCurrentUserId()) { if (GlobalParam::getCurrentUserId()) {
$pointsSaleArray = $pointsSaleArray->with([ $pointsSaleArray = $pointsSaleArray->with([
'userPointSale' => function ($query) {
$query->onCondition(
['id_user' => GlobalParam::getCurrentUserId()]
);
}
]);
'userPointSale' => function ($query) {
$query->onCondition(
['id_user' => GlobalParam::getCurrentUserId()]
);
}
]);
} }


$pointsSaleArray = $pointsSaleArray->where(['id_producer' => $idProducer]) $pointsSaleArray = $pointsSaleArray->where(['id_producer' => $idProducer])
->andWhere(
'status = 1 AND (restricted_access = 0 OR (restricted_access = 1 AND (SELECT COUNT(*) FROM user_point_sale WHERE point_sale.id = user_point_sale.id_point_sale AND user_point_sale.id_user = :id_user) > 0))'
)
->params([':id_user' => GlobalParam::getCurrentUserId()])
->orderBy('code ASC, restricted_access ASC, is_bread_box ASC, `default` DESC, name ASC')
->all();
->andWhere(
'status = 1 AND (restricted_access = 0 OR (restricted_access = 1 AND (SELECT COUNT(*) FROM user_point_sale WHERE point_sale.id = user_point_sale.id_point_sale AND user_point_sale.id_user = :id_user) > 0))'
)
->params([':id_user' => GlobalParam::getCurrentUserId()])
->orderBy('code ASC, restricted_access ASC, is_bread_box ASC, `default` DESC, name ASC')
->all();


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


foreach ($pointsSaleArray as &$pointSale) { foreach ($pointsSaleArray as &$pointSale) {
$pointSale = array_merge($pointSale->getAttributes(), [ $pointSale = array_merge($pointSale->getAttributes(), [
'pointSaleDistribution' => [
'id_distribution' => $pointSale->pointSaleDistribution ? $pointSale->pointSaleDistribution[0]->id_distribution : false,
'id_point_sale' => $pointSale->pointSaleDistribution ? $pointSale->pointSaleDistribution[0]->id_point_sale : false,
'delivery' => $pointSale->pointSaleDistribution ? $pointSale->pointSaleDistribution[0]->delivery : false,
],
'userPointSale' => ($pointSale->userPointSale ? $pointSale->userPointSale[0] : '')
'pointSaleDistribution' => [
'id_distribution' => $pointSale->pointSaleDistribution ? $pointSale->pointSaleDistribution[0]->id_distribution : false,
'id_point_sale' => $pointSale->pointSaleDistribution ? $pointSale->pointSaleDistribution[0]->id_point_sale : false,
'delivery' => $pointSale->pointSaleDistribution ? $pointSale->pointSaleDistribution[0]->delivery : false,
],
'userPointSale' => ($pointSale->userPointSale ? $pointSale->userPointSale[0] : '')
]); ]);
if ($pointSale['code'] && strlen($pointSale['code'])) { if ($pointSale['code'] && strlen($pointSale['code'])) {
$pointSale['code'] = '***'; $pointSale['code'] = '***';


if ($distribution) { if ($distribution) {
$pointSale['count_orders'] = (int)Order::searchCount([ $pointSale['count_orders'] = (int)Order::searchCount([
'id_distribution' => $distribution->id,
'id_point_sale' => $pointSale['id']
]);
'id_distribution' => $distribution->id,
'id_point_sale' => $pointSale['id']
]);
} }


$pointSale['position'] = $position; $pointSale['position'] = $position;
} }


return $this->render('confirm', [ return $this->render('confirm', [
'order' => $order,
'returnPayment' => $returnPayment
'order' => $order,
'returnPayment' => $returnPayment
]); ]);
} }



+ 1
- 2
producer/controllers/ProducerBaseController.php View File

/** /**
* Retourne le producteur courant. * Retourne le producteur courant.
*
*/ */
public function getProducer()
public function getProducer() : Producer
{ {
if($this->producer) { if($this->producer) {
return $this->producer ; return $this->producer ;

+ 93
- 126
producer/controllers/SiteController.php View File



use common\forms\ContactForm; use common\forms\ContactForm;
use common\helpers\GlobalParam; use common\helpers\GlobalParam;
use common\logic\User\User\User;
use common\logic\User\UserProducer\UserProducer;
use common\models\ProductCategory;
use common\logic\PointSale\PointSale\PointSale;
use common\logic\Product\Product\Product;
use common\logic\Product\ProductCategory\ProductCategory;
use yii\data\ActiveDataProvider;
use yii\helpers\Html;


class SiteController extends ProducerBaseController class SiteController extends ProducerBaseController
{ {
public function actions() public function actions()
{ {
return [ return [
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
],
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
],
]; ];
} }


/** /**
* Affiche et gère les erreurs. * Affiche et gère les erreurs.
*
* @return mixed
*/ */
public function actionError() public function actionError()
{ {
$exception = Yii::$app->errorHandler->exception;
$exception = \Yii::$app->errorHandler->exception;


if ($exception !== null) { if ($exception !== null) {
if ($exception->getMessage() == 'Producteur introuvable') { if ($exception->getMessage() == 'Producteur introuvable') {
Yii::$app->getResponse()->redirect(
Yii::$app->urlManagerFrontend->createAbsoluteUrl(['site/error', 'producer_not_found' => true])
\Yii::$app->getResponse()->redirect(
\Yii::$app->urlManagerFrontend->createAbsoluteUrl(['site/error', 'producer_not_found' => true])
)->send(); )->send();
return;
} else { } else {
return $this->render('error', ['exception' => $exception]); return $this->render('error', ['exception' => $exception]);
} }


/** /**
* Affiche la page d'accueil des producteurs comprenant une image, une * Affiche la page d'accueil des producteurs comprenant une image, une
* description, la liste des points de vente et les produits
*
* @return ProducerView
* description, la liste des points de vente et les produits.
*/ */
public function actionIndex() public function actionIndex()
{ {
// points de vente // points de vente
$dataProviderPointsSale = new ActiveDataProvider([ $dataProviderPointsSale = new ActiveDataProvider([
'query' => PointSale::find()
->where([
'id_producer' => $this->getProducer(
)->id,
'restricted_access' => 0,
'status' => 1
])->orderBy(
'code ASC, restricted_access ASC, is_bread_box ASC, `default` DESC, name ASC'
//'default DESC, is_bread_box ASC, name ASC'
),
'pagination' => [
'pageSize' => 50,
],
'sort' => false,
]);
'query' => PointSale::find()
->where([
'id_producer' => $this->getProducer()->id,
'restricted_access' => 0,
'status' => 1
])->orderBy(
'code ASC, restricted_access ASC, is_bread_box ASC, `default` DESC, name ASC'
),
'pagination' => [
'pageSize' => 50,
],
'sort' => false,
]);


// produits // produits
$categoriesArray = ProductCategory::searchAll([], ['orderby' => 'product_category.position ASC']);
$categoriesArray = ProductCategory::searchAll([], ['orderby' => 'product_category.position ASC']);
$dataProviderProductsByCategories = []; $dataProviderProductsByCategories = [];
foreach ($categoriesArray as $category) { foreach ($categoriesArray as $category) {
$dataProviderProductsByCategories[$category->id] = new ActiveDataProvider([ $dataProviderProductsByCategories[$category->id] = new ActiveDataProvider([
'query' => Product::find()
->andWhere([
'id_producer' => $this->getProducer(
)->id,
'active' => true,
])
->andWhere(
'product.id_product_category = :id_product_category'
)
->params(
[':id_product_category' => $category->id]
)
->orderBy(
'order ASC'
),
'pagination' => [
'pageSize' => 500,
],
'sort' => false,
]);
'query' => Product::find()
->andWhere([
'id_producer' => $this->getProducer()->id,
'active' => true,
])
->andWhere(
'product.id_product_category = :id_product_category'
)
->params(
[':id_product_category' => $category->id]
)
->orderBy(
'order ASC'
),
'pagination' => [
'pageSize' => 500,
],
'sort' => false,
]);
} }


$queryProducts = Product::find()
->andWhere([
'id_producer' => $this->getProducer()->id,
'active' => true,
'id_product_category' => null,
])
->orderBy('order ASC');
$queryProducts = Product::find()
->andWhere([
'id_producer' => $this->getProducer()->id,
'active' => true,
'id_product_category' => null,
])
->orderBy('order ASC');


$dataProviderProducts = new ActiveDataProvider([ $dataProviderProducts = new ActiveDataProvider([
'query' => $queryProducts,
'pagination' => [
'pageSize' => 500,
],
'sort' => false,
]);
'query' => $queryProducts,
'pagination' => [
'pageSize' => 500,
],
'sort' => false,
]);


$products = $queryProducts->all(); $products = $queryProducts->all();
foreach ($dataProviderProductsByCategories as $dataProvider) { foreach ($dataProviderProductsByCategories as $dataProvider) {
$products = array_merge( $products = array_merge(
$products,
$dataProvider->query->all()
$products,
$dataProvider->query->all()
); );
} }


} }


return $this->render('index', [ return $this->render('index', [
'dataProviderProductsByCategories' => $dataProviderProductsByCategories,
'dataProviderPointsSale' => $dataProviderPointsSale,
'dataProviderProducts' => $dataProviderProducts,
'hasProductPhoto' => $hasProductPhoto,
'hasProductWeight' => $hasProductWeight,
'categories' => $categoriesArray,
'dataProviderProductsByCategories' => $dataProviderProductsByCategories,
'dataProviderPointsSale' => $dataProviderPointsSale,
'dataProviderProducts' => $dataProviderProducts,
'hasProductPhoto' => $hasProductPhoto,
'hasProductWeight' => $hasProductWeight,
'categories' => $categoriesArray,
]); ]);
} }


/** /**
* Affiche et traite le formulaire de contact dédié aux producteurs
*
* @return ProducerView
* Affiche et traite le formulaire de contact dédié aux producteurs.
*/ */
public function actionContact() public function actionContact()
{ {
$model = new ContactForm(); $model = new ContactForm();
$producer = $this->getProducer(); $producer = $this->getProducer();


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 = '';
$contact = $producer->getMainContact();
if ($contact) {
$email = $contact->email;
}

$email = $this->getLogic()->getProducerContainer()->getSolver()->getMainContactEmail($producer);
if (strlen($email) && $model->sendEmail($email)) { if (strlen($email) && $model->sendEmail($email)) {
$isSent = true; $isSent = true;
} }
} }


if ($isSent) { if ($isSent) {
Yii::$app->session->setFlash('success', 'Votre message a bien été envoyé.');
$this->setFlash('success', 'Votre message a bien été envoyé.');
} else { } else {
Yii::$app->session->setFlash('error', 'Il y a eu une erreur lors de l\'envoi de votre message.');
$this->setFlash('error', 'Il y a eu une erreur lors de l\'envoi de votre message.');
} }


return $this->refresh(); return $this->refresh();
} else { } else {
return $this->render('contact', [ return $this->render('contact', [
'model' => $model,
'model' => $model,
]); ]);
} }
} }
/** /**
* Ajoute ou supprime un producteur des favoris de l'utilisateur. * Ajoute ou supprime un producteur des favoris de l'utilisateur.
* Redirige vers la page d'accueil du producteur. * Redirige vers la page d'accueil du producteur.
*
* @param $action 'add' ou 'delete'
*/ */
public function actionBookmarks($action)
public function actionBookmarks(string $action)
{ {
$producer = $this->getProducer(); $producer = $this->getProducer();
$userProducer = UserProducer::find()
->where([
'id_user' => GlobalParam::getCurrentUserId(),
'id_producer' => $producer->id
])
->one();

if (!$userProducer) {
$userProducer = $this->getLogic()->getProducerContainer()->getBuilder()->addUser(GlobalParam::getCurrentUserId(), $producer->id);
}

if ($userProducer) {
if ($action == 'add') {
$userProducer->bookmark = 1;
Yii::$app->session->setFlash(
'success',
'Le producteur <strong>' . Html::encode(
$producer->name
) . '</strong> vient d\'être ajouté à vos favoris.'
);
} else {
$userProducer->bookmark = 0;
Yii::$app->session->setFlash(
'success',
'Le producteur <strong>' . Html::encode(
$producer->name
) . '</strong> vient d\'être supprimé de vos favoris.'
);
}
$userProducer->save();
$userProducer = $this->getLogic()->getUserProducerContainer()
->getBuilder()->createIfNotExist(GlobalParam::getCurrentUser(), $producer);

if ($action == 'add') {
$userProducer->bookmark = 1;
$this->setFlash(
'success',
'Le producteur <strong>' . Html::encode($producer->name) . '</strong> vient d\'être ajouté à vos favoris.'
);
} else {
$userProducer->bookmark = 0;
$this->setFlash(
'success',
'Le producteur <strong>' . Html::encode($producer->name) . '</strong> vient d\'être supprimé de vos favoris.'
);
} }
$userProducer->save();


$this->redirect(['site/index']);
return $this->redirect(['site/index']);
} }


/** /**
* Affiche les mentions légales du producteur. * Affiche les mentions légales du producteur.
*
* @return ProducerView
*/ */
public function actionMentions() public function actionMentions()
{ {
} }


return $this->render('mentions', [ return $this->render('mentions', [
'producer' => $producer
'producer' => $producer
]); ]);
} }


/** /**
* Affiche les conditions générales de vente du producteur. * Affiche les conditions générales de vente du producteur.
*
* @return ProducerView
*/ */
public function actionGcs() public function actionGcs()
{ {
} }


return $this->render('gcs', [ return $this->render('gcs', [
'producer' => $producer
'producer' => $producer
]); ]);
} }
} }

+ 90
- 100
producer/controllers/SubscriptionController.php View File



namespace producer\controllers; namespace producer\controllers;


use common\helpers\Debug;
use common\forms\SubscriptionForm;
use common\helpers\GlobalParam; use common\helpers\GlobalParam;
use common\logic\User\User\User;
use common\logic\PointSale\PointSale\PointSale;
use common\logic\Product\Product\Product;
use common\logic\Subscription\ProductSubscription\ProductSubscription;
use common\logic\Subscription\Subscription\SubscriptionSearch;
use common\logic\User\UserProducer\UserProducer; use common\logic\User\UserProducer\UserProducer;
use yii\base\UserException; use yii\base\UserException;
use yii\filters\AccessControl;
use yii\web\NotFoundHttpException;


class SubscriptionController extends ProducerBaseController class SubscriptionController extends ProducerBaseController
{ {
public function behaviors() public function behaviors()
{ {
return [ return [
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'allow' => true,
'roles' => ['@'],
]
],
'access' => [
'class' => AccessControl::class,
'rules' => [
[
'allow' => true,
'roles' => ['@'],
]
], ],
],
]; ];
} }


/** /**
* Liste les commandes récurrente du producteur.
*
* @return string
* Liste les abonnements de l'utilisateur.
*/ */
public function actionIndex() public function actionIndex()
{ {
if(\Yii::$app->user->isGuest) {
if (\Yii::$app->user->isGuest) {
$producer = $this->getProducer(); $producer = $this->getProducer();
return $this->redirect(Yii::$app->urlManagerFrontend->createAbsoluteUrl(['site/producer','id' => $producer->id])) ;
return $this->redirect($this->getUrlManagerFrontend()->createAbsoluteUrl(['site/producer', 'id' => $producer->id]));
} }


$searchModel = new SubscriptionSearch;
$searchModel = new SubscriptionSearch();
$searchModel->id_user = GlobalParam::getCurrentUserId(); $searchModel->id_user = GlobalParam::getCurrentUserId();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$dataProvider = $searchModel->search(\Yii::$app->request->queryParams);


return $this->render('index', [ return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider
'searchModel' => $searchModel,
'dataProvider' => $dataProvider
]); ]);
} }


public function actionAjaxProcess() public function actionAjaxProcess()
{ {
// form
$model = new SubscriptionForm;
$subscriptionRepository = $this->getLogic()->getSubscriptionContainer()->getRepository();
$model = new SubscriptionForm();
$model->id_producer = GlobalParam::getCurrentProducerId(); $model->id_producer = GlobalParam::getCurrentProducerId();
$model->id_user = GlobalParam::getCurrentUserId(); $model->id_user = GlobalParam::getCurrentUserId();


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


$idSubscription = (int)$posts['idSubscription']; $idSubscription = (int)$posts['idSubscription'];
$isUpdate = false; $isUpdate = false;
if ($idSubscription) { if ($idSubscription) {
$subscription = Subscription::findOne($idSubscription);
$subscription = $subscriptionRepository->getOneById($idSubscription);

if ($subscription) { if ($subscription) {
$model->id = $idSubscription; $model->id = $idSubscription;
$isUpdate = true; $isUpdate = true;
} }
} }


if ($model->load($posts) && $model->validate()
&& $model->save()) {
$subscription = Subscription::searchOne([
'id' => $model->id
]);
if ($model->load($posts) && $model->validate() && $model->save()) {

$subscription = $subscriptionRepository->getOneById($model->id);
$subscription->updateIncomingDistributions($isUpdate); $subscription->updateIncomingDistributions($isUpdate);


if ($isUpdate) { if ($isUpdate) {
Yii::$app->getSession()->setFlash('success', 'Abonnement modifié');
$this->setFlash('success', 'Abonnement modifié');
} else { } else {
Yii::$app->getSession()->setFlash('success', 'Abonnement ajouté');
$this->setFlash('success', 'Abonnement ajouté');
} }
} }
} }


/** /**
* Crée une commande récurrente. * Crée une commande récurrente.
*
* @return string
*/ */
public function actionForm($id = 0)
public function actionForm(int $id = 0)
{ {
if(\Yii::$app->user->isGuest) {
if (\Yii::$app->user->isGuest) {
$producer = $this->getProducer(); $producer = $this->getProducer();
return $this->redirect(Yii::$app->urlManagerFrontend->createAbsoluteUrl(['site/producer','id' => $producer->id])) ;
return $this->redirect($this->getUrlManagerFrontend()->createAbsoluteUrl(['site/producer', 'id' => $producer->id]));
} }


return $this->render('form', [ return $this->render('form', [
'idSubscription' => (int)$id
'idSubscription' => (int) $id
]); ]);
} }


/** /**
* Modifie une commande récurrente. * Modifie une commande récurrente.
*
* @param integer $id
* @return string
* @throws NotFoundHttpException
*/ */
public function actionUpdate($id) public function actionUpdate($id)
{ {
if(\Yii::$app->user->isGuest) {
if (\Yii::$app->user->isGuest) {
$producer = $this->getProducer(); $producer = $this->getProducer();
return $this->redirect(Yii::$app->urlManagerFrontend->createAbsoluteUrl(['site/producer','id' => $producer->id])) ;
return $this->redirect($this->getUrlManagerFrontend()->createAbsoluteUrl(['site/producer', 'id' => $producer->id]));
} }


// form
$subscriptionRepository = $this->getLogic()->getSubscriptionContainer()->getRepository();
$model = new SubscriptionForm; $model = new SubscriptionForm;
$subscription = Subscription::findOne($id);
$subscription = $subscriptionRepository->getOneById($id);

if ($subscription) { if ($subscription) {
$model->id = $id; $model->id = $id;
$model->id_producer = $subscription->id_producer; $model->id_producer = $subscription->id_producer;
$model->week_frequency = $subscription->week_frequency; $model->week_frequency = $subscription->week_frequency;


// produits // produits
$arrayProductsSubscription = ProductSubscription::searchAll([
'id_subscription' => $model->id
]);
$arrayProductsSubscription = ProductSubscription::searchAll([
'id_subscription' => $model->id
]);


foreach ($arrayProductsSubscription as $productSubscription) { foreach ($arrayProductsSubscription as $productSubscription) {
$model->products['product_' . $productSubscription->id_product] = $productSubscription->quantity; $model->products['product_' . $productSubscription->id_product] = $productSubscription->quantity;
throw new NotFoundHttpException('L\'abonnement est introuvable.', 404); throw new NotFoundHttpException('L\'abonnement est introuvable.', 404);
} }


// produits
$productsArray = Product::searchAll();
$productsArray = $this->getLogic()->getProductContainer()->getRepository()->get();


if ($model->load(Yii::$app->request->post()) && $model->validate()) {
if ($model->load(\Yii::$app->request->post()) && $model->validate()) {
if (!strlen($model->date_end)) { if (!strlen($model->date_end)) {
$model->date_end = null; $model->date_end = null;
} }
if ($model->save()) { if ($model->save()) {
Yii::$app->getSession()->setFlash('success', 'Abonnement modifié');
$this->setFlash('success', 'Abonnement modifié');

$subscription = $subscriptionRepository->getOneById($model->id);
$matchedDistributionsArray = $subscriptionRepository->searchMatchedIncomingDistributions($subscription);


$subscription = Subscription::findOne($model->id);
$matchedDistributionsArray = $subscription->searchMatchedIncomingDistributions();
if (count($matchedDistributionsArray)) { if (count($matchedDistributionsArray)) {
return $this->redirect( return $this->redirect(
[
'subscription/update-distributions',
'idSubscription' => $subscription->id,
'update' => true
]
[
'subscription/update-distributions',
'idSubscription' => $subscription->id,
'update' => true
]
); );
} else { } else {
return $this->redirect(['subscription/index']); return $this->redirect(['subscription/index']);
} }


return $this->render('update', [ return $this->render('update', [
'model' => $model,
'productsArray' => $productsArray
'model' => $model,
'productsArray' => $productsArray
]); ]);
} }


/** /**
* Supprime un abonnement
*
* @param integer $id
* Supprime un abonnement.
*/ */
public function actionDelete($id) public function actionDelete($id)
{ {
if(\Yii::$app->user->isGuest) {
if (\Yii::$app->user->isGuest) {
$producer = $this->getProducer(); $producer = $this->getProducer();
return $this->redirect(Yii::$app->urlManagerFrontend->createAbsoluteUrl(['site/producer','id' => $producer->id])) ;
return $this->redirect(\Yii::$app->urlManagerFrontend->createAbsoluteUrl(['site/producer', 'id' => $producer->id]));
} }


$subscription = Subscription::searchOne([
'id' => $id
]);
ProductSubscription::deleteAll(['id_subscription' => $id]);
$subscription = $this->getLogic()->getSubscriptionContainer()->getRepository()->getOneById($id);
ProductSubscription::deleteAll(['id_subscription' => $id]);
$subscription->deleteOrdersIncomingDistributions(); $subscription->deleteOrdersIncomingDistributions();
$subscription->delete(); $subscription->delete();
Yii::$app->getSession()->setFlash('success', 'Abonnement supprimé');
\Yii::$app->getSession()->setFlash('success', 'Abonnement supprimé');

return $this->redirect(['subscription/index']); return $this->redirect(['subscription/index']);
} }




$user = GlobalParam::getCurrentUser(); $user = GlobalParam::getCurrentUser();
$userProducer = UserProducer::searchOne([ $userProducer = UserProducer::searchOne([
'id_user' => GlobalParam::getCurrentUserId()
]);
'id_user' => GlobalParam::getCurrentUserId()
]);
$pointSale = false; $pointSale = false;


if ($idSubscription > 0) { if ($idSubscription > 0) {
$arrayProductsSubscription = ProductSubscription::searchAll([
'id_subscription' => $idSubscription
]);
$arrayProductsSubscription = ProductSubscription::searchAll([
'id_subscription' => $idSubscription
]);


$subscription = Subscription::findOne($idSubscription);
$subscription = $this->getLogic()->getSubscriptionContainer()->getRepository()->getOneById($idSubscription);


if ($subscription) { if ($subscription) {
if ($subscription->id_point_sale) { if ($subscription->id_point_sale) {
} }


// Produits // Produits
$productsArray = Product::searchAll();
$productsArray = Product::searchAll();
$indexProduct = 0; $indexProduct = 0;
foreach ($productsArray as &$product) { foreach ($productsArray as &$product) {
$quantity = 0; $quantity = 0;
$coefficientUnit = Product::$unitsArray[$product->unit]['coefficient'];
$coefficientUnit = Product::$unitsArray[$product->unit]['coefficient'];
if (isset($arrayProductsSubscription) && count($arrayProductsSubscription)) { if (isset($arrayProductsSubscription) && count($arrayProductsSubscription)) {
foreach ($arrayProductsSubscription as $productSubscription) { foreach ($arrayProductsSubscription as $productSubscription) {
if ($product->id == $productSubscription->id_product) { if ($product->id == $productSubscription->id_product) {
$coefficientUnit = Product::$unitsArray[$productSubscription->product->unit]['coefficient'];
$coefficientUnit = Product::$unitsArray[$productSubscription->product->unit]['coefficient'];
$quantity = $productSubscription->quantity * $coefficientUnit; $quantity = $productSubscription->quantity * $coefficientUnit;
} }
} }
} }


$product = array_merge( $product = array_merge(
$product->getAttributes(),
[
'index' => $indexProduct++,
'quantity_form' => $quantity,
'coefficient_unit' => $coefficientUnit,
'wording_unit' => Product::strUnit($product->unit, 'wording_unit', true),
'wording_short' => Product::strUnit($product->unit, 'wording_short'),
'price_with_tax' => $product->getPriceWithTax([
'user' => $user,
'user_producer' => $userProducer,
'point_sale' => $pointSale
]),
]
$product->getAttributes(),
[
'index' => $indexProduct++,
'quantity_form' => $quantity,
'coefficient_unit' => $coefficientUnit,
'wording_unit' => Product::strUnit($product->unit, 'wording_unit', true),
'wording_short' => Product::strUnit($product->unit, 'wording_short'),
'price_with_tax' => $product->getPriceWithTax([
'user' => $user,
'user_producer' => $userProducer,
'point_sale' => $pointSale
]),
]
); );
} }


$pointsSaleArray = PointSale::searchAll(); $pointsSaleArray = PointSale::searchAll();
foreach ($pointsSaleArray as &$pointSale) { foreach ($pointsSaleArray as &$pointSale) {
$pointSale = array_merge($pointSale->getAttributes(), [ $pointSale = array_merge($pointSale->getAttributes(), [
'userPointSale' => ($pointSale->userPointSale ? $pointSale->userPointSale[0] : '')
'userPointSale' => ($pointSale->userPointSale ? $pointSale->userPointSale[0] : '')
]); ]);
if ($pointSale['code'] && strlen($pointSale['code'])) { if ($pointSale['code'] && strlen($pointSale['code'])) {
$pointSale['code'] = '***'; $pointSale['code'] = '***';
$params['points_sale'] = $pointsSaleArray; $params['points_sale'] = $pointsSaleArray;


if ($idSubscription > 0) { if ($idSubscription > 0) {
$subscription = Subscription::searchOne([
'id' => $idSubscription
]);
$subscription = Subscription::searchOne([
'id' => $idSubscription
]);


if (!$subscription || $subscription->id_user != GlobalParam::getCurrentUserId()) { if (!$subscription || $subscription->id_user != GlobalParam::getCurrentUserId()) {
throw new UserException('Abonnement introuvable'); throw new UserException('Abonnement introuvable');


/** /**
* Vérifie le code saisi pour un point de vente. * Vérifie le code saisi pour un point de vente.
*
* @param integer $idPointSale
* @param string $code
* @return boolean
*/ */
public function actionAjaxValidateCodePointSale($idPointSale, $code) public function actionAjaxValidateCodePointSale($idPointSale, $code)
{ {

Loading…
Cancel
Save