|
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685 |
- <?php
-
-
-
- namespace producer\controllers;
-
- use common\helpers\Debug;
- use common\helpers\GlobalParam;
- use common\models\ProductDistribution;
- use common\models\User;
- use common\models\Producer;
- use common\models\Order;
- use common\models\UserPointSale;
- use common\models\Product;
- use DateTime;
-
- class OrderController extends ProducerBaseController
- {
- var $enableCsrfValidation = false;
-
- public function behaviors()
- {
- return [
- 'access' => [
- 'class' => AccessControl::className(),
- 'rules' => [
- [
- 'allow' => true,
- 'roles' => ['@'],
- ]
- ],
- ],
- ];
- }
-
- public function actionOrder($id = 0, $date = '')
- {
- $params = [];
-
- if ($id) {
- $order = Order::searchOne([
- 'id' => $id
- ]);
- if ($order) {
- if ($order->getState() == Order::STATE_OPEN) {
- $params['order'] = $order;
- }
- }
- }
-
- if (strlen($date)) {
- $distribution = Distribution::searchOne([
- 'date' => $date,
- 'id_producer' => GlobalParam::getCurrentProducerId()
- ]);
- if ($distribution) {
- $params['date'] = $date;
- }
- }
-
- return $this->render('order', $params);
- }
-
-
-
- public function actionHistory($type = 'incoming')
- {
- $query = Order::find()
- ->with('productOrder', 'pointSale', 'creditHistory')
- ->joinWith('distribution', 'distribution.producer')
- ->where([
- 'id_user' => Yii::$app->user->id,
- 'distribution.id_producer' => GlobalParam::getCurrentProducerId()
- ])
- ->params([':date_today' => date('Y-m-d')]);
-
- $queryIncoming = clone $query;
- $queryIncoming->andWhere('distribution.date >= :date_today')->orderBy('distribution.date ASC');
-
- $queryPassed = clone $query;
- $queryPassed->andWhere('distribution.date < :date_today')->orderBy('distribution.date DESC');
-
- $dataProviderOrders = new ActiveDataProvider([
- 'query' => ($type == 'incoming') ? $queryIncoming : $queryPassed,
- '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' => $queryIncoming->count(),
- 'countPassed' => $queryPassed->count(),
- ]);
- }
-
-
-
- public function actionRemoveProducer($id = 0)
- {
- $userProducer = UserProducer::find()
- ->where(['id_producer' => $id, 'id_user' => User::getCurrentId()])
- ->one();
-
- $userProducer->active = 0;
- $userProducer->save();
-
- $this->redirect(['order/index']);
- }
-
-
-
- public function actionAjaxProcess()
- {
- \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
- $order = new Order;
- $idProducer = $this->getProducer()->id;
-
- $posts = Yii::$app->request->post();
-
- if ($idProducer) {
- $this->_verifyProducerActive($idProducer);
- }
-
- if ($order->load($posts)) {
- $order = Order::find()
- ->where('id_distribution = :id_distribution')
- ->andWhere('id_user = :id_user')
- ->params([
- ':id_distribution' => $posts['Order']['id_distribution'],
- ':id_user' => User::getCurrentId()
- ])
- ->one();
-
- if (!$order) {
- $order = new Order;
- $order->load(Yii::$app->request->post());
- $order->id_user = User::getCurrentId();
- $order->status = 'tmp-order';
- $order->date = date('Y-m-d H:i:s');
- $order->origin = Order::ORIGIN_USER;
- }
-
- $errors = $this->processForm($order);
-
- if (count($errors)) {
- return ['status' => 'error', 'errors' => $errors];
- }
- }
-
- return ['status' => 'success', 'idOrder' => $order->id];
- }
-
-
-
- public function _verifyProducerActive($idProducer)
- {
- $producer = Producer::findOne($idProducer);
- if ($producer && !$producer->active) {
- throw new NotFoundHttpException('Ce producteur est actuellement hors ligne.');
- }
- }
-
-
-
- public function processForm($order)
- {
- $posts = Yii::$app->request->post();
- $productsArray = [];
- $totalQuantity = 0;
- $producer = $this->getProducer();
-
- foreach ($posts['products'] as $key => $quantity) {
- $product = Product::find()->where(['id' => (int)$key])->one();
- $totalQuantity += $quantity;
- if ($product && $quantity) {
- $productsArray[] = $product;
- }
- }
-
-
- $errorDate = false;
- if (isset($order->id_distribution)) {
-
- $distribution = Distribution::find()->where(['id' => $order->id_distribution])->one();
- $date = $this->getProducer()->getEarliestDateOrder();
-
- if ($order->getState() != Order::STATE_OPEN) {
- $errorDate = true;
- }
- }
-
-
- $errorPointSale = false;
- if (isset($distribution) && $distribution) {
-
- $pointSaleDistribution = PointSaleDistribution::searchOne([
- 'id_distribution' => $distribution->id,
- 'id_point_sale' => $posts['Order']['id_point_sale']
- ]);
-
- if (!$pointSaleDistribution || !$pointSaleDistribution->delivery) {
- $errorPointSale = true;
- }
-
- $pointSale = PointSale::findOne($posts['Order']['id_point_sale']);
-
- if ($pointSale) {
- if (strlen($pointSale->code) && !$pointSale->validateCode($posts['code_point_sale'])) {
- $errorPointSale = true;
- }
- } else {
- $errorPointSale = true;
- }
-
- $userPointSale = UserPointSale::searchOne([
- 'id_user' => User::getCurrentId(),
- 'id_point_sale' => $pointSale->id
- ]);
-
- if ($pointSale->restricted_access && !$userPointSale) {
- $errorPointSale = true;
- }
- }
-
- $errors = [];
-
- if ($order->validate() && count($productsArray) && !$errorDate && !$errorPointSale) {
-
- $userProducer = UserProducer::searchOne([
- 'id_producer' => $order->distribution->id_producer,
- 'id_user' => User::getCurrentId()
- ]);
-
-
- $pointSale = PointSale::searchOne([
- 'id' => $order->id_point_sale
- ]);
-
- $order->comment_point_sale = ($pointSale && strlen($pointSale->getComment())) ?
- $pointSale->getComment() : '';
-
-
- $order->date_delete = null;
-
-
- $order->save();
-
- $order->changeOrderStatus('new-order', 'user');
-
- Producer::addUser(User::getCurrentId(), $distribution->id_producer);
-
-
- if (!is_null($order)) {
- ProductOrder::deleteAll(['id_order' => $order->id]);
-
- $stepsArray = [];
- if (isset($order->productOrder)) {
- foreach ($order->productOrder as $productOrder) {
- $unitsArray[$productOrder->id_product] = $productOrder->unit;
- }
- }
- }
-
-
- $availableProducts = ProductDistribution::searchByDistribution($distribution->id);
-
-
- foreach ($productsArray as $product) {
- if (isset($availableProducts[$product->id])) {
- $productOrder = new ProductOrder();
- $productOrder->id_order = $order->id;
- $productOrder->id_product = $product->id;
-
- $productOrder->price = $product->price;
- $productOrder->id_tax_rate = $product->id_tax_rate;
-
- $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->unit = $product->unit;
- $productOrder->step = $product->step;
- $productOrder->save();
- }
- }
-
-
- $pointSale->linkUser(User::getCurrentId());
-
-
- $credit = Producer::getConfig('credit');
- $creditLimit = Producer::getConfig('credit_limit');
- $creditFunctioning = $pointSale->getCreditFunctioning();
- $creditUser = Yii::$app->user->identity->getCredit($distribution->id_producer);
- $order = Order::searchOne([
- 'id' => $order->id
- ]);
- $amountPaid = $order->getAmount(Order::AMOUNT_PAID);
- $amountRemaining = $order->getAmount(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)
- )) {
- $order->changeOrderStatus('waiting-paiement-by-credit', 'user');
-
-
- if ($order->getPaymentStatus() == Order::PAYMENT_UNPAID) {
-
- if (!is_null($creditLimit) && $amountRemaining > $creditUser - $creditLimit) {
- $amountRemaining = $creditUser - $creditLimit;
- }
-
- if ($amountRemaining > 0) {
- $order->saveCreditHistory(
- CreditHistory::TYPE_PAYMENT,
- $amountRemaining,
- $distribution->id_producer,
- User::getCurrentId(),
- User::getCurrentId()
- );
- $order->changeOrderStatus('paid-by-credit', 'user');
- }else{
- $order->changeOrderStatus('waiting-paiement-on-delivery', 'user');
- }
- }
- elseif ($order->getPaymentStatus() == Order::PAYMENT_SURPLUS) {
- $amountSurplus = $order->getAmount(Order::AMOUNT_SURPLUS);
- $order->saveCreditHistory(
- CreditHistory::TYPE_REFUND,
- $amountSurplus,
- $distribution->id_producer,
- User::getCurrentId(),
- User::getCurrentId()
- );
- }
- }else{
- $order->changeOrderStatus('waiting-paiement-on-delivery', 'user');
- }
- }
-
-
- 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($id)
- {
- $order = Order::searchOne([
- 'id' => $id
- ]);
-
- if (!$order) {
- throw new \yii\web\NotFoundHttpException('Commande introuvable');
- }
-
- if ($order->getState() != Order::STATE_OPEN) {
- throw new UserException('Vous ne pouvez plus annuler cette commande.');
- }
-
- if ($order && User::getCurrentId() == $order->id_user) {
- $order->delete();
- $order->changeOrderStatus('canceled', 'user');
- Yii::$app->session->setFlash('success', 'Votre commande a bien été annulée.');
- }
-
- $this->redirect(Yii::$app->urlManager->createUrl(['order/history']));
- }
-
-
-
- public function actionAjaxValidateCodePointSale($idPointSale, $code)
- {
- \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
-
- $pointSale = PointSale::findOne($idPointSale);
- if ($pointSale) {
- if ($pointSale->validateCode($code)) {
- return 1;
- }
- }
- return 0;
- }
-
- public function actionAjaxInfos($date = '')
- {
- \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
-
- $json = [];
-
- $format = 'Y-m-d';
- $dateObject = DateTime::createFromFormat($format, $date);
-
-
- $producer = Producer::searchOne([
- 'id' => $this->getProducer()->id
- ]);
- $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
- ];
-
-
- $dateMini = $producer->getEarliestDateOrder();
-
- $distributionsArray = Distribution::searchAll([
- 'active' => 1
- ], [
- 'conditions' => ['date > :date'],
- 'params' => [':date' => $dateMini],
- ]);
- $json['distributions'] = $distributionsArray;
-
-
- $ordersUserArray = Order::searchAll([
- 'id_user' => User::getCurrentId()
- ], [
- 'conditions' => [
- 'distribution.date > :date'
- ],
- 'params' => [
- ':date' => $dateMini
- ]
- ]);
- if (is_array($ordersUserArray) && count($ordersUserArray)) {
- foreach ($ordersUserArray as &$order) {
- $order = array_merge($order->getAttributes(), [
- 'amount_total' => $order->getAmountWithTax(Order::AMOUNT_TOTAL),
- 'date_distribution' => $order->distribution->date,
- 'pointSale' => $order->pointSale->getAttributes()
- ]);
- }
- $json['orders'] = $ordersUserArray;
- }
-
-
- $userProducer = UserProducer::searchOne([
- 'id_producer' => $producer->id,
- 'id_user' => User::getCurrentId()
- ]);
-
- $json['user'] = [
- 'credit' => $userProducer->credit,
- 'credit_active' => $userProducer->credit_active,
- ];
-
- if ($dateObject && $dateObject->format($format) === $date) {
-
-
- $orderUser = Order::searchOne([
- 'distribution.date' => $date,
- 'id_user' => User::getCurrentId(),
- ]);
-
- if ($orderUser) {
- $json['order'] = array_merge($orderUser->getAttributes(), [
- 'amount_total' => $orderUser->getAmountWithTax(Order::AMOUNT_TOTAL),
- 'amount_paid' => $orderUser->getAmount(Order::AMOUNT_PAID),
- ]);
- }
-
-
- $distribution = Distribution::initDistribution($date);
- $json['distribution'] = $distribution;
-
- $pointsSaleArray = PointSale::find()
- ->joinWith(['pointSaleDistribution' => function ($query) use ($distribution) {
- $query->where(['id_distribution' => $distribution->id]);
- }
- ])
- ->with(['userPointSale' => function ($query) {
- $query->onCondition(['id_user' => User::getCurrentId()]);
- }])
- ->where(['id_producer' => $distribution->id_producer])
- ->andWhere('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' => User::getCurrentId()])
- ->all();
-
- $creditFunctioningProducer = Producer::getConfig('credit_functioning');
-
- foreach ($pointsSaleArray as &$pointSale) {
- $pointSale = array_merge($pointSale->getAttributes(), [
- 'pointSaleDistribution' => [
- 'id_distribution' => $pointSale->pointSaleDistribution[0]->id_distribution,
- 'id_point_sale' => $pointSale->pointSaleDistribution[0]->id_point_sale,
- 'delivery' => $pointSale->pointSaleDistribution[0]->delivery
- ],
- 'userPointSale' => ($pointSale->userPointSale ? $pointSale->userPointSale[0] : '')
- ]);
- if ($pointSale['code'] && strlen($pointSale['code'])) {
- $pointSale['code'] = '***';
- }
- if (!strlen($pointSale['credit_functioning'])) {
- $pointSale['credit_functioning'] = $creditFunctioningProducer;
- }
- }
-
- $favoritePointSale = User::getCurrent()->getFavoritePointSale();
-
- 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);
- }
- }
-
- $json['points_sale'] = $pointsSaleArray;
-
-
- $ordersArray = Order::searchAll([
- 'distribution.date' => $date,
- ]);
-
-
- if (Producer::getConfig('option_allow_user_gift')) {
- $productsArray = Product::find()
- ->orWhere(['id_producer' => $this->getProducer()->id,])
- ->orWhere(['id_producer' => 0,]);
- } else {
- $productsArray = Product::find()
- ->where(['id_producer' => $this->getProducer()->id,]);
- }
-
- $productsArray = $productsArray->joinWith(['productDistribution' => function ($query) use ($distribution) {
- $query->andOnCondition('product_distribution.id_distribution = ' . $distribution->id);
- }])
- ->orderBy('product_distribution.active DESC, order ASC')
- ->all();
-
- $indexProduct = 0;
- foreach ($productsArray as &$product) {
-
- $product = array_merge(
- $product->getAttributes(),
- [
- 'price_with_tax' => $product->getPriceWithTax(),
- 'productDistribution' => $product['productDistribution']
- ]
- );
-
-
- $coefficient_unit = Product::$unitsArray[$product['unit']]['coefficient'];
-
- if (is_null($product['photo'])) {
- $product['photo'] = '';
- }
-
- $product['quantity_max'] = $product['productDistribution'][0]['quantity_max'];
- $quantityOrder = Order::getProductQuantity($product['id'], $ordersArray);
- $product['quantity_ordered'] = $quantityOrder;
- $product['quantity_remaining'] = $product['quantity_max'] - $quantityOrder;
-
- if ($orderUser) {
- $quantityOrderUser = Order::getProductQuantity($product['id'], [$orderUser], true);
- $product['quantity_ordered'] = $quantityOrder;
- $product['quantity_remaining'] = $product['quantity_max'] - $quantityOrder + $quantityOrderUser;
- $product['quantity_form'] = $quantityOrderUser * $coefficient_unit;
- foreach ($orderUser->productOrder as $productOrder) {
- if ($productOrder->id_product == $product['id']) {
- $product['wording_unit'] = Product::strUnit($productOrder->unit, 'wording_unit', true);
- $product['step'] = $productOrder->step;
- }
- }
- } else {
- $product['quantity_form'] = 0;
- $product['wording_unit'] = Product::strUnit($product['unit'], 'wording_unit', true);
- }
- $product['coefficient_unit'] = $coefficient_unit;
-
- if ($product['quantity_remaining'] < 0) $product['quantity_remaining'] = 0;
- $product['index'] = $indexProduct++;
- }
-
- $json['products'] = $productsArray;
- }
-
- return $json;
- }
-
- public function actionConfirm($idOrder)
- {
- $order = Order::searchOne(['id' => $idOrder]);
-
- if (!$order || $order->id_user != User::getCurrentId()) {
- throw new \yii\base\UserException('Commande introuvable.');
- }
-
- return $this->render('confirm', [
- 'order' => $order
- ]);
- }
-
- }
-
|