You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

657 lines
19KB

  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. * Retourne le statut de paiement de la commande (payée, surplus, ou impayée).
  274. *
  275. * @return string
  276. */
  277. public function getPaymentStatus()
  278. {
  279. // payé
  280. if ($this->getAmount() - $this->getAmount(self::AMOUNT_PAID) < 0.01 &&
  281. $this->getAmount() - $this->getAmount(self::AMOUNT_PAID) >= 0)
  282. {
  283. return self::PAYMENT_PAID ;
  284. }
  285. // à rembourser
  286. elseif ($this->getAmount() - $this->getAmount(self::AMOUNT_PAID) <= -0.01) {
  287. return self::PAYMENT_SURPLUS ;
  288. }
  289. // reste à payer
  290. elseif ($this->getAmount() - $this->getAmount(self::AMOUNT_PAID) >= 0.01) {
  291. return self::PAYMENT_UNPAID ;
  292. }
  293. }
  294. /**
  295. * Retourne le résumé du panier au format HTML.
  296. *
  297. * @return string
  298. */
  299. public function getCartSummary()
  300. {
  301. if (!isset($this->productOrder)) {
  302. $this->productOrder = productOrder::find()->where(['id_order' => $this->id])->all();
  303. }
  304. $html = '';
  305. $count = count($this->productOrder);
  306. $i = 0;
  307. foreach ($this->productOrder as $p) {
  308. if (isset($p->product)) {
  309. $html .= $p->quantity . ' x ' . Html::encode($p->product->name);
  310. if (++$i != $count) {
  311. $html .= '<br />';
  312. }
  313. }
  314. }
  315. return $html;
  316. }
  317. /**
  318. * Retourne le résumé du point de vente lié à la commande au format HTML.
  319. *
  320. * @return string
  321. */
  322. public function getPointSaleSummary()
  323. {
  324. $html = '';
  325. if (isset($this->pointSale)) {
  326. $html .= '<span class="name-point-sale">' .
  327. Html::encode($this->pointSale->name) .
  328. '</span>' .
  329. '<br /><span class="locality">'
  330. . Html::encode($this->pointSale->locality)
  331. . '</span>';
  332. if (strlen($this->comment_point_sale)) {
  333. $html .= '<div class="comment"><span>'
  334. . Html::encode($this->comment_point_sale)
  335. . '</span></div>';
  336. }
  337. } else {
  338. $html .= 'Point de vente supprimé';
  339. }
  340. return $html;
  341. }
  342. /**
  343. * Retourne le résumé du paiement (montant, statut).
  344. *
  345. * @return string
  346. */
  347. public function getAmountSummary()
  348. {
  349. $html = '';
  350. $html .= $this->getAmount(self::AMOUNT_TOTAL, true) . '<br />';
  351. if ($this->paid_amount) {
  352. if ($this->getPaymentStatus() == Order::PAYMENT_PAID) {
  353. $html .= '<span class="label label-success">Payée</span>';
  354. } elseif ($this->getPaymentStatus() == Order::PAYMENT_UNPAID) {
  355. $html .= '<span class="label label-danger">Non payée</span><br />
  356. Reste <strong>' . $this->getAmount(Order::AMOUNT_REMAINING, true) . '</strong> à payer';
  357. } elseif ($this->getPaymentStatus() == Order::PAYMENT_SURPLUS) {
  358. $html .= '<span class="label label-success">Payée</span>';
  359. }
  360. }
  361. else {
  362. $html .= '<span class="label label-default">Non réglé</span>';
  363. }
  364. return $html;
  365. }
  366. /**
  367. * Retourne une chaine de caractère décrivant l'utilisateur lié à la commande.
  368. *
  369. * @return string
  370. */
  371. public function getStrUser()
  372. {
  373. if (isset($this->user)) {
  374. return Html::encode($this->user->name . ' ' . $this->user->lastname);
  375. } elseif (strlen($this->username)) {
  376. return Html::encode($this->username);
  377. } else {
  378. return 'Client introuvable';
  379. }
  380. }
  381. /**
  382. * Retourne l'état de la commande (livrée, modifiable ou en préparation)
  383. *
  384. * @return string
  385. */
  386. public function getState()
  387. {
  388. $orderDelay = Producer::getConfig(
  389. 'order_delay',
  390. $this->distribution->id_producer
  391. );
  392. $orderDeadline = Producer::getConfig(
  393. 'order_deadline',
  394. $this->distribution->id_producer
  395. );
  396. $orderDate = strtotime($this->distribution->date);
  397. $today = strtotime(date('Y-m-d'));
  398. $todayHour = date('G');
  399. $nbDays = (int) (($orderDate - $today) / (24 * 60 * 60));
  400. if ($nbDays <= 0) {
  401. return self::STATE_DELIVERED;
  402. }
  403. elseif ($nbDays >= $orderDelay &&
  404. ($nbDays != $orderDelay ||
  405. ($nbDays == $orderDelay && $todayHour < $orderDeadline)))
  406. {
  407. return self::STATE_OPEN;
  408. }
  409. return self::STATE_PREPARATION ;
  410. }
  411. /**
  412. * Retourne l'origine de la commande (client, automatique ou admin) sous forme
  413. * texte ou HTML.
  414. *
  415. * @param boolean $with_label
  416. * @return string
  417. */
  418. public function getStrOrigin($withLabel = false)
  419. {
  420. $classLabel = '';
  421. $str = '';
  422. if ($this->origin == self::ORIGIN_USER) {
  423. $classLabel = 'success';
  424. $str = 'Client';
  425. }
  426. elseif ($this->origin == self::ORIGIN_AUTO) {
  427. $classLabel = 'default';
  428. $str = 'Auto';
  429. }
  430. elseif ($this->origin == self::ORIGIN_ADMIN) {
  431. $classLabel = 'warning';
  432. $str = 'Vous';
  433. }
  434. if ($withLabel) {
  435. return '<span class="label label-' . $classLabel . '">'
  436. . $str . '</span>';
  437. }
  438. else {
  439. return $str;
  440. }
  441. }
  442. /**
  443. * Retourne l'historique de la commande (ajoutée, modifiée, supprimée) au
  444. * format HTML.
  445. *
  446. * @return string
  447. */
  448. public function getStrHistory()
  449. {
  450. $arr = [
  451. 'class' => 'create',
  452. 'glyphicon' => 'plus',
  453. 'str' => 'Ajoutée',
  454. 'date' => $this->date
  455. ] ;
  456. if(!is_null($this->date_update)) {
  457. $arr = [
  458. 'class' => 'update',
  459. 'glyphicon' => 'pencil',
  460. 'str' => 'Modifiée',
  461. 'date' => $this->date_update
  462. ] ;
  463. }
  464. if(!is_null($this->date_delete)) {
  465. $arr = [
  466. 'class' => 'delete',
  467. 'glyphicon' => 'remove',
  468. 'str' => 'Annulée',
  469. 'date' => $this->date_delete
  470. ] ;
  471. }
  472. $html = '<div class="small"><span class="'.$arr['class'].'">'
  473. . '<span class="glyphicon glyphicon-'.$arr['glyphicon'].'"></span> '
  474. . $arr['str'].'</span> le <strong>'
  475. . date('d/m/Y à G\hi', strtotime($arr['date'])).'</strong></div>' ;
  476. return $html ;
  477. }
  478. /**
  479. * Retourne une classe identifiant l'historique de la commande (ajoutée,
  480. * modifiée, supprimée).
  481. *
  482. * @return string
  483. */
  484. public function getClassHistory()
  485. {
  486. if(!is_null($this->date_delete)) {
  487. return 'commande-delete' ;
  488. }
  489. if(!is_null($this->date_update)) {
  490. return 'commande-update' ;
  491. }
  492. return 'commande-create' ;
  493. }
  494. /**
  495. * Retourne la quantité d'un produit donné de plusieurs commandes.
  496. *
  497. * @param integer $idProduct
  498. * @param array $orders
  499. * @param boolean $ignoreCancel
  500. *
  501. * @return integer
  502. */
  503. public static function getProductQuantity($idProduct, $orders, $ignoreCancel = false)
  504. {
  505. $quantity = 0;
  506. if (isset($orders) && is_array($orders) && count($orders)) {
  507. foreach ($orders as $c) {
  508. if(is_null($c->date_delete) || $ignoreCancel) {
  509. foreach ($c->productOrder as $po) {
  510. if ($po->id_product == $idProduct) {
  511. $quantity += $po->quantity ;
  512. }
  513. }
  514. }
  515. }
  516. }
  517. return $quantity ;
  518. }
  519. /**
  520. * Recherche et initialise des commandes.
  521. *
  522. * @param array $params
  523. * @param array $conditions
  524. * @param string $orderby
  525. * @param integer $limit
  526. * @return array
  527. */
  528. public static function searchBy($params = [], $options = [])
  529. {
  530. $orders = parent::searchBy($params, $options) ;
  531. /*
  532. * Initialisation des commandes
  533. */
  534. if(is_array($orders)) {
  535. if(count($orders)) {
  536. foreach($orders as $order) {
  537. $order->init() ;
  538. }
  539. return $orders ;
  540. }
  541. }
  542. else {
  543. $order = $orders ;
  544. if(is_a($order, 'common\models\Order')) {
  545. return $order->init() ;
  546. }
  547. // count
  548. else {
  549. return $order ;
  550. }
  551. }
  552. return false ;
  553. }
  554. /**
  555. * Retourne le nombre de produits commandés
  556. *
  557. * @return integer
  558. */
  559. public function countProducts()
  560. {
  561. $count = 0 ;
  562. if($this->productOrder && is_array($this->productOrder)) {
  563. foreach($this->productOrder as $productOrder) {
  564. $count += $productOrder->quantity ;
  565. }
  566. }
  567. return $count ;
  568. }
  569. /**
  570. * Retourne un bloc html présentant une date.
  571. *
  572. * @return string
  573. */
  574. public function getBlockDate()
  575. {
  576. return '<div class="block-date">
  577. <div class="day">'.strftime('%A', strtotime($this->distribution->date)).'</div>
  578. <div class="num">'.date('d', strtotime($this->distribution->date)).'</div>
  579. <div class="month">'.strftime('%B', strtotime($this->distribution->date)).'</div>
  580. </div>' ;
  581. }
  582. }