You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

675 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->date = date('Y-m-d H:i:s');
  164. $order->origin = Order::ORIGIN_USER;
  165. }
  166. $errors = $this->processForm($order);
  167. if (count($errors)) {
  168. return ['status' => 'error', 'errors' => $errors];
  169. }
  170. }
  171. return ['status' => 'success', 'idOrder' => $order->id];
  172. }
  173. /**
  174. * Vérifie si un producteur est actif.
  175. *
  176. * @param integer $idProducer
  177. * @throws NotFoundHttpException
  178. */
  179. public function _verifyProducerActive($idProducer)
  180. {
  181. $producer = Producer::findOne($idProducer);
  182. if ($producer && !$producer->active) {
  183. throw new NotFoundHttpException('Ce producteur est actuellement hors ligne.');
  184. }
  185. }
  186. /**
  187. * Traite le formulaire de création/modification de commande.
  188. *
  189. * @param Commande $order
  190. */
  191. public function processForm($order)
  192. {
  193. $posts = Yii::$app->request->post();
  194. $productsArray = [];
  195. $totalQuantity = 0;
  196. $producer = $this->getProducer();
  197. foreach ($posts['products'] as $key => $quantity) {
  198. $product = Product::find()->where(['id' => (int)$key])->one();
  199. $totalQuantity += $quantity;
  200. if ($product && $quantity) {
  201. $productsArray[] = $product;
  202. }
  203. }
  204. // date
  205. $errorDate = false;
  206. if (isset($order->id_distribution)) {
  207. // date de commande
  208. $distribution = Distribution::find()->where(['id' => $order->id_distribution])->one();
  209. $date = $this->getProducer()->getEarliestDateOrder();
  210. if ($order->getState() != Order::STATE_OPEN) {
  211. $errorDate = true;
  212. }
  213. }
  214. // point de vente
  215. $errorPointSale = false;
  216. if (isset($distribution) && $distribution) {
  217. $pointSaleDistribution = PointSaleDistribution::searchOne([
  218. 'id_distribution' => $distribution->id,
  219. 'id_point_sale' => $posts['Order']['id_point_sale']
  220. ]);
  221. if (!$pointSaleDistribution || !$pointSaleDistribution->delivery) {
  222. $errorPointSale = true;
  223. }
  224. $pointSale = PointSale::findOne($posts['Order']['id_point_sale']);
  225. if ($pointSale) {
  226. if (strlen($pointSale->code) && !$pointSale->validateCode($posts['code_point_sale'])) {
  227. $errorPointSale = true;
  228. }
  229. } else {
  230. $errorPointSale = true;
  231. }
  232. $userPointSale = UserPointSale::searchOne([
  233. 'id_user' => User::getCurrentId(),
  234. 'id_point_sale' => $pointSale->id
  235. ]);
  236. if ($pointSale->restricted_access && !$userPointSale) {
  237. $errorPointSale = true;
  238. }
  239. }
  240. $errors = [];
  241. if ($order->validate() && count($productsArray) && !$errorDate && !$errorPointSale) {
  242. $userProducer = UserProducer::searchOne([
  243. 'id_producer' => $order->distribution->id_producer,
  244. 'id_user' => User::getCurrentId()
  245. ]);
  246. // gestion point de vente
  247. $pointSale = PointSale::searchOne([
  248. 'id' => $order->id_point_sale
  249. ]);
  250. $order->comment_point_sale = ($pointSale && strlen($pointSale->getComment())) ?
  251. $pointSale->getComment() : '';
  252. // la commande est automatiquement réactivée lors d'une modification
  253. $order->date_delete = null;
  254. // sauvegarde de la commande
  255. $order->save();
  256. // ajout de l'utilisateur à l'établissement
  257. Producer::addUser(User::getCurrentId(), $distribution->id_producer);
  258. // suppression de tous les enregistrements ProductOrder
  259. if (!is_null($order)) {
  260. ProductOrder::deleteAll(['id_order' => $order->id]);
  261. $stepsArray = [];
  262. if (isset($order->productOrder)) {
  263. foreach ($order->productOrder as $productOrder) {
  264. $unitsArray[$productOrder->id_product] = $productOrder->unit;
  265. }
  266. }
  267. }
  268. // produits dispos
  269. $availableProducts = ProductDistribution::searchByDistribution($distribution->id);
  270. // sauvegarde des produits
  271. foreach ($productsArray as $product) {
  272. if (isset($availableProducts[$product->id])) {
  273. $productOrder = new ProductOrder();
  274. $productOrder->id_order = $order->id;
  275. $productOrder->id_product = $product->id;
  276. $productOrder->price = $product->price;
  277. $unit = (!is_null($order) && isset($unitsArray[$product->id])) ? $unitsArray[$product->id] : $product->unit;
  278. $coefficient = Product::$unitsArray[$unit]['coefficient'];
  279. $quantity = ((float)$posts['products'][$product->id]) / $coefficient;
  280. if ($availableProducts[$product->id]['quantity_max'] && $quantity > $availableProducts[$product->id]['quantity_remaining']) {
  281. $quantity = $availableProducts[$product->id]['quantity_remaining'];
  282. }
  283. $productOrder->quantity = $quantity;
  284. $productOrder->unit = $product->unit;
  285. $productOrder->step = $product->step;
  286. $productOrder->save();
  287. }
  288. }
  289. // lien utilisateur / point de vente
  290. $pointSale->linkUser(User::getCurrentId());
  291. // credit
  292. $credit = Producer::getConfig('credit');
  293. $creditLimit = Producer::getConfig('credit_limit');
  294. $creditFunctioning = $pointSale->getCreditFunctioning();
  295. $creditUser = Yii::$app->user->identity->getCredit($distribution->id_producer);
  296. $order = Order::searchOne([
  297. 'id' => $order->id
  298. ]);
  299. $amountPaid = $order->getAmount(Order::AMOUNT_PAID);
  300. $amountRemaining = $order->getAmount(Order::AMOUNT_REMAINING);
  301. if ($credit && $pointSale->credit &&
  302. (($creditFunctioning == Producer::CREDIT_FUNCTIONING_OPTIONAL && $posts['use_credit']) ||
  303. $creditFunctioning == Producer::CREDIT_FUNCTIONING_MANDATORY ||
  304. ($creditFunctioning == Producer::CREDIT_FUNCTIONING_USER && $userProducer->credit_active)
  305. )) {
  306. // à payer
  307. if ($order->getPaymentStatus() == Order::PAYMENT_UNPAID) {
  308. if (!is_null($creditLimit) && $amountRemaining > $creditUser - $creditLimit) {
  309. $amountRemaining = $creditUser - $creditLimit;
  310. }
  311. if ($amountRemaining > 0) {
  312. $order->saveCreditHistory(
  313. CreditHistory::TYPE_PAYMENT,
  314. $amountRemaining,
  315. $distribution->id_producer,
  316. User::getCurrentId(),
  317. User::getCurrentId()
  318. );
  319. }
  320. } // surplus à rembourser
  321. elseif ($order->getPaymentStatus() == Order::PAYMENT_SURPLUS) {
  322. $amountSurplus = $order->getAmount(Order::AMOUNT_SURPLUS);
  323. $order->saveCreditHistory(
  324. CreditHistory::TYPE_REFUND,
  325. $amountSurplus,
  326. $distribution->id_producer,
  327. User::getCurrentId(),
  328. User::getCurrentId()
  329. );
  330. }
  331. }
  332. }
  333. if (!count($productsArray)) {
  334. $errors[] = "Vous n'avez choisi aucun produit";
  335. }
  336. if ($errorDate) {
  337. $errors[] = "Vous ne pouvez pas commander pour cette date.";
  338. }
  339. if ($errorPointSale) {
  340. $errors[] = "Point de vente invalide.";
  341. }
  342. return $errors;
  343. }
  344. /**
  345. * Annule une commande.
  346. *
  347. * @param integer $id
  348. * @throws \yii\web\NotFoundHttpException
  349. * @throws UserException
  350. */
  351. public function actionCancel($id)
  352. {
  353. $order = Order::searchOne([
  354. 'id' => $id
  355. ]);
  356. if (!$order) {
  357. throw new \yii\web\NotFoundHttpException('Commande introuvable');
  358. }
  359. if ($order->getState() != Order::STATE_OPEN) {
  360. throw new UserException('Vous ne pouvez plus annuler cette commande.');
  361. }
  362. if ($order && User::getCurrentId() == $order->id_user) {
  363. $order->delete();
  364. Yii::$app->session->setFlash('success', 'Votre commande a bien été annulée.');
  365. }
  366. $this->redirect(Yii::$app->urlManager->createUrl(['order/history']));
  367. }
  368. /**
  369. * Vérifie le code saisi pour un point de vente.
  370. *
  371. * @param integer $idPointSale
  372. * @param string $code
  373. * @return boolean
  374. */
  375. public function actionAjaxValidateCodePointSale($idPointSale, $code)
  376. {
  377. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  378. $pointSale = PointSale::findOne($idPointSale);
  379. if ($pointSale) {
  380. if ($pointSale->validateCode($code)) {
  381. return 1;
  382. }
  383. }
  384. return 0;
  385. }
  386. public function actionAjaxInfos($date = '')
  387. {
  388. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  389. $json = [];
  390. $format = 'Y-m-d';
  391. $dateObject = DateTime::createFromFormat($format, $date);
  392. // Producteur
  393. $producer = Producer::searchOne([
  394. 'id' => $this->getProducer()->id
  395. ]);
  396. $json['producer'] = [
  397. 'order_infos' => $producer->order_infos,
  398. 'credit' => $producer->credit,
  399. 'credit_functioning' => $producer->credit_functioning,
  400. 'use_credit_checked_default' => $producer->use_credit_checked_default,
  401. 'credit_limit' => is_numeric($producer->credit_limit) ? $producer->credit_limit : null
  402. ];
  403. // Distributions
  404. $dateMini = $producer->getEarliestDateOrder();
  405. $distributionsArray = Distribution::searchAll([
  406. 'active' => 1
  407. ], [
  408. 'conditions' => ['date > :date'],
  409. 'params' => [':date' => $dateMini],
  410. ]);
  411. $json['distributions'] = $distributionsArray;
  412. // Commandes de l'utilisateur
  413. $ordersUserArray = Order::searchAll([
  414. 'id_user' => User::getCurrentId()
  415. ], [
  416. 'conditions' => [
  417. 'distribution.date > :date'
  418. ],
  419. 'params' => [
  420. ':date' => $dateMini
  421. ]
  422. ]);
  423. if (is_array($ordersUserArray) && count($ordersUserArray)) {
  424. foreach ($ordersUserArray as &$order) {
  425. $order = array_merge($order->getAttributes(), [
  426. 'amount_total' => $order->getAmount(Order::AMOUNT_TOTAL),
  427. 'date_distribution' => $order->distribution->date,
  428. 'pointSale' => $order->pointSale->getAttributes()
  429. ]);
  430. }
  431. $json['orders'] = $ordersUserArray;
  432. }
  433. // User
  434. $userProducer = UserProducer::searchOne([
  435. 'id_producer' => $producer->id,
  436. 'id_user' => User::getCurrentId()
  437. ]);
  438. $json['user'] = [
  439. 'credit' => $userProducer->credit,
  440. 'credit_active' => $userProducer->credit_active,
  441. ];
  442. if ($dateObject && $dateObject->format($format) === $date) {
  443. // Commande de l'utilisateur
  444. $orderUser = Order::searchOne([
  445. 'distribution.date' => $date,
  446. 'id_user' => User::getCurrentId(),
  447. ]);
  448. if ($orderUser) {
  449. $json['order'] = array_merge($orderUser->getAttributes(), [
  450. 'amount_total' => $orderUser->getAmount(Order::AMOUNT_TOTAL),
  451. 'amount_paid' => $orderUser->getAmount(Order::AMOUNT_PAID),
  452. ]);
  453. }
  454. // distribution
  455. $distribution = Distribution::initDistribution($date);
  456. $json['distribution'] = $distribution;
  457. $pointsSaleArray = PointSale::find()
  458. ->joinWith(['pointSaleDistribution' => function ($query) use ($distribution) {
  459. $query->where(['id_distribution' => $distribution->id]);
  460. }
  461. ])
  462. ->with(['userPointSale' => function ($query) {
  463. $query->onCondition(['id_user' => User::getCurrentId()]);
  464. }])
  465. ->where(['id_producer' => $distribution->id_producer])
  466. ->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)')
  467. ->params([':id_user' => User::getCurrentId()])
  468. ->all();
  469. $creditFunctioningProducer = Producer::getConfig('credit_functioning');
  470. foreach ($pointsSaleArray as &$pointSale) {
  471. $pointSale = array_merge($pointSale->getAttributes(), [
  472. 'pointSaleDistribution' => [
  473. 'id_distribution' => $pointSale->pointSaleDistribution[0]->id_distribution,
  474. 'id_point_sale' => $pointSale->pointSaleDistribution[0]->id_point_sale,
  475. 'delivery' => $pointSale->pointSaleDistribution[0]->delivery
  476. ],
  477. 'userPointSale' => ($pointSale->userPointSale ? $pointSale->userPointSale[0] : '')
  478. ]);
  479. if ($pointSale['code'] && strlen($pointSale['code'])) {
  480. $pointSale['code'] = '***';
  481. }
  482. if (!strlen($pointSale['credit_functioning'])) {
  483. $pointSale['credit_functioning'] = $creditFunctioningProducer;
  484. }
  485. }
  486. $favoritePointSale = User::getCurrent()->getFavoritePointSale();
  487. if ($favoritePointSale) {
  488. for ($i = 0; $i < count($pointsSaleArray); $i++) {
  489. if ($pointsSaleArray[$i]['id'] == $favoritePointSale->id) {
  490. $theFavoritePointSale = $pointsSaleArray[$i];
  491. unset($pointsSaleArray[$i]);
  492. }
  493. }
  494. if (isset($theFavoritePointSale)) {
  495. $pointsSaleArray = array_reverse($pointsSaleArray, false);
  496. $pointsSaleArray[] = $theFavoritePointSale;
  497. $pointsSaleArray = array_reverse($pointsSaleArray, false);
  498. }
  499. }
  500. $json['points_sale'] = $pointsSaleArray;
  501. // Commandes totales
  502. $ordersArray = Order::searchAll([
  503. 'distribution.date' => $date,
  504. ]);
  505. // Produits
  506. if (Producer::getConfig('option_allow_user_gift')) {
  507. $productsArray = Product::find()
  508. ->orWhere(['id_producer' => $this->getProducer()->id,])
  509. ->orWhere(['id_producer' => 0,]); // produit "Don";
  510. } else {
  511. $productsArray = Product::find()
  512. ->where(['id_producer' => $this->getProducer()->id,]);
  513. }
  514. $productsArray = $productsArray->joinWith(['productDistribution' => function ($query) use ($distribution) {
  515. $query->andOnCondition('product_distribution.id_distribution = ' . $distribution->id);
  516. }])
  517. ->orderBy('product_distribution.active DESC, order ASC')
  518. ->all();
  519. $indexProduct = 0;
  520. foreach ($productsArray as &$product) {
  521. $product = array_merge(
  522. $product->getAttributes(),
  523. [
  524. 'price_with_tax' => $product->getPriceWithTax(),
  525. 'productDistribution' => $product['productDistribution']
  526. ]
  527. );
  528. $coefficient_unit = Product::$unitsArray[$product['unit']]['coefficient'];
  529. if (is_null($product['photo'])) {
  530. $product['photo'] = '';
  531. }
  532. $product['quantity_max'] = $product['productDistribution'][0]['quantity_max'];
  533. $quantityOrder = Order::getProductQuantity($product['id'], $ordersArray);
  534. $product['quantity_ordered'] = $quantityOrder;
  535. $product['quantity_remaining'] = $product['quantity_max'] - $quantityOrder;
  536. if ($orderUser) {
  537. $quantityOrderUser = Order::getProductQuantity($product['id'], [$orderUser], true);
  538. $product['quantity_ordered'] = $quantityOrder;
  539. $product['quantity_remaining'] = $product['quantity_max'] - $quantityOrder + $quantityOrderUser;
  540. $product['quantity_form'] = $quantityOrderUser * $coefficient_unit;
  541. foreach ($orderUser->productOrder as $productOrder) {
  542. if ($productOrder->id_product == $product['id']) {
  543. $product['wording_unit'] = Product::strUnit($productOrder->unit, 'wording_unit', true);
  544. $product['step'] = $productOrder->step;
  545. }
  546. }
  547. } else {
  548. $product['quantity_form'] = 0;
  549. $product['wording_unit'] = Product::strUnit($product['unit'], 'wording_unit', true);
  550. }
  551. $product['coefficient_unit'] = $coefficient_unit;
  552. if ($product['quantity_remaining'] < 0) $product['quantity_remaining'] = 0;
  553. $product['index'] = $indexProduct++;
  554. }
  555. $json['products'] = $productsArray;
  556. }
  557. return $json;
  558. }
  559. public function actionConfirm($idOrder)
  560. {
  561. $order = Order::searchOne(['id' => $idOrder]);
  562. if (!$order || $order->id_user != User::getCurrentId()) {
  563. throw new \yii\base\UserException('Commande introuvable.');
  564. }
  565. return $this->render('confirm', [
  566. 'order' => $order
  567. ]);
  568. }
  569. }