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.

DistributionController.php 22KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  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 behaviors()
  44. {
  45. return [
  46. 'access' => [
  47. 'class' => AccessControl::className(),
  48. 'rules' => [
  49. [
  50. 'actions' => ['report-cron'],
  51. 'allow' => true,
  52. 'roles' => ['?']
  53. ],
  54. [
  55. 'allow' => true,
  56. 'roles' => ['@'],
  57. 'matchCallback' => function ($rule, $action) {
  58. return User::getCurrentStatus() == USER::STATUS_ADMIN
  59. || User::getCurrentStatus() == USER::STATUS_PRODUCER;
  60. }
  61. ]
  62. ],
  63. ],
  64. ];
  65. }
  66. public function actionIndex($date = '')
  67. {
  68. $this->checkProductsPointsSale() ;
  69. $format = 'Y-m-d' ;
  70. $theDate = '' ;
  71. $dateObject = DateTime::createFromFormat($format, $date);
  72. if($dateObject && $dateObject->format($format) === $date) {
  73. $theDate = $date ;
  74. }
  75. return $this->render('index', [
  76. 'date' => $theDate
  77. ]) ;
  78. }
  79. public function actionAjaxInfos($date = '')
  80. {
  81. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  82. $json = [
  83. 'distribution' => [],
  84. 'products' => []
  85. ] ;
  86. $format = 'Y-m-d' ;
  87. $dateObject = DateTime::createFromFormat($format, $date);
  88. $producer = Producer::getCurrent() ;
  89. $json['producer'] = [
  90. 'credit' => $producer->credit
  91. ];
  92. $distributionsArray = Distribution::searchAll([
  93. 'active' => 1
  94. ], [
  95. 'conditions' => ['date > :date_begin','date < :date_end'],
  96. 'params' => [':date_begin' => date('Y-m-d', strtotime('-1 month')), ':date_end' => date('Y-m-d', strtotime('+3 month')), ],
  97. ]) ;
  98. $json['distributions'] = $distributionsArray ;
  99. if($dateObject && $dateObject->format($format) === $date) {
  100. // distribution
  101. $distribution = Distribution::initDistribution($date) ;
  102. $json['distribution'] = [
  103. 'id' => $distribution->id,
  104. 'active' => $distribution->active,
  105. 'url_report' => Yii::$app->urlManagerBackend->createUrl(['distribution/report','date' => $distribution->date])
  106. ] ;
  107. // commandes
  108. $ordersArray = Order::searchAll([
  109. 'distribution.date' => $date,
  110. ],[
  111. 'orderby' => 'user.lastname ASC, user.name ASC'
  112. ]);
  113. // montant et poids des commandes
  114. $revenues = 0;
  115. $weight = 0 ;
  116. if($ordersArray) {
  117. foreach ($ordersArray as $order) {
  118. if(is_null($order->date_delete)) {
  119. $revenues += $order->amount;
  120. $weight += $order->weight;
  121. }
  122. }
  123. }
  124. $json['distribution']['revenues'] = Price::format($revenues);
  125. $json['distribution']['weight'] = number_format($weight, 2);
  126. // products
  127. $productsArray = Product::find()
  128. ->orWhere(['id_producer' => Producer::getId(),])
  129. ->joinWith(['productDistribution' => function($query) use($distribution) {
  130. $query->andOnCondition('product_distribution.id_distribution = '.$distribution->id) ;
  131. }])
  132. ->orderBy('product_distribution.active DESC, order ASC')
  133. ->asArray()
  134. ->all();
  135. $potentialRevenues = 0;
  136. $potentialWeight = 0;
  137. foreach($productsArray as &$theProduct) {
  138. $quantityOrder = Order::getProductQuantity($theProduct['id'], $ordersArray) ;
  139. $theProduct['quantity_ordered'] = $quantityOrder ;
  140. $theProduct['quantity_remaining'] = $theProduct['quantity_max'] - $quantityOrder ;
  141. if($theProduct['quantity_remaining'] < 0) $theProduct['quantity_remaining'] = 0 ;
  142. $theProduct['quantity_form'] = 0 ;
  143. if($theProduct['productDistribution'][0]['active'] && $theProduct['productDistribution'][0]['quantity_max']) {
  144. $potentialRevenues += $theProduct['productDistribution'][0]['quantity_max'] * $theProduct['price'];
  145. $potentialWeight += $theProduct['productDistribution'][0]['quantity_max'] * $theProduct['weight'] / 1000;
  146. }
  147. }
  148. $json['distribution']['potential_revenues'] = Price::format($potentialRevenues) ;
  149. $json['distribution']['potential_weight'] = number_format($potentialWeight, 2) ;
  150. $json['products'] = $productsArray ;
  151. // orders as array
  152. if($ordersArray) {
  153. foreach($ordersArray as &$order) {
  154. $productOrderArray = \yii\helpers\ArrayHelper::map($order->productOrder, 'id_product', 'quantity') ;
  155. foreach($productsArray as $product) {
  156. if(!isset($productOrderArray[$product['id']])) {
  157. $productOrderArray[$product['id']] = 0 ;
  158. }
  159. }
  160. $creditHistoryArray = [] ;
  161. foreach($order->creditHistory as $creditHistory) {
  162. $creditHistoryArray[] = [
  163. 'date' => date('d/m/Y H:i:s', strtotime($creditHistory->date)),
  164. 'user_action' => $creditHistory->strUserAction(),
  165. 'wording' => $creditHistory->getStrWording(),
  166. 'debit' => ($creditHistory->isTypeDebit() ? '-&nbsp;'.$creditHistory->getAmount(Order::AMOUNT_TOTAL,true) : ''),
  167. 'credit' => ($creditHistory->isTypeCredit() ? '+&nbsp;'.$creditHistory->getAmount(Order::AMOUNT_TOTAL,true) : '')
  168. ] ;
  169. }
  170. $arrayCreditUser = [] ;
  171. if(isset($order->user) && isset($order->user->userProducer)) {
  172. $arrayCreditUser['credit'] = $order->user->userProducer[0]->credit ;
  173. }
  174. $oneProductUnactivated = false ;
  175. foreach($order->productOrder as $productOrder) {
  176. foreach($productsArray as $product) {
  177. if($productOrder->id_product == $product['id'] && !$product['productDistribution'][0]['active']) {
  178. $oneProductUnactivated = true ;
  179. }
  180. }
  181. }
  182. $order = array_merge($order->getAttributes(), [
  183. 'amount' => $order->getAmount(Order::AMOUNT_TOTAL),
  184. 'amount_paid' => $order->getAmount(Order::AMOUNT_PAID),
  185. 'amount_remaining' => $order->getAmount(Order::AMOUNT_REMAINING),
  186. 'amount_surplus' => $order->getAmount(Order::AMOUNT_SURPLUS),
  187. 'user' => (isset($order->user)) ? array_merge($order->user->getAttributes(), $arrayCreditUser) : null,
  188. 'pointSale' => ['id' => $order->pointSale->id, 'name' => $order->pointSale->name],
  189. 'productOrder' => $productOrderArray,
  190. 'creditHistory' => $creditHistoryArray,
  191. 'oneProductUnactivated' => $oneProductUnactivated
  192. ]) ;
  193. }
  194. }
  195. $json['orders'] = $ordersArray ;
  196. // points de vente
  197. $pointsSaleArray = PointSale::find()
  198. ->joinWith(['pointSaleDistribution' => function($q) use ($distribution) {
  199. $q->where(['id_distribution' => $distribution->id]);
  200. }])
  201. ->where([
  202. 'id_producer' => Producer::getId(),
  203. ])
  204. ->asArray()
  205. ->all();
  206. $idPointSaleDefault = 0 ;
  207. foreach($pointsSaleArray as $pointSale) {
  208. if($pointSale['default']) {
  209. $idPointSaleDefault = $pointSale['id'] ;
  210. }
  211. }
  212. $json['points_sale'] = $pointsSaleArray ;
  213. // order create
  214. $productOrderArray = [] ;
  215. foreach($productsArray as $product) {
  216. $productOrderArray[$product['id']] = 0 ;
  217. }
  218. $json['order_create'] = [
  219. 'id_point_sale' => $idPointSaleDefault,
  220. 'id_user' => 0,
  221. 'username' => '',
  222. 'comment' => '',
  223. 'productOrder' => $productOrderArray
  224. ] ;
  225. // utilisateurs
  226. $usersArray = User::findBy()->all() ;
  227. $json['users'] = $usersArray ;
  228. // une production de la semaine activée ou non
  229. $oneDistributionWeekActive = false ;
  230. $week = sprintf('%02d',date('W',strtotime($date)));
  231. $start = strtotime(date('Y',strtotime($date)).'W'.$week);
  232. $dateMonday = date('Y-m-d',strtotime('Monday',$start)) ;
  233. $dateTuesday = date('Y-m-d',strtotime('Tuesday',$start)) ;
  234. $dateWednesday = date('Y-m-d',strtotime('Wednesday',$start)) ;
  235. $dateThursday = date('Y-m-d',strtotime('Thursday',$start)) ;
  236. $dateFriday = date('Y-m-d',strtotime('Friday',$start)) ;
  237. $dateSaturday = date('Y-m-d',strtotime('Saturday',$start)) ;
  238. $dateSunday = date('Y-m-d',strtotime('Sunday',$start)) ;
  239. $weekDistribution = Distribution::find()
  240. ->andWhere([
  241. 'id_producer' => Producer::getId(),
  242. 'active' => 1,
  243. ])
  244. ->andWhere(['or',
  245. ['date' => $dateMonday],
  246. ['date' => $dateTuesday],
  247. ['date' => $dateWednesday],
  248. ['date' => $dateThursday],
  249. ['date' => $dateFriday],
  250. ['date' => $dateSaturday],
  251. ['date' => $dateSunday],
  252. ])
  253. ->one();
  254. if($weekDistribution) {
  255. $oneDistributionWeekActive = true ;
  256. }
  257. $json['one_distribution_week_active'] = $oneDistributionWeekActive ;
  258. }
  259. return $json ;
  260. }
  261. /**
  262. * Génére un PDF récapitulatif des des commandes d'un producteur pour une
  263. * date donnée (Méthode appelable via CRON)
  264. *
  265. * @param string $date
  266. * @param boolean $save
  267. * @param integer $idProducer
  268. * @param string $key
  269. * @return PDF|null
  270. */
  271. public function actionReportCron($date = '', $save = false, $idProducer = 0, $key = '')
  272. {
  273. if($key == '64ac0bdab7e9f5e48c4d991ec5201d57') {
  274. $this->actionReport($date, $save, $idProducer) ;
  275. }
  276. }
  277. /**
  278. * Génére un PDF récapitulatif des commandes d'un producteur pour une
  279. * date donnée.
  280. *
  281. * @param string $date
  282. * @param boolean $save
  283. * @param integer $idProducer
  284. * @return PDF|null
  285. */
  286. public function actionReport($date = '', $save = false, $idProducer = 0)
  287. {
  288. if (!Yii::$app->user->isGuest) {
  289. $idProducer = Producer::getId() ;
  290. }
  291. $ordersArray = Order::searchAll([
  292. 'distribution.date' => $date,
  293. ],
  294. [
  295. 'orderby' => 'comment_point_sale ASC, user.name ASC',
  296. 'conditions' => 'date_delete IS NULL'
  297. ]) ;
  298. $distribution = Distribution::searchOne([],[
  299. 'conditions' => 'date LIKE :date',
  300. 'params' => [':date' => $date]
  301. ]) ;
  302. if ($distribution) {
  303. $selectedProductsArray = ProductDistribution::searchByDistribution($distribution->id) ;
  304. $pointsSaleArray = PointSale::searchAll() ;
  305. foreach ($pointsSaleArray as $pointSale) {
  306. $pointSale->initOrders($ordersArray) ;
  307. }
  308. // produits
  309. $productsArray = Product::searchAll() ;
  310. // get your HTML raw content without any layouts or scripts
  311. $content = $this->renderPartial('report', [
  312. 'date' => $date,
  313. 'distribution' => $distribution,
  314. 'selectedProductsArray' => $selectedProductsArray,
  315. 'pointsSaleArray' => $pointsSaleArray,
  316. 'productsArray' => $productsArray,
  317. 'ordersArray' => $ordersArray
  318. ]);
  319. $dateStr = date('d/m/Y', strtotime($date));
  320. if ($save) {
  321. $destination = Pdf::DEST_FILE;
  322. } else {
  323. $destination = Pdf::DEST_BROWSER;
  324. }
  325. $pdf = new Pdf([
  326. // set to use core fonts only
  327. 'mode' => Pdf::MODE_UTF8,
  328. // A4 paper format
  329. 'format' => Pdf::FORMAT_A4,
  330. // portrait orientation
  331. 'orientation' => Pdf::ORIENT_PORTRAIT,
  332. // stream to browser inline
  333. 'destination' => $destination,
  334. 'filename' => Yii::getAlias('@app/web/pdf/Commandes-' . $date . '-' . $idProducer . '.pdf'),
  335. // your html content input
  336. 'content' => $content,
  337. // format content from your own css file if needed or use the
  338. // enhanced bootstrap css built by Krajee for mPDF formatting
  339. //'cssFile' => '@vendor/kartik-v/yii2-mpdf/assets/kv-mpdf-bootstrap.min.css',
  340. // any css to be embedded if required
  341. //'cssInline' => '.kv-heading-1{font-size:18px}',
  342. // set mPDF properties on the fly
  343. //'options' => ['title' => 'Krajee Report Title'],
  344. // call mPDF methods on the fly
  345. 'methods' => [
  346. 'SetHeader' => ['Commandes du ' . $dateStr],
  347. 'SetFooter' => ['{PAGENO}'],
  348. ]
  349. ]);
  350. // return the pdf output as per the destination setting
  351. return $pdf->render();
  352. }
  353. return null ;
  354. }
  355. public function actionAjaxProcessProductQuantityMax($idDistribution, $idProduct, $quantityMax)
  356. {
  357. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  358. $productDistribution = ProductDistribution::searchOne([
  359. 'id_distribution' => $idDistribution,
  360. 'id_product' => $idProduct,
  361. ]) ;
  362. $productDistribution->quantity_max = (!$quantityMax) ? null : (int) $quantityMax ;
  363. $productDistribution->save() ;
  364. return ['success'] ;
  365. }
  366. public function actionAjaxProcessActiveProduct($idDistribution, $idProduct, $active)
  367. {
  368. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  369. $productDistribution = ProductDistribution::searchOne([
  370. 'id_distribution' => $idDistribution,
  371. 'id_product' => $idProduct,
  372. ]) ;
  373. $productDistribution->active = $active ;
  374. $productDistribution->save() ;
  375. return ['success'] ;
  376. }
  377. public function actionAjaxProcessActivePointSale($idDistribution, $idPointSale, $delivery)
  378. {
  379. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  380. $pointSaleDistribution = PointSaleDistribution::searchOne([
  381. 'id_distribution' => $idDistribution,
  382. 'id_point_sale' => $idPointSale,
  383. ]) ;
  384. $pointSaleDistribution->delivery = $delivery ;
  385. $pointSaleDistribution->save() ;
  386. return ['success'] ;
  387. }
  388. /**
  389. * Active/désactive un jour de distribution.
  390. *
  391. * @param integer $idDistribution
  392. * @param string $date
  393. * @param boolean $active
  394. * @return array
  395. */
  396. public function actionAjaxProcessActiveDistribution($idDistribution = 0, $date = '', $active)
  397. {
  398. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  399. if($idDistribution) {
  400. $distribution = Distribution::searchOne([
  401. 'id' => $idDistribution
  402. ]) ;
  403. }
  404. $format = 'Y-m-d' ;
  405. $dateObject = DateTime::createFromFormat($format, $date);
  406. if($dateObject && $dateObject->format($format) === $date) {
  407. $distribution = Distribution::initDistribution($date) ;
  408. }
  409. if($distribution) {
  410. $distribution->active = (int) $active ;
  411. $distribution->save() ;
  412. if ($active) {
  413. // ajout des abonnements
  414. Subscription::addAll($distribution->date);
  415. }
  416. return ['success'] ;
  417. }
  418. return ['error'] ;
  419. }
  420. /**
  421. * Change l'état d'une semaine de production (activé, désactivé).
  422. *
  423. * @param string $date
  424. * @param integer $active
  425. */
  426. public function actionAjaxProcessActiveWeekDistribution($date, $active)
  427. {
  428. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  429. $week = sprintf('%02d',date('W',strtotime($date)));
  430. $start = strtotime(date('Y',strtotime($date)).'W'.$week);
  431. $dateMonday = date('Y-m-d',strtotime('Monday',$start)) ;
  432. $dateTuesday = date('Y-m-d',strtotime('Tuesday',$start)) ;
  433. $dateWednesday = date('Y-m-d',strtotime('Wednesday',$start)) ;
  434. $dateThursday = date('Y-m-d',strtotime('Thursday',$start)) ;
  435. $dateFriday = date('Y-m-d',strtotime('Friday',$start)) ;
  436. $dateSaturday = date('Y-m-d',strtotime('Saturday',$start)) ;
  437. $dateSunday = date('Y-m-d',strtotime('Sunday',$start)) ;
  438. $pointsSaleArray = PointSale::searchAll() ;
  439. $activeMonday = false ;
  440. $activeTuesday = false ;
  441. $activeWednesday = false ;
  442. $activeThursday = false ;
  443. $activeFriday = false ;
  444. $activeSaturday = false ;
  445. $activeSunday = false ;
  446. foreach($pointsSaleArray as $pointSale) {
  447. if($pointSale->delivery_monday) $activeMonday = true ;
  448. if($pointSale->delivery_tuesday) $activeTuesday = true ;
  449. if($pointSale->delivery_wednesday) $activeWednesday = true ;
  450. if($pointSale->delivery_thursday) $activeThursday = true ;
  451. if($pointSale->delivery_friday) $activeFriday = true ;
  452. if($pointSale->delivery_saturday) $activeSaturday = true ;
  453. if($pointSale->delivery_sunday) $activeSunday = true ;
  454. }
  455. if($activeMonday || !$active) {
  456. $this->actionAjaxProcessActiveDistribution(0, $dateMonday, $active) ;
  457. }
  458. if($activeTuesday || !$active) {
  459. $this->actionAjaxProcessActiveDistribution(0, $dateTuesday, $active) ;
  460. }
  461. if($activeWednesday || !$active) {
  462. $this->actionAjaxProcessActiveDistribution(0, $dateWednesday, $active) ;
  463. }
  464. if($activeThursday || !$active) {
  465. $this->actionAjaxProcessActiveDistribution(0, $dateThursday, $active) ;
  466. }
  467. if($activeFriday || !$active) {
  468. $this->actionAjaxProcessActiveDistribution(0, $dateFriday, $active) ;
  469. }
  470. if($activeSaturday || !$active) {
  471. $this->actionAjaxProcessActiveDistribution(0, $dateSaturday, $active) ;
  472. }
  473. if($activeSunday || !$active) {
  474. $this->actionAjaxProcessActiveDistribution(0, $dateSunday, $active) ;
  475. }
  476. return ['success'] ;
  477. }
  478. /**
  479. * Ajoute les commandes récurrentes pour une date donnée.
  480. *
  481. * @param string $date
  482. */
  483. public function actionAjaxProcessAddSubscriptions($date)
  484. {
  485. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  486. Subscription::addAll($date, true);
  487. return ['success'] ;
  488. }
  489. }