選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

688 行
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. 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. $order->changeOrderStatus('new-order', 'user');
  257. // ajout de l'utilisateur à l'établissement
  258. Producer::addUser(User::getCurrentId(), $distribution->id_producer);
  259. // suppression de tous les enregistrements ProductOrder
  260. if (!is_null($order)) {
  261. ProductOrder::deleteAll(['id_order' => $order->id]);
  262. $stepsArray = [];
  263. if (isset($order->productOrder)) {
  264. foreach ($order->productOrder as $productOrder) {
  265. $unitsArray[$productOrder->id_product] = $productOrder->unit;
  266. }
  267. }
  268. }
  269. // produits dispos
  270. $availableProducts = ProductDistribution::searchByDistribution($distribution->id);
  271. // sauvegarde des produits
  272. foreach ($productsArray as $product) {
  273. if (isset($availableProducts[$product->id])) {
  274. $productOrder = new ProductOrder();
  275. $productOrder->id_order = $order->id;
  276. $productOrder->id_product = $product->id;
  277. $productOrder->price = $product->price;
  278. $productOrder->id_tax_rate = $product->taxRate->id;
  279. $unit = (!is_null($order) && isset($unitsArray[$product->id])) ? $unitsArray[$product->id] : $product->unit;
  280. $coefficient = Product::$unitsArray[$unit]['coefficient'];
  281. $quantity = ((float)$posts['products'][$product->id]) / $coefficient;
  282. if ($availableProducts[$product->id]['quantity_max'] && $quantity > $availableProducts[$product->id]['quantity_remaining']) {
  283. $quantity = $availableProducts[$product->id]['quantity_remaining'];
  284. }
  285. $productOrder->quantity = $quantity;
  286. $productOrder->unit = $product->unit;
  287. $productOrder->step = $product->step;
  288. $productOrder->save();
  289. }
  290. }
  291. // lien utilisateur / point de vente
  292. $pointSale->linkUser(User::getCurrentId());
  293. // credit
  294. $credit = Producer::getConfig('credit');
  295. $creditLimit = Producer::getConfig('credit_limit');
  296. $creditFunctioning = $pointSale->getCreditFunctioning();
  297. $creditUser = Yii::$app->user->identity->getCredit($distribution->id_producer);
  298. $order = Order::searchOne([
  299. 'id' => $order->id
  300. ]);
  301. $amountPaid = $order->getAmount(Order::AMOUNT_PAID);
  302. $amountRemaining = $order->getAmount(Order::AMOUNT_REMAINING);
  303. if ($credit && $pointSale->credit &&
  304. (($creditFunctioning == Producer::CREDIT_FUNCTIONING_OPTIONAL && $posts['use_credit']) ||
  305. $creditFunctioning == Producer::CREDIT_FUNCTIONING_MANDATORY ||
  306. ($creditFunctioning == Producer::CREDIT_FUNCTIONING_USER && $userProducer->credit_active)
  307. )) {
  308. $order->changeOrderStatus('waiting-paiement-by-credit', 'user');
  309. // à payer
  310. if ($order->getPaymentStatus() == Order::PAYMENT_UNPAID) {
  311. if (!is_null($creditLimit) && $amountRemaining > $creditUser - $creditLimit) {
  312. $amountRemaining = $creditUser - $creditLimit;
  313. }
  314. if ($amountRemaining > 0) {
  315. $order->saveCreditHistory(
  316. CreditHistory::TYPE_PAYMENT,
  317. $amountRemaining,
  318. $distribution->id_producer,
  319. User::getCurrentId(),
  320. User::getCurrentId()
  321. );
  322. $order->changeOrderStatus('paid-by-credit', 'user');
  323. }else{
  324. $order->changeOrderStatus('waiting-paiement-on-delivery', 'user');
  325. }
  326. } // surplus à rembourser
  327. elseif ($order->getPaymentStatus() == Order::PAYMENT_SURPLUS) {
  328. $amountSurplus = $order->getAmount(Order::AMOUNT_SURPLUS);
  329. $order->saveCreditHistory(
  330. CreditHistory::TYPE_REFUND,
  331. $amountSurplus,
  332. $distribution->id_producer,
  333. User::getCurrentId(),
  334. User::getCurrentId()
  335. );
  336. }
  337. }
  338. else{
  339. $order->changeOrderStatus('waiting-paiement-on-delivery', 'user');
  340. }
  341. $order->setTillerSynchronization() ;
  342. }
  343. if (!count($productsArray)) {
  344. $errors[] = "Vous n'avez choisi aucun produit";
  345. }
  346. if ($errorDate) {
  347. $errors[] = "Vous ne pouvez pas commander pour cette date.";
  348. }
  349. if ($errorPointSale) {
  350. $errors[] = "Point de vente invalide.";
  351. }
  352. return $errors;
  353. }
  354. /**
  355. * Annule une commande.
  356. *
  357. * @param integer $id
  358. * @throws \yii\web\NotFoundHttpException
  359. * @throws UserException
  360. */
  361. public function actionCancel($id)
  362. {
  363. $order = Order::searchOne([
  364. 'id' => $id
  365. ]);
  366. if (!$order) {
  367. throw new \yii\web\NotFoundHttpException('Commande introuvable');
  368. }
  369. if ($order->getState() != Order::STATE_OPEN) {
  370. throw new UserException('Vous ne pouvez plus annuler cette commande.');
  371. }
  372. if ($order && User::getCurrentId() == $order->id_user) {
  373. $order->delete();
  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 = date('Y-m-d') ;
  415. $distributionsArray = Distribution::searchAll([
  416. 'active' => 1
  417. ], [
  418. 'conditions' => ['date > :date'],
  419. 'params' => [':date' => $dateMini],
  420. ]);
  421. $distributionsArray = Distribution::filterDistributionsByDateDelay($distributionsArray) ;
  422. $json['distributions'] = $distributionsArray;
  423. // Commandes de l'utilisateur
  424. $ordersUserArray = Order::searchAll([
  425. 'id_user' => User::getCurrentId()
  426. ], [
  427. 'conditions' => [
  428. 'distribution.date > :date'
  429. ],
  430. 'params' => [
  431. ':date' => $dateMini
  432. ]
  433. ]);
  434. if (is_array($ordersUserArray) && count($ordersUserArray)) {
  435. foreach ($ordersUserArray as &$order) {
  436. $order = array_merge($order->getAttributes(), [
  437. 'amount_total' => $order->getAmountWithTax(Order::AMOUNT_TOTAL),
  438. 'date_distribution' => $order->distribution->date,
  439. 'pointSale' => $order->pointSale->getAttributes()
  440. ]);
  441. }
  442. $json['orders'] = $ordersUserArray;
  443. }
  444. // User
  445. $userProducer = UserProducer::searchOne([
  446. 'id_producer' => $producer->id,
  447. 'id_user' => User::getCurrentId()
  448. ]);
  449. $json['user'] = [
  450. 'credit' => $userProducer->credit,
  451. 'credit_active' => $userProducer->credit_active,
  452. ];
  453. if ($dateObject && $dateObject->format($format) === $date) {
  454. // Commande de l'utilisateur
  455. $orderUser = Order::searchOne([
  456. 'distribution.date' => $date,
  457. 'id_user' => User::getCurrentId(),
  458. ]);
  459. if ($orderUser) {
  460. $json['order'] = array_merge($orderUser->getAttributes(), [
  461. 'amount_total' => $orderUser->getAmountWithTax(Order::AMOUNT_TOTAL),
  462. 'amount_paid' => $orderUser->getAmount(Order::AMOUNT_PAID),
  463. ]);
  464. }
  465. // distribution
  466. $distribution = Distribution::initDistribution($date);
  467. $json['distribution'] = $distribution;
  468. $pointsSaleArray = PointSale::find()
  469. ->joinWith(['pointSaleDistribution' => function ($query) use ($distribution) {
  470. $query->where(['id_distribution' => $distribution->id]);
  471. }
  472. ])
  473. ->with(['userPointSale' => function ($query) {
  474. $query->onCondition(['id_user' => User::getCurrentId()]);
  475. }])
  476. ->where(['id_producer' => $distribution->id_producer])
  477. ->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)')
  478. ->params([':id_user' => User::getCurrentId()])
  479. ->all();
  480. $creditFunctioningProducer = Producer::getConfig('credit_functioning');
  481. foreach ($pointsSaleArray as &$pointSale) {
  482. $pointSale = array_merge($pointSale->getAttributes(), [
  483. 'pointSaleDistribution' => [
  484. 'id_distribution' => $pointSale->pointSaleDistribution[0]->id_distribution,
  485. 'id_point_sale' => $pointSale->pointSaleDistribution[0]->id_point_sale,
  486. 'delivery' => $pointSale->pointSaleDistribution[0]->delivery
  487. ],
  488. 'userPointSale' => ($pointSale->userPointSale ? $pointSale->userPointSale[0] : '')
  489. ]);
  490. if ($pointSale['code'] && strlen($pointSale['code'])) {
  491. $pointSale['code'] = '***';
  492. }
  493. if (!strlen($pointSale['credit_functioning'])) {
  494. $pointSale['credit_functioning'] = $creditFunctioningProducer;
  495. }
  496. }
  497. $favoritePointSale = User::getCurrent()->getFavoritePointSale();
  498. if ($favoritePointSale) {
  499. for ($i = 0; $i < count($pointsSaleArray); $i++) {
  500. if ($pointsSaleArray[$i]['id'] == $favoritePointSale->id) {
  501. $theFavoritePointSale = $pointsSaleArray[$i];
  502. unset($pointsSaleArray[$i]);
  503. }
  504. }
  505. if (isset($theFavoritePointSale)) {
  506. $pointsSaleArray = array_reverse($pointsSaleArray, false);
  507. $pointsSaleArray[] = $theFavoritePointSale;
  508. $pointsSaleArray = array_reverse($pointsSaleArray, false);
  509. }
  510. }
  511. $json['points_sale'] = $pointsSaleArray;
  512. // Commandes totales
  513. $ordersArray = Order::searchAll([
  514. 'distribution.date' => $date,
  515. ]);
  516. // Produits
  517. if (Producer::getConfig('option_allow_user_gift')) {
  518. $productsArray = Product::find()
  519. ->orWhere(['id_producer' => $this->getProducer()->id,])
  520. //->orWhere(['id_producer' => 0,]) // produit "Don";
  521. ;
  522. } else {
  523. $productsArray = Product::find()
  524. ->where(['id_producer' => $this->getProducer()->id,]);
  525. }
  526. $productsArray = $productsArray->joinWith(['productDistribution' => function ($query) use ($distribution) {
  527. $query->andOnCondition('product_distribution.id_distribution = ' . $distribution->id);
  528. }])
  529. ->orderBy('product_distribution.active DESC, order ASC')
  530. ->all();
  531. $indexProduct = 0;
  532. foreach ($productsArray as &$product) {
  533. $product = array_merge(
  534. $product->getAttributes(),
  535. [
  536. 'price_with_tax' => $product->getPriceWithTax(),
  537. 'productDistribution' => $product['productDistribution']
  538. ]
  539. );
  540. $coefficient_unit = Product::$unitsArray[$product['unit']]['coefficient'];
  541. if (is_null($product['photo'])) {
  542. $product['photo'] = '';
  543. }
  544. $product['quantity_max'] = $product['productDistribution'][0]['quantity_max'];
  545. $quantityOrder = Order::getProductQuantity($product['id'], $ordersArray);
  546. $product['quantity_ordered'] = $quantityOrder;
  547. $product['quantity_remaining'] = $product['quantity_max'] - $quantityOrder;
  548. if ($orderUser) {
  549. $quantityOrderUser = Order::getProductQuantity($product['id'], [$orderUser], true);
  550. $product['quantity_ordered'] = $quantityOrder;
  551. $product['quantity_remaining'] = $product['quantity_max'] - $quantityOrder + $quantityOrderUser;
  552. $product['quantity_form'] = $quantityOrderUser * $coefficient_unit;
  553. foreach ($orderUser->productOrder as $productOrder) {
  554. if ($productOrder->id_product == $product['id']) {
  555. $product['wording_unit'] = Product::strUnit($productOrder->unit, 'wording_unit', true);
  556. $product['step'] = $productOrder->step;
  557. }
  558. }
  559. } else {
  560. $product['quantity_form'] = 0;
  561. $product['wording_unit'] = Product::strUnit($product['unit'], 'wording_unit', true);
  562. }
  563. $product['coefficient_unit'] = $coefficient_unit;
  564. if ($product['quantity_remaining'] < 0) $product['quantity_remaining'] = 0;
  565. $product['index'] = $indexProduct++;
  566. }
  567. $json['products'] = $productsArray;
  568. }
  569. return $json;
  570. }
  571. public function actionConfirm($idOrder)
  572. {
  573. $order = Order::searchOne(['id' => $idOrder]);
  574. if (!$order || $order->id_user != User::getCurrentId()) {
  575. throw new \yii\base\UserException('Commande introuvable.');
  576. }
  577. return $this->render('confirm', [
  578. 'order' => $order
  579. ]);
  580. }
  581. }