Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

OrderController.php 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  1. <?php
  2. /**
  3. Copyright La boîte à pain (2018)
  4. contact@laboiteapain.net
  5. Ce logiciel est un programme informatique servant à aider les producteurs
  6. à distribuer leur production en circuits courts.
  7. Ce logiciel est régi par la licence CeCILL soumise au droit français et
  8. respectant les principes de diffusion des logiciels libres. Vous pouvez
  9. utiliser, modifier et/ou redistribuer ce programme sous les conditions
  10. de la licence CeCILL telle que diffusée par le CEA, le CNRS et l'INRIA
  11. sur le site "http://www.cecill.info".
  12. En contrepartie de l'accessibilité au code source et des droits de copie,
  13. de modification et de redistribution accordés par cette licence, il n'est
  14. offert aux utilisateurs qu'une garantie limitée. Pour les mêmes raisons,
  15. seule une responsabilité restreinte pèse sur l'auteur du programme, le
  16. titulaire des droits patrimoniaux et les concédants successifs.
  17. A cet égard l'attention de l'utilisateur est attirée sur les risques
  18. associés au chargement, à l'utilisation, à la modification et/ou au
  19. développement et à la reproduction du logiciel par l'utilisateur étant
  20. donné sa spécificité de logiciel libre, qui peut le rendre complexe à
  21. manipuler et qui le réserve donc à des développeurs et des professionnels
  22. avertis possédant des connaissances informatiques approfondies. Les
  23. utilisateurs sont donc invités à charger et tester l'adéquation du
  24. logiciel à leurs besoins dans des conditions permettant d'assurer la
  25. sécurité de leurs systèmes et ou de leurs données et, plus généralement,
  26. à l'utiliser et l'exploiter dans les mêmes conditions de sécurité.
  27. Le fait que vous puissiez accéder à cet en-tête signifie que vous avez
  28. pris connaissance de la licence CeCILL, et que vous en avez accepté les
  29. termes.
  30. */
  31. namespace producer\controllers;
  32. use common\models\ProductDistribution ;
  33. class OrderController extends ProducerBaseController
  34. {
  35. public function behaviors()
  36. {
  37. return [
  38. 'access' => [
  39. 'class' => AccessControl::className(),
  40. 'rules' => [
  41. [
  42. 'allow' => true,
  43. 'roles' => ['@'],
  44. ]
  45. ],
  46. ],
  47. ];
  48. }
  49. /**
  50. * Retourne au format JSON toutes les informations relatives à une
  51. * production donnée.
  52. *
  53. * @param integer $idDistribution
  54. * @return mixed
  55. */
  56. public function actionInfosDistribution($idDistribution)
  57. {
  58. $distribution = Distribution::searchOne($idDistribution);
  59. if ($distribution) {
  60. $arr = [];
  61. $productsArray = ProductDistribution::searchByDistribution($distribution->id) ;
  62. $data['products'] = $productsArray;
  63. $pointSaleArray = PointSale::find()
  64. ->joinWith(['pointSaleDistribution' => function($q) use ($distribution) {
  65. $q->where(['id_distribution' => $distribution->id]);
  66. }])
  67. ->where([
  68. 'id_producer' => $distribution->id_producer,
  69. ])
  70. ->all();
  71. $data['pointsSale'] = [];
  72. foreach ($pointSaleArray as $pointSale) {
  73. if (isset($pointSale->pointSaleDistribution) &&
  74. isset($pointSale->pointSaleDistribution[0])) {
  75. $data['points_vente'][$pointSale->id] = $pointSale->pointSaleDistribution[0]->delivery;
  76. } else {
  77. $data['points_vente'][$pointSale->id] = false;
  78. }
  79. }
  80. return json_encode($data);
  81. }
  82. return json_encode([]);
  83. }
  84. /**
  85. * Initialise le formulaire de création/modification de commande.
  86. *
  87. * @param Order $order
  88. * @return array
  89. */
  90. public function initForm($order = null) {
  91. // Producteurs
  92. $producersArray = Yii::$app->user->identity->getBookmarkedProducers();
  93. $idProducer = $this->getProducer()->id;
  94. // Producteur
  95. $producer = Producer::findOne($idProducer);
  96. // Points de vente
  97. $pointsSaleArray = PointSale::find()
  98. ->with('userPointSale')
  99. ->where(['id_producer' => $idProducer])
  100. ->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 point_sale_user.id_user = :id_user) > 0)')
  101. ->params([':id_user' => User::getCurrentId()])
  102. ->all();
  103. // jours de production
  104. $deadline = 20;
  105. $date = date('Y-m-d');
  106. if (isset($producer)) {
  107. $deadline = $producer->order_deadline;
  108. if (date('H') >= $deadline) {
  109. $date = date('Y-m-d', strtotime(date('Y-m-d')) + ($producer->order_delay) * (24 * 60 * 60));
  110. } else {
  111. $date = date('Y-m-d', strtotime(date('Y-m-d')) + ($producer->order_delay - 1) * (24 * 60 * 60));
  112. }
  113. }
  114. $distributionDays = Distribution::find()
  115. ->where(['active' => 1])
  116. ->andWhere('date > :date')
  117. ->andWhere(['id_producer' => $idProducer])
  118. ->addParams([':date' => $date])
  119. ->all();
  120. $distributionDaysArray = array('' => '--');
  121. foreach ($distributionDays as $distribution) {
  122. $distributionDaysArray[$distribution->id] = date('d/m/Y', strtotime($distribution->date));
  123. }
  124. // produits
  125. $products = Product::find()
  126. ->leftJoin('product_distribution', 'product.id = product_distribution.id_product')
  127. ->where(['product.active' => 1, 'id_producer' => $idProducer])
  128. ->orderBy('product.order ASC')->all();
  129. $productsArray = [] ;
  130. foreach ($products as $p)
  131. $productsArray[] = $p;
  132. // produits selec
  133. $posts = Yii::$app->request->post();
  134. $selectedProducts = [];
  135. if (isset($posts['Product'])) {
  136. foreach ($posts['Product'] as $key => $quantity) {
  137. $key = (int) str_replace('product_', '', $key);
  138. $product = Product::find()->where(['id' => $key])->one();
  139. if ($product && $quantity)
  140. $selectedProducts[$product->id] = (int) $quantity;
  141. }
  142. }
  143. elseif (!is_null($order)) {
  144. $productOrderArray = ProductOrder::searchAll([
  145. 'id_order' => $order->id
  146. ]) ;
  147. foreach ($productOrderArray as $productOrder) {
  148. $selectedProducts[$productOrder->id_product] = (int) $productOrder->quantity;
  149. }
  150. }
  151. $availableProducts = [] ;
  152. $distribution = null;
  153. if (!is_null($order) && $order->id_distribution) {
  154. $availableProducts = ProductDistribution::searchByDistribution($order->id_distribution);
  155. $distribution = Distribution::find()->where(['id' => $order->id_distribution])->one();
  156. }
  157. $orders = Order::searchAll([
  158. 'id_user' => User::getCurrentId()
  159. ]) ;
  160. if ($idProducer) {
  161. $userProducer = UserProducer::searchOne([
  162. 'id_producer' => $idProducer,
  163. 'id_user' => User::getCurrentId()
  164. ]) ;
  165. $credit = $userProducer->credit;
  166. } else {
  167. $credit = 0;
  168. }
  169. return [
  170. 'pointsSaleArray' => $pointsSaleArray,
  171. 'distributionDaysArray' => $distributionDaysArray,
  172. 'productsArray' => $productsArray,
  173. 'selectedProducts' => $selectedProducts,
  174. 'availableProducts' => $availableProducts,
  175. 'distribution' => $distribution,
  176. 'ordersArray' => $orders,
  177. 'producersArray' => $producersArray,
  178. 'idProducer' => $idProducer,
  179. 'producer' => $producer,
  180. 'credit' => $credit
  181. ];
  182. }
  183. /**
  184. * Affiche l'historique des commandes de l'utilisateur
  185. *
  186. * @return ProducerView
  187. */
  188. public function actionHistory()
  189. {
  190. $dataProviderOrders = new ActiveDataProvider([
  191. 'query' => Order::find()
  192. ->with('productOrder', 'pointSale', 'creditHistory')
  193. ->joinWith('distribution', 'distribution.producer')
  194. ->where([
  195. 'id_user' => Yii::$app->user->id,
  196. 'distribution.id_producer' => $this->getProducer()->id
  197. ])
  198. ->andWhere('date_delete IS NULL')
  199. ->orderBy('distribution.date DESC'),
  200. 'pagination' => [
  201. 'pageSize' => 10,
  202. ],
  203. ]);
  204. return $this->render('history', [
  205. 'dataProviderOrders' => $dataProviderOrders,
  206. 'orderOk' => Yii::$app->getRequest()->get('orderOk', false),
  207. 'cancelOk' => Yii::$app->getRequest()->get('cancelOk', false),
  208. ]);
  209. }
  210. /**
  211. * Supprime un producteur.
  212. *
  213. * @param integer $id
  214. */
  215. public function actionRemoveProducer($id = 0)
  216. {
  217. $userProducer = UserProducer::find()
  218. ->where(['id_producer' => $id, 'id_user' => User::getCurrentId()])
  219. ->one();
  220. $userProducer->active = 0;
  221. $userProducer->save();
  222. $this->redirect(['order/index']);
  223. }
  224. /**
  225. * Crée une commande.
  226. *
  227. * @return mixed
  228. */
  229. public function actionCreate()
  230. {
  231. $idProducer = $this->getProducer()->id ;
  232. $order = new Order;
  233. $posts = Yii::$app->request->post();
  234. if ($idProducer) {
  235. $this->_verifyProducerActive($idProducer);
  236. }
  237. if ($order->load($posts)) {
  238. $order = Order::find()->where('id_distribution = ' . $posts['Order']['id_distribution'])->andWhere('id_user = ' . User::getCurrentId())->one();
  239. if (!$order) {
  240. $order = new Order;
  241. $order->load(Yii::$app->request->post());
  242. $order->id_user = User::getCurrentId();
  243. $order->date = date('Y-m-d H:i:s');
  244. $order->type = Order::ORIGIN_USER;
  245. }
  246. $this->processForm($Order);
  247. }
  248. return $this->render('create', array_merge($this->initForm($order), [
  249. 'model' => $order
  250. ]));
  251. }
  252. /**
  253. * Modifie une commande.
  254. *
  255. * @param integer $id
  256. * @return mixed
  257. * @throws UserException
  258. */
  259. public function actionUpdate($id)
  260. {
  261. $order = sOrder::searchOne([
  262. 'id' => $id
  263. ]) ;
  264. if ($order->getState() != Order::STATE_OPEN) {
  265. throw new UserException('Cette commande n\'est pas modifiable.');
  266. }
  267. $this->_verifyProducerActive($order->distribution->id_producer);
  268. if ($order && $order->load(Yii::$app->request->post())) {
  269. $order->date_update = date('Y-m-d H:i:s');
  270. $this->processForm($order);
  271. }
  272. return $this->render('update', array_merge($this->processForm($order), [
  273. 'model' => $order,
  274. 'orderNotfound' => !$order,
  275. ]));
  276. }
  277. /**
  278. * Vérifie si un producteur est actif.
  279. *
  280. * @param integer $idProducer
  281. * @throws NotFoundHttpException
  282. */
  283. public function _verifyProducerActive($idProducer)
  284. {
  285. $producer = Producer::findOne($idProducer);
  286. if ($producer && !$producer->active) {
  287. throw new NotFoundHttpException('Ce producteur est actuellement hors ligne.');
  288. }
  289. }
  290. /**
  291. * Traite le formulaire de création/modification de commande.
  292. *
  293. * @param Commande $order
  294. */
  295. public function processForm($order)
  296. {
  297. $posts = Yii::$app->request->post();
  298. $productsArray = [];
  299. $totalQuantity = 0;
  300. foreach ($posts['Product'] as $key => $quantity) {
  301. $key = (int) str_replace('product_', '', $key);
  302. $product = Produit::find()->where(['id' => $key])->one();
  303. $totalQuantity += $quantity;
  304. if ($product && $quantity) {
  305. $productsArray[] = $product;
  306. }
  307. }
  308. // date
  309. $errorDate = false;
  310. if (isset($order->id_distribution)) {
  311. // date de commande
  312. $distribution = Distribution::find()->where(['id' => $order->id_distribution])->one();
  313. if (date('H') >= 20) {
  314. $date = date('Y-m-d', strtotime(date('Y-m-d')) + 60 * 60 * 24);
  315. } else {
  316. $date = date('Y-m-d');
  317. }
  318. if ($distribution->date < $date) {
  319. $errorDate = true;
  320. }
  321. }
  322. // point de vente
  323. $errorPointSale = false;
  324. if (isset($distribution) && $distribution) {
  325. $pointSaleDistribution = PointSaleDistribution::searchOne([
  326. 'id_distribution' => $distribution->id,
  327. 'id_point_sale' => $posts['Order']['id_point_sale']
  328. ]) ;
  329. if (!$pointSaleDistribution || !$pointSaleDistribution->delivery) {
  330. $errorPointSale = true;
  331. }
  332. $pointSale = PointSale::findOne($posts['Commande']['id_point_vente']);
  333. if ($pointSale) {
  334. if (strlen($pointSale->code) && !$pointSale->validateCode($posts['code_point_sale_' . $pointSale->id])) {
  335. $errorPointSale = true;
  336. }
  337. } else {
  338. $errorPointSale = true;
  339. }
  340. }
  341. if ($order->validate() && count($productsArray) && !$errorDate && !$errorPointSale) {
  342. // gestion point de vente
  343. $pointSale = PointSale::searchOne([
  344. 'id' => $order->id_point_sale
  345. ]) ;
  346. if ($pointSale && strlen($pointSale->getComment()))
  347. $order->comment_point_sale = $pv->getComment();
  348. else
  349. $order->comment_point_sale = '';
  350. // sauvegarde de la commande
  351. $order->save();
  352. // ajout de l'utilisateur à l'établissement
  353. Producer::addUser(User::getCurrentId(), $distribution->id_producer) ;
  354. // suppression de tous les enregistrements ProductOrder
  355. if (!is_null($order)) {
  356. ProductOrder::deleteAll(['id_order' => $order->id]);
  357. }
  358. // produits dispos
  359. $availableProducts = ProductDistribution::searchByDistribution($distribution->id) ;
  360. // sauvegarde des produits
  361. foreach ($productsArray as $product) {
  362. if (isset($availableProducts[$product->id])) {
  363. $productOrder = new ProductOrder();
  364. $productOrder->id_order = $order->id;
  365. $productOrder->id_product = $product->id;
  366. $productOrder->price = $product->price;
  367. $quantity = (int) $posts['Product']['product_' . $product->id];
  368. if ($produits_dispos[$product->id]['quantity_max'] && $quantity > $availableProducts[$product->id]['quantity_remaining']) {
  369. $quantity = $availableProducts[$p->id]['quantity_remaining'];
  370. }
  371. $productOrder->quantity = $quantity;
  372. $productOrder->save();
  373. }
  374. }
  375. // credit
  376. $credit = isset($posts['credit']) && $posts['credit'];
  377. if ($credit && ($pointSale->credit || $order->getAmount(Order::AMOUNT_PAID))) {
  378. $order = Order::searchOne([
  379. 'id' => $order->id
  380. ]) ;
  381. $amountPaid = $order->getAmount(Order::AMOUNT_PAID);
  382. // à payer
  383. if ($order->getPaymentStatus() == Order::PAYMENT_UNPAID) {
  384. $amountRemaining = $order->getAmount(Order::AMOUNT_REMAINING) ;
  385. $credit = Yii::$app->user->identity->getCredit($distribution->id_producer);
  386. if ($amountRemaining > $credit) {
  387. $amountRemaining = $credit;
  388. }
  389. if ($amountRemaining > 0) {
  390. $order->creditHistory(
  391. CreditHistory::TYPE_PAYMENT,
  392. $amountRemaining,
  393. $distribution->id_producer,
  394. User::getCurrentId(),
  395. User::getCurrentId()
  396. );
  397. }
  398. }
  399. // surplus à rembourser
  400. elseif ($order->getPaymentStatus() == Order::PAYMENT_SURPLUS) {
  401. $amountSurplus = $order->getAmount(Order::AMOUNT_SURPLUS) ;
  402. $order->creditHistory(
  403. CreditHistory::TYPE_REFUND,
  404. $amountSurplus,
  405. $distribution->id_producer,
  406. User::getCurrentId(),
  407. User::getCurrentId()
  408. );
  409. }
  410. }
  411. // redirection
  412. $this->redirect(Yii::$app->urlManager->createUrl(['order/history', 'orderOk' => true]));
  413. }
  414. else {
  415. if (!count($productsArray)) {
  416. Yii::$app->session->setFlash('error', "Vous n'avez choisi aucun produit");
  417. }
  418. if ($errorDate) {
  419. Yii::$app->session->setFlash('error', "Vous ne pouvez pas commander pour cette date.");
  420. }
  421. if ($errorPointSale) {
  422. Yii::$app->session->setFlash('error', "Point de vente invalide.");
  423. }
  424. }
  425. }
  426. /**
  427. * Annule une commande.
  428. *
  429. * @param integer $id
  430. * @throws \yii\web\NotFoundHttpException
  431. * @throws UserException
  432. */
  433. public function actionCancel($id)
  434. {
  435. $order = Order::searchOne([
  436. 'id' => $id
  437. ]) ;
  438. if(!$order) {
  439. throw new \yii\web\NotFoundHttpException('Commande introuvable');
  440. }
  441. if ($order->getState() != Order::STATE_OPEN) {
  442. throw new UserException('Vous ne pouvez plus annuler cette commande.');
  443. }
  444. if ($order && User::getCurrentId() == $order->id_user) {
  445. // remboursement
  446. if ($order->getAmount(Order::AMOUNT_PAID)) {
  447. $order->creditHistory(
  448. CreditHistory::PAYMENT_REFUND,
  449. $order->getAmount(Order::AMOUNT_PAID),
  450. $order->distribution->id_producer,
  451. User::getCurrentId(),
  452. User::getCurrentId()
  453. );
  454. }
  455. // delete
  456. $order->date_delete = date('Y-m-d H:i:s');
  457. $order->save() ;
  458. Yii::$app->session->setFlash('success','Votre commande a bien été annulée.') ;
  459. }
  460. $this->redirect(Yii::$app->urlManager->createUrl(['order/history']));
  461. }
  462. /**
  463. * Vérifie le code saisi pour un point de vente.
  464. *
  465. * @param integer $idPointSale
  466. * @param string $code
  467. * @return boolean
  468. */
  469. public function actionvalidateCodePointSale($idPointSale, $code)
  470. {
  471. $pointSale = PointSale::findOne($idPointSale);
  472. if ($pointSale) {
  473. if ($pointSale->validateCode($code)) {
  474. return true;
  475. }
  476. }
  477. return false;
  478. }
  479. }