Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

722 lines
22KB

  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','productOrder.product','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. $this->amount += $productOrder->price * $productOrder->quantity ;
  162. if ($productOrder->unit == 'piece') {
  163. if(isset($productOrder->product)) {
  164. $this->weight += ($productOrder->quantity * $productOrder->product->weight) / 1000 ;
  165. }
  166. }
  167. else {
  168. $this->weight += $productOrder->quantity ;
  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. public function delete() {
  196. // remboursement si l'utilisateur a payé pour cette commande
  197. $amountPaid = $this->getAmount(Order::AMOUNT_PAID);
  198. if ($amountPaid > 0.01) {
  199. $this->saveCreditHistory(
  200. CreditHistory::TYPE_REFUND,
  201. $amountPaid,
  202. Producer::getId(),
  203. $this->id_user,
  204. User::getCurrentId()
  205. );
  206. }
  207. // delete
  208. if(Producer::getConfig('option_behavior_cancel_order') == Producer::BEHAVIOR_DELETE_ORDER_DELETE ||
  209. (Producer::getConfig('option_behavior_cancel_order') == Producer::BEHAVIOR_DELETE_ORDER_STATUS && strlen($this->date_delete)) ) {
  210. ProductOrder::deleteAll(['id_order' => $this->id]);
  211. return parent::delete() ;
  212. }
  213. // status 'delete'
  214. elseif(Producer::getConfig('option_behavior_cancel_order') == Producer::BEHAVIOR_DELETE_ORDER_STATUS) {
  215. $this->date_delete = date('Y-m-d H:i:s');
  216. return $this->save() ;
  217. }
  218. }
  219. /**
  220. * Retourne le montant de la commande (total, payé, restant, ou en surplus).
  221. *
  222. * @param boolean $format
  223. * @return float
  224. */
  225. public function getAmount($type = self::AMOUNT_TOTAL, $format = false)
  226. {
  227. switch($type) {
  228. case self::AMOUNT_TOTAL :
  229. $amount = $this->amount ;
  230. break ;
  231. case self::AMOUNT_PAID :
  232. $this->initPaidAmount() ;
  233. $amount = $this->paid_amount ;
  234. break ;
  235. case self::AMOUNT_REMAINING :
  236. $amount = $this->getAmount(self::AMOUNT_TOTAL)
  237. - $this->getAmount(self::AMOUNT_PAID) ;
  238. break ;
  239. case self::AMOUNT_SURPLUS :
  240. $amount = $this->getAmount(self::AMOUNT_PAID)
  241. - $this->getAmount(self::AMOUNT_TOTAL) ;
  242. break ;
  243. }
  244. if ($format) {
  245. return number_format($amount, 2) . ' €';
  246. }
  247. else {
  248. return $amount;
  249. }
  250. }
  251. /**
  252. * Retourne les informations relatives à la commande au format JSON.
  253. *
  254. * @return string
  255. */
  256. public function getDataJson()
  257. {
  258. $order = Order::searchOne(['order.id' => $this->id]) ;
  259. $jsonOrder = [] ;
  260. if($order) {
  261. $jsonOrder = [
  262. 'products' => [],
  263. 'amount' => $order->amount,
  264. 'str_amount' => $order->getAmount(self::AMOUNT_TOTAL, true),
  265. 'paid_amount' => $order->getAmount(self::AMOUNT_PAID),
  266. 'comment' => $order->comment,
  267. ];
  268. foreach ($order->productOrder as $productOrder) {
  269. $jsonOrder['products'][$productOrder->id_product] = $productOrder->quantity;
  270. }
  271. }
  272. return json_encode($jsonOrder);
  273. }
  274. /**
  275. * Enregistre un modèle de type CreditHistory.
  276. *
  277. * @param string $type
  278. * @param float $montant
  279. * @param integer $idProducer
  280. * @param integer $idUser
  281. * @param integer $idUserAction
  282. */
  283. public function saveCreditHistory($type, $amount, $idProducer, $idUser, $idUserAction)
  284. {
  285. $creditHistory = new CreditHistory;
  286. $creditHistory->id_user = $this->id_user;
  287. $creditHistory->id_order = $this->id;
  288. $creditHistory->amount = $amount;
  289. $creditHistory->type = $type;
  290. $creditHistory->id_producer = $idProducer;
  291. $creditHistory->id_user_action = $idUserAction;
  292. $creditHistory->populateRelation('order', $this) ;
  293. $creditHistory->populateRelation('user', User::find()->where(['id' => $this->id_user])->one()) ;
  294. $creditHistory->save();
  295. }
  296. /**
  297. * Ajuste le crédit pour que la commande soit payée.
  298. *
  299. * @return boolean
  300. */
  301. public function processCredit()
  302. {
  303. if($this->id_user) {
  304. $paymentStatus = $this->getPaymentStatus() ;
  305. if($paymentStatus == self::PAYMENT_PAID) {
  306. return true;
  307. }
  308. elseif($paymentStatus == self::PAYMENT_SURPLUS) {
  309. $type = CreditHistory::TYPE_REFUND ;
  310. $amount = $this->getAmount(self::AMOUNT_SURPLUS) ;
  311. }
  312. elseif($paymentStatus == self::PAYMENT_UNPAID) {
  313. $type = CreditHistory::TYPE_PAYMENT ;
  314. $amount = $this->getAmount(self::AMOUNT_REMAINING) ;
  315. }
  316. $this->saveCreditHistory(
  317. $type,
  318. $amount,
  319. Producer::getId(),
  320. $this->id_user,
  321. User::getCurrentId()
  322. );
  323. }
  324. }
  325. /**
  326. * Retourne le statut de paiement de la commande (payée, surplus, ou impayée).
  327. *
  328. * @return string
  329. */
  330. public function getPaymentStatus()
  331. {
  332. // payé
  333. if ($this->getAmount() - $this->getAmount(self::AMOUNT_PAID) < 0.01 &&
  334. $this->getAmount() - $this->getAmount(self::AMOUNT_PAID) > -0.01)
  335. {
  336. return self::PAYMENT_PAID ;
  337. }
  338. // à rembourser
  339. elseif ($this->getAmount() - $this->getAmount(self::AMOUNT_PAID) <= -0.01) {
  340. return self::PAYMENT_SURPLUS ;
  341. }
  342. // reste à payer
  343. elseif ($this->getAmount() - $this->getAmount(self::AMOUNT_PAID) >= 0.01) {
  344. return self::PAYMENT_UNPAID ;
  345. }
  346. }
  347. /**
  348. * Retourne le résumé du panier au format HTML.
  349. *
  350. * @return string
  351. */
  352. public function getCartSummary()
  353. {
  354. if (!isset($this->productOrder)) {
  355. $this->productOrder = productOrder::find()->where(['id_order' => $this->id])->all();
  356. }
  357. $html = '';
  358. $count = count($this->productOrder);
  359. $i = 0;
  360. foreach ($this->productOrder as $p) {
  361. if (isset($p->product)) {
  362. $html .= Html::encode($p->product->name) .' ('. $p->quantity .'&nbsp;'.Product::strUnit($p->unit, 'wording_short', true).')';
  363. if (++$i != $count) {
  364. $html .= '<br />';
  365. }
  366. }
  367. }
  368. return $html;
  369. }
  370. /**
  371. * Retourne le résumé du point de vente lié à la commande au format HTML.
  372. *
  373. * @return string
  374. */
  375. public function getPointSaleSummary()
  376. {
  377. $html = '';
  378. if (isset($this->pointSale)) {
  379. $html .= '<span class="name-point-sale">' .
  380. Html::encode($this->pointSale->name) .
  381. '</span>' .
  382. '<br /><span class="locality">'
  383. . Html::encode($this->pointSale->locality)
  384. . '</span>';
  385. if (strlen($this->comment_point_sale)) {
  386. $html .= '<div class="comment"><span>'
  387. . Html::encode($this->comment_point_sale)
  388. . '</span></div>';
  389. }
  390. } else {
  391. $html .= 'Point de vente supprimé';
  392. }
  393. return $html;
  394. }
  395. /**
  396. * Retourne le résumé du paiement (montant, statut).
  397. *
  398. * @return string
  399. */
  400. public function getAmountSummary()
  401. {
  402. $html = '';
  403. $html .= $this->getAmount(self::AMOUNT_TOTAL, true) . '<br />';
  404. if ($this->paid_amount) {
  405. if ($this->getPaymentStatus() == Order::PAYMENT_PAID) {
  406. $html .= '<span class="label label-success">Payée</span>';
  407. } elseif ($this->getPaymentStatus() == Order::PAYMENT_UNPAID) {
  408. $html .= '<span class="label label-danger">Non payée</span><br />
  409. Reste <strong>' . $this->getAmount(Order::AMOUNT_REMAINING, true) . '</strong> à payer';
  410. } elseif ($this->getPaymentStatus() == Order::PAYMENT_SURPLUS) {
  411. $html .= '<span class="label label-success">Payée</span>';
  412. }
  413. }
  414. else {
  415. $html .= '<span class="label label-default">Non réglé</span>';
  416. }
  417. return $html;
  418. }
  419. /**
  420. * Retourne une chaine de caractère décrivant l'utilisateur lié à la commande.
  421. *
  422. * @return string
  423. */
  424. public function getStrUser()
  425. {
  426. if (isset($this->user)) {
  427. return Html::encode($this->user->name . ' ' . $this->user->lastname);
  428. } elseif (strlen($this->username)) {
  429. return Html::encode($this->username);
  430. } else {
  431. return 'Client introuvable';
  432. }
  433. }
  434. /**
  435. * Retourne l'état de la commande (livrée, modifiable ou en préparation)
  436. *
  437. * @return string
  438. */
  439. public function getState()
  440. {
  441. $orderDelay = Producer::getConfig(
  442. 'order_delay',
  443. $this->distribution->id_producer
  444. );
  445. $orderDeadline = Producer::getConfig(
  446. 'order_deadline',
  447. $this->distribution->id_producer
  448. );
  449. $orderDate = strtotime($this->distribution->date);
  450. $today = strtotime(date('Y-m-d'));
  451. $todayHour = date('G');
  452. $nbDays = (int) (($orderDate - $today) / (24 * 60 * 60));
  453. if ($nbDays <= 0) {
  454. return self::STATE_DELIVERED;
  455. }
  456. elseif ($nbDays >= $orderDelay &&
  457. ($nbDays != $orderDelay ||
  458. ($nbDays == $orderDelay && $todayHour < $orderDeadline)))
  459. {
  460. return self::STATE_OPEN;
  461. }
  462. return self::STATE_PREPARATION ;
  463. }
  464. /**
  465. * Retourne l'origine de la commande (client, automatique ou admin) sous forme
  466. * texte ou HTML.
  467. *
  468. * @param boolean $with_label
  469. * @return string
  470. */
  471. public function getStrOrigin($withLabel = false)
  472. {
  473. $classLabel = '';
  474. $str = '';
  475. if ($this->origin == self::ORIGIN_USER) {
  476. $classLabel = 'success';
  477. $str = 'Client';
  478. }
  479. elseif ($this->origin == self::ORIGIN_AUTO) {
  480. $classLabel = 'default';
  481. $str = 'Auto';
  482. }
  483. elseif ($this->origin == self::ORIGIN_ADMIN) {
  484. $classLabel = 'warning';
  485. $str = 'Vous';
  486. }
  487. if ($withLabel) {
  488. return '<span class="label label-' . $classLabel . '">'
  489. . $str . '</span>';
  490. }
  491. else {
  492. return $str;
  493. }
  494. }
  495. /**
  496. * Retourne l'historique de la commande (ajoutée, modifiée, supprimée) au
  497. * format HTML.
  498. *
  499. * @return string
  500. */
  501. public function getStrHistory()
  502. {
  503. $arr = [
  504. 'class' => 'create',
  505. 'glyphicon' => 'plus',
  506. 'str' => 'Ajoutée',
  507. 'date' => $this->date
  508. ] ;
  509. if(!is_null($this->date_update)) {
  510. $arr = [
  511. 'class' => 'update',
  512. 'glyphicon' => 'pencil',
  513. 'str' => 'Modifiée',
  514. 'date' => $this->date_update
  515. ] ;
  516. }
  517. if(!is_null($this->date_delete)) {
  518. $arr = [
  519. 'class' => 'delete',
  520. 'glyphicon' => 'remove',
  521. 'str' => 'Annulée',
  522. 'date' => $this->date_delete
  523. ] ;
  524. }
  525. $html = '<div class="small"><span class="'.$arr['class'].'">'
  526. . '<span class="glyphicon glyphicon-'.$arr['glyphicon'].'"></span> '
  527. . $arr['str'].'</span> le <strong>'
  528. . date('d/m/Y à G\hi', strtotime($arr['date'])).'</strong></div>' ;
  529. return $html ;
  530. }
  531. /**
  532. * Retourne une classe identifiant l'historique de la commande (ajoutée,
  533. * modifiée, supprimée).
  534. *
  535. * @return string
  536. */
  537. public function getClassHistory()
  538. {
  539. if(!is_null($this->date_delete)) {
  540. return 'commande-delete' ;
  541. }
  542. if(!is_null($this->date_update)) {
  543. return 'commande-update' ;
  544. }
  545. return 'commande-create' ;
  546. }
  547. /**
  548. * Retourne la quantité d'un produit donné de plusieurs commandes.
  549. *
  550. * @param integer $idProduct
  551. * @param array $orders
  552. * @param boolean $ignoreCancel
  553. *
  554. * @return integer
  555. */
  556. public static function getProductQuantity($idProduct, $orders, $ignoreCancel = false, $unit = null)
  557. {
  558. $quantity = 0;
  559. if (isset($orders) && is_array($orders) && count($orders)) {
  560. foreach ($orders as $c) {
  561. if(is_null($c->date_delete) || $ignoreCancel) {
  562. foreach ($c->productOrder as $po) {
  563. if ($po->id_product == $idProduct &&
  564. ((is_null($unit) && $po->product->unit == $po->unit) || (!is_null($unit) && strlen($unit) && $po->unit == $unit))) {
  565. $quantity += $po->quantity ;
  566. }
  567. }
  568. }
  569. }
  570. }
  571. return $quantity ;
  572. }
  573. /**
  574. * Recherche et initialise des commandes.
  575. *
  576. * @param array $params
  577. * @param array $conditions
  578. * @param string $orderby
  579. * @param integer $limit
  580. * @return array
  581. */
  582. public static function searchBy($params = [], $options = [])
  583. {
  584. $orders = parent::searchBy($params, $options) ;
  585. /*
  586. * Initialisation des commandes
  587. */
  588. if(is_array($orders)) {
  589. if(count($orders)) {
  590. foreach($orders as $order) {
  591. $order->init() ;
  592. }
  593. return $orders ;
  594. }
  595. }
  596. else {
  597. $order = $orders ;
  598. if(is_a($order, 'common\models\Order')) {
  599. return $order->init() ;
  600. }
  601. // count
  602. else {
  603. return $order ;
  604. }
  605. }
  606. return false ;
  607. }
  608. /**
  609. * Retourne le nombre de produits commandés
  610. *
  611. * @return integer
  612. */
  613. public function countProducts()
  614. {
  615. $count = 0 ;
  616. if($this->productOrder && is_array($this->productOrder)) {
  617. foreach($this->productOrder as $productOrder) {
  618. if($productOrder->unit == 'piece') {
  619. $count ++ ;
  620. }
  621. else {
  622. $count += $productOrder->quantity ;
  623. }
  624. }
  625. }
  626. return $count ;
  627. }
  628. /**
  629. * Retourne un bloc html présentant une date.
  630. *
  631. * @return string
  632. */
  633. public function getBlockDate()
  634. {
  635. return '<div class="block-date">
  636. <div class="day">'.strftime('%A', strtotime($this->distribution->date)).'</div>
  637. <div class="num">'.date('d', strtotime($this->distribution->date)).'</div>
  638. <div class="month">'.strftime('%B', strtotime($this->distribution->date)).'</div>
  639. </div>' ;
  640. }
  641. }