- <?php
-
-
-
- namespace producer\controllers;
-
- use common\helpers\GlobalParam;
- use common\helpers\Image;
- use common\helpers\Password;
- use domain\Config\Unit\UnitDefinition;
- use domain\Distribution\Distribution\Distribution;
- use domain\Feature\Feature\Feature;
- use domain\Order\Order\Order;
- use domain\Order\Order\OrderRepositoryQuery;
- use domain\Order\OrderStatus\OrderStatus;
- use domain\Order\ProductOrder\ProductOrder;
- use domain\PointSale\PointSale\PointSale;
- use domain\Producer\Producer\Producer;
- use domain\Product\Product\Product;
- use DateTime;
- use domain\User\User\User;
- use yii\base\UserException;
- use yii\data\ActiveDataProvider;
- use yii\filters\AccessControl;
- use yii\web\NotFoundHttpException;
-
- class OrderController extends ProducerBaseController
- {
- var $enableCsrfValidation = false;
-
- public function behaviors()
- {
- return [
- 'access' => [
- 'class' => AccessControl::class,
- 'only' => [
- 'history',
- 'remove-producer',
- 'cancel'
- ],
- 'rules' => [
- [
- 'allow' => true,
- 'roles' => ['@']
- ]
- ],
- ],
- ];
- }
-
- public function actionOrder(int $id = 0, string $date = '', int $idPointSale = null)
- {
- $orderModule = $this->getOrderModule();
- $distributionModule = $this-> getDistributionModule();
-
- $params = [];
- $producer = $this->getProducerCurrent();
-
- if (\Yii::$app->user->isGuest && !$producer->option_allow_order_guest) {
- return $this->redirect(
- $this->getUrlManagerFrontend()->createAbsoluteUrl([
- 'site/producer',
- 'id' => $producer->id,
- 'return_url' => \Yii::$app->urlManagerProducer->createAbsoluteUrl(['order/order', 'slug_producer' => $this->getProducerCurrent()->slug])
- ])
- );
- }
-
- $order = $orderModule->getRepository()->findOneOrderById($id);
- if ($order && $orderModule->getRepository()->isOrderStateOpen($order)) {
- $params['order'] = $order;
- }
-
- if ($distributionModule->isDistributionDateAvailable($date)) {
- $params['date'] = $date;
- }
-
- if($idPointSale) {
- $params['idPointSale'] = $idPointSale;
- }
-
- return $this->render('order', $params);
- }
-
-
-
- public function actionHistory($type = 'incoming')
- {
- $queryHistoryArray = $this->getOrderModule()
- ->queryOrdersHistory($this->getProducerCurrent(), $this->getUserCurrent());
- $queryHistoryIncoming = $queryHistoryArray['incoming'];
- $queryHistoryPassed = $queryHistoryArray['passed'];
-
- $dataProviderOrders = new ActiveDataProvider([
- 'query' => ($type == 'incoming') ? $queryHistoryIncoming->query() : $queryHistoryPassed->query(),
- '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->getProducerModule()->findOneProducerById($id);
-
- $this->getUserProducerModule()->updateActive(
- $this->getUserCurrent(),
- $producer,
- false
- );
-
- return $this->redirect(['order/index']);
- }
-
-
-
- public function actionAjaxProcess()
- {
- \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
- $posts = \Yii::$app->request->post();
-
- $orderModule = $this->getOrderModule();
- $producerModule = $this->getProducerModule();
- $userModule = $this->getUserModule();
- $productOrderModule = $this->getProductOrderModule();
-
- $producer = $this->getProducerCurrent();
- $redirect = null;
- $idProducer = $producer->id;
- $order = new Order;
-
- 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')
- ->andWhere(OrderRepositoryQuery::getSqlFilterIsValid())
- ->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'];
- }
- } else {
-
- 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;
- $userModule->setPassword($user, Password::generate());
- $userModule->generateAuthKey($user);
- $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();
-
- $producerModule->addUser($user, $producer);
- } else {
- $producerModule->addUser($user, $producer);
- }
- }
-
- $order = new Order;
- $order->load(\Yii::$app->request->post());
- $order->id_user = $user ? $user->id : null;
- $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 ($producerModule->getSolver()->isOnlinePaymentActive($producer) && $posts['payment_method'] == 'online') {
- $order = $orderModule->findOneOrderById($order->id);
- \Stripe\Stripe::setApiKey(
- $producerModule->getPrivateKeyApiStripe($producer)
- );
-
- $lineItems = [];
- foreach ($order->productOrder as $productOrder) {
- $product = $productOrder->product;
- $lineItems[] = [
- 'price_data' => [
- 'currency' => 'eur',
- 'product_data' => [
- 'name' => $product->name . ' (' . $productOrder->quantity . ' ' . $this->getProductModule()->getSolver()->strUnit(
- $product,
- UnitDefinition::WORDING_SHORT,
- true
- ) . ')',
- ],
- 'unit_amount' => intval($productOrderModule->getSolver()->getPriceWithTax($productOrder) * 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];
- }
-
-
-
- public function _verifyProducerActive($idProducer)
- {
- $producer = $this->getProducerModule()->findOneProducerById($idProducer);
- if ($producer && !$producer->active) {
- throw new NotFoundHttpException('Ce producteur est actuellement hors ligne.');
- }
- }
-
-
-
- public function processForm($order, $user)
- {
- $productModule = $this->getProductModule();
- $distributionModule = $this-> getDistributionModule();
- $pointSaleDistributionModule = $this->getPointSaleDistributionModule();
- $pointSaleModule = $this->getPointSaleModule();
- $userPointSaleModule = $this->getUserPointSaleModule();
- $userProducerModule = $this->getUserProducerModule();
- $orderModule = $this->getOrderModule();
- $producerModule = $this->getProducerModule();
- $productOrderModule = $this->getProductOrderModule();
- $userModule = $this->getUserModule();
- $paymentManager = $this->getPaymentModule();
-
- $posts = \Yii::$app->request->post();
- $productsArray = [];
- $totalQuantity = 0;
- $producer = $this->getProducerCurrent();
-
- $isNewOrder = false;
- if (!$order->id) {
- $isNewOrder = true;
- }
-
- foreach ($posts['products'] as $key => $quantity) {
- $product = $productModule->findOneProductById((int)$key);
-
- $totalQuantity += $quantity;
- if ($product && $quantity) {
- $productsArray[] = $product;
- }
- }
-
- $errorDate = false;
- if (isset($order->id_distribution)) {
- $distribution = $distributionModule->findOneDistributionById($order->id_distribution);
- if ($orderModule->getState($order) != Order::STATE_OPEN) {
- $errorDate = true;
- }
- }
-
- $errorPointSale = false;
- if (isset($distribution) && $distribution) {
- $order->populateDistribution($distribution);
- $pointSale = $pointSaleModule->findOnePointSaleById($posts['Order']['id_point_sale']);
- $pointSaleDistribution = $pointSaleDistributionModule->findOnePointSaleDistribution($distribution, $pointSale);
-
- if (!$pointSaleDistribution || !$pointSaleDistribution->delivery) {
- $errorPointSale = true;
- }
-
- if ($pointSale) {
- if (strlen($pointSale->code) && !$pointSaleModule->validateCode($pointSale, $posts['code_point_sale'])) {
- $errorPointSale = true;
- }
- } else {
- $errorPointSale = true;
- }
-
- $userPointSale = $userPointSaleModule->findOneUserPointSale(GlobalParam::getCurrentUser(), $pointSale);
- if ($pointSale && $pointSale->restricted_access && !$userPointSale) {
- $errorPointSale = true;
- }
- }
-
- $errors = [];
-
- if ($order->validate() && count($productsArray) && !$errorDate && !$errorPointSale) {
- $userProducer = $userProducerModule->findOneUserProducer($user);
- $pointSale = $pointSaleModule->findOnePointSaleById($order->id_point_sale);
-
- $order->comment_point_sale = ($pointSale && strlen($pointSaleModule->getComment($pointSale))) ?
- $pointSaleModule->getComment($pointSale) : '';
-
-
- if($order->isOrderStatusCanceled()) {
- $orderModule->getManager()->changeOrderStatus($order, OrderStatus::ALIAS_UPDATED, $this->getUserCurrent());
- }
-
- $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;
-
-
- if($order->delivery_address && !$user->address) {
- $user->address = $order->delivery_address;
- $user->save();
- }
-
- $order->comment = isset($posts['Order']['comment']) ? $posts['Order']['comment'] : null;
- $order->save();
-
- $orderModule->generateOrderReference($order);
- if($isNewOrder) {
- $orderModule->getManager()->changeOrderStatus($order, OrderStatus::ALIAS_ORDERED, $user);
- }
- else {
- $orderModule->getManager()->changeOrderStatus($order, OrderStatus::ALIAS_UPDATED, $user);
- }
- $producerModule->addUser($user, $producer);
-
-
- if (!is_null($order)) {
- $productOrderModule->deleteProductOrdersByOrder($order);
-
- if (isset($order->productOrder)) {
- foreach ($order->productOrder as $productOrder) {
- $unitsArray[$productOrder->id_product] = $productOrder->unit;
- }
- }
- }
-
- $availableProducts = $orderModule->findProductDistributionsByDistribution($distribution);
- foreach ($productsArray as $product) {
- if (isset($availableProducts[$product->id])
- && $availableProducts[$product->id]
- && $availableProducts[$product->id]['active']) {
-
- $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;
- $quantityRemaining = $orderModule->getResolver()->getProductQuantityRemaining($product, $order->distribution);
- if(!is_null($quantityRemaining) && $quantity > $quantityRemaining) {
- $quantity = $quantityRemaining;
- }
- $productOrder->quantity = $quantity;
- $productOrder->price = $productModule->getPrice($product, [
- 'user' => $this->getUserCurrent(),
- 'user_producer' => $userProducer,
- 'point_sale' => $pointSale,
- 'quantity' => $quantity
- ]);
- $productOrder->unit = $product->unit;
- $productOrder->step = $product->step;
-
- if($quantity) {
- $productOrder->save();
- }
- }
- }
-
-
- $pointSaleModule->addUser($user, $pointSale);
-
-
- $credit = $producerModule->getConfig('credit');
- $creditFunctioning = $producerModule->getPointSaleCreditFunctioning($pointSale);
- $order = $orderModule->findOneOrderById($order->id);
- $orderModule->initOrder($order);
-
- if ($credit
- && $this->getUserCurrent()
- && $pointSale->payment_method_credit
- && $posts['payment_method'] == 'credit'
- && ($creditFunctioning == Producer::CREDIT_FUNCTIONING_OPTIONAL ||
- $creditFunctioning == Producer::CREDIT_FUNCTIONING_MANDATORY ||
- ($creditFunctioning == Producer::CREDIT_FUNCTIONING_USER && $userProducer->credit_active)
- )) {
-
- if ($orderModule->getPaymentStatus($order) == Order::PAYMENT_UNPAID) {
- $paymentManager->payOrderByCredit($order, $this->getUserCurrent(), true);
- }
- elseif ($orderModule->getPaymentStatus($order) == Order::PAYMENT_SURPLUS) {
- $paymentManager->refundSurplusOrderCredit($order, $this->getUserCurrent());
- }
- }
-
-
-
- $emailSubject = 'Confirmation de commande';
- $emailContentParams = [
- 'order' => $order,
- 'pointSale' => $pointSale,
- 'distribution' => $distribution,
- 'user' => $user,
- 'producer' => $producer
- ];
-
-
- if ($producerModule->getConfig('option_email_confirm')) {
- \Yii::$app->mailerService->sendFromProducer(
- $emailSubject,
- 'orderConfirm',
- $emailContentParams,
- $user->email,
- $producer
- );
-
- }
-
-
- $contactProducer = $producerModule->getMainContact($producer);
- if ($producerModule->getConfig('option_email_confirm_producer') && $contactProducer && strlen(
- $contactProducer->email
- )) {
-
- \Yii::$app->mailerService->sendFromSite(
- $emailSubject,
- 'orderConfirmProducer',
- $emailContentParams,
- $contactProducer->email
- );
- }
-
-
- $order = $orderModule->findOneOrderById($order->id);
- $orderModule->initOrder($order);
- $orderModule->updateOrderTillerSynchronization($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;
- }
-
-
-
- public function actionCancel(int $id)
- {
- $orderModule = $this->getOrderModule();
- $order = $this->getOrderModule()->findOneOrderById($id);
-
- if (!$order) {
- throw new \yii\web\NotFoundHttpException('Commande introuvable');
- }
-
- $orderModule->getBuilder()->initOrder($order);
-
- if (!$orderModule->isOrderStateOpen($order)) {
- throw new UserException('Vous ne pouvez plus annuler cette commande.');
- }
-
- if ($orderModule->isOrderbelongsToUser($order, GlobalParam::getCurrentUser())) {
- $orderModule->getManager()->deleteOrder($order, $this->getUserCurrent());
- $this->setFlash('success', 'Votre commande a bien été annulée.');
- }
-
- return $this->redirect($this->getUrlManagerProducer()->createUrl(['order/history']));
- }
-
-
-
- public function actionConfirm(int $idOrder, string $returnPayment = '')
- {
- $orderModule = $this->getOrderModule();
-
- $order = $orderModule->findOneOrderById($idOrder);
- $producer = $this->getProducerCurrent();
-
- if (!$order || (!$producer->option_allow_order_guest && !$orderModule->isOrderBelongsToUser($order, GlobalParam::getCurrentUser()))) {
- $this->setFlash('error', 'Commande introuvable');
- return $this->redirect(['order/history']);
- }
-
- $orderModule->initOrder($order);
-
- return $this->render('confirm', [
- 'order' => $order,
- 'returnPayment' => $returnPayment
- ]);
- }
-
-
-
- public function actionAjaxValidateCodePointSale(int $idPointSale, string $code)
- {
- \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
- $pointSaleModule = $this->getPointSaleModule();
- $pointSale = $pointSaleModule->findOnePointSaleById($idPointSale);
-
- if ($pointSale && $pointSaleModule->validateCode($pointSale, $code)) {
- return 1;
- }
-
- return 0;
- }
-
- public function actionAjaxInfos(string $date = '', int $pointSaleId = 0, string $productsJson = null, bool $loadingProducts = false)
- {
- \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
- $productsArray = json_decode($productsJson, true);
- $user = GlobalParam::getCurrentUser();
- $producer = $this->getProducerCurrent();
- $pointSale = $this->getPointSaleModule()->findOnePointSaleById($pointSaleId);
- $order = $this->getOrderUser($date, $pointSale);
-
- return $this->buildJsonAjaxInfos($date, $producer, $pointSale, $user, $order, $productsArray, $loadingProducts);
- }
-
- public function buildJsonAjaxInfos(
- string $date,
- Producer $producer,
- PointSale $pointSale = null,
- User $user = null,
- Order $order = null,
- array $productsArray = null,
- bool $loadingProducts = false
- )
- {
- $orderModule = $this->getOrderModule();
- $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);
- $json['leave_period'] = $this->ajaxInfosLeavePeriod($producer);
-
- if ($dateObject && $dateObject->format($format) === $date) {
- $distribution = $this-> getDistributionModule()->createDistributionIfNotExist($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, $productsArray);
-
- if ($order) {
- $json['order'] = array_merge($order->getAttributes(), [
- 'amount_total' => $orderModule->getOrderAmountWithTax($order, Order::AMOUNT_TOTAL),
- 'amount_paid' => $orderModule->getOrderAmountPaidByCredit($order),
- ]);
- }
- }
-
- return $json;
- }
-
- public function ajaxInfosLeavePeriod(Producer $producer)
- {
- if($this->getProducerModule()->getSolver()->hasLeavePeriodDefined($producer)) {
- return [
- 'start' => $producer->option_leave_period_start,
- 'end' => $producer->option_leave_period_end,
- ];
- }
-
- return false;
- }
-
- public function ajaxInfosProducer(Producer $producer)
- {
- return [
- 'order_infos' => nl2br($producer->order_infos),
- 'payment_infos' => nl2br($producer->option_payment_info),
- '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,
- 'has_specific_delays' => $this->getProducerModule()->getSolver()->hasSpecificDelays($producer),
- 'feature_product_accessory_enabled' => $this->getFeatureModule()->getChecker()->isEnabled(Feature::ALIAS_PRODUCT_ACCESSORY),
- ];
- }
-
- public function ajaxInfosDistributions(Producer $producer, PointSale $pointSaleCurrent = null)
- {
- $distributionModule = $this-> getDistributionModule();
- $dateMini = date('Y-m-d');
-
- $distributionsArray = Distribution::searchAll([
- 'active' => 1,
- 'id_producer' => $producer->id
- ], [
- 'conditions' => ['date > :date'],
- 'params' => [':date' => $dateMini],
- 'join_with' => ['pointSaleDistribution'],
- ]);
- $distributionsArray = $distributionModule->getSolver()->filterDistributionsByDateDelay($distributionsArray);
-
-
- foreach ($distributionsArray as $keyDistribution => $distribution) {
- if($this->getProducerModule()->getSolver()->isOnLeavePeriod($this->getProducerCurrent(), new DateTime($distribution->date))) {
- unset($distributionsArray[$keyDistribution]);
- }
- }
-
-
- $newDistributionsArray = [];
- foreach($distributionsArray as $distribution) {
- $newDistributionsArray[] = $distribution;
- }
- $distributionsArray = $newDistributionsArray;
-
-
- if ($pointSaleCurrent && $producer->option_order_entry_point == Producer::ORDER_ENTRY_POINT_POINT_SALE) {
- $distributionsArrayFilterPointSale = [];
- foreach($distributionsArray as $distribution) {
- if ($distribution && $distributionModule->isPointSaleActive($distribution, $pointSaleCurrent)) {
- $countOrders = Order::searchCount([
- 'id_distribution' => $distribution->id,
- 'id_point_sale' => $pointSaleCurrent->id
- ]);
- $orderUserPointSale = $this->getOrderUser($distribution->date, $pointSaleCurrent);
- if (!$pointSaleCurrent->maximum_number_orders
- || ($orderUserPointSale && $orderUserPointSale->id_point_sale == $pointSaleCurrent->id)
- || ($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
- {
- $orderModule = $this->getOrderModule();
- $dateMini = date('Y-m-d');
- $ordersUserArray = [];
- if (GlobalParam::getCurrentUserId()) {
- $conditionsOrdersUser = [
- 'distribution.date > :date',
- 'order.online_payment_url IS NULL'
- ];
- $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;
- }
-
- $conditionsOrdersUser[] = OrderRepositoryQuery::getSqlFilterIsValid();
-
- $ordersUserArray = Order::searchAll([
- 'id_user' => GlobalParam::getCurrentUserId()
- ], [
- 'conditions' => $conditionsOrdersUser,
- 'params' => $paramsOrdersUser
- ]);
- }
-
- if (is_array($ordersUserArray) && count($ordersUserArray)) {
- foreach ($ordersUserArray as &$order) {
- $orderModule->initOrder($order);
- $order = array_merge($order->getAttributes(), [
- 'amount_total' => $orderModule->getOrderAmountWithTax($order, Order::AMOUNT_TOTAL),
- 'date_distribution' => $order->distribution->date,
- 'pointSale' => $order->pointSale->getAttributes()
- ]);
- }
- }
-
- return $ordersUserArray;
- }
-
- public function ajaxInfosUser(Producer $producer)
- {
- $userProducerModule = $this->getUserProducerModule();
- $producerModule = $this->getProducerModule();
-
- $user = GlobalParam::getCurrentUser();
-
- if($user) {
- $userProducer = $userProducerModule->findOneUserProducer($user);
- if (!$userProducer) {
- $userProducer = $producerModule->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($producer, $distribution = null)
- {
- $pointSaleModule = $this->getPointSaleModule();
- $producerModule = $this->getProducerModule();
- $orderModule = $this->getOrderModule();
-
- $user = GlobalParam::getCurrentUser();
- $userProducer = null;
- if($user) {
- $userProducer = $this->getUserProducerModule()->getRepository()->findOneUserProducer($user);
- }
- $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' => $producer->id])
- ->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 = $producerModule->getConfig('credit_functioning');
- $position = 0;
-
- foreach ($pointsSaleArray as &$pointSale) {
- $pointSaleObject = $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['infos'] = $pointSaleModule->getSolver()->getStrInfosByDistribution($pointSaleObject, $distribution);
- }
-
- $pointSale['producers_sharing_point_sale_as_string'] = false;
- if($this->getFeatureModule()->getChecker()->isEnabled(Feature::ALIAS_SHARED_POINT_SALE)) {
- $pointSale['producers_sharing_point_sale_as_string'] = $this->getSharedPointSaleModule()->getResolver()
- ->getProducersSharingPointSaleAsString($pointSaleObject, $distribution, ', ', true);
- }
-
- $pointSale['position'] = $position;
- $position++;
- }
-
- $favoritePointSale = false;
- if ($user) {
- $favoritePointSale = $orderModule->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);
- }
- }
-
-
- if($userProducer) {
- $pointsSaleArray = $this->getUserProducerModule()->getSolver()->filterPointsSaleByExclusiveAccess(
- $userProducer,
- $pointsSaleArray
- );
- }
-
- return $pointsSaleArray;
- }
-
- public function ajaxInfosProductCategories(Producer $producer)
- {
- $categoriesArray = $this->getProductCategoryModule()->findProductCategoriesAsArray();
- $countProductsWithoutCategory = $this->getProductModule()->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 = null,
- User $user = null,
- Order $order = null,
- array $productsFormArray = null
- )
- {
- $unitModule = $this->getUnitModule();
- $productModule = $this->getProductModule();
- $orderModule = $this->getOrderModule();
- $ordersArray = $this->getOrderModule()->findOrdersByDistribution($distribution);
-
- $productsArray = Product::find()
- ->where([
- 'id_producer' => $producer->id,
- 'product.status' => 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 = $productModule->filterProductsByPointSale($productsArray, $pointSale);
- $orderCurrent = $order;
- if($productsFormArray && count($productsFormArray)) {
- $productOrdersArray = [];
- foreach($productsFormArray as $idProduct => $quantityProduct) {
- if($idProduct) {
- $productObject1 = $productModule->getRepository()->findOneProductById($idProduct);
- $productOrdersArray[$idProduct] = [
- 'quantity' => $quantityProduct / $productModule->getSolver()->getUnitCoefficient($productObject1)
- ];
- }
- }
- $orderCurrent = $orderModule->getBuilder()->instanciateOrderFromProductOrdersArray($productOrdersArray, $orderCurrent);
- }
-
- $indexProduct = 0;
- foreach ($productsArrayFilter as $key => &$product) {
- $productObject = $product;
- $product = array_merge(
- $product->getAttributes(),
- [
- 'unit_coefficient' => Product::$unitsArray[$product->unit]['coefficient'],
- 'prices' => $productModule->getPriceArray($product, $user, $pointSale),
- 'price_unit_ref' => $productModule->getSolver()->getPriceUnitReferenceWithTax($product),
- 'productDistribution' => $product['productDistribution'],
- 'productPointSale' => $product['productPointSale'],
- ]
- );
-
- if (is_null($product['photo']) || strlen($product['photo']) == 0) {
- $product['photo'] = '';
- }
- else {
- $product['photo_big'] = Image::getThumbnailBig($product['photo']);
- $product['photo'] = Image::getThumbnailSmall($product['photo']);
- }
-
- $coefficientUnit = Product::$unitsArray[$product['unit']]['coefficient'];
- $product['coefficient_unit'] = $coefficientUnit;
- $product['quantity_max'] = $orderModule->getResolver()->getProductQuantityMaxOrderable($productObject, $distribution, $orderCurrent);
- $product['quantity_remaining'] = $orderModule->getResolver()->getProductQuantityRemaining($productObject, $distribution, $orderCurrent);
- $product['wording_unit'] = $unitModule->getSolver()->strUnit($product['unit'], UnitDefinition::WORDING_UNIT, true);
- $product['wording_unit_ref'] = $unitModule->getSolver()->strUnit($product['unit'], UnitDefinition::WORDING_SHORT, true);
- $quantityOrderUser = $orderModule->getSolver()->getProductQuantity($productObject, $orderCurrent ? [$orderCurrent] : [], true);
- $product['quantity_form'] = $quantityOrderUser * $coefficientUnit;
- if($product['quantity_remaining'] < 0 && $product['quantity_form']) {
- $product['quantity_form'] = $product['quantity_form'] + ($product['quantity_remaining'] * $coefficientUnit);
- $orderModule->getBuilder()->deleteProductOrderQuantity($orderCurrent, $productObject, abs($product['quantity_remaining']));
- $product['quantity_remaining'] = $orderModule->getResolver()->getProductQuantityRemaining($productObject, $distribution, $orderCurrent);
- }
- $product['wording_unit'] = $unitModule->getSolver()->strUnit($product['unit'], 'wording_unit', true);
-
- if ($order) {
- foreach ($order->productOrder as $productOrder) {
- if ($productOrder->id_product == $product['id']) {
- $product['wording_unit'] = $productModule->getSolver()->strUnit($productOrder->product, 'wording_unit', true);
- $product['step'] = $productOrder->step;
- }
- }
- }
-
- $product['index'] = $indexProduct++;
- }
-
- return $productsArrayFilter;
- }
-
- private function getOrderUser(string $date, PointSale $pointSale = null)
- {
- $orderModule = $this->getOrderModule();
-
- $orderUser = null;
- if (GlobalParam::getCurrentUserId()) {
- $conditionOrderUser = [
- 'distribution.date' => $date,
- 'id_user' => GlobalParam::getCurrentUserId()
- ];
- if ($pointSale) {
- $conditionOrderUser['id_point_sale'] = $pointSale->id;
- }
- $orderUser = Order::searchOne($conditionOrderUser, [
- 'conditions' => OrderRepositoryQuery::getSqlFilterIsValid()
- ]);
-
- if ($orderUser && $orderUser->online_payment_url) {
- $orderUser = null;
- }
- }
-
- if($orderUser) {
- $orderModule->initOrder($orderUser);
- }
-
- return $orderUser;
- }
- }
-
|