Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

Order.php 33KB

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