You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

DistributionController.php 19KB

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