Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

689 lines
20KB

  1. <?php
  2. /**
  3. Copyright distrib (2018)
  4. contact@opendistrib.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 common\models;
  32. use Yii;
  33. use yii\helpers\Html;
  34. use common\models\Producer;
  35. use common\components\ActiveRecordCommon ;
  36. /**
  37. * This is the model class for table "order".
  38. *
  39. * @property integer $id
  40. * @property integer $id_user
  41. * @property string $date
  42. * @property string $date_update
  43. * @property integer $id_point_sale
  44. * @property integer $id_distribution
  45. * @property boolean $auto_payment
  46. * @property integer $id_subscription
  47. */
  48. class Order extends ActiveRecordCommon
  49. {
  50. var $amount = 0 ;
  51. var $paid_amount = 0 ;
  52. var $weight = 0 ;
  53. const ORIGIN_AUTO = 'auto';
  54. const ORIGIN_USER = 'user';
  55. const ORIGIN_ADMIN = 'admin';
  56. const PAYMENT_PAID = 'paid';
  57. const PAYMENT_UNPAID = 'unpaid';
  58. const PAYMENT_SURPLUS = 'surplus';
  59. const AMOUNT_TOTAL = 'total' ;
  60. const AMOUNT_PAID = 'paid' ;
  61. const AMOUNT_REMAINING = 'remaining' ;
  62. const AMOUNT_SURPLUS = 'surplus' ;
  63. const STATE_OPEN = 'open';
  64. const STATE_PREPARATION = 'preparation';
  65. const STATE_DELIVERED = 'delivered';
  66. /**
  67. * @inheritdoc
  68. */
  69. public static function tableName()
  70. {
  71. return 'order';
  72. }
  73. /**
  74. * @inheritdoc
  75. */
  76. public function rules()
  77. {
  78. return [
  79. [['id_user', 'date', 'id_point_sale', 'id_distribution'], 'required', 'message' => ''],
  80. [['id_user', 'id_point_sale', 'id_distribution','id_subscription'], 'integer'],
  81. [['auto_payment'], 'boolean'],
  82. [['date', 'date_update', 'comment', 'comment_point_sale'], 'safe']
  83. ];
  84. }
  85. /**
  86. * @inheritdoc
  87. */
  88. public function attributeLabels()
  89. {
  90. return [
  91. 'id' => 'ID',
  92. 'id_user' => 'Id User',
  93. 'date' => 'Date',
  94. 'date_update' => 'Date de modification',
  95. 'id_point_sale' => 'Point de vente',
  96. 'id_distribution' => 'Date de distribution',
  97. 'id_subscription' => 'Abonnement',
  98. ];
  99. }
  100. /*
  101. * Relations
  102. */
  103. public function getUser()
  104. {
  105. return $this->hasOne(User::className(), ['id' => 'id_user']);
  106. }
  107. public function getProductOrder()
  108. {
  109. return $this->hasMany(ProductOrder::className(),['id_order' => 'id'])
  110. ->with('product');
  111. }
  112. public function getDistribution()
  113. {
  114. return $this->hasOne(Distribution::className(), ['id' => 'id_distribution'])
  115. ->with('producer');
  116. }
  117. public function getPointSale()
  118. {
  119. return $this->hasOne(PointSale::className(), ['id' => 'id_point_sale'])
  120. ->with('userPointSale');
  121. }
  122. public function getCreditHistory()
  123. {
  124. return $this->hasMany(CreditHistory::className(), ['id_order' => 'id']);
  125. }
  126. public function getSubscription()
  127. {
  128. return $this->hasOne(Subscription::className(), ['id' => 'id_subscription'])
  129. ->with('productSubscription');
  130. }
  131. /**
  132. * Retourne les options de base nécessaires à la fonction de recherche.
  133. *
  134. * @return array
  135. */
  136. public static function defaultOptionsSearch() {
  137. return [
  138. 'with' => ['productOrder', 'creditHistory','creditHistory.userAction' , 'pointSale'],
  139. 'join_with' => ['distribution', 'user', 'user.userProducer'],
  140. 'orderby' => 'order.date ASC',
  141. 'attribute_id_producer' => 'distribution.id_producer'
  142. ] ;
  143. }
  144. /**
  145. * Initialise le montant total, le montant déjà payé et le poids de la
  146. * commande.
  147. */
  148. public function init()
  149. {
  150. $this->initAmount() ;
  151. $this->initPaidAmount() ;
  152. return $this ;
  153. }
  154. /**
  155. * Initialise le montant de la commande.
  156. *
  157. */
  158. public function initAmount() {
  159. if (isset($this->productOrder)) {
  160. foreach ($this->productOrder as $productOrder) {
  161. if ($productOrder->sale_mode == Product::SALE_MODE_UNIT) {
  162. $this->amount += $productOrder->price * $productOrder->quantity ;
  163. if(isset($productOrder->product)) {
  164. $this->weight += ($productOrder->quantity * $productOrder->product->weight) / 1000 ;
  165. }
  166. }
  167. elseif ($productOrder->sale_mode == Product::SALE_MODE_WEIGHT) {
  168. $this->amount += $productOrder->price * $productOrder->quantity / 1000;
  169. }
  170. }
  171. }
  172. }
  173. /**
  174. * Initialise le montant payé de la commande et le retourne.
  175. *
  176. * @return float
  177. */
  178. public function initPaidAmount()
  179. {
  180. $history = CreditHistory::find()
  181. ->where(['id_order' => $this->id])
  182. ->all();
  183. $this->paid_amount = 0 ;
  184. if(count($history)) {
  185. foreach ($history as $ch) {
  186. if ($ch->type == CreditHistory::TYPE_PAYMENT) {
  187. $this->paid_amount += $ch->amount;
  188. }
  189. elseif ($ch->type == CreditHistory::TYPE_REFUND) {
  190. $this->paid_amount -= $ch->amount;
  191. }
  192. }
  193. }
  194. }
  195. /**
  196. * Retourne le montant de la commande (total, payé, restant, ou en surplus).
  197. *
  198. * @param boolean $format
  199. * @return float
  200. */
  201. public function getAmount($type = self::AMOUNT_TOTAL, $format = false)
  202. {
  203. switch($type) {
  204. case self::AMOUNT_TOTAL :
  205. $amount = $this->amount ;
  206. break ;
  207. case self::AMOUNT_PAID :
  208. $this->initPaidAmount() ;
  209. $amount = $this->paid_amount ;
  210. break ;
  211. case self::AMOUNT_REMAINING :
  212. $amount = $this->getAmount(self::AMOUNT_TOTAL)
  213. - $this->getAmount(self::AMOUNT_PAID) ;
  214. break ;
  215. case self::AMOUNT_SURPLUS :
  216. $amount = $this->getAmount(self::AMOUNT_PAID)
  217. - $this->getAmount(self::AMOUNT_TOTAL) ;
  218. break ;
  219. }
  220. if ($format) {
  221. return number_format($amount, 2) . ' €';
  222. }
  223. else {
  224. return $amount;
  225. }
  226. }
  227. /**
  228. * Retourne les informations relatives à la commande au format JSON.
  229. *
  230. * @return string
  231. */
  232. public function getDataJson()
  233. {
  234. $order = Order::searchOne(['order.id' => $this->id]) ;
  235. $jsonOrder = [] ;
  236. if($order) {
  237. $jsonOrder = [
  238. 'products' => [],
  239. 'amount' => $order->amount,
  240. 'str_amount' => $order->getAmount(self::AMOUNT_TOTAL, true),
  241. 'paid_amount' => $order->getAmount(self::AMOUNT_PAID),
  242. 'comment' => $order->comment,
  243. ];
  244. foreach ($order->productOrder as $productOrder) {
  245. $jsonOrder['products'][$productOrder->id_product] = $productOrder->quantity;
  246. }
  247. }
  248. return json_encode($jsonOrder);
  249. }
  250. /**
  251. * Enregistre un modèle de type CreditHistory.
  252. *
  253. * @param string $type
  254. * @param float $montant
  255. * @param integer $idProducer
  256. * @param integer $idUser
  257. * @param integer $idUserAction
  258. */
  259. public function saveCreditHistory($type, $amount, $idProducer, $idUser, $idUserAction)
  260. {
  261. $creditHistory = new CreditHistory;
  262. $creditHistory->id_user = $this->id_user;
  263. $creditHistory->id_order = $this->id;
  264. $creditHistory->amount = $amount;
  265. $creditHistory->type = $type;
  266. $creditHistory->id_producer = $idProducer;
  267. $creditHistory->id_user_action = $idUserAction;
  268. $creditHistory->populateRelation('order', $this) ;
  269. $creditHistory->populateRelation('user', User::find()->where(['id' => $this->id_user])->one()) ;
  270. $creditHistory->save();
  271. }
  272. /**
  273. * Ajuste le crédit pour que la commande soit payée.
  274. *
  275. * @return boolean
  276. */
  277. public function processCredit()
  278. {
  279. if($this->id_user) {
  280. $paymentStatus = $this->getPaymentStatus() ;
  281. if($paymentStatus == self::PAYMENT_PAID) {
  282. return true;
  283. }
  284. elseif($paymentStatus == self::PAYMENT_SURPLUS) {
  285. $type = CreditHistory::TYPE_REFUND ;
  286. $amount = $this->getAmount(self::AMOUNT_SURPLUS) ;
  287. }
  288. elseif($paymentStatus == self::PAYMENT_UNPAID) {
  289. $type = CreditHistory::TYPE_PAYMENT ;
  290. $amount = $this->getAmount(self::AMOUNT_REMAINING) ;
  291. }
  292. $this->saveCreditHistory(
  293. $type,
  294. $amount,
  295. Producer::getId(),
  296. $this->id_user,
  297. User::getCurrentId()
  298. );
  299. }
  300. }
  301. /**
  302. * Retourne le statut de paiement de la commande (payée, surplus, ou impayée).
  303. *
  304. * @return string
  305. */
  306. public function getPaymentStatus()
  307. {
  308. // payé
  309. if ($this->getAmount() - $this->getAmount(self::AMOUNT_PAID) < 0.01 &&
  310. $this->getAmount() - $this->getAmount(self::AMOUNT_PAID) > -0.01)
  311. {
  312. return self::PAYMENT_PAID ;
  313. }
  314. // à rembourser
  315. elseif ($this->getAmount() - $this->getAmount(self::AMOUNT_PAID) <= -0.01) {
  316. return self::PAYMENT_SURPLUS ;
  317. }
  318. // reste à payer
  319. elseif ($this->getAmount() - $this->getAmount(self::AMOUNT_PAID) >= 0.01) {
  320. return self::PAYMENT_UNPAID ;
  321. }
  322. }
  323. /**
  324. * Retourne le résumé du panier au format HTML.
  325. *
  326. * @return string
  327. */
  328. public function getCartSummary()
  329. {
  330. if (!isset($this->productOrder)) {
  331. $this->productOrder = productOrder::find()->where(['id_order' => $this->id])->all();
  332. }
  333. $html = '';
  334. $count = count($this->productOrder);
  335. $i = 0;
  336. foreach ($this->productOrder as $p) {
  337. if (isset($p->product)) {
  338. $html .= $p->quantity . ' x ' . Html::encode($p->product->name);
  339. if (++$i != $count) {
  340. $html .= '<br />';
  341. }
  342. }
  343. }
  344. return $html;
  345. }
  346. /**
  347. * Retourne le résumé du point de vente lié à la commande au format HTML.
  348. *
  349. * @return string
  350. */
  351. public function getPointSaleSummary()
  352. {
  353. $html = '';
  354. if (isset($this->pointSale)) {
  355. $html .= '<span class="name-point-sale">' .
  356. Html::encode($this->pointSale->name) .
  357. '</span>' .
  358. '<br /><span class="locality">'
  359. . Html::encode($this->pointSale->locality)
  360. . '</span>';
  361. if (strlen($this->comment_point_sale)) {
  362. $html .= '<div class="comment"><span>'
  363. . Html::encode($this->comment_point_sale)
  364. . '</span></div>';
  365. }
  366. } else {
  367. $html .= 'Point de vente supprimé';
  368. }
  369. return $html;
  370. }
  371. /**
  372. * Retourne le résumé du paiement (montant, statut).
  373. *
  374. * @return string
  375. */
  376. public function getAmountSummary()
  377. {
  378. $html = '';
  379. $html .= $this->getAmount(self::AMOUNT_TOTAL, true) . '<br />';
  380. if ($this->paid_amount) {
  381. if ($this->getPaymentStatus() == Order::PAYMENT_PAID) {
  382. $html .= '<span class="label label-success">Payée</span>';
  383. } elseif ($this->getPaymentStatus() == Order::PAYMENT_UNPAID) {
  384. $html .= '<span class="label label-danger">Non payée</span><br />
  385. Reste <strong>' . $this->getAmount(Order::AMOUNT_REMAINING, true) . '</strong> à payer';
  386. } elseif ($this->getPaymentStatus() == Order::PAYMENT_SURPLUS) {
  387. $html .= '<span class="label label-success">Payée</span>';
  388. }
  389. }
  390. else {
  391. $html .= '<span class="label label-default">Non réglé</span>';
  392. }
  393. return $html;
  394. }
  395. /**
  396. * Retourne une chaine de caractère décrivant l'utilisateur lié à la commande.
  397. *
  398. * @return string
  399. */
  400. public function getStrUser()
  401. {
  402. if (isset($this->user)) {
  403. return Html::encode($this->user->name . ' ' . $this->user->lastname);
  404. } elseif (strlen($this->username)) {
  405. return Html::encode($this->username);
  406. } else {
  407. return 'Client introuvable';
  408. }
  409. }
  410. /**
  411. * Retourne l'état de la commande (livrée, modifiable ou en préparation)
  412. *
  413. * @return string
  414. */
  415. public function getState()
  416. {
  417. $orderDelay = Producer::getConfig(
  418. 'order_delay',
  419. $this->distribution->id_producer
  420. );
  421. $orderDeadline = Producer::getConfig(
  422. 'order_deadline',
  423. $this->distribution->id_producer
  424. );
  425. $orderDate = strtotime($this->distribution->date);
  426. $today = strtotime(date('Y-m-d'));
  427. $todayHour = date('G');
  428. $nbDays = (int) (($orderDate - $today) / (24 * 60 * 60));
  429. if ($nbDays <= 0) {
  430. return self::STATE_DELIVERED;
  431. }
  432. elseif ($nbDays >= $orderDelay &&
  433. ($nbDays != $orderDelay ||
  434. ($nbDays == $orderDelay && $todayHour < $orderDeadline)))
  435. {
  436. return self::STATE_OPEN;
  437. }
  438. return self::STATE_PREPARATION ;
  439. }
  440. /**
  441. * Retourne l'origine de la commande (client, automatique ou admin) sous forme
  442. * texte ou HTML.
  443. *
  444. * @param boolean $with_label
  445. * @return string
  446. */
  447. public function getStrOrigin($withLabel = false)
  448. {
  449. $classLabel = '';
  450. $str = '';
  451. if ($this->origin == self::ORIGIN_USER) {
  452. $classLabel = 'success';
  453. $str = 'Client';
  454. }
  455. elseif ($this->origin == self::ORIGIN_AUTO) {
  456. $classLabel = 'default';
  457. $str = 'Auto';
  458. }
  459. elseif ($this->origin == self::ORIGIN_ADMIN) {
  460. $classLabel = 'warning';
  461. $str = 'Vous';
  462. }
  463. if ($withLabel) {
  464. return '<span class="label label-' . $classLabel . '">'
  465. . $str . '</span>';
  466. }
  467. else {
  468. return $str;
  469. }
  470. }
  471. /**
  472. * Retourne l'historique de la commande (ajoutée, modifiée, supprimée) au
  473. * format HTML.
  474. *
  475. * @return string
  476. */
  477. public function getStrHistory()
  478. {
  479. $arr = [
  480. 'class' => 'create',
  481. 'glyphicon' => 'plus',
  482. 'str' => 'Ajoutée',
  483. 'date' => $this->date
  484. ] ;
  485. if(!is_null($this->date_update)) {
  486. $arr = [
  487. 'class' => 'update',
  488. 'glyphicon' => 'pencil',
  489. 'str' => 'Modifiée',
  490. 'date' => $this->date_update
  491. ] ;
  492. }
  493. if(!is_null($this->date_delete)) {
  494. $arr = [
  495. 'class' => 'delete',
  496. 'glyphicon' => 'remove',
  497. 'str' => 'Annulée',
  498. 'date' => $this->date_delete
  499. ] ;
  500. }
  501. $html = '<div class="small"><span class="'.$arr['class'].'">'
  502. . '<span class="glyphicon glyphicon-'.$arr['glyphicon'].'"></span> '
  503. . $arr['str'].'</span> le <strong>'
  504. . date('d/m/Y à G\hi', strtotime($arr['date'])).'</strong></div>' ;
  505. return $html ;
  506. }
  507. /**
  508. * Retourne une classe identifiant l'historique de la commande (ajoutée,
  509. * modifiée, supprimée).
  510. *
  511. * @return string
  512. */
  513. public function getClassHistory()
  514. {
  515. if(!is_null($this->date_delete)) {
  516. return 'commande-delete' ;
  517. }
  518. if(!is_null($this->date_update)) {
  519. return 'commande-update' ;
  520. }
  521. return 'commande-create' ;
  522. }
  523. /**
  524. * Retourne la quantité d'un produit donné de plusieurs commandes.
  525. *
  526. * @param integer $idProduct
  527. * @param array $orders
  528. * @param boolean $ignoreCancel
  529. *
  530. * @return integer
  531. */
  532. public static function getProductQuantity($idProduct, $orders, $ignoreCancel = false)
  533. {
  534. $quantity = 0;
  535. if (isset($orders) && is_array($orders) && count($orders)) {
  536. foreach ($orders as $c) {
  537. if(is_null($c->date_delete) || $ignoreCancel) {
  538. foreach ($c->productOrder as $po) {
  539. if ($po->id_product == $idProduct) {
  540. $quantity += $po->quantity ;
  541. }
  542. }
  543. }
  544. }
  545. }
  546. return $quantity ;
  547. }
  548. /**
  549. * Recherche et initialise des commandes.
  550. *
  551. * @param array $params
  552. * @param array $conditions
  553. * @param string $orderby
  554. * @param integer $limit
  555. * @return array
  556. */
  557. public static function searchBy($params = [], $options = [])
  558. {
  559. $orders = parent::searchBy($params, $options) ;
  560. /*
  561. * Initialisation des commandes
  562. */
  563. if(is_array($orders)) {
  564. if(count($orders)) {
  565. foreach($orders as $order) {
  566. $order->init() ;
  567. }
  568. return $orders ;
  569. }
  570. }
  571. else {
  572. $order = $orders ;
  573. if(is_a($order, 'common\models\Order')) {
  574. return $order->init() ;
  575. }
  576. // count
  577. else {
  578. return $order ;
  579. }
  580. }
  581. return false ;
  582. }
  583. /**
  584. * Retourne le nombre de produits commandés
  585. *
  586. * @return integer
  587. */
  588. public function countProducts()
  589. {
  590. $count = 0 ;
  591. if($this->productOrder && is_array($this->productOrder)) {
  592. foreach($this->productOrder as $productOrder) {
  593. $count += $productOrder->quantity ;
  594. }
  595. }
  596. return $count ;
  597. }
  598. /**
  599. * Retourne un bloc html présentant une date.
  600. *
  601. * @return string
  602. */
  603. public function getBlockDate()
  604. {
  605. return '<div class="block-date">
  606. <div class="day">'.strftime('%A', strtotime($this->distribution->date)).'</div>
  607. <div class="num">'.date('d', strtotime($this->distribution->date)).'</div>
  608. <div class="month">'.strftime('%B', strtotime($this->distribution->date)).'</div>
  609. </div>' ;
  610. }
  611. }