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.

933 lines
36KB

  1. <?php
  2. /**
  3. * Copyright distrib (2018)
  4. *
  5. * contact@opendistrib.net
  6. *
  7. * Ce logiciel est un programme informatique servant à aider les producteurs
  8. * à distribuer leur production en circuits courts.
  9. *
  10. * Ce logiciel est régi par la licence CeCILL soumise au droit français et
  11. * respectant les principes de diffusion des logiciels libres. Vous pouvez
  12. * utiliser, modifier et/ou redistribuer ce programme sous les conditions
  13. * de la licence CeCILL telle que diffusée par le CEA, le CNRS et l'INRIA
  14. * sur le site "http://www.cecill.info".
  15. *
  16. * En contrepartie de l'accessibilité au code source et des droits de copie,
  17. * de modification et de redistribution accordés par cette licence, il n'est
  18. * offert aux utilisateurs qu'une garantie limitée. Pour les mêmes raisons,
  19. * seule une responsabilité restreinte pèse sur l'auteur du programme, le
  20. * titulaire des droits patrimoniaux et les concédants successifs.
  21. *
  22. * A cet égard l'attention de l'utilisateur est attirée sur les risques
  23. * associés au chargement, à l'utilisation, à la modification et/ou au
  24. * développement et à la reproduction du logiciel par l'utilisateur étant
  25. * donné sa spécificité de logiciel libre, qui peut le rendre complexe à
  26. * manipuler et qui le réserve donc à des développeurs et des professionnels
  27. * avertis possédant des connaissances informatiques approfondies. Les
  28. * utilisateurs sont donc invités à charger et tester l'adéquation du
  29. * logiciel à leurs besoins dans des conditions permettant d'assurer la
  30. * sécurité de leurs systèmes et ou de leurs données et, plus généralement,
  31. * à l'utiliser et l'exploiter dans les mêmes conditions de sécurité.
  32. *
  33. * Le fait que vous puissiez accéder à cet en-tête signifie que vous avez
  34. * pris connaissance de la licence CeCILL, et que vous en avez accepté les
  35. * termes.
  36. */
  37. namespace common\models;
  38. use common\helpers\Debug;
  39. use common\helpers\GlobalParam;
  40. use common\helpers\Price;
  41. use common\models\Producer;
  42. use Yii;
  43. use yii\helpers\Html;
  44. use common\components\ActiveRecordCommon;
  45. use yii\web\NotFoundHttpException;
  46. /**
  47. * This is the model class for table "order".
  48. *
  49. * @property integer $id
  50. * @property integer $id_user
  51. * @property string $date
  52. * @property string $date_update
  53. * @property integer $id_point_sale
  54. * @property integer $id_distribution
  55. * @property boolean $auto_payment
  56. * @property integer $id_subscription
  57. */
  58. class Order extends ActiveRecordCommon
  59. {
  60. var $amount = 0;
  61. var $amount_with_tax = 0;
  62. var $paid_amount = 0;
  63. var $weight = 0;
  64. const ORIGIN_AUTO = 'auto';
  65. const ORIGIN_USER = 'user';
  66. const ORIGIN_ADMIN = 'admin';
  67. const PAYMENT_PAID = 'paid';
  68. const PAYMENT_UNPAID = 'unpaid';
  69. const PAYMENT_SURPLUS = 'surplus';
  70. const AMOUNT_TOTAL = 'total';
  71. const AMOUNT_PAID = 'paid';
  72. const AMOUNT_REMAINING = 'remaining';
  73. const AMOUNT_SURPLUS = 'surplus';
  74. const STATE_OPEN = 'open';
  75. const STATE_PREPARATION = 'preparation';
  76. const STATE_DELIVERED = 'delivered';
  77. /**
  78. * @inheritdoc
  79. */
  80. public static function tableName()
  81. {
  82. return 'order';
  83. }
  84. /**
  85. * @inheritdoc
  86. */
  87. public function rules()
  88. {
  89. return [
  90. [['id_user', 'date', 'status'], 'required', 'message' => ''],
  91. [['id_user', 'id_point_sale', 'id_distribution', 'id_subscription', 'id_invoice', 'id_quotation', 'id_delivery_note'], 'integer'],
  92. [['auto_payment', 'tiller_synchronization'], 'boolean'],
  93. [['status'], 'string'],
  94. [['date', 'date_update', 'comment', 'comment_point_sale', 'mean_payment'], 'safe']
  95. ];
  96. }
  97. /**
  98. * @inheritdoc
  99. */
  100. public function attributeLabels()
  101. {
  102. return [
  103. 'id' => 'ID',
  104. 'id_user' => 'Id User',
  105. 'date' => 'Date',
  106. 'date_update' => 'Date de modification',
  107. 'id_point_sale' => 'Point de vente',
  108. 'id_distribution' => 'Date de distribution',
  109. 'id_subscription' => 'Abonnement',
  110. 'status' => 'Statut',
  111. 'id_invoice' => 'Facture',
  112. 'id_quotation' => 'Devis',
  113. 'id_delivery_note' => 'Bon de livraison'
  114. ];
  115. }
  116. /*
  117. * Relations
  118. */
  119. public function getUser()
  120. {
  121. return $this->hasOne(User::className(), ['id' => 'id_user']);
  122. }
  123. public function getProductOrder()
  124. {
  125. return $this->hasMany(ProductOrder::className(), ['id_order' => 'id'])
  126. ->orderBy(['product.order' => SORT_ASC])
  127. ->joinWith('product');
  128. }
  129. public function getDistribution()
  130. {
  131. return $this->hasOne(Distribution::className(), ['id' => 'id_distribution'])
  132. ->with('producer');
  133. }
  134. public function getPointSale()
  135. {
  136. return $this->hasOne(PointSale::className(), ['id' => 'id_point_sale'])
  137. ->with('userPointSale');
  138. }
  139. public function getCreditHistory()
  140. {
  141. return $this->hasMany(CreditHistory::className(), ['id_order' => 'id']);
  142. }
  143. public function getSubscription()
  144. {
  145. return $this->hasOne(Subscription::className(), ['id' => 'id_subscription'])
  146. ->with('productSubscription');
  147. }
  148. public function getInvoice()
  149. {
  150. return $this->hasOne(Invoice::className(), ['id' => 'id_invoice']);
  151. }
  152. public function getQuotation()
  153. {
  154. return $this->hasOne(Quotation::className(), ['id' => 'id_quotation']);
  155. }
  156. public function getDeliveryNote()
  157. {
  158. return $this->hasOne(DeliveryNote::className(), ['id' => 'id_delivery_note']);
  159. }
  160. /**
  161. * Retourne les options de base nécessaires à la fonction de recherche.
  162. *
  163. * @return array
  164. */
  165. public static function defaultOptionsSearch()
  166. {
  167. return [
  168. 'with' => ['productOrder', 'productOrder.product', 'creditHistory', 'creditHistory.userAction', 'pointSale'],
  169. 'join_with' => ['distribution', 'user', 'user.userProducer'],
  170. 'orderby' => 'order.date ASC',
  171. 'attribute_id_producer' => 'distribution.id_producer'
  172. ];
  173. }
  174. /**
  175. * Initialise le montant total, le montant déjà payé et le poids de la
  176. * commande.
  177. */
  178. public function init()
  179. {
  180. $this->initAmount();
  181. $this->initPaidAmount();
  182. return $this;
  183. }
  184. /**
  185. * Initialise le montant de la commande.
  186. *
  187. */
  188. public function initAmount()
  189. {
  190. $this->amount = 0;
  191. $this->amount_with_tax = 0;
  192. $this->weight = 0;
  193. if (isset($this->productOrder)) {
  194. foreach ($this->productOrder as $productOrder) {
  195. $this->amount += $productOrder->price * $productOrder->quantity;
  196. $this->amount_with_tax += Price::getPriceWithTax($productOrder->price, $productOrder->taxRate->value) * $productOrder->quantity;
  197. if ($productOrder->unit == 'piece') {
  198. if (isset($productOrder->product)) {
  199. $this->weight += ($productOrder->quantity * $productOrder->product->weight) / 1000;
  200. }
  201. } else {
  202. $this->weight += $productOrder->quantity;
  203. }
  204. }
  205. }
  206. }
  207. /**
  208. * Initialise le montant payé de la commande et le retourne.
  209. *
  210. * @return float
  211. */
  212. public function initPaidAmount()
  213. {
  214. if (isset($this->creditHistory)) {
  215. $history = $this->creditHistory;
  216. } else {
  217. $history = CreditHistory::find()
  218. ->where(['id_order' => $this->id])
  219. ->all();
  220. }
  221. $this->paid_amount = 0;
  222. if (count($history)) {
  223. foreach ($history as $ch) {
  224. if ($ch->type == CreditHistory::TYPE_PAYMENT) {
  225. $this->paid_amount += $ch->amount;
  226. } elseif ($ch->type == CreditHistory::TYPE_REFUND) {
  227. $this->paid_amount -= $ch->amount;
  228. }
  229. }
  230. }
  231. }
  232. public function delete()
  233. {
  234. // remboursement si l'utilisateur a payé pour cette commande
  235. $amountPaid = $this->getAmount(Order::AMOUNT_PAID);
  236. if ($amountPaid > 0.01) {
  237. $this->saveCreditHistory(
  238. CreditHistory::TYPE_REFUND,
  239. $amountPaid,
  240. GlobalParam::getCurrentProducerId(),
  241. $this->id_user,
  242. User::getCurrentId()
  243. );
  244. }
  245. // delete
  246. if (Producer::getConfig('option_behavior_cancel_order') == Producer::BEHAVIOR_DELETE_ORDER_DELETE ||
  247. (Producer::getConfig('option_behavior_cancel_order') == Producer::BEHAVIOR_DELETE_ORDER_STATUS && strlen($this->date_delete))) {
  248. ProductOrder::deleteAll(['id_order' => $this->id]);
  249. return parent::delete();
  250. } // status 'delete'
  251. elseif (Producer::getConfig('option_behavior_cancel_order') == Producer::BEHAVIOR_DELETE_ORDER_STATUS) {
  252. $this->date_delete = date('Y-m-d H:i:s');
  253. return $this->save();
  254. }
  255. }
  256. /**
  257. * Changement de statut d'une commande
  258. *
  259. * @param $newStatus
  260. */
  261. public function changeOrderStatus($newStatus, $origin)
  262. {
  263. $orderStatusArray = GlobalParam::get('orderStatus');
  264. switch ($newStatus) {
  265. case 'new-order' :
  266. $this->addOrderStatusHistory($newStatus, $origin);
  267. $this->status = $newStatus;
  268. $this->save();
  269. break;
  270. case 'waiting-paiement-on-delivery':
  271. if(in_array($newStatus, $orderStatusArray[$this->status]['nextStatusAllow'])){
  272. $this->addOrderStatusHistory($newStatus, $origin);
  273. $this->status = $newStatus;
  274. $this->save();
  275. }
  276. break;
  277. case 'waiting-paiement-by-credit':
  278. if(in_array($newStatus, $orderStatusArray[$this->status]['nextStatusAllow'])){
  279. $this->addOrderStatusHistory($newStatus, $origin);
  280. $this->status = $newStatus;
  281. $this->save();
  282. }
  283. break;
  284. case 'paid-by-credit':
  285. if(in_array($newStatus, $orderStatusArray[$this->status]['nextStatusAllow'])){
  286. $this->addOrderStatusHistory($newStatus, $origin);
  287. $this->status = $newStatus;
  288. $this->save();
  289. }
  290. break;
  291. case 'waiting-delevery' :
  292. if(in_array($newStatus, $orderStatusArray[$this->status]['nextStatusAllow'])){
  293. $this->addOrderStatusHistory($newStatus, $origin);
  294. $this->status = $newStatus;
  295. $this->save();
  296. }
  297. break;
  298. case 'delivered':
  299. if(in_array($newStatus, $orderStatusArray[$this->status]['nextStatusAllow'])){
  300. $this->addOrderStatusHistory($newStatus, $origin);
  301. $this->status = $newStatus;
  302. $this->save();
  303. }
  304. break;
  305. case 'refunded':
  306. if(in_array($newStatus, $orderStatusArray[$this->status]['nextStatusAllow'])){
  307. $this->addOrderStatusHistory($newStatus, $origin);
  308. $this->status = $newStatus;
  309. $this->save();
  310. }
  311. break;
  312. case 'cancel':
  313. if(in_array($newStatus, $orderStatusArray[$this->status]['nextStatusAllow'])){
  314. $this->addOrderStatusHistory($newStatus, $origin);
  315. $this->status = $newStatus;
  316. $this->save();
  317. }
  318. break;
  319. default:
  320. throw new NotFoundHttpException('Statut de commande inconnu.');
  321. break;
  322. }
  323. }
  324. public function addOrderStatusHistory($newStatus,$origin)
  325. {
  326. $orderStatusHistory = new OrderStatusHistory();
  327. $orderStatusHistory->id_user = User::getCurrentId();
  328. $orderStatusHistory->id_order = $this->id;
  329. $orderStatusHistory->status = $newStatus;
  330. $orderStatusHistory->origin = $origin;
  331. $orderStatusHistory->date = date('Y-m-d H:i:s');
  332. $orderStatusHistory->save();
  333. }
  334. /**
  335. * Retourne le montant de la commande (total, payé, restant, ou en surplus).
  336. *
  337. * @param boolean $format
  338. * @return float
  339. */
  340. public function getAmount($type = self::AMOUNT_TOTAL, $format = false)
  341. {
  342. return $this->_getAmountGeneric($type, $this->amount, $format) ;
  343. }
  344. public function getAmountWithTax($type = self::AMOUNT_TOTAL, $format = false)
  345. {
  346. return $this->_getAmountGeneric($type, $this->amount_with_tax, $format) ;
  347. }
  348. protected function _getAmountGeneric($type, $amountOrder, $format)
  349. {
  350. switch ($type) {
  351. case self::AMOUNT_TOTAL :
  352. $amount = $amountOrder;
  353. break;
  354. case self::AMOUNT_PAID :
  355. $this->initPaidAmount();
  356. $amount = $this->paid_amount;
  357. break;
  358. case self::AMOUNT_REMAINING :
  359. $amount = $this->getAmountWithTax(self::AMOUNT_TOTAL)
  360. - $this->getAmountWithTax(self::AMOUNT_PAID);
  361. break;
  362. case self::AMOUNT_SURPLUS :
  363. $amount = $this->getAmountWithTax(self::AMOUNT_PAID)
  364. - $this->getAmountWithTax(self::AMOUNT_TOTAL);
  365. break;
  366. default:
  367. throw new NotFoundHttpException('Type de montant inconnu.') ;
  368. }
  369. if ($format) {
  370. return Price::format($amount) ;
  371. } else {
  372. return $amount;
  373. }
  374. }
  375. /**
  376. * Retourne les informations relatives à la commande au format JSON.
  377. *
  378. * @return string
  379. */
  380. public function getDataJson()
  381. {
  382. $order = Order::searchOne(['order.id' => $this->id]);
  383. $jsonOrder = [];
  384. if ($order) {
  385. $jsonOrder = [
  386. 'products' => [],
  387. 'amount' => $order->amount,
  388. 'str_amount' => $order->getAmountWithTax(self::AMOUNT_TOTAL, true),
  389. 'paid_amount' => $order->getAmount(self::AMOUNT_PAID),
  390. 'comment' => $order->comment,
  391. ];
  392. foreach ($order->productOrder as $productOrder) {
  393. $jsonOrder['products'][$productOrder->id_product] = $productOrder->quantity;
  394. }
  395. }
  396. return json_encode($jsonOrder);
  397. }
  398. /**
  399. * Enregistre un modèle de type CreditHistory.
  400. *
  401. * @param string $type
  402. * @param float $montant
  403. * @param integer $idProducer
  404. * @param integer $idUser
  405. * @param integer $idUserAction
  406. */
  407. public function saveCreditHistory($type, $amount, $idProducer, $idUser, $idUserAction)
  408. {
  409. $creditHistory = new CreditHistory;
  410. $creditHistory->id_user = $this->id_user;
  411. $creditHistory->id_order = $this->id;
  412. $creditHistory->amount = $amount;
  413. $creditHistory->type = $type;
  414. $creditHistory->id_producer = $idProducer;
  415. $creditHistory->id_user_action = $idUserAction;
  416. $creditHistory->populateRelation('order', $this);
  417. $creditHistory->populateRelation('user', User::find()->where(['id' => $this->id_user])->one());
  418. $creditHistory->save();
  419. }
  420. /**
  421. * Ajuste le crédit pour que la commande soit payée.
  422. *
  423. * @return boolean
  424. */
  425. public function processCredit()
  426. {
  427. if ($this->id_user) {
  428. $paymentStatus = $this->getPaymentStatus();
  429. if ($paymentStatus == self::PAYMENT_PAID) {
  430. return true;
  431. } elseif ($paymentStatus == self::PAYMENT_SURPLUS) {
  432. $type = CreditHistory::TYPE_REFUND;
  433. $amount = $this->getAmount(self::AMOUNT_SURPLUS);
  434. } elseif ($paymentStatus == self::PAYMENT_UNPAID) {
  435. $type = CreditHistory::TYPE_PAYMENT;
  436. $amount = $this->getAmount(self::AMOUNT_REMAINING);
  437. }
  438. $this->saveCreditHistory(
  439. $type,
  440. $amount,
  441. GlobalParam::getCurrentProducerId(),
  442. $this->id_user,
  443. User::getCurrentId()
  444. );
  445. }
  446. }
  447. public function setTillerSynchronization()
  448. {
  449. $order = Order::searchOne(['id' => $this->id]);
  450. $paymentStatus = $order->getPaymentStatus();
  451. if ($paymentStatus == self::PAYMENT_PAID) {
  452. $order->tiller_synchronization = 1 ;
  453. }
  454. else {
  455. $order->tiller_synchronization = 0 ;
  456. }
  457. $order->save() ;
  458. return $order ;
  459. }
  460. /**
  461. * Retourne le statut de paiement de la commande (payée, surplus, ou impayée).
  462. *
  463. * @return string
  464. */
  465. public function getPaymentStatus()
  466. {
  467. // payé
  468. if ($this->getAmountWithtax() - $this->getAmount(self::AMOUNT_PAID) < 0.01 &&
  469. $this->getAmountWithtax() - $this->getAmount(self::AMOUNT_PAID) > -0.01) {
  470. return self::PAYMENT_PAID;
  471. } // à rembourser
  472. elseif ($this->getAmountWithtax() - $this->getAmount(self::AMOUNT_PAID) <= -0.01) {
  473. return self::PAYMENT_SURPLUS;
  474. } // reste à payer
  475. elseif ($this->getAmountWithtax() - $this->getAmount(self::AMOUNT_PAID) >= 0.01) {
  476. return self::PAYMENT_UNPAID;
  477. }
  478. }
  479. /**
  480. * Retourne le résumé du panier au format HTML.
  481. *
  482. * @return string
  483. */
  484. public function getCartSummary()
  485. {
  486. if (!isset($this->productOrder)) {
  487. $this->productOrder = productOrder::find()->where(['id_order' => $this->id])->all();
  488. }
  489. $html = '';
  490. $count = count($this->productOrder);
  491. $i = 0;
  492. foreach ($this->productOrder as $p) {
  493. if (isset($p->product)) {
  494. $html .= Html::encode($p->product->name) . ' (' . $p->quantity . '&nbsp;' . Product::strUnit($p->unit, 'wording_short', true) . ')';
  495. if (++$i != $count) {
  496. $html .= '<br />';
  497. }
  498. }
  499. }
  500. return $html;
  501. }
  502. /**
  503. * Retourne le résumé du point de vente lié à la commande au format HTML.
  504. *
  505. * @return string
  506. */
  507. public function getPointSaleSummary()
  508. {
  509. $html = '';
  510. if (isset($this->pointSale)) {
  511. $html .= '<span class="name-point-sale">' .
  512. Html::encode($this->pointSale->name) .
  513. '</span>' .
  514. '<br /><span class="locality">'
  515. . Html::encode($this->pointSale->locality)
  516. . '</span>';
  517. if (strlen($this->comment_point_sale)) {
  518. $html .= '<div class="comment"><span>'
  519. . Html::encode($this->comment_point_sale)
  520. . '</span></div>';
  521. }
  522. } else {
  523. $html .= 'Point de vente supprimé';
  524. }
  525. return $html;
  526. }
  527. /**
  528. * Retourne le résumé du paiement (montant, statut).
  529. *
  530. * @return string
  531. */
  532. public function getAmountSummary()
  533. {
  534. $html = '';
  535. $creditActive = Producer::getConfig('credit') ;
  536. $html .= $this->getAmountWithTax(self::AMOUNT_TOTAL, true) ;
  537. if($creditActive) {
  538. $html .= '<br />' ;
  539. if ($this->paid_amount) {
  540. if ($this->getPaymentStatus() == Order::PAYMENT_PAID) {
  541. $html .= '<span class="label label-success">Payée</span>';
  542. }
  543. elseif ($this->getPaymentStatus() == Order::PAYMENT_UNPAID) {
  544. $html .= '<span class="label label-danger">Non payée</span><br />
  545. Reste <strong>' . $this->getAmount(Order::AMOUNT_REMAINING, true) . '</strong> à payer';
  546. }
  547. elseif ($this->getPaymentStatus() == Order::PAYMENT_SURPLUS) {
  548. $html .= '<span class="label label-success">Payée</span>';
  549. }
  550. }
  551. else {
  552. $html .= '<span class="label label-default">Non réglé</span>';
  553. }
  554. }
  555. return $html;
  556. }
  557. /**
  558. * Retourne une chaine de caractère décrivant l'utilisateur lié à la commande.
  559. *
  560. * @return string
  561. */
  562. public function getStrUser()
  563. {
  564. if (isset($this->user)) {
  565. if(isset($this->user->name_legal_person) && strlen($this->user->name_legal_person)) {
  566. return Html::encode($this->user->name_legal_person);
  567. }
  568. else {
  569. return Html::encode($this->user->lastname . ' ' . $this->user->name);
  570. }
  571. }
  572. elseif (strlen($this->username)) {
  573. return Html::encode($this->username);
  574. }
  575. else {
  576. return 'Client introuvable';
  577. }
  578. }
  579. /**
  580. * Retourne l'état de la commande (livrée, modifiable ou en préparation)
  581. *
  582. * @return string
  583. */
  584. public function getState()
  585. {
  586. $orderDate = strtotime($this->distribution->date);
  587. $today = strtotime(date('Y-m-d'));
  588. $todayHour = date('G');
  589. $dayDistribution = strtolower(date('l', strtotime($this->distribution->date))) ;
  590. $orderDelay = Producer::getConfig(
  591. 'order_delay',
  592. $this->distribution->id_producer
  593. );
  594. $orderDelaySpecific = Producer::getConfig(
  595. 'order_delay_'.$dayDistribution,
  596. $this->distribution->id_producer
  597. );
  598. if($orderDelaySpecific) {
  599. $orderDelay = $orderDelaySpecific ;
  600. }
  601. $orderDeadline = Producer::getConfig(
  602. 'order_deadline',
  603. $this->distribution->id_producer
  604. );
  605. $orderDeadlineSpecific = Producer::getConfig(
  606. 'order_deadline_'.$dayDistribution,
  607. $this->distribution->id_producer
  608. );
  609. if($orderDeadlineSpecific) {
  610. $orderDeadline = $orderDeadlineSpecific ;
  611. }
  612. $nbDays = (int) round((($orderDate - $today) / (24 * 60 * 60)));
  613. if ($nbDays <= 0) {
  614. return self::STATE_DELIVERED;
  615. } elseif ($nbDays >= $orderDelay &&
  616. ($nbDays != $orderDelay ||
  617. ($nbDays == $orderDelay && $todayHour < $orderDeadline))) {
  618. return self::STATE_OPEN;
  619. }
  620. return self::STATE_PREPARATION;
  621. }
  622. /**
  623. * Retourne l'origine de la commande (client, automatique ou admin) sous forme
  624. * texte ou HTML.
  625. *
  626. * @param boolean $with_label
  627. * @return string
  628. */
  629. public function getStrOrigin($withLabel = false)
  630. {
  631. $classLabel = '';
  632. $str = '';
  633. if ($this->origin == self::ORIGIN_USER) {
  634. $classLabel = 'success';
  635. $str = 'Client';
  636. } elseif ($this->origin == self::ORIGIN_AUTO) {
  637. $classLabel = 'default';
  638. $str = 'Auto';
  639. } elseif ($this->origin == self::ORIGIN_ADMIN) {
  640. $classLabel = 'warning';
  641. $str = 'Vous';
  642. }
  643. if ($withLabel) {
  644. return '<span class="label label-' . $classLabel . '">'
  645. . $str . '</span>';
  646. } else {
  647. return $str;
  648. }
  649. }
  650. /**
  651. * Retourne l'historique de la commande (ajoutée, modifiée, supprimée) au
  652. * format HTML.
  653. *
  654. * @return string
  655. */
  656. public function getStrHistory()
  657. {
  658. $arr = [
  659. 'class' => 'create',
  660. 'glyphicon' => 'plus',
  661. 'str' => 'Ajoutée',
  662. 'date' => $this->date
  663. ];
  664. if (!is_null($this->date_update)) {
  665. $arr = [
  666. 'class' => 'update',
  667. 'glyphicon' => 'pencil',
  668. 'str' => 'Modifiée',
  669. 'date' => $this->date_update
  670. ];
  671. }
  672. if (!is_null($this->date_delete)) {
  673. $arr = [
  674. 'class' => 'delete',
  675. 'glyphicon' => 'remove',
  676. 'str' => 'Annulée',
  677. 'date' => $this->date_delete
  678. ];
  679. }
  680. $html = '<div class="small"><span class="' . $arr['class'] . '">'
  681. . '<span class="glyphicon glyphicon-' . $arr['glyphicon'] . '"></span> '
  682. . $arr['str'] . '</span> le <strong>'
  683. . date('d/m/Y à G\hi', strtotime($arr['date'])) . '</strong></div>';
  684. return $html;
  685. }
  686. /**
  687. * Retourne une classe identifiant l'historique de la commande (ajoutée,
  688. * modifiée, supprimée).
  689. *
  690. * @return string
  691. */
  692. public function getClassHistory()
  693. {
  694. if (!is_null($this->date_delete)) {
  695. return 'commande-delete';
  696. }
  697. if (!is_null($this->date_update)) {
  698. return 'commande-update';
  699. }
  700. return 'commande-create';
  701. }
  702. /**
  703. * Retourne la quantité d'un produit donné de plusieurs commandes.
  704. *
  705. * @param integer $idProduct
  706. * @param array $orders
  707. * @param boolean $ignoreCancel
  708. *
  709. * @return integer
  710. */
  711. public static function getProductQuantity($idProduct, $orders, $ignoreCancel = false, $unit = null)
  712. {
  713. $quantity = 0;
  714. if (isset($orders) && is_array($orders) && count($orders)) {
  715. foreach ($orders as $c) {
  716. if (is_null($c->date_delete) || $ignoreCancel) {
  717. foreach ($c->productOrder as $po) {
  718. if ($po->id_product == $idProduct &&
  719. ((is_null($unit) && $po->product->unit == $po->unit) || (!is_null($unit) && strlen($unit) && $po->unit == $unit))) {
  720. $quantity += $po->quantity;
  721. }
  722. }
  723. }
  724. }
  725. }
  726. return $quantity;
  727. }
  728. public static function getProductQuantityPieces($idProduct, $orders)
  729. {
  730. $quantity = 0;
  731. if (isset($orders) && is_array($orders) && count($orders)) {
  732. foreach ($orders as $c) {
  733. if (is_null($c->date_delete)) {
  734. foreach ($c->productOrder as $po) {
  735. if ($po->id_product == $idProduct) {
  736. if($po->unit == 'piece') {
  737. $quantity += $po->quantity ;
  738. }
  739. else {
  740. if(isset($po->product) && $po->product->weight > 0) {
  741. $quantity += ($po->quantity * Product::$unitsArray[$po->unit]['coefficient']) / $po->product->weight ;
  742. }
  743. }
  744. }
  745. }
  746. }
  747. }
  748. }
  749. return $quantity;
  750. }
  751. /**
  752. * Recherche et initialise des commandes.
  753. *
  754. * @param array $params
  755. * @param array $conditions
  756. * @param string $orderby
  757. * @param integer $limit
  758. * @return array
  759. */
  760. public static function searchBy($params = [], $options = [])
  761. {
  762. $orders = parent::searchBy($params, $options);
  763. /*
  764. * Initialisation des commandes
  765. */
  766. if (is_array($orders)) {
  767. if (count($orders)) {
  768. foreach ($orders as $order) {
  769. if (is_a($order, 'common\models\Order')) {
  770. $order->init();
  771. }
  772. }
  773. return $orders;
  774. }
  775. } else {
  776. $order = $orders;
  777. if (is_a($order, 'common\models\Order')) {
  778. return $order->init();
  779. } // count
  780. else {
  781. return $order;
  782. }
  783. }
  784. return false;
  785. }
  786. /**
  787. * Retourne le nombre de produits commandés
  788. *
  789. * @return integer
  790. */
  791. public function countProducts()
  792. {
  793. $count = 0;
  794. if ($this->productOrder && is_array($this->productOrder)) {
  795. foreach ($this->productOrder as $productOrder) {
  796. if ($productOrder->unit == 'piece') {
  797. $count++;
  798. } else {
  799. $count += $productOrder->quantity;
  800. }
  801. }
  802. }
  803. return $count;
  804. }
  805. /**
  806. * Retourne un bloc html présentant une date.
  807. *
  808. * @return string
  809. */
  810. public function getBlockDate()
  811. {
  812. return '<div class="block-date">
  813. <div class="day">' . strftime('%A', strtotime($this->distribution->date)) . '</div>
  814. <div class="num">' . date('d', strtotime($this->distribution->date)) . '</div>
  815. <div class="month">' . strftime('%B', strtotime($this->distribution->date)) . '</div>
  816. </div>';
  817. }
  818. public function getUsername()
  819. {
  820. $username = '' ;
  821. if($this->user) {
  822. $username = $this->user->getUsername() ;
  823. }
  824. if(strlen($this->username)) {
  825. $username = $this->username ;
  826. }
  827. return $username ;
  828. }
  829. }