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

529 行
20KB

  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. class CommandeController extends ProducerBaseController {
  33. public function behaviors() {
  34. return [
  35. 'access' => [
  36. 'class' => AccessControl::className(),
  37. 'rules' => [
  38. [
  39. 'allow' => true,
  40. 'roles' => ['@'],
  41. ]
  42. ],
  43. ],
  44. ];
  45. }
  46. public function actionInfosProduction($id_production) {
  47. $production = Production::findOne($id_production);
  48. if ($production) {
  49. $arr = [];
  50. $produits_dispos = ProductionProduit::findProduits($production->id);
  51. $arr['produits_dispos'] = $produits_dispos;
  52. $points_vente = PointVente::find()
  53. ->joinWith(['productionPointVente' => function($q) use ($production) {
  54. $q->where(['id_production' => $production->id]);
  55. }])
  56. ->where([
  57. 'id_etablissement' => $production->id_etablissement,
  58. ])
  59. ->all();
  60. $arr['points_vente'] = [];
  61. foreach ($points_vente as $pv) {
  62. if (isset($pv->productionPointVente) &&
  63. isset($pv->productionPointVente[0])) {
  64. $arr['points_vente'][$pv->id] = $pv->productionPointVente[0]->livraison;
  65. } else {
  66. $arr['points_vente'][$pv->id] = false;
  67. }
  68. }
  69. return json_encode($arr);
  70. }
  71. return json_encode([]);
  72. }
  73. public function initForm($commande = null) {
  74. // etablissements
  75. $etablissements = Yii::$app->user->identity->getEtablissementsFavoris();
  76. $id_etablissement = $this->getProducer()->id;
  77. $etablissement_paiement_ok = false;
  78. if ($id_etablissement) {
  79. $etablissement = Etablissement::findOne($id_etablissement);
  80. if ($etablissement->etatPaiement() == Etablissement::PAIEMENT_OK || $etablissement->etatPaiement() == Etablissement::PAIEMENT_ESSAI) {
  81. $etablissement_paiement_ok = true;
  82. }
  83. }
  84. // etablissement
  85. $etablissement = Etablissement::findOne($id_etablissement);
  86. // points de vente
  87. $points_vente = PointVente::find()
  88. ->with('pointVenteUser')
  89. ->where(['id_etablissement' => $id_etablissement])
  90. ->andWhere('acces_restreint = 0 OR (acces_restreint = 1 AND (SELECT COUNT(*) FROM point_vente_user WHERE point_vente.id = point_vente_user.id_point_vente AND point_vente_user.id_user = :id_user) > 0)')
  91. ->params([':id_user' => Yii::$app->user->identity->id])
  92. ->all();
  93. $arr_points_vente = $points_vente;
  94. // jours de production
  95. $heure_limite = 20;
  96. $date = date('Y-m-d');
  97. if (isset($etablissement)) {
  98. $heure_limite = $etablissement->heure_limite_commande;
  99. if (date('H') >= $heure_limite) {
  100. $date = date('Y-m-d', strtotime(date('Y-m-d')) + ($etablissement->delai_commande) * (24 * 60 * 60));
  101. } else {
  102. $date = date('Y-m-d', strtotime(date('Y-m-d')) + ($etablissement->delai_commande - 1) * (24 * 60 * 60));
  103. }
  104. }
  105. $jours_production = Production::find()
  106. ->where(['actif' => 1])
  107. ->andWhere('date > :date')
  108. ->andWhere(['id_etablissement' => $id_etablissement])
  109. ->addParams([':date' => $date])
  110. ->all();
  111. $arr_jours_production = array('' => '--');
  112. foreach ($jours_production as $j)
  113. $arr_jours_production[$j->id] = date('d/m/Y', strtotime($j->date));
  114. // produits
  115. $produits = Produit::find()
  116. ->leftJoin('production_produit', 'produit.id = production_produit.id_produit')
  117. ->where(['produit.actif' => 1, 'id_etablissement' => $id_etablissement])
  118. ->andWhere('produit.vrac IS NULL OR produit.vrac = 0')
  119. ->orderBy('produit.order ASC')->all();
  120. $arr_produits = array();
  121. foreach ($produits as $p)
  122. $arr_produits[] = $p;
  123. // produits vrac
  124. $produits_vrac = Produit::find()->where(['actif' => 1, 'vrac' => 1])->orderBy('order ASC')->all();
  125. // produits selec
  126. $posts = Yii::$app->request->post();
  127. $produits_selec = [];
  128. if (isset($posts['Produit'])) {
  129. foreach ($posts['Produit'] as $key => $quantity) {
  130. $key = (int) str_replace('produit_', '', $key);
  131. $p = Produit::find()->where(['id' => $key])->one();
  132. if ($p && $quantity)
  133. $produits_selec[$p->id] = (int) $quantity;
  134. }
  135. }
  136. elseif (!is_null($commande)) {
  137. $produits_commande = CommandeProduit::find()->where(['id_commande' => $commande->id])->all();
  138. foreach ($produits_commande as $pc) {
  139. $produits_selec[$pc->id_produit] = (int) $pc->quantite;
  140. }
  141. }
  142. $produits_dispos = [];
  143. $production = null;
  144. if (!is_null($commande) && $commande->id_production) {
  145. $produits_dispos = ProductionProduit::findProduits($commande->id_production);
  146. $production = Production::find()->where(['id' => $commande->id_production])->one();
  147. }
  148. $commandes = Commande::find()
  149. ->where(['id_user' => Yii::$app->user->identity->id])
  150. ->all();
  151. if ($id_etablissement) {
  152. $user_etablissement = UserEtablissement::find()
  153. ->where([
  154. 'id_etablissement' => $id_etablissement,
  155. 'id_user' => Yii::$app->user->identity->id
  156. ])
  157. ->one();
  158. $credit = $user_etablissement->credit;
  159. } else {
  160. $credit = 0;
  161. }
  162. return [
  163. 'points_vente' => $arr_points_vente,
  164. 'jours_production' => $arr_jours_production,
  165. 'produits' => $produits,
  166. 'produits_selec' => $produits_selec,
  167. 'produits_dispos' => $produits_dispos,
  168. 'production' => $production,
  169. 'commandes_en_cours' => $commandes,
  170. 'produits_vrac' => $produits_vrac,
  171. 'etablissements' => $etablissements,
  172. 'id_etablissement' => $id_etablissement,
  173. 'etablissement' => $etablissement,
  174. 'etablissement_paiement_ok' => $etablissement_paiement_ok,
  175. 'credit' => $credit
  176. ];
  177. }
  178. /**
  179. * Affiche l'historique des commandes de l'utilisateur
  180. *
  181. * @return ProducerView
  182. */
  183. public function actionHistorique() {
  184. $data_provider_commandes = new ActiveDataProvider([
  185. 'query' => Commande::find()
  186. ->with('commandeProduits', 'pointVente', 'creditHistorique')
  187. ->joinWith('production', 'production.etablissement')
  188. ->where([
  189. 'id_user' => Yii::$app->user->id,
  190. 'production.id_etablissement' => $this->getProducer()->id
  191. ])
  192. ->andWhere('date_delete IS NULL')
  193. ->orderBy('production.date DESC'),
  194. 'pagination' => [
  195. 'pageSize' => 10,
  196. ],
  197. ]);
  198. return $this->render('historique', [
  199. 'data_provider_commandes' => $data_provider_commandes,
  200. 'commande_ok' => Yii::$app->getRequest()->get('commande_ok', false),
  201. 'annule_ok' => Yii::$app->getRequest()->get('annule_ok', false),
  202. ]);
  203. }
  204. public function actionRemoveEtablissement($id = 0) {
  205. $user_etablissement = UserEtablissement::find()
  206. ->where(['id_etablissement' => $id, 'id_user' => Yii::$app->user->identity->id])
  207. ->one();
  208. $user_etablissement->actif = 0;
  209. $user_etablissement->save();
  210. $this->redirect(['commande/index']);
  211. }
  212. public function actionCreate() {
  213. $id_etablissement = $this->getProducer()->id ;
  214. $commande = new Commande;
  215. $posts = Yii::$app->request->post();
  216. if ($id_etablissement)
  217. $this->_verifEtablissementActif($id_etablissement);
  218. if ($commande->load($posts)) {
  219. $commande = Commande::find()->where('id_production = ' . $posts['Commande']['id_production'])->andWhere('id_user = ' . Yii::$app->user->id)->one();
  220. if (!$commande) {
  221. $commande = new Commande;
  222. $commande->load(Yii::$app->request->post());
  223. $commande->id_user = Yii::$app->user->id;
  224. $commande->date = date('Y-m-d H:i:s');
  225. $commande->type = Commande::TYPE_USER;
  226. }
  227. $this->gestionForm($commande);
  228. }
  229. return $this->render('create', array_merge($this->initForm($commande), [
  230. 'model' => $commande
  231. ]));
  232. }
  233. public function actionUpdate($id) {
  234. $commande = Commande::find()
  235. ->with('production')
  236. ->where(['id' => $id])
  237. ->one();
  238. if ($commande->getEtat() != Commande::ETAT_MODIFIABLE) {
  239. throw new UserException('Cette commande n\'est pas modifiable.');
  240. }
  241. $this->_verifEtablissementActif($commande->production->id_etablissement);
  242. if ($commande && $commande->load(Yii::$app->request->post())) {
  243. $commande->date_update = date('Y-m-d H:i:s');
  244. $this->gestionForm($commande);
  245. }
  246. return $this->render('update', array_merge($this->initForm($commande), [
  247. 'model' => $commande,
  248. 'commande_introuvable' => !$commande,
  249. ]));
  250. }
  251. public function _verifEtablissementActif($id_etablissement) {
  252. $etablissement = Etablissement::findOne($id_etablissement);
  253. if ($etablissement && !$etablissement->actif) {
  254. throw new NotFoundHttpException('Cet établissement est actuellement hors ligne.');
  255. }
  256. }
  257. public function gestionForm($commande) {
  258. $posts = Yii::$app->request->post();
  259. $produits = array();
  260. $quantite_totale = 0;
  261. foreach ($posts['Produit'] as $key => $quantity) {
  262. $key = (int) str_replace('produit_', '', $key);
  263. $p = Produit::find()->where(['id' => $key])->one();
  264. $quantite_totale += $quantity;
  265. if ($p && $quantity)
  266. $produits[] = $p;
  267. }
  268. // nombre de produits
  269. $err_nb_produits = false;
  270. if (!Yii::$app->user->identity->confiance && $quantite_totale > 3) {
  271. $err_nb_produits = true;
  272. }
  273. // date
  274. $err_date = false;
  275. $pate_deja_petrie = false;
  276. if (isset($commande->id_production)) {
  277. // date de commande
  278. $production = Production::find()->where(['id' => $commande->id_production])->one();
  279. if (date('H') >= 20) {
  280. $date = date('Y-m-d', strtotime(date('Y-m-d')) + 60 * 60 * 24);
  281. } else {
  282. $date = date('Y-m-d');
  283. }
  284. if ($production->date < $date) {
  285. $err_date = true;
  286. }
  287. }
  288. // point de vente
  289. $err_point_vente = false;
  290. if (isset($production) && $production) {
  291. $ppv = ProductionPointVente::find()
  292. ->where([
  293. 'id_production' => $production->id,
  294. 'id_point_vente' => $posts['Commande']['id_point_vente']
  295. ])
  296. ->one();
  297. if (!$ppv || !$ppv->livraison) {
  298. $err_point_vente = true;
  299. }
  300. $point_vente = PointVente::findOne($posts['Commande']['id_point_vente']);
  301. if ($point_vente) {
  302. if (strlen($point_vente->code) && !$point_vente->verifCode($posts['code_point_vente_' . $point_vente->id])) {
  303. $err_point_vente = true;
  304. }
  305. } else {
  306. $err_point_vente = true;
  307. }
  308. }
  309. if ($commande->validate() && count($produits) && !$err_nb_produits && !$err_date && !$err_point_vente) {
  310. // gestion point de vente
  311. $pv = PointVente::find()
  312. ->with('pointVenteUser')
  313. ->where(['id' => $commande->id_point_vente])
  314. ->one();
  315. if ($pv && strlen($pv->getCommentaire()))
  316. $commande->commentaire_point_vente = $pv->getCommentaire();
  317. else
  318. $commande->commentaire_point_vente = '';
  319. // sauvegarde de la commande
  320. $commande->save();
  321. // ajout de l'utilisateur à l'établissement
  322. Etablissement::addUser(Yii::$app->user->identity->id, $production->id_etablissement) ;
  323. // suppression de tous les enregistrements CommandeProduit
  324. if (!is_null($commande)) {
  325. CommandeProduit::deleteAll(['id_commande' => $commande->id]);
  326. }
  327. // produits dispos
  328. $produits_dispos = ProductionProduit::findProduits($production->id);
  329. // sauvegarde des produits
  330. foreach ($produits as $p) {
  331. // le produit doit etre dispo à la vente
  332. if (isset($produits_dispos[$p->id]) && $produits_dispos[$p->id]['actif']) {
  333. $commande_produit = new CommandeProduit();
  334. $commande_produit->id_commande = $commande->id;
  335. $commande_produit->id_produit = $p->id;
  336. $commande_produit->prix = $p->prix;
  337. $quantite_voulue = (int) $posts['Produit']['produit_' . $p->id];
  338. if ($produits_dispos[$p->id]['quantite_max'] && $quantite_voulue > $produits_dispos[$p->id]['quantite_restante'])
  339. $quantite_voulue = $produits_dispos[$p->id]['quantite_restante'];
  340. $commande_produit->quantite = $quantite_voulue;
  341. $commande_produit->save();
  342. }
  343. }
  344. // credit pain
  345. $credit_pain = isset($posts['credit_pain']) && $posts['credit_pain'];
  346. if ($credit_pain && ($pv->credit_pain || $commande->getMontantPaye())) {
  347. $commande = Commande::find()
  348. ->with('commandeProduits')
  349. ->where(['id' => $commande->id])
  350. ->one();
  351. $commande->init();
  352. $montant_paye = $commande->getMontantPaye();
  353. // à payer
  354. if ($commande->getStatutPaiement() == Commande::STATUT_IMPAYEE) {
  355. $montant_payer = $commande->montant - $montant_paye;
  356. $credit = Yii::$app->user->identity->getCredit($production->id_etablissement);
  357. if ($montant_payer > $credit) {
  358. $montant_payer = $credit;
  359. }
  360. if ($montant_payer > 0) {
  361. $commande->creditHistorique(
  362. CreditHistorique::TYPE_PAIEMENT,
  363. $montant_payer,
  364. $production->id_etablissement,
  365. Yii::$app->user->identity->id,
  366. Yii::$app->user->identity->id
  367. );
  368. }
  369. }
  370. // surplus à rembourser
  371. elseif ($commande->getStatutPaiement() == Commande::STATUT_SURPLUS) {
  372. $montant_rembourser = $montant_paye - $commande->montant;
  373. $commande->creditHistorique(
  374. CreditHistorique::TYPE_REMBOURSEMENT,
  375. $montant_rembourser,
  376. $production->id_etablissement,
  377. Yii::$app->user->identity->id,
  378. Yii::$app->user->identity->id
  379. );
  380. }
  381. }
  382. // redirection
  383. $this->redirect(Yii::$app->urlManager->createUrl(['commande/historique', 'commande_ok' => true, 'pate_deja_petrie' => $pate_deja_petrie]));
  384. } else {
  385. if (!count($produits))
  386. Yii::$app->session->setFlash('error', "Vous n'avez choisi aucun produit");
  387. if ($err_nb_produits)
  388. Yii::$app->session->setFlash('error', "Vous ne pouvez pas commander plus de 3 produits");
  389. if ($err_date)
  390. Yii::$app->session->setFlash('error', "Vous ne pouvez pas commander pour cette date.");
  391. if ($err_point_vente)
  392. Yii::$app->session->setFlash('error', "Point de vente invalide.");
  393. }
  394. }
  395. public function actionAnnuler($id) {
  396. $commande = Commande::find()
  397. ->with('production', 'creditHistorique', 'commandeProduits')
  398. ->where(['id' => $id])
  399. ->one();
  400. if(!$commande)
  401. throw new \yii\web\NotFoundHttpException('Commande introuvable');
  402. if ($commande->getEtat() != Commande::ETAT_MODIFIABLE) {
  403. throw new UserException('Vous ne pouvez plus annuler cette commande.');
  404. }
  405. $commande->init();
  406. if ($commande && Yii::$app->user->id == $commande->id_user) {
  407. // remboursement
  408. if ($commande->getMontantPaye()) {
  409. $commande->creditHistorique(
  410. CreditHistorique::TYPE_REMBOURSEMENT,
  411. $commande->getMontantPaye(),
  412. $commande->production->id_etablissement,
  413. Yii::$app->user->identity->id,
  414. Yii::$app->user->identity->id
  415. );
  416. }
  417. // delete
  418. $commande->date_delete = date('Y-m-d H:i:s');
  419. $commande->save() ;
  420. Yii::$app->session->setFlash('success','Votre commande a bien été annulée.') ;
  421. }
  422. $this->redirect(Yii::$app->urlManager->createUrl(['commande/historique']));
  423. }
  424. public function actionVerifCodePointVente($id_point_vente, $code) {
  425. $point_vente = PointVente::findOne($id_point_vente);
  426. if ($point_vente) {
  427. if ($point_vente->verifCode($code)) {
  428. return true;
  429. }
  430. }
  431. return false;
  432. }
  433. }