Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878
  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. ->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. $html .= $this->getAmountWithTax(self::AMOUNT_TOTAL, true) . '<br />';
  536. if ($this->paid_amount) {
  537. if ($this->getPaymentStatus() == Order::PAYMENT_PAID) {
  538. $html .= '<span class="label label-success">Payée</span>';
  539. } elseif ($this->getPaymentStatus() == Order::PAYMENT_UNPAID) {
  540. $html .= '<span class="label label-danger">Non payée</span><br />
  541. Reste <strong>' . $this->getAmount(Order::AMOUNT_REMAINING, true) . '</strong> à payer';
  542. } elseif ($this->getPaymentStatus() == Order::PAYMENT_SURPLUS) {
  543. $html .= '<span class="label label-success">Payée</span>';
  544. }
  545. } else {
  546. $html .= '<span class="label label-default">Non réglé</span>';
  547. }
  548. return $html;
  549. }
  550. /**
  551. * Retourne une chaine de caractère décrivant l'utilisateur lié à la commande.
  552. *
  553. * @return string
  554. */
  555. public function getStrUser()
  556. {
  557. if (isset($this->user)) {
  558. return Html::encode($this->user->lastname . ' ' . $this->user->name);
  559. } elseif (strlen($this->username)) {
  560. return Html::encode($this->username);
  561. } else {
  562. return 'Client introuvable';
  563. }
  564. }
  565. /**
  566. * Retourne l'état de la commande (livrée, modifiable ou en préparation)
  567. *
  568. * @return string
  569. */
  570. public function getState()
  571. {
  572. $orderDelay = Producer::getConfig(
  573. 'order_delay',
  574. $this->distribution->id_producer
  575. );
  576. $orderDeadline = Producer::getConfig(
  577. 'order_deadline',
  578. $this->distribution->id_producer
  579. );
  580. $orderDate = strtotime($this->distribution->date);
  581. $today = strtotime(date('Y-m-d'));
  582. $todayHour = date('G');
  583. $nbDays = (int) round((($orderDate - $today) / (24 * 60 * 60)));
  584. if ($nbDays <= 0) {
  585. return self::STATE_DELIVERED;
  586. } elseif ($nbDays >= $orderDelay &&
  587. ($nbDays != $orderDelay ||
  588. ($nbDays == $orderDelay && $todayHour < $orderDeadline))) {
  589. return self::STATE_OPEN;
  590. }
  591. return self::STATE_PREPARATION;
  592. }
  593. /**
  594. * Retourne l'origine de la commande (client, automatique ou admin) sous forme
  595. * texte ou HTML.
  596. *
  597. * @param boolean $with_label
  598. * @return string
  599. */
  600. public function getStrOrigin($withLabel = false)
  601. {
  602. $classLabel = '';
  603. $str = '';
  604. if ($this->origin == self::ORIGIN_USER) {
  605. $classLabel = 'success';
  606. $str = 'Client';
  607. } elseif ($this->origin == self::ORIGIN_AUTO) {
  608. $classLabel = 'default';
  609. $str = 'Auto';
  610. } elseif ($this->origin == self::ORIGIN_ADMIN) {
  611. $classLabel = 'warning';
  612. $str = 'Vous';
  613. }
  614. if ($withLabel) {
  615. return '<span class="label label-' . $classLabel . '">'
  616. . $str . '</span>';
  617. } else {
  618. return $str;
  619. }
  620. }
  621. /**
  622. * Retourne l'historique de la commande (ajoutée, modifiée, supprimée) au
  623. * format HTML.
  624. *
  625. * @return string
  626. */
  627. public function getStrHistory()
  628. {
  629. $arr = [
  630. 'class' => 'create',
  631. 'glyphicon' => 'plus',
  632. 'str' => 'Ajoutée',
  633. 'date' => $this->date
  634. ];
  635. if (!is_null($this->date_update)) {
  636. $arr = [
  637. 'class' => 'update',
  638. 'glyphicon' => 'pencil',
  639. 'str' => 'Modifiée',
  640. 'date' => $this->date_update
  641. ];
  642. }
  643. if (!is_null($this->date_delete)) {
  644. $arr = [
  645. 'class' => 'delete',
  646. 'glyphicon' => 'remove',
  647. 'str' => 'Annulée',
  648. 'date' => $this->date_delete
  649. ];
  650. }
  651. $html = '<div class="small"><span class="' . $arr['class'] . '">'
  652. . '<span class="glyphicon glyphicon-' . $arr['glyphicon'] . '"></span> '
  653. . $arr['str'] . '</span> le <strong>'
  654. . date('d/m/Y à G\hi', strtotime($arr['date'])) . '</strong></div>';
  655. return $html;
  656. }
  657. /**
  658. * Retourne une classe identifiant l'historique de la commande (ajoutée,
  659. * modifiée, supprimée).
  660. *
  661. * @return string
  662. */
  663. public function getClassHistory()
  664. {
  665. if (!is_null($this->date_delete)) {
  666. return 'commande-delete';
  667. }
  668. if (!is_null($this->date_update)) {
  669. return 'commande-update';
  670. }
  671. return 'commande-create';
  672. }
  673. /**
  674. * Retourne la quantité d'un produit donné de plusieurs commandes.
  675. *
  676. * @param integer $idProduct
  677. * @param array $orders
  678. * @param boolean $ignoreCancel
  679. *
  680. * @return integer
  681. */
  682. public static function getProductQuantity($idProduct, $orders, $ignoreCancel = false, $unit = null)
  683. {
  684. $quantity = 0;
  685. if (isset($orders) && is_array($orders) && count($orders)) {
  686. foreach ($orders as $c) {
  687. if (is_null($c->date_delete) || $ignoreCancel) {
  688. foreach ($c->productOrder as $po) {
  689. if ($po->id_product == $idProduct &&
  690. ((is_null($unit) && $po->product->unit == $po->unit) || (!is_null($unit) && strlen($unit) && $po->unit == $unit))) {
  691. $quantity += $po->quantity;
  692. }
  693. }
  694. }
  695. }
  696. }
  697. return $quantity;
  698. }
  699. /**
  700. * Recherche et initialise des commandes.
  701. *
  702. * @param array $params
  703. * @param array $conditions
  704. * @param string $orderby
  705. * @param integer $limit
  706. * @return array
  707. */
  708. public static function searchBy($params = [], $options = [])
  709. {
  710. $orders = parent::searchBy($params, $options);
  711. /*
  712. * Initialisation des commandes
  713. */
  714. if (is_array($orders)) {
  715. if (count($orders)) {
  716. foreach ($orders as $order) {
  717. if (is_a($order, 'common\models\Order')) {
  718. $order->init();
  719. }
  720. }
  721. return $orders;
  722. }
  723. } else {
  724. $order = $orders;
  725. if (is_a($order, 'common\models\Order')) {
  726. return $order->init();
  727. } // count
  728. else {
  729. return $order;
  730. }
  731. }
  732. return false;
  733. }
  734. /**
  735. * Retourne le nombre de produits commandés
  736. *
  737. * @return integer
  738. */
  739. public function countProducts()
  740. {
  741. $count = 0;
  742. if ($this->productOrder && is_array($this->productOrder)) {
  743. foreach ($this->productOrder as $productOrder) {
  744. if ($productOrder->unit == 'piece') {
  745. $count++;
  746. } else {
  747. $count += $productOrder->quantity;
  748. }
  749. }
  750. }
  751. return $count;
  752. }
  753. /**
  754. * Retourne un bloc html présentant une date.
  755. *
  756. * @return string
  757. */
  758. public function getBlockDate()
  759. {
  760. return '<div class="block-date">
  761. <div class="day">' . strftime('%A', strtotime($this->distribution->date)) . '</div>
  762. <div class="num">' . date('d', strtotime($this->distribution->date)) . '</div>
  763. <div class="month">' . strftime('%B', strtotime($this->distribution->date)) . '</div>
  764. </div>';
  765. }
  766. public function getUsername()
  767. {
  768. $username = '' ;
  769. if($this->user) {
  770. $username = $this->user->getUsername() ;
  771. }
  772. if(strlen($this->username)) {
  773. $username = $this->username ;
  774. }
  775. return $username ;
  776. }
  777. }