|
- <?php
-
- /**
- * Copyright distrib (2018)
- *
- * contact@opendistrib.net
- *
- * Ce logiciel est un programme informatique servant à aider les producteurs
- * à distribuer leur production en circuits courts.
- *
- * Ce logiciel est régi par la licence CeCILL soumise au droit français et
- * respectant les principes de diffusion des logiciels libres. Vous pouvez
- * utiliser, modifier et/ou redistribuer ce programme sous les conditions
- * de la licence CeCILL telle que diffusée par le CEA, le CNRS et l'INRIA
- * sur le site "http://www.cecill.info".
- *
- * En contrepartie de l'accessibilité au code source et des droits de copie,
- * de modification et de redistribution accordés par cette licence, il n'est
- * offert aux utilisateurs qu'une garantie limitée. Pour les mêmes raisons,
- * seule une responsabilité restreinte pèse sur l'auteur du programme, le
- * titulaire des droits patrimoniaux et les concédants successifs.
- *
- * A cet égard l'attention de l'utilisateur est attirée sur les risques
- * associés au chargement, à l'utilisation, à la modification et/ou au
- * développement et à la reproduction du logiciel par l'utilisateur étant
- * donné sa spécificité de logiciel libre, qui peut le rendre complexe à
- * manipuler et qui le réserve donc à des développeurs et des professionnels
- * avertis possédant des connaissances informatiques approfondies. Les
- * utilisateurs sont donc invités à charger et tester l'adéquation du
- * logiciel à leurs besoins dans des conditions permettant d'assurer la
- * sécurité de leurs systèmes et ou de leurs données et, plus généralement,
- * à l'utiliser et l'exploiter dans les mêmes conditions de sécurité.
- *
- * Le fait que vous puissiez accéder à cet en-tête signifie que vous avez
- * pris connaissance de la licence CeCILL, et que vous en avez accepté les
- * termes.
- */
-
- namespace producer\controllers;
-
- use common\helpers\GlobalParam;
- use common\helpers\Mailjet;
- use common\helpers\Password;
- use common\logic\Distribution\Distribution\Distribution;
- use common\logic\Order\Order\Order;
- use common\logic\Order\ProductOrder\ProductOrder;
- use common\logic\PointSale\PointSale\PointSale;
- use common\logic\Producer\Producer\Producer;
- use common\logic\Product\Product\Product;
- use common\logic\User\CreditHistory\CreditHistory;
- use common\logic\User\User\User;
- use common\logic\User\UserProducer\UserProducer;
- use DateTime;
- use yii\base\UserException;
- use yii\data\ActiveDataProvider;
- use yii\web\NotFoundHttpException;
-
- class OrderController extends ProducerBaseController
- {
- var $enableCsrfValidation = false;
-
- public function behaviors()
- {
- return [];
- }
-
- public function actionOrder(int $id = 0, $date = '')
- {
- $params = [];
- $producer = $this->getProducer();
-
- if (\Yii::$app->user->isGuest && !$producer->option_allow_order_guest) {
- return $this->redirect(
- $this->getUrlManagerFrontend()->createAbsoluteUrl(['site/producer', 'id' => $producer->id])
- );
- }
-
- $order = $this->getOrderManager()->findOneOrderById($id);
- if ($order && $this->getOrderManager()->isOrderStateOpen($order)) {
- $params['order'] = $order;
- }
-
- if ($this->getDistributionManager()->isDistributionDateAvailable($producer, $date)) {
- $params['date'] = $date;
- }
-
- return $this->render('order', $params);
- }
-
- /**
- * Affiche l'historique des commandes de l'utilisateur.
- */
- public function actionHistory($type = 'incoming')
- {
- $queryHistoryArray = $this->getOrderManager()
- ->queryOrdersHistory($this->getProducer(), $this->getUserCurrent(), $type);
- $queryHistoryIncoming = $queryHistoryArray['incoming'];
- $queryHistoryPassed = $queryHistoryArray['passed'];
-
- $dataProviderOrders = new ActiveDataProvider([
- 'query' => ($type == 'incoming') ? $queryHistoryIncoming : $queryHistoryPassed,
- 'pagination' => [
- 'pageSize' => 10,
- ],
- ]);
-
- return $this->render('history', [
- 'dataProviderOrders' => $dataProviderOrders,
- 'orderOk' => \Yii::$app->getRequest()->get('orderOk', false),
- 'cancelOk' => \Yii::$app->getRequest()->get('cancelOk', false),
- 'type' => $type,
- 'countIncoming' => $queryHistoryIncoming->count(),
- 'countPassed' => $queryHistoryPassed->count(),
- ]);
- }
-
- public function actionRemoveProducer(int $id = 0)
- {
- $producer = $this->getProducerManager()->findOneProducerById($id);
-
- $this->getUserProducerManager()->updateActive(
- $this->getUserCurrent(),
- $producer,
- false
- );
-
- return $this->redirect(['order/index']);
- }
-
- /**
- * Crée une commande.
- */
- public function actionAjaxProcess()
- {
- \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
- $posts = \Yii::$app->request->post();
-
- $orderManager = $this->getOrderManager();
- $producerManager = $this->getProducerManager();
- $redirect = null;
- $producer = $this->getProducer();
- $idProducer = $producer->id;
- $order = $orderManager->instanciateOrder();
-
- if ($idProducer) {
- $this->_verifyProducerActive($idProducer);
- }
-
- if ($order->load($posts)) {
- $user = $this->getUserCurrent();
-
- $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();
-
- if ($order && !$order->online_payment_url) {
- if ($order->id_point_sale != $posts['Order']['id_point_sale']) {
- $order->id_point_sale = $posts['Order']['id_point_sale'];
- $order->date_update = date('Y-m-d H:i:s');
- }
- } else {
- // gestion user : option_allow_order_guest
- if (isset($posts['user']) && $posts['user']) {
- $userIndividualExist = User::searchOne([
- 'email' => $posts['user']['email'],
- 'type' => User::TYPE_INDIVIDUAL
- ]);
-
- if ($userIndividualExist) {
- $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.';
- return ['status' => 'error', 'errors' => [$errorUserGuest]];
- }
-
- $user = User::searchOne([
- 'email' => $posts['user']['email'],
- 'type' => User::TYPE_GUEST
- ]);
-
- if (!$user) {
- $user = new User;
- $user->id_producer = 0;
- $user->type = User::TYPE_GUEST;
- $password = Password::generate();
- $user->setPassword($password);
- $user->generateAuthKey();
- $user->username = $posts['user']['email'];
- $user->email = $posts['user']['email'];
- $user->name = $posts['user']['firstname'];
- $user->lastname = $posts['user']['lastname'];
- $user->phone = $posts['user']['phone'];
- $user->save();
- // liaison producer / user
- $producer->addUser($user->id, $idProducer);
- } else {
- $producer->addUser($user->id, $idProducer);
- }
- }
-
- $order = new Order;
- $order->load(\Yii::$app->request->post());
- $order->id_user = $user ? $user->id : null;
- $order->status = 'tmp-order';
- $order->date = date('Y-m-d H:i:s');
- $order->origin = Order::ORIGIN_USER;
- }
-
- $errors = $this->processForm($order, $user);
-
- if (count($errors)) {
- return ['status' => 'error', 'errors' => $errors];
- }
-
- if ($producerManager->isOnlinePaymentActiveAndTypeOrder($producer)) {
- $order = $orderManager->findOneOrderById($order->id);
- \Stripe\Stripe::setApiKey(
- $producerManager->getPrivateKeyApiStripe($producer)
- );
-
- $lineItems = [];
- foreach ($order->productOrder as $productOrder) {
- $product = $productOrder->product;
- $lineItems[] = [
- 'price_data' => [
- 'currency' => 'eur',
- 'product_data' => [
- 'name' => $product->name . ' (' . $productOrder->quantity . ' ' . $this->getProductManager()->strUnit(
- $product->unit,
- 'wording_short',
- true
- ) . ')',
- ],
- 'unit_amount' => $productOrder->price * 100 * $productOrder->quantity,
- ],
- 'quantity' => 1,
- ];
- }
-
- $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' => $this->getUrlManagerProducer()->createAbsoluteUrl(
- [
- 'order/confirm',
- 'idOrder' => $order->id,
- 'returnPayment' => 'success'
- ]
- ),
- 'cancel_url' => $this->getUrlManagerProducer()->createAbsoluteUrl(
- [
- 'order/confirm',
- 'idOrder' => $order->id,
- 'returnPayment' => 'cancel'
- ]
- ),
- ]);
- $redirect = $checkout_session->url;
-
- $order->online_payment_url = $redirect;
- $order->save();
- }
- }
-
- return ['status' => 'success', 'idOrder' => $order->id, 'redirect' => $redirect];
- }
-
- /**
- * Vérifie si un producteur est actif.
- */
- public function _verifyProducerActive($idProducer)
- {
- $producer = $this->getProducerManager()->findOneProducerById($idProducer);
- if ($producer && !$producer->active) {
- throw new NotFoundHttpException('Ce producteur est actuellement hors ligne.');
- }
- }
-
- /**
- * Traite le formulaire de création/modification de commande.
- */
- 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();
- $productsArray = [];
- $totalQuantity = 0;
- $producer = $this->getProducer();
-
- $isNewOrder = false;
- if (!$order->id) {
- $isNewOrder = true;
- }
-
- foreach ($posts['products'] as $key => $quantity) {
- $product = $productManager->findOneProductById((int)$key);
-
- $totalQuantity += $quantity;
- if ($product && $quantity) {
- $productsArray[] = $product;
- }
- }
-
- $errorDate = false;
- if (isset($order->id_distribution)) {
- $distribution = $distributionManager->findOneDistributionById($order->id_distribution);
- if ($order->getState() != Order::STATE_OPEN) {
- $errorDate = true;
- }
- }
-
- $errorPointSale = false;
- if (isset($distribution) && $distribution) {
- $pointSale = $pointSaleManager->findOnePointSaleById($posts['Order']['id_point_sale']);
- $pointSaleDistribution = $pointSaleDistributionManager->findOnePointSaleDistribution($distribution, $pointSale);
-
- if (!$pointSaleDistribution || !$pointSaleDistribution->delivery) {
- $errorPointSale = true;
- }
-
- if ($pointSale) {
- if (strlen($pointSale->code) && !$pointSaleManager->validateCode($pointSale, $posts['code_point_sale'])) {
- $errorPointSale = true;
- }
- } else {
- $errorPointSale = true;
- }
-
- $userPointSale = $userPointSaleManager->findOneUserPointSale(GlobalParam::getCurrentUser(), $pointSale);
- if ($pointSale->restricted_access && !$userPointSale) {
- $errorPointSale = true;
- }
- }
-
- $errors = [];
-
- if ($order->validate() && count($productsArray) && !$errorDate && !$errorPointSale) {
- $userProducer = $userProducerManager->findOneUserProducer($user, $producer);
- $pointSale = $pointSaleManager->findOnePointSaleById($order->id_point_sale);
-
- // commentaire point de vente
- $order->comment_point_sale = ($pointSale && strlen($pointSale->getComment())) ?
- $pointSale->getComment() : '';
-
- // la commande est automatiquement réactivée lors d'une modification
- $order->date_delete = null;
-
- // delivery
- $order->delivery_home = isset($posts['Order']['delivery_home']) ? $posts['Order']['delivery_home'] : false;
- $order->delivery_address = (isset($posts['Order']['delivery_address']) && $order->delivery_home) ? $posts['Order']['delivery_address'] : null;
-
- // comment
- $order->comment = isset($posts['Order']['comment']) ? $posts['Order']['comment'] : null;
-
- // sauvegarde de la commande
- $order->save();
-
- $orderManager->generateOrderReference($order);
- $orderManager->changeOrderStatus($order, 'new-order', 'user');
- $producerManager->addUser($user, $producer);
-
- // suppression de tous les enregistrements ProductOrder
- if (!is_null($order)) {
- $productOrderManager->deleteProductOrdersByOrder($order);
-
- if (isset($order->productOrder)) {
- foreach ($order->productOrder as $productOrder) {
- $unitsArray[$productOrder->id_product] = $productOrder->unit;
- }
- }
- }
-
- $availableProducts = $productManager->findProductsByDistribution($distribution);
- foreach ($productsArray as $product) {
- if (isset($availableProducts[$product->id])) {
- $productOrder = new ProductOrder();
- $productOrder->id_order = $order->id;
- $productOrder->id_product = $product->id;
- $productOrder->id_tax_rate = $product->taxRate->id;
- $unit = (!is_null(
- $order
- ) && isset($unitsArray[$product->id])) ? $unitsArray[$product->id] : $product->unit;
- $coefficient = Product::$unitsArray[$unit]['coefficient'];
- $quantity = ((float)$posts['products'][$product->id]) / $coefficient;
- if ($availableProducts[$product->id]['quantity_max'] && $quantity > $availableProducts[$product->id]['quantity_remaining']) {
- $quantity = $availableProducts[$product->id]['quantity_remaining'];
- }
- $productOrder->quantity = $quantity;
- $productOrder->price = $product->getPrice([
- 'user' => GlobalParam::getCurrentUser(),
- 'user_producer' => $userProducer,
- 'point_sale' => $pointSale,
- 'quantity' => $quantity
- ]);
- $productOrder->unit = $product->unit;
- $productOrder->step = $product->step;
- $productOrder->save();
- }
- }
-
- // lien utilisateur / point de vente
- $pointSaleManager->addUser($user, $pointSale);
-
- // credit
- $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 &&
- (($creditFunctioning == Producer::CREDIT_FUNCTIONING_OPTIONAL && $posts['use_credit']) ||
- $creditFunctioning == Producer::CREDIT_FUNCTIONING_MANDATORY ||
- ($creditFunctioning == Producer::CREDIT_FUNCTIONING_USER && $userProducer->credit_active)
- )) {
- $orderManager->changeOrderStatus($order, 'waiting-paiement-by-credit', 'user');
-
- // à payer
- if ($orderManager->getPaymentStatus($order) == Order::PAYMENT_UNPAID) {
- if (!is_null($creditLimit) && $amountRemaining > $creditUser - $creditLimit) {
- $amountRemaining = $creditUser - $creditLimit;
- }
-
- if ($amountRemaining > 0) {
- $creditHistoryManager->createCreditHistory(
- CreditHistory::TYPE_PAYMENT,
- $amountRemaining,
- $producer,
- GlobalParam::getCurrentUser(),
- GlobalParam::getCurrentUser()
- );
- $orderManager->changeOrderStatus($order, 'paid-by-credit', 'user');
- } else {
- $orderManager->changeOrderStatus($order, 'waiting-paiement-on-delivery', 'user');
- }
- } // surplus à rembourser
- elseif ($order->getPaymentStatus() == Order::PAYMENT_SURPLUS) {
- $amountSurplus = $orderManager->getAmount($order, Order::AMOUNT_SURPLUS);
- $creditHistoryManager->createCreditHistory(
- CreditHistory::TYPE_REFUND,
- $amountSurplus,
- $producer,
- GlobalParam::getCurrentUser(),
- GlobalParam::getCurrentUser()
- );
- }
- } else {
- $orderManager->changeOrderStatus($order, 'waiting-paiement-on-delivery', 'user');
- }
-
- $paramsEmail = [
- 'from_email' => $producerManager->getEmailOpendistrib($producer),
- 'from_name' => $producer->name,
- 'to_email' => $user->email,
- 'to_name' => $userManager->getUsername($user),
- '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
- ]
- ];
-
- /*
- * Envoi email de confirmation
- */
- if ($isNewOrder) {
- // au client
- if ($producerManager->getConfig('option_email_confirm')) {
- Mailjet::sendMail($paramsEmail);
- }
-
- // au producteur
- $contactProducer = $producerManager->getMainContact($producer);
- if ($producerManager->getConfig('option_email_confirm_producer') && $contactProducer && strlen(
- $contactProducer->email
- )) {
- $paramsEmail['to_email'] = $contactProducer->email;
- $paramsEmail['to_name'] = $contactProducer->name;
- $paramsEmail['content_view_text'] = '@common/mail/orderConfirmProducer-text.php';
- $paramsEmail['content_view_html'] = '@common/mail/orderConfirmProducer-html.php';
- Mailjet::sendMail($paramsEmail);
- }
- }
-
- $orderManager->setTillerSynchronization($order);
- }
-
-
- if (!count($productsArray)) {
- $errors[] = "Vous n'avez choisi aucun produit";
- }
- if ($errorDate) {
- $errors[] = "Vous ne pouvez pas commander pour cette date.";
- }
- if ($errorPointSale) {
- $errors[] = "Point de vente invalide.";
- }
-
- return $errors;
- }
-
- /**
- * Annule une commande.
- */
- public function actionCancel(int $id)
- {
- $orderManager = $this->getOrderManager();
- $order = $this->getOrderManager()->findOneOrderById($id);
-
- if (!$order) {
- throw new \yii\web\NotFoundHttpException('Commande introuvable');
- }
-
- if ($orderManager->isOrderStateOpen($order)) {
- throw new UserException('Vous ne pouvez plus annuler cette commande.');
- }
-
- if ($orderManager->isOrderbelongsToUser($order, GlobalParam::getCurrentUser())) {
- $orderManager->deleteOrder($order);
- $this->setFlash('success', 'Votre commande a bien été annulée.');
- }
-
- return $this->redirect($this->getUrlManagerProducer()->createUrl(['order/history']));
- }
-
- /**
- * Page de confirmation de commande.
- */
- public function actionConfirm(int $idOrder, string $returnPayment = '')
- {
- $orderManager = $this->getOrderManager();
- $order = $orderManager->findOneOrderById($idOrder);
- $producer = $this->getProducer();
-
- if (!$order || (!$orderManager->isOrderBelongsToUser($order, GlobalParam::getCurrentUser()) && !$producer->option_allow_order_guest)) {
- throw new \yii\base\UserException('Commande introuvable.');
- }
-
- return $this->render('confirm', [
- 'order' => $order,
- 'returnPayment' => $returnPayment
- ]);
- }
-
- /**
- * Vérifie le code saisi pour un point de vente.
- */
- public function actionAjaxValidateCodePointSale(int $idPointSale, string $code)
- {
- \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
- $pointSaleManager = $this->getPointSaleManager();
- $pointSale = $pointSaleManager->findOnePointSaleById($idPointSale);
-
- if ($pointSale && $pointSaleManager->validateCode($pointSale, $code)) {
- return 1;
- }
-
- return 0;
- }
-
- public function actionAjaxInfos(string $date = '', int $pointSaleId = 0)
- {
- \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
- $user = GlobalParam::getCurrentUser();
- $producer = $this->getProducer();
- $pointSale = $this->getPointSaleManager()->findOnePointSaleById($pointSaleId);
- $order = $this->getOrderUser($date, $pointSale);
-
- return $this->buildJsonAjaxInfos($date, $producer, $pointSale, $user, $order);
- }
-
- public function buildJsonAjaxInfos(
- string $date,
- Producer $producer,
- PointSale $pointSale = null,
- User $user = null,
- Order $order = null
- )
- {
- $json = [];
- $format = 'Y-m-d';
- $dateObject = DateTime::createFromFormat($format, $date);
-
- $json['producer'] = $this->ajaxInfosProducer($producer);
- $json['distributions'] = $this->ajaxInfosDistributions($producer, $pointSale);
- $json['orders'] = $this->ajaxInfosOrders($producer);
- $json['user'] = $this->ajaxInfosUser($producer);
- $json['points_sale'] = $this->ajaxInfosPointsSale($producer);
-
- if ($dateObject && $dateObject->format($format) === $date) {
- $distribution = $this->getDistributionManager()->createDistributionIfNotExist($producer, $date);
- $json['distribution'] = $distribution;
- $json['points_sale'] = $this->ajaxInfosPointsSale($producer, $distribution);
- $json['categories'] = $this->ajaxInfosProductCategories($producer);
- $json['products'] = $this->ajaxInfosProducts($producer, $distribution, $pointSale, $user, $order);
- }
-
- return $json;
- }
-
- public function ajaxInfosProducer(Producer $producer)
- {
- return [
- '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
- ];
- }
-
- public function ajaxInfosDistributions(Producer $producer, PointSale $pointSaleCurrent = null)
- {
- $distributionManager = $this->getDistributionManager();
- $dateMini = date('Y-m-d');
-
- $distributionsArray = Distribution::searchAll([
- 'active' => 1,
- 'id_producer' => $producer->id
- ], [
- 'conditions' => ['date > :date'],
- 'params' => [':date' => $dateMini],
- 'join_with' => ['pointSaleDistribution'],
- ]);
- $distributionsArray = $distributionManager->filterDistributionsByDateDelay($distributionsArray);
-
- // Filtre par point de vente
- if ($pointSaleCurrent && $producer->option_order_entry_point == Producer::ORDER_ENTRY_POINT_POINT_SALE) {
- $distributionsArrayFilterPointSale = [];
- for ($i = 0; $i < count($distributionsArray); $i++) {
- $distribution = $distributionsArray[$i];
- if ($distributionManager->isPointSaleActive($distribution, $pointSaleCurrent)) {
- $countOrders = Order::searchCount([
- 'id_distribution' => $distribution->id,
- 'id_point_sale' => $pointSaleCurrent->id
- ]);
- $orderUserPointSale = $this->_getOrderUser($distribution->date, $pointSaleId);
-
- if (!$pointSaleCurrent->maximum_number_orders
- || ($orderUserPointSale && $orderUserPointSale->id_point_sale == $pointSaleId)
- || ($pointSaleCurrent->maximum_number_orders &&
- ($countOrders < $pointSaleCurrent->maximum_number_orders))) {
- $distributionsArrayFilterPointSale[] = $distribution;
- }
- }
- }
-
- return $distributionsArrayFilterPointSale;
- } else {
- return $distributionsArray;
- }
- }
-
- public function ajaxInfosOrders(Producer $producer, PointSale $pointSaleCurrent = null): array
- {
- $producerManager = $this->getProducerManager();
- $orderManager = $this->getOrderManager();
-
- $dateMini = date('Y-m-d');
- $ordersUserArray = [];
- if (GlobalParam::getCurrentUserId() && !$producerManager->isOnlinePaymentActiveAndTypeOrder($producer)) {
- $conditionsOrdersUser = [
- 'distribution.date > :date'
- ];
- $paramsOrdersUser = [
- ':date' => $dateMini
- ];
-
- if ($pointSaleCurrent && $producer->option_order_entry_point == Producer::ORDER_ENTRY_POINT_POINT_SALE) {
- $conditionsOrdersUser[] = 'order.id_point_sale = :id_point_sale';
- $paramsOrdersUser[':id_point_sale'] = $pointSaleCurrent->id;
- }
-
- $ordersUserArray = Order::searchAll([
- 'id_user' => GlobalParam::getCurrentUserId()
- ], [
- 'conditions' => $conditionsOrdersUser,
- 'params' => $paramsOrdersUser
- ]);
- }
-
- if (is_array($ordersUserArray) && count($ordersUserArray)) {
- foreach ($ordersUserArray as &$order) {
- $order = array_merge($order->getAttributes(), [
- 'amount_total' => $orderManager->getAmountWithTax($order, Order::AMOUNT_TOTAL),
- 'date_distribution' => $order->distribution->date,
- 'pointSale' => $order->pointSale->getAttributes()
- ]);
- }
- }
-
- return $ordersUserArray;
- }
-
- public function ajaxInfosUser(Producer $producer)
- {
- $userProducerManager = $this->getUserProducerManager();
- $producerManager = $this->getProducerManager();
-
- $user = GlobalParam::getCurrentUser();
- $userProducer = $userProducerManager->findOneUserProducer($user, $producer);
-
- if ($user && !$userProducer) {
- $userProducer = $producerManager->addUser($user, $producer);
- }
-
- $jsonUser = false;
- if ($user && $userProducer) {
- $jsonUser = [
- 'address' => $user->address,
- 'credit' => $userProducer->credit,
- 'credit_active' => $userProducer->credit_active,
- ];
- }
-
- return $jsonUser;
- }
-
- private function ajaxInfosPointsSale($idProducer, $distribution = false)
- {
- $userManager = $this->getUserManager();
- $producerManager = $this->getProducerManager();
-
- $user = GlobalParam::getCurrentUser();
- $pointsSaleArray = PointSale::find();
-
- if ($distribution) {
- $pointsSaleArray = $pointsSaleArray->joinWith([
- 'pointSaleDistribution' => function ($query) use (
- $distribution
- ) {
- $query->where(
- [
- 'id_distribution' => $distribution->id,
- 'delivery' => 1
- ]
- );
- }
- ]);
- }
-
- if (GlobalParam::getCurrentUserId()) {
- $pointsSaleArray = $pointsSaleArray->with([
- 'userPointSale' => function ($query) {
- $query->onCondition(
- ['id_user' => GlobalParam::getCurrentUserId()]
- );
- }
- ]);
- }
-
- $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();
-
- $creditFunctioningProducer = $producerManager->getConfig('credit_functioning');
- $position = 0;
-
- foreach ($pointsSaleArray as &$pointSale) {
- $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] : '')
- ]);
- if ($pointSale['code'] && strlen($pointSale['code'])) {
- $pointSale['code'] = '***';
- }
- if (!strlen($pointSale['credit_functioning'])) {
- $pointSale['credit_functioning'] = $creditFunctioningProducer;
- }
-
- if ($distribution) {
- $pointSale['count_orders'] = (int)Order::searchCount([
- 'id_distribution' => $distribution->id,
- 'id_point_sale' => $pointSale['id']
- ]);
- }
-
- $pointSale['position'] = $position;
- $position++;
- }
-
- $favoritePointSale = false;
- if ($user) {
- $favoritePointSale = $userManager->getUserFavoritePointSale($user);
- }
-
- if ($favoritePointSale) {
- for ($i = 0; $i < count($pointsSaleArray); $i++) {
- if ($pointsSaleArray[$i]['id'] == $favoritePointSale->id) {
- $theFavoritePointSale = $pointsSaleArray[$i];
- unset($pointsSaleArray[$i]);
- }
- }
-
- if (isset($theFavoritePointSale)) {
- $pointsSaleArray = array_reverse($pointsSaleArray, false);
- $pointsSaleArray[] = $theFavoritePointSale;
- $pointsSaleArray = array_reverse($pointsSaleArray, false);
- }
- }
-
- return $pointsSaleArray;
- }
-
- public function ajaxInfosProductCategories(Producer $producer)
- {
- $categoriesArray = $this->getProductCategoryManager()->findProductCategoriesAsArray();
- $countProductsWithoutCategory = $this->getProductManager()->countProductsWithoutCategory($producer);
-
- if ($countProductsWithoutCategory) {
- array_unshift($categoriesArray, ['id' => null, 'name' => 'Catégorie par défaut']);
- }
-
- return $categoriesArray;
- }
-
- public function ajaxInfosProducts(
- Producer $producer,
- Distribution $distribution,
- PointSale $pointSale,
- User $user = null,
- Order $order = null
- )
- {
- $productManager = $this->getProductManager();
- $orderManager = $this->getOrderManager();
- $ordersArray = $this->getOrderManager()->findOrdersByDistribution($distribution);
-
- $productsArray = Product::find()
- ->where([
- 'id_producer' => $producer->id,
- 'product.active' => 1,
- ]);
-
- $productsArray = $productsArray->joinWith([
- 'productDistribution' => function ($query) use (
- $distribution
- ) {
- $query->andOnCondition(
- 'product_distribution.id_distribution = ' . $distribution->id
- );
- },
- 'productPrice'
- ])
- ->orderBy('product_distribution.active DESC, order ASC')
- ->all();
-
- $productsArrayFilter = [];
-
- // filtre sur les points de vente
- foreach ($productsArray as $product) {
- if ($productManager->isAvailableOnPointSale($product, $pointSale)) {
- $productsArrayFilter[] = $product;
- }
- }
-
- $indexProduct = 0;
- foreach ($productsArrayFilter as $key => &$product) {
- $productObject = $product;
- $product = array_merge(
- $product->getAttributes(),
- [
- 'unit_coefficient' => Product::$unitsArray[$product->unit]['coefficient'],
- 'prices' => $productManager->getPriceArray($product, $user, $pointSale),
- 'productDistribution' => $product['productDistribution'],
- 'productPointSale' => $product['productPointSale'],
- ]
- );
-
- $coefficient_unit = Product::$unitsArray[$product['unit']]['coefficient'];
-
- if (is_null($product['photo'])) {
- $product['photo'] = '';
- }
-
- $product['quantity_max'] = $product['productDistribution'][0]['quantity_max'];
- $quantityOrder = $orderManager->getProductQuantity($productObject, $ordersArray);
- $product['quantity_ordered'] = $quantityOrder;
- $product['quantity_remaining'] = $product['quantity_max'] - $quantityOrder;
- $product['wording_unit'] = $productManager->strUnit($product['unit'], 'wording_unit', true);
- $product['wording_unit_ref'] = $productManager->strUnit($product['unit'], 'wording_short', true);
-
- if ($order) {
- $quantityOrderUser = $orderManager->getProductQuantity($productObject, [$order], true);
- $product['quantity_ordered'] = $quantityOrder;
- $product['quantity_remaining'] = $product['quantity_max'] - $quantityOrder + $quantityOrderUser;
- $product['quantity_form'] = $quantityOrderUser * $coefficient_unit;
- foreach ($order->productOrder as $productOrder) {
- if ($productOrder->id_product == $product['id']) {
- $product['wording_unit'] = $productManager->strUnit($productOrder->unit, 'wording_unit', true);
- $product['step'] = $productOrder->step;
- }
- }
- } else {
- $product['quantity_form'] = 0;
- $product['wording_unit'] = $productManager->strUnit($product['unit'], 'wording_unit', true);
- }
- $product['coefficient_unit'] = $coefficient_unit;
-
- if ($product['quantity_remaining'] < 0) {
- $product['quantity_remaining'] = 0;
- }
- $product['index'] = $indexProduct++;
- }
-
- return $productsArrayFilter;
- }
-
- private function getOrderUser(string $date, PointSale $pointSale = null)
- {
- $orderManager = $this->getOrderManager();
-
- $orderUser = false;
- if (GlobalParam::getCurrentUserId()) {
- $conditionOrderUser = [
- 'distribution.date' => $date,
- 'id_user' => GlobalParam::getCurrentUserId(),
- ];
-
- if ($pointSale) {
- $conditionOrderUser['id_point_sale'] = $pointSale;
- }
-
- $orderUser = Order::searchOne($conditionOrderUser);
-
- if ($orderUser && $orderUser->online_payment_url) {
- $orderUser = false;
- }
- }
-
- if ($orderUser) {
- $json['order'] = array_merge($orderUser->getAttributes(), [
- 'amount_total' => $orderManager->getAmountWithTax($orderUser, Order::AMOUNT_TOTAL),
- 'amount_paid' => $orderManager->getAmount($orderUser, Order::AMOUNT_PAID),
- ]);
- }
-
- return $orderUser;
- }
- }
|