Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

669 lines
30KB

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