Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

DistributionController.php 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  1. <?php
  2. /**
  3. Copyright distrib (2018)
  4. contact@opendistrib.net
  5. Ce logiciel est un programme informatique servant à aider les producteurs
  6. à distribuer leur production en circuits courts.
  7. Ce logiciel est régi par la licence CeCILL soumise au droit français et
  8. respectant les principes de diffusion des logiciels libres. Vous pouvez
  9. utiliser, modifier et/ou redistribuer ce programme sous les conditions
  10. de la licence CeCILL telle que diffusée par le CEA, le CNRS et l'INRIA
  11. sur le site "http://www.cecill.info".
  12. En contrepartie de l'accessibilité au code source et des droits de copie,
  13. de modification et de redistribution accordés par cette licence, il n'est
  14. offert aux utilisateurs qu'une garantie limitée. Pour les mêmes raisons,
  15. seule une responsabilité restreinte pèse sur l'auteur du programme, le
  16. titulaire des droits patrimoniaux et les concédants successifs.
  17. A cet égard l'attention de l'utilisateur est attirée sur les risques
  18. associés au chargement, à l'utilisation, à la modification et/ou au
  19. développement et à la reproduction du logiciel par l'utilisateur étant
  20. donné sa spécificité de logiciel libre, qui peut le rendre complexe à
  21. manipuler et qui le réserve donc à des développeurs et des professionnels
  22. avertis possédant des connaissances informatiques approfondies. Les
  23. utilisateurs sont donc invités à charger et tester l'adéquation du
  24. logiciel à leurs besoins dans des conditions permettant d'assurer la
  25. sécurité de leurs systèmes et ou de leurs données et, plus généralement,
  26. à l'utiliser et l'exploiter dans les mêmes conditions de sécurité.
  27. Le fait que vous puissiez accéder à cet en-tête signifie que vous avez
  28. pris connaissance de la licence CeCILL, et que vous en avez accepté les
  29. termes.
  30. */
  31. namespace backend\controllers;
  32. use backend\controllers\BackendController ;
  33. use common\models\Distribution ;
  34. use common\models\Product ;
  35. use common\models\Producer ;
  36. use common\models\Order ;
  37. use common\models\User ;
  38. use common\models\Subscription ;
  39. use common\helpers\Price ;
  40. use DateTime;
  41. class DistributionController extends BackendController
  42. {
  43. public function actionIndex($date = '')
  44. {
  45. $format = 'Y-m-d' ;
  46. $theDate = '' ;
  47. $dateObject = DateTime::createFromFormat($format, $date);
  48. if($dateObject && $dateObject->format($format) === $date) {
  49. $theDate = $date ;
  50. }
  51. return $this->render('index', [
  52. 'date' => $theDate
  53. ]) ;
  54. }
  55. public function actionAjaxInfos($date = '')
  56. {
  57. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  58. $json = [
  59. 'distribution' => [],
  60. 'products' => []
  61. ] ;
  62. $format = 'Y-m-d' ;
  63. $dateObject = DateTime::createFromFormat($format, $date);
  64. $distributionsArray = Distribution::searchAll([
  65. 'active' => 1
  66. ], [
  67. 'conditions' => ['date > :date_begin','date < :date_end'],
  68. 'params' => [':date_begin' => date('Y-m-d', strtotime('-1 month')), ':date_end' => date('Y-m-d', strtotime('+3 month')), ],
  69. ]) ;
  70. $json['distributions'] = $distributionsArray ;
  71. if($dateObject && $dateObject->format($format) === $date) {
  72. // distribution
  73. $distribution = Distribution::initDistribution($date) ;
  74. $json['distribution'] = [
  75. 'id' => $distribution->id,
  76. 'active' => $distribution->active,
  77. 'url_report' => Yii::$app->urlManagerBackend->createUrl(['distribution/report','date' => $distribution->date])
  78. ] ;
  79. // commandes
  80. $ordersArray = Order::searchAll([
  81. 'distribution.date' => $date,
  82. ],[
  83. 'orderby' => 'user.lastname ASC, user.name ASC'
  84. ]);
  85. // montant et poids des commandes
  86. $revenues = 0;
  87. $weight = 0 ;
  88. if($ordersArray) {
  89. foreach ($ordersArray as $order) {
  90. if(is_null($order->date_delete)) {
  91. $revenues += $order->amount;
  92. $weight += $order->weight;
  93. }
  94. }
  95. }
  96. $json['distribution']['revenues'] = Price::format($revenues);
  97. $json['distribution']['weight'] = number_format($weight, 2);
  98. // products
  99. $productsArray = Product::find()
  100. ->orWhere(['id_producer' => Producer::getId(),])
  101. ->joinWith(['productDistribution' => function($query) use($distribution) {
  102. $query->andOnCondition('product_distribution.id_distribution = '.$distribution->id) ;
  103. }])
  104. ->orderBy('product_distribution.active DESC, order ASC')
  105. ->asArray()
  106. ->all();
  107. $potentialRevenues = 0;
  108. $potentialWeight = 0;
  109. foreach($productsArray as &$theProduct) {
  110. $quantityOrder = Order::getProductQuantity($theProduct['id'], $ordersArray) ;
  111. $theProduct['quantity_ordered'] = $quantityOrder ;
  112. $theProduct['quantity_remaining'] = $theProduct['quantity_max'] - $quantityOrder ;
  113. if($theProduct['quantity_remaining'] < 0) $theProduct['quantity_remaining'] = 0 ;
  114. $theProduct['quantity_form'] = 0 ;
  115. if($theProduct['productDistribution'][0]['active'] && $theProduct['productDistribution'][0]['quantity_max']) {
  116. $potentialRevenues += $theProduct['productDistribution'][0]['quantity_max'] * $theProduct['price'];
  117. $potentialWeight += $theProduct['productDistribution'][0]['quantity_max'] * $theProduct['weight'] / 1000;
  118. }
  119. }
  120. $json['distribution']['potential_revenues'] = Price::format($potentialRevenues) ;
  121. $json['distribution']['potential_weight'] = number_format($potentialWeight, 2) ;
  122. $json['products'] = $productsArray ;
  123. // orders as array
  124. if($ordersArray) {
  125. foreach($ordersArray as &$order) {
  126. $productOrderArray = \yii\helpers\ArrayHelper::map($order->productOrder, 'id_product', 'quantity') ;
  127. foreach($productsArray as $product) {
  128. if(!isset($productOrderArray[$product['id']])) {
  129. $productOrderArray[$product['id']] = 0 ;
  130. }
  131. }
  132. $creditHistoryArray = [] ;
  133. foreach($order->creditHistory as $creditHistory) {
  134. $creditHistoryArray[] = [
  135. 'date' => date('d/m/Y H:i:s', strtotime($creditHistory->date)),
  136. 'user_action' => $creditHistory->strUserAction(),
  137. 'wording' => $creditHistory->getStrWording(),
  138. 'debit' => ($creditHistory->isTypeDebit() ? '-&nbsp;'.$creditHistory->getAmount(Order::AMOUNT_TOTAL,true) : ''),
  139. 'credit' => ($creditHistory->isTypeCredit() ? '+&nbsp;'.$creditHistory->getAmount(Order::AMOUNT_TOTAL,true) : '')
  140. ] ;
  141. }
  142. $arrayCreditUser = [] ;
  143. if(isset($order->user) && isset($order->user->userProducer)) {
  144. $arrayCreditUser['credit'] = $order->user->userProducer[0]->credit ;
  145. }
  146. $order = array_merge($order->getAttributes(), [
  147. 'amount' => $order->getAmount(Order::AMOUNT_TOTAL),
  148. 'amount_paid' => $order->getAmount(Order::AMOUNT_PAID),
  149. 'amount_remaining' => $order->getAmount(Order::AMOUNT_REMAINING),
  150. 'amount_surplus' => $order->getAmount(Order::AMOUNT_SURPLUS),
  151. 'user' => (isset($order->user)) ? array_merge($order->user->getAttributes(), $arrayCreditUser) : null,
  152. 'pointSale' => ['id' => $order->pointSale->id, 'name' => $order->pointSale->name],
  153. 'productOrder' => $productOrderArray,
  154. 'creditHistory' => $creditHistoryArray
  155. ]) ;
  156. }
  157. }
  158. $json['orders'] = $ordersArray ;
  159. // order create
  160. $productOrderArray = [] ;
  161. foreach($productsArray as $product) {
  162. $productOrderArray[$product['id']] = 0 ;
  163. }
  164. $json['order_create'] = [
  165. 'id_point_sale' => 0,
  166. 'id_user' => 0,
  167. 'username' => '',
  168. 'comment' => '',
  169. 'productOrder' => $productOrderArray
  170. ] ;
  171. // points de vente
  172. $pointsSaleArray = PointSale::find()
  173. ->joinWith(['pointSaleDistribution' => function($q) use ($distribution) {
  174. $q->where(['id_distribution' => $distribution->id]);
  175. }])
  176. ->where([
  177. 'id_producer' => Producer::getId(),
  178. ])
  179. ->asArray()
  180. ->all();
  181. $json['points_sale'] = $pointsSaleArray ;
  182. // utilisateurs
  183. $usersArray = User::findBy()->all() ;
  184. $json['users'] = $usersArray ;
  185. // une production de la semaine activée ou non
  186. $oneDistributionWeekActive = false ;
  187. $week = sprintf('%02d',date('W',strtotime($date)));
  188. $start = strtotime(date('Y',strtotime($date)).'W'.$week);
  189. $dateMonday = date('Y-m-d',strtotime('Monday',$start)) ;
  190. $dateTuesday = date('Y-m-d',strtotime('Tuesday',$start)) ;
  191. $dateWednesday = date('Y-m-d',strtotime('Wednesday',$start)) ;
  192. $dateThursday = date('Y-m-d',strtotime('Thursday',$start)) ;
  193. $dateFriday = date('Y-m-d',strtotime('Friday',$start)) ;
  194. $dateSaturday = date('Y-m-d',strtotime('Saturday',$start)) ;
  195. $dateSunday = date('Y-m-d',strtotime('Sunday',$start)) ;
  196. $weekDistribution = Distribution::find()
  197. ->andWhere([
  198. 'id_producer' => Producer::getId(),
  199. 'active' => 1,
  200. ])
  201. ->andWhere(['or',
  202. ['date' => $dateMonday],
  203. ['date' => $dateTuesday],
  204. ['date' => $dateWednesday],
  205. ['date' => $dateThursday],
  206. ['date' => $dateFriday],
  207. ['date' => $dateSaturday],
  208. ['date' => $dateSunday],
  209. ])
  210. ->one();
  211. if($weekDistribution) {
  212. $oneDistributionWeekActive = true ;
  213. }
  214. $json['one_distribution_week_active'] = $oneDistributionWeekActive ;
  215. }
  216. return $json ;
  217. }
  218. /**
  219. * Génére un PDF récapitulatif des commandes d'un producteur pour une
  220. * date donnée.
  221. *
  222. * @param string $date
  223. * @param boolean $save
  224. * @param integer $idProducer
  225. * @return PDF|null
  226. */
  227. public function actionReport($date = '', $save = false, $idProducer = 0)
  228. {
  229. if (!Yii::$app->user->isGuest) {
  230. $idProducer = Producer::getId() ;
  231. }
  232. $ordersArray = Order::searchAll([
  233. 'distribution.date' => $date,
  234. ],
  235. [
  236. 'orderby' => 'comment_point_sale ASC, user.name ASC',
  237. 'conditions' => 'date_delete IS NULL'
  238. ]) ;
  239. $distribution = Distribution::searchOne([],[
  240. 'conditions' => 'date LIKE :date',
  241. 'params' => [':date' => $date]
  242. ]) ;
  243. if ($distribution) {
  244. $selectedProductsArray = ProductDistribution::searchByDistribution($distribution->id) ;
  245. $pointsSaleArray = PointSale::searchAll() ;
  246. foreach ($pointsSaleArray as $pointSale) {
  247. $pointSale->initOrders($ordersArray) ;
  248. }
  249. // produits
  250. $productsArray = Product::searchAll() ;
  251. // get your HTML raw content without any layouts or scripts
  252. $content = $this->renderPartial('report', [
  253. 'date' => $date,
  254. 'distribution' => $distribution,
  255. 'selectedProductsArray' => $selectedProductsArray,
  256. 'pointsSaleArray' => $pointsSaleArray,
  257. 'productsArray' => $productsArray,
  258. 'ordersArray' => $ordersArray
  259. ]);
  260. $dateStr = date('d/m/Y', strtotime($date));
  261. if ($save) {
  262. $destination = Pdf::DEST_FILE;
  263. } else {
  264. $destination = Pdf::DEST_BROWSER;
  265. }
  266. $pdf = new Pdf([
  267. // set to use core fonts only
  268. 'mode' => Pdf::MODE_UTF8,
  269. // A4 paper format
  270. 'format' => Pdf::FORMAT_A4,
  271. // portrait orientation
  272. 'orientation' => Pdf::ORIENT_PORTRAIT,
  273. // stream to browser inline
  274. 'destination' => $destination,
  275. 'filename' => Yii::getAlias('@app/web/pdf/Commandes-' . $date . '-' . $idProducer . '.pdf'),
  276. // your html content input
  277. 'content' => $content,
  278. // format content from your own css file if needed or use the
  279. // enhanced bootstrap css built by Krajee for mPDF formatting
  280. //'cssFile' => '@vendor/kartik-v/yii2-mpdf/assets/kv-mpdf-bootstrap.min.css',
  281. // any css to be embedded if required
  282. //'cssInline' => '.kv-heading-1{font-size:18px}',
  283. // set mPDF properties on the fly
  284. //'options' => ['title' => 'Krajee Report Title'],
  285. // call mPDF methods on the fly
  286. 'methods' => [
  287. 'SetHeader' => ['Commandes du ' . $dateStr],
  288. 'SetFooter' => ['{PAGENO}'],
  289. ]
  290. ]);
  291. // return the pdf output as per the destination setting
  292. return $pdf->render();
  293. }
  294. return null ;
  295. }
  296. public function actionAjaxProcessProductQuantityMax($idDistribution, $idProduct, $quantityMax)
  297. {
  298. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  299. $productDistribution = ProductDistribution::searchOne([
  300. 'id_distribution' => $idDistribution,
  301. 'id_product' => $idProduct,
  302. ]) ;
  303. $productDistribution->quantity_max = (!$quantityMax) ? null : (int) $quantityMax ;
  304. $productDistribution->save() ;
  305. return ['success'] ;
  306. }
  307. public function actionAjaxProcessActiveProduct($idDistribution, $idProduct, $active)
  308. {
  309. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  310. $productDistribution = ProductDistribution::searchOne([
  311. 'id_distribution' => $idDistribution,
  312. 'id_product' => $idProduct,
  313. ]) ;
  314. $productDistribution->active = $active ;
  315. $productDistribution->save() ;
  316. return ['success'] ;
  317. }
  318. public function actionAjaxProcessActivePointSale($idDistribution, $idPointSale, $delivery)
  319. {
  320. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  321. $pointSaleDistribution = PointSaleDistribution::searchOne([
  322. 'id_distribution' => $idDistribution,
  323. 'id_point_sale' => $idPointSale,
  324. ]) ;
  325. $pointSaleDistribution->delivery = $delivery ;
  326. $pointSaleDistribution->save() ;
  327. return ['success'] ;
  328. }
  329. /**
  330. * Active/désactive un jour de distribution.
  331. *
  332. * @param integer $idDistribution
  333. * @param string $date
  334. * @param boolean $active
  335. * @return array
  336. */
  337. public function actionAjaxProcessActiveDistribution($idDistribution = 0, $date = '', $active)
  338. {
  339. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  340. if($idDistribution) {
  341. $distribution = Distribution::searchOne([
  342. 'id' => $idDistribution
  343. ]) ;
  344. }
  345. $format = 'Y-m-d' ;
  346. $dateObject = DateTime::createFromFormat($format, $date);
  347. if($dateObject && $dateObject->format($format) === $date) {
  348. $distribution = Distribution::initDistribution($date) ;
  349. }
  350. if($distribution) {
  351. $distribution->active = (int) $active ;
  352. $distribution->save() ;
  353. if ($active) {
  354. // ajout des abonnements
  355. Subscription::addAll($distribution->date);
  356. }
  357. return ['success'] ;
  358. }
  359. return ['error'] ;
  360. }
  361. /**
  362. * Change l'état d'une semaine de production (activé, désactivé).
  363. *
  364. * @param string $date
  365. * @param integer $active
  366. */
  367. public function actionAjaxProcessActiveWeekDistribution($date, $active)
  368. {
  369. $week = sprintf('%02d',date('W',strtotime($date)));
  370. $start = strtotime(date('Y',strtotime($date)).'W'.$week);
  371. $dateMonday = date('Y-m-d',strtotime('Monday',$start)) ;
  372. $dateTuesday = date('Y-m-d',strtotime('Tuesday',$start)) ;
  373. $dateWednesday = date('Y-m-d',strtotime('Wednesday',$start)) ;
  374. $dateThursday = date('Y-m-d',strtotime('Thursday',$start)) ;
  375. $dateFriday = date('Y-m-d',strtotime('Friday',$start)) ;
  376. $dateSaturday = date('Y-m-d',strtotime('Saturday',$start)) ;
  377. $dateSunday = date('Y-m-d',strtotime('Sunday',$start)) ;
  378. $pointsSaleArray = PointSale::searchAll() ;
  379. $activeMonday = false ;
  380. $activeTuesday = false ;
  381. $activeWednesday = false ;
  382. $activeThursday = false ;
  383. $activeFriday = false ;
  384. $activeSaturday = false ;
  385. $activeSunday = false ;
  386. foreach($pointsSaleArray as $pointSale) {
  387. if($pointSale->delivery_monday) $activeMonday = true ;
  388. if($pointSale->delivery_tuesday) $activeTuesday = true ;
  389. if($pointSale->delivery_wednesday) $activeWednesday = true ;
  390. if($pointSale->delivery_thursday) $activeThursday = true ;
  391. if($pointSale->delivery_friday) $activeFriday = true ;
  392. if($pointSale->delivery_saturday) $activeSaturday = true ;
  393. if($pointSale->delivery_sunday) $activeSunday = true ;
  394. }
  395. if($activeMonday || !$active) {
  396. $this->actionAjaxProcessActiveDistribution(0, $dateMonday, $active) ;
  397. }
  398. if($activeTuesday || !$active) {
  399. $this->actionAjaxProcessActiveDistribution(0, $dateTuesday, $active) ;
  400. }
  401. if($activeWednesday || !$active) {
  402. $this->actionAjaxProcessActiveDistribution(0, $dateWednesday, $active) ;
  403. }
  404. if($activeThursday || !$active) {
  405. $this->actionAjaxProcessActiveDistribution(0, $dateThursday, $active) ;
  406. }
  407. if($activeFriday || !$active) {
  408. $this->actionAjaxProcessActiveDistribution(0, $dateFriday, $active) ;
  409. }
  410. if($activeSaturday || !$active) {
  411. $this->actionAjaxProcessActiveDistribution(0, $dateSaturday, $active) ;
  412. }
  413. if($activeSunday || !$active) {
  414. $this->actionAjaxProcessActiveDistribution(0, $dateSunday, $active) ;
  415. }
  416. return ['success'] ;
  417. }
  418. }