Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

685 lines
31KB

  1. <?php
  2. /**
  3. * Copyright distrib (2018)
  4. *
  5. * contact@opendistrib.net
  6. *
  7. * Ce logiciel est un programme informatique servant à aider les producteurs
  8. * à distribuer leur production en circuits courts.
  9. *
  10. * Ce logiciel est régi par la licence CeCILL soumise au droit français et
  11. * respectant les principes de diffusion des logiciels libres. Vous pouvez
  12. * utiliser, modifier et/ou redistribuer ce programme sous les conditions
  13. * de la licence CeCILL telle que diffusée par le CEA, le CNRS et l'INRIA
  14. * sur le site "http://www.cecill.info".
  15. *
  16. * En contrepartie de l'accessibilité au code source et des droits de copie,
  17. * de modification et de redistribution accordés par cette licence, il n'est
  18. * offert aux utilisateurs qu'une garantie limitée. Pour les mêmes raisons,
  19. * seule une responsabilité restreinte pèse sur l'auteur du programme, le
  20. * titulaire des droits patrimoniaux et les concédants successifs.
  21. *
  22. * A cet égard l'attention de l'utilisateur est attirée sur les risques
  23. * associés au chargement, à l'utilisation, à la modification et/ou au
  24. * développement et à la reproduction du logiciel par l'utilisateur étant
  25. * donné sa spécificité de logiciel libre, qui peut le rendre complexe à
  26. * manipuler et qui le réserve donc à des développeurs et des professionnels
  27. * avertis possédant des connaissances informatiques approfondies. Les
  28. * utilisateurs sont donc invités à charger et tester l'adéquation du
  29. * logiciel à leurs besoins dans des conditions permettant d'assurer la
  30. * sécurité de leurs systèmes et ou de leurs données et, plus généralement,
  31. * à l'utiliser et l'exploiter dans les mêmes conditions de sécurité.
  32. *
  33. * Le fait que vous puissiez accéder à cet en-tête signifie que vous avez
  34. * pris connaissance de la licence CeCILL, et que vous en avez accepté les
  35. * termes.
  36. */
  37. namespace producer\controllers;
  38. use common\helpers\Debug;
  39. use common\helpers\GlobalParam;
  40. use common\models\ProductDistribution;
  41. use common\models\User;
  42. use common\models\Producer;
  43. use common\models\Order;
  44. use common\models\UserPointSale;
  45. use common\models\Product;
  46. use DateTime;
  47. class OrderController extends ProducerBaseController
  48. {
  49. var $enableCsrfValidation = false;
  50. public function behaviors()
  51. {
  52. return [
  53. 'access' => [
  54. 'class' => AccessControl::className(),
  55. 'rules' => [
  56. [
  57. 'allow' => true,
  58. 'roles' => ['@'],
  59. ]
  60. ],
  61. ],
  62. ];
  63. }
  64. public function actionOrder($id = 0, $date = '')
  65. {
  66. $params = [];
  67. if ($id) {
  68. $order = Order::searchOne([
  69. 'id' => $id
  70. ]);
  71. if ($order) {
  72. if ($order->getState() == Order::STATE_OPEN) {
  73. $params['order'] = $order;
  74. }
  75. }
  76. }
  77. if (strlen($date)) {
  78. $distribution = Distribution::searchOne([
  79. 'date' => $date,
  80. 'id_producer' => GlobalParam::getCurrentProducerId()
  81. ]);
  82. if ($distribution) {
  83. $params['date'] = $date;
  84. }
  85. }
  86. return $this->render('order', $params);
  87. }
  88. /**
  89. * Affiche l'historique des commandes de l'utilisateur
  90. *
  91. * @return ProducerView
  92. */
  93. public function actionHistory($type = 'incoming')
  94. {
  95. $query = Order::find()
  96. ->with('productOrder', 'pointSale', 'creditHistory')
  97. ->joinWith('distribution', 'distribution.producer')
  98. ->where([
  99. 'id_user' => Yii::$app->user->id,
  100. 'distribution.id_producer' => GlobalParam::getCurrentProducerId()
  101. ])
  102. ->params([':date_today' => date('Y-m-d')]);
  103. $queryIncoming = clone $query;
  104. $queryIncoming->andWhere('distribution.date >= :date_today')->orderBy('distribution.date ASC');
  105. $queryPassed = clone $query;
  106. $queryPassed->andWhere('distribution.date < :date_today')->orderBy('distribution.date DESC');
  107. $dataProviderOrders = new ActiveDataProvider([
  108. 'query' => ($type == 'incoming') ? $queryIncoming : $queryPassed,
  109. 'pagination' => [
  110. 'pageSize' => 10,
  111. ],
  112. ]);
  113. return $this->render('history', [
  114. 'dataProviderOrders' => $dataProviderOrders,
  115. 'orderOk' => Yii::$app->getRequest()->get('orderOk', false),
  116. 'cancelOk' => Yii::$app->getRequest()->get('cancelOk', false),
  117. 'type' => $type,
  118. 'countIncoming' => $queryIncoming->count(),
  119. 'countPassed' => $queryPassed->count(),
  120. ]);
  121. }
  122. /**
  123. * Supprime un producteur.
  124. *
  125. * @param integer $id
  126. */
  127. public function actionRemoveProducer($id = 0)
  128. {
  129. $userProducer = UserProducer::find()
  130. ->where(['id_producer' => $id, 'id_user' => User::getCurrentId()])
  131. ->one();
  132. $userProducer->active = 0;
  133. $userProducer->save();
  134. $this->redirect(['order/index']);
  135. }
  136. /**
  137. * Crée une commande.
  138. *
  139. * @return mixed
  140. */
  141. public function actionAjaxProcess()
  142. {
  143. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  144. $order = new Order;
  145. $idProducer = $this->getProducer()->id;
  146. $posts = Yii::$app->request->post();
  147. if ($idProducer) {
  148. $this->_verifyProducerActive($idProducer);
  149. }
  150. if ($order->load($posts)) {
  151. $order = Order::find()
  152. ->where('id_distribution = :id_distribution')
  153. ->andWhere('id_user = :id_user')
  154. ->params([
  155. ':id_distribution' => $posts['Order']['id_distribution'],
  156. ':id_user' => User::getCurrentId()
  157. ])
  158. ->one();
  159. if (!$order) {
  160. $order = new Order;
  161. $order->load(Yii::$app->request->post());
  162. $order->id_user = User::getCurrentId();
  163. $order->status = 'tmp-order';
  164. $order->date = date('Y-m-d H:i:s');
  165. $order->origin = Order::ORIGIN_USER;
  166. }
  167. $errors = $this->processForm($order);
  168. if (count($errors)) {
  169. return ['status' => 'error', 'errors' => $errors];
  170. }
  171. }
  172. return ['status' => 'success', 'idOrder' => $order->id];
  173. }
  174. /**
  175. * Vérifie si un producteur est actif.
  176. *
  177. * @param integer $idProducer
  178. * @throws NotFoundHttpException
  179. */
  180. public function _verifyProducerActive($idProducer)
  181. {
  182. $producer = Producer::findOne($idProducer);
  183. if ($producer && !$producer->active) {
  184. throw new NotFoundHttpException('Ce producteur est actuellement hors ligne.');
  185. }
  186. }
  187. /**
  188. * Traite le formulaire de création/modification de commande.
  189. *
  190. * @param Commande $order
  191. */
  192. public function processForm($order)
  193. {
  194. $posts = Yii::$app->request->post();
  195. $productsArray = [];
  196. $totalQuantity = 0;
  197. $producer = $this->getProducer();
  198. foreach ($posts['products'] as $key => $quantity) {
  199. $product = Product::find()->where(['id' => (int)$key])->one();
  200. $totalQuantity += $quantity;
  201. if ($product && $quantity) {
  202. $productsArray[] = $product;
  203. }
  204. }
  205. // date
  206. $errorDate = false;
  207. if (isset($order->id_distribution)) {
  208. // date de commande
  209. $distribution = Distribution::find()->where(['id' => $order->id_distribution])->one();
  210. $date = $this->getProducer()->getEarliestDateOrder();
  211. if ($order->getState() != Order::STATE_OPEN) {
  212. $errorDate = true;
  213. }
  214. }
  215. // point de vente
  216. $errorPointSale = false;
  217. if (isset($distribution) && $distribution) {
  218. $pointSaleDistribution = PointSaleDistribution::searchOne([
  219. 'id_distribution' => $distribution->id,
  220. 'id_point_sale' => $posts['Order']['id_point_sale']
  221. ]);
  222. if (!$pointSaleDistribution || !$pointSaleDistribution->delivery) {
  223. $errorPointSale = true;
  224. }
  225. $pointSale = PointSale::findOne($posts['Order']['id_point_sale']);
  226. if ($pointSale) {
  227. if (strlen($pointSale->code) && !$pointSale->validateCode($posts['code_point_sale'])) {
  228. $errorPointSale = true;
  229. }
  230. } else {
  231. $errorPointSale = true;
  232. }
  233. $userPointSale = UserPointSale::searchOne([
  234. 'id_user' => User::getCurrentId(),
  235. 'id_point_sale' => $pointSale->id
  236. ]);
  237. if ($pointSale->restricted_access && !$userPointSale) {
  238. $errorPointSale = true;
  239. }
  240. }
  241. $errors = [];
  242. if ($order->validate() && count($productsArray) && !$errorDate && !$errorPointSale) {
  243. $userProducer = UserProducer::searchOne([
  244. 'id_producer' => $order->distribution->id_producer,
  245. 'id_user' => User::getCurrentId()
  246. ]);
  247. // gestion point de vente
  248. $pointSale = PointSale::searchOne([
  249. 'id' => $order->id_point_sale
  250. ]);
  251. $order->comment_point_sale = ($pointSale && strlen($pointSale->getComment())) ?
  252. $pointSale->getComment() : '';
  253. // la commande est automatiquement réactivée lors d'une modification
  254. $order->date_delete = null;
  255. // sauvegarde de la commande
  256. $order->save();
  257. $order->changeOrderStatus('new-order', 'user');
  258. // ajout de l'utilisateur à l'établissement
  259. Producer::addUser(User::getCurrentId(), $distribution->id_producer);
  260. // suppression de tous les enregistrements ProductOrder
  261. if (!is_null($order)) {
  262. ProductOrder::deleteAll(['id_order' => $order->id]);
  263. $stepsArray = [];
  264. if (isset($order->productOrder)) {
  265. foreach ($order->productOrder as $productOrder) {
  266. $unitsArray[$productOrder->id_product] = $productOrder->unit;
  267. }
  268. }
  269. }
  270. // produits dispos
  271. $availableProducts = ProductDistribution::searchByDistribution($distribution->id);
  272. // sauvegarde des produits
  273. foreach ($productsArray as $product) {
  274. if (isset($availableProducts[$product->id])) {
  275. $productOrder = new ProductOrder();
  276. $productOrder->id_order = $order->id;
  277. $productOrder->id_product = $product->id;
  278. $productOrder->price = $product->price;
  279. $productOrder->id_tax_rate = $product->id_tax_rate;
  280. $unit = (!is_null($order) && isset($unitsArray[$product->id])) ? $unitsArray[$product->id] : $product->unit;
  281. $coefficient = Product::$unitsArray[$unit]['coefficient'];
  282. $quantity = ((float)$posts['products'][$product->id]) / $coefficient;
  283. if ($availableProducts[$product->id]['quantity_max'] && $quantity > $availableProducts[$product->id]['quantity_remaining']) {
  284. $quantity = $availableProducts[$product->id]['quantity_remaining'];
  285. }
  286. $productOrder->quantity = $quantity;
  287. $productOrder->unit = $product->unit;
  288. $productOrder->step = $product->step;
  289. $productOrder->save();
  290. }
  291. }
  292. // lien utilisateur / point de vente
  293. $pointSale->linkUser(User::getCurrentId());
  294. // credit
  295. $credit = Producer::getConfig('credit');
  296. $creditLimit = Producer::getConfig('credit_limit');
  297. $creditFunctioning = $pointSale->getCreditFunctioning();
  298. $creditUser = Yii::$app->user->identity->getCredit($distribution->id_producer);
  299. $order = Order::searchOne([
  300. 'id' => $order->id
  301. ]);
  302. $amountPaid = $order->getAmount(Order::AMOUNT_PAID);
  303. $amountRemaining = $order->getAmount(Order::AMOUNT_REMAINING);
  304. if ($credit && $pointSale->credit &&
  305. (($creditFunctioning == Producer::CREDIT_FUNCTIONING_OPTIONAL && $posts['use_credit']) ||
  306. $creditFunctioning == Producer::CREDIT_FUNCTIONING_MANDATORY ||
  307. ($creditFunctioning == Producer::CREDIT_FUNCTIONING_USER && $userProducer->credit_active)
  308. )) {
  309. $order->changeOrderStatus('waiting-paiement-by-credit', 'user');
  310. // à payer
  311. if ($order->getPaymentStatus() == Order::PAYMENT_UNPAID) {
  312. if (!is_null($creditLimit) && $amountRemaining > $creditUser - $creditLimit) {
  313. $amountRemaining = $creditUser - $creditLimit;
  314. }
  315. if ($amountRemaining > 0) {
  316. $order->saveCreditHistory(
  317. CreditHistory::TYPE_PAYMENT,
  318. $amountRemaining,
  319. $distribution->id_producer,
  320. User::getCurrentId(),
  321. User::getCurrentId()
  322. );
  323. $order->changeOrderStatus('paid-by-credit', 'user');
  324. }else{
  325. $order->changeOrderStatus('waiting-paiement-on-delivery', 'user');
  326. }
  327. } // surplus à rembourser
  328. elseif ($order->getPaymentStatus() == Order::PAYMENT_SURPLUS) {
  329. $amountSurplus = $order->getAmount(Order::AMOUNT_SURPLUS);
  330. $order->saveCreditHistory(
  331. CreditHistory::TYPE_REFUND,
  332. $amountSurplus,
  333. $distribution->id_producer,
  334. User::getCurrentId(),
  335. User::getCurrentId()
  336. );
  337. }
  338. }else{
  339. $order->changeOrderStatus('waiting-paiement-on-delivery', 'user');
  340. }
  341. }
  342. if (!count($productsArray)) {
  343. $errors[] = "Vous n'avez choisi aucun produit";
  344. }
  345. if ($errorDate) {
  346. $errors[] = "Vous ne pouvez pas commander pour cette date.";
  347. }
  348. if ($errorPointSale) {
  349. $errors[] = "Point de vente invalide.";
  350. }
  351. return $errors;
  352. }
  353. /**
  354. * Annule une commande.
  355. *
  356. * @param integer $id
  357. * @throws \yii\web\NotFoundHttpException
  358. * @throws UserException
  359. */
  360. public function actionCancel($id)
  361. {
  362. $order = Order::searchOne([
  363. 'id' => $id
  364. ]);
  365. if (!$order) {
  366. throw new \yii\web\NotFoundHttpException('Commande introuvable');
  367. }
  368. if ($order->getState() != Order::STATE_OPEN) {
  369. throw new UserException('Vous ne pouvez plus annuler cette commande.');
  370. }
  371. if ($order && User::getCurrentId() == $order->id_user) {
  372. $order->delete();
  373. $order->changeOrderStatus('canceled', 'user');
  374. Yii::$app->session->setFlash('success', 'Votre commande a bien été annulée.');
  375. }
  376. $this->redirect(Yii::$app->urlManager->createUrl(['order/history']));
  377. }
  378. /**
  379. * Vérifie le code saisi pour un point de vente.
  380. *
  381. * @param integer $idPointSale
  382. * @param string $code
  383. * @return boolean
  384. */
  385. public function actionAjaxValidateCodePointSale($idPointSale, $code)
  386. {
  387. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  388. $pointSale = PointSale::findOne($idPointSale);
  389. if ($pointSale) {
  390. if ($pointSale->validateCode($code)) {
  391. return 1;
  392. }
  393. }
  394. return 0;
  395. }
  396. public function actionAjaxInfos($date = '')
  397. {
  398. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  399. $json = [];
  400. $format = 'Y-m-d';
  401. $dateObject = DateTime::createFromFormat($format, $date);
  402. // Producteur
  403. $producer = Producer::searchOne([
  404. 'id' => $this->getProducer()->id
  405. ]);
  406. $json['producer'] = [
  407. 'order_infos' => $producer->order_infos,
  408. 'credit' => $producer->credit,
  409. 'credit_functioning' => $producer->credit_functioning,
  410. 'use_credit_checked_default' => $producer->use_credit_checked_default,
  411. 'credit_limit' => is_numeric($producer->credit_limit) ? $producer->credit_limit : null
  412. ];
  413. // Distributions
  414. $dateMini = $producer->getEarliestDateOrder();
  415. $distributionsArray = Distribution::searchAll([
  416. 'active' => 1
  417. ], [
  418. 'conditions' => ['date > :date'],
  419. 'params' => [':date' => $dateMini],
  420. ]);
  421. $json['distributions'] = $distributionsArray;
  422. // Commandes de l'utilisateur
  423. $ordersUserArray = Order::searchAll([
  424. 'id_user' => User::getCurrentId()
  425. ], [
  426. 'conditions' => [
  427. 'distribution.date > :date'
  428. ],
  429. 'params' => [
  430. ':date' => $dateMini
  431. ]
  432. ]);
  433. if (is_array($ordersUserArray) && count($ordersUserArray)) {
  434. foreach ($ordersUserArray as &$order) {
  435. $order = array_merge($order->getAttributes(), [
  436. 'amount_total' => $order->getAmountWithTax(Order::AMOUNT_TOTAL),
  437. 'date_distribution' => $order->distribution->date,
  438. 'pointSale' => $order->pointSale->getAttributes()
  439. ]);
  440. }
  441. $json['orders'] = $ordersUserArray;
  442. }
  443. // User
  444. $userProducer = UserProducer::searchOne([
  445. 'id_producer' => $producer->id,
  446. 'id_user' => User::getCurrentId()
  447. ]);
  448. $json['user'] = [
  449. 'credit' => $userProducer->credit,
  450. 'credit_active' => $userProducer->credit_active,
  451. ];
  452. if ($dateObject && $dateObject->format($format) === $date) {
  453. // Commande de l'utilisateur
  454. $orderUser = Order::searchOne([
  455. 'distribution.date' => $date,
  456. 'id_user' => User::getCurrentId(),
  457. ]);
  458. if ($orderUser) {
  459. $json['order'] = array_merge($orderUser->getAttributes(), [
  460. 'amount_total' => $orderUser->getAmountWithTax(Order::AMOUNT_TOTAL),
  461. 'amount_paid' => $orderUser->getAmount(Order::AMOUNT_PAID),
  462. ]);
  463. }
  464. // distribution
  465. $distribution = Distribution::initDistribution($date);
  466. $json['distribution'] = $distribution;
  467. $pointsSaleArray = PointSale::find()
  468. ->joinWith(['pointSaleDistribution' => function ($query) use ($distribution) {
  469. $query->where(['id_distribution' => $distribution->id]);
  470. }
  471. ])
  472. ->with(['userPointSale' => function ($query) {
  473. $query->onCondition(['id_user' => User::getCurrentId()]);
  474. }])
  475. ->where(['id_producer' => $distribution->id_producer])
  476. ->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)')
  477. ->params([':id_user' => User::getCurrentId()])
  478. ->all();
  479. $creditFunctioningProducer = Producer::getConfig('credit_functioning');
  480. foreach ($pointsSaleArray as &$pointSale) {
  481. $pointSale = array_merge($pointSale->getAttributes(), [
  482. 'pointSaleDistribution' => [
  483. 'id_distribution' => $pointSale->pointSaleDistribution[0]->id_distribution,
  484. 'id_point_sale' => $pointSale->pointSaleDistribution[0]->id_point_sale,
  485. 'delivery' => $pointSale->pointSaleDistribution[0]->delivery
  486. ],
  487. 'userPointSale' => ($pointSale->userPointSale ? $pointSale->userPointSale[0] : '')
  488. ]);
  489. if ($pointSale['code'] && strlen($pointSale['code'])) {
  490. $pointSale['code'] = '***';
  491. }
  492. if (!strlen($pointSale['credit_functioning'])) {
  493. $pointSale['credit_functioning'] = $creditFunctioningProducer;
  494. }
  495. }
  496. $favoritePointSale = User::getCurrent()->getFavoritePointSale();
  497. if ($favoritePointSale) {
  498. for ($i = 0; $i < count($pointsSaleArray); $i++) {
  499. if ($pointsSaleArray[$i]['id'] == $favoritePointSale->id) {
  500. $theFavoritePointSale = $pointsSaleArray[$i];
  501. unset($pointsSaleArray[$i]);
  502. }
  503. }
  504. if (isset($theFavoritePointSale)) {
  505. $pointsSaleArray = array_reverse($pointsSaleArray, false);
  506. $pointsSaleArray[] = $theFavoritePointSale;
  507. $pointsSaleArray = array_reverse($pointsSaleArray, false);
  508. }
  509. }
  510. $json['points_sale'] = $pointsSaleArray;
  511. // Commandes totales
  512. $ordersArray = Order::searchAll([
  513. 'distribution.date' => $date,
  514. ]);
  515. // Produits
  516. if (Producer::getConfig('option_allow_user_gift')) {
  517. $productsArray = Product::find()
  518. ->orWhere(['id_producer' => $this->getProducer()->id,])
  519. ->orWhere(['id_producer' => 0,]); // produit "Don";
  520. } else {
  521. $productsArray = Product::find()
  522. ->where(['id_producer' => $this->getProducer()->id,]);
  523. }
  524. $productsArray = $productsArray->joinWith(['productDistribution' => function ($query) use ($distribution) {
  525. $query->andOnCondition('product_distribution.id_distribution = ' . $distribution->id);
  526. }])
  527. ->orderBy('product_distribution.active DESC, order ASC')
  528. ->all();
  529. $indexProduct = 0;
  530. foreach ($productsArray as &$product) {
  531. $product = array_merge(
  532. $product->getAttributes(),
  533. [
  534. 'price_with_tax' => $product->getPriceWithTax(),
  535. 'productDistribution' => $product['productDistribution']
  536. ]
  537. );
  538. $coefficient_unit = Product::$unitsArray[$product['unit']]['coefficient'];
  539. if (is_null($product['photo'])) {
  540. $product['photo'] = '';
  541. }
  542. $product['quantity_max'] = $product['productDistribution'][0]['quantity_max'];
  543. $quantityOrder = Order::getProductQuantity($product['id'], $ordersArray);
  544. $product['quantity_ordered'] = $quantityOrder;
  545. $product['quantity_remaining'] = $product['quantity_max'] - $quantityOrder;
  546. if ($orderUser) {
  547. $quantityOrderUser = Order::getProductQuantity($product['id'], [$orderUser], true);
  548. $product['quantity_ordered'] = $quantityOrder;
  549. $product['quantity_remaining'] = $product['quantity_max'] - $quantityOrder + $quantityOrderUser;
  550. $product['quantity_form'] = $quantityOrderUser * $coefficient_unit;
  551. foreach ($orderUser->productOrder as $productOrder) {
  552. if ($productOrder->id_product == $product['id']) {
  553. $product['wording_unit'] = Product::strUnit($productOrder->unit, 'wording_unit', true);
  554. $product['step'] = $productOrder->step;
  555. }
  556. }
  557. } else {
  558. $product['quantity_form'] = 0;
  559. $product['wording_unit'] = Product::strUnit($product['unit'], 'wording_unit', true);
  560. }
  561. $product['coefficient_unit'] = $coefficient_unit;
  562. if ($product['quantity_remaining'] < 0) $product['quantity_remaining'] = 0;
  563. $product['index'] = $indexProduct++;
  564. }
  565. $json['products'] = $productsArray;
  566. }
  567. return $json;
  568. }
  569. public function actionConfirm($idOrder)
  570. {
  571. $order = Order::searchOne(['id' => $idOrder]);
  572. if (!$order || $order->id_user != User::getCurrentId()) {
  573. throw new \yii\base\UserException('Commande introuvable.');
  574. }
  575. return $this->render('confirm', [
  576. 'order' => $order
  577. ]);
  578. }
  579. }