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.

969 lines
38KB

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