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 20KB

6 jaren geleden
6 jaren geleden
6 jaren geleden
6 jaren geleden
6 jaren geleden
6 jaren geleden
6 jaren geleden
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  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. $oneProductUnactivated = false ;
  147. foreach($order->productOrder as $productOrder) {
  148. foreach($productsArray as $product) {
  149. if($productOrder->id_product == $product['id'] && !$product['productDistribution'][0]['active']) {
  150. $oneProductUnactivated = true ;
  151. }
  152. }
  153. }
  154. $order = array_merge($order->getAttributes(), [
  155. 'amount' => $order->getAmount(Order::AMOUNT_TOTAL),
  156. 'amount_paid' => $order->getAmount(Order::AMOUNT_PAID),
  157. 'amount_remaining' => $order->getAmount(Order::AMOUNT_REMAINING),
  158. 'amount_surplus' => $order->getAmount(Order::AMOUNT_SURPLUS),
  159. 'user' => (isset($order->user)) ? array_merge($order->user->getAttributes(), $arrayCreditUser) : null,
  160. 'pointSale' => ['id' => $order->pointSale->id, 'name' => $order->pointSale->name],
  161. 'productOrder' => $productOrderArray,
  162. 'creditHistory' => $creditHistoryArray,
  163. 'oneProductUnactivated' => $oneProductUnactivated
  164. ]) ;
  165. }
  166. }
  167. $json['orders'] = $ordersArray ;
  168. // points de vente
  169. $pointsSaleArray = PointSale::find()
  170. ->joinWith(['pointSaleDistribution' => function($q) use ($distribution) {
  171. $q->where(['id_distribution' => $distribution->id]);
  172. }])
  173. ->where([
  174. 'id_producer' => Producer::getId(),
  175. ])
  176. ->asArray()
  177. ->all();
  178. $idPointSaleDefault = 0 ;
  179. foreach($pointsSaleArray as $pointSale) {
  180. if($pointSale['default']) {
  181. $idPointSaleDefault = $pointSale['id'] ;
  182. }
  183. }
  184. $json['points_sale'] = $pointsSaleArray ;
  185. // order create
  186. $productOrderArray = [] ;
  187. foreach($productsArray as $product) {
  188. $productOrderArray[$product['id']] = 0 ;
  189. }
  190. $json['order_create'] = [
  191. 'id_point_sale' => $idPointSaleDefault,
  192. 'id_user' => 0,
  193. 'username' => '',
  194. 'comment' => '',
  195. 'productOrder' => $productOrderArray
  196. ] ;
  197. // utilisateurs
  198. $usersArray = User::findBy()->all() ;
  199. $json['users'] = $usersArray ;
  200. // une production de la semaine activée ou non
  201. $oneDistributionWeekActive = false ;
  202. $week = sprintf('%02d',date('W',strtotime($date)));
  203. $start = strtotime(date('Y',strtotime($date)).'W'.$week);
  204. $dateMonday = date('Y-m-d',strtotime('Monday',$start)) ;
  205. $dateTuesday = date('Y-m-d',strtotime('Tuesday',$start)) ;
  206. $dateWednesday = date('Y-m-d',strtotime('Wednesday',$start)) ;
  207. $dateThursday = date('Y-m-d',strtotime('Thursday',$start)) ;
  208. $dateFriday = date('Y-m-d',strtotime('Friday',$start)) ;
  209. $dateSaturday = date('Y-m-d',strtotime('Saturday',$start)) ;
  210. $dateSunday = date('Y-m-d',strtotime('Sunday',$start)) ;
  211. $weekDistribution = Distribution::find()
  212. ->andWhere([
  213. 'id_producer' => Producer::getId(),
  214. 'active' => 1,
  215. ])
  216. ->andWhere(['or',
  217. ['date' => $dateMonday],
  218. ['date' => $dateTuesday],
  219. ['date' => $dateWednesday],
  220. ['date' => $dateThursday],
  221. ['date' => $dateFriday],
  222. ['date' => $dateSaturday],
  223. ['date' => $dateSunday],
  224. ])
  225. ->one();
  226. if($weekDistribution) {
  227. $oneDistributionWeekActive = true ;
  228. }
  229. $json['one_distribution_week_active'] = $oneDistributionWeekActive ;
  230. }
  231. return $json ;
  232. }
  233. /**
  234. * Génére un PDF récapitulatif des commandes d'un producteur pour une
  235. * date donnée.
  236. *
  237. * @param string $date
  238. * @param boolean $save
  239. * @param integer $idProducer
  240. * @return PDF|null
  241. */
  242. public function actionReport($date = '', $save = false, $idProducer = 0)
  243. {
  244. if (!Yii::$app->user->isGuest) {
  245. $idProducer = Producer::getId() ;
  246. }
  247. $ordersArray = Order::searchAll([
  248. 'distribution.date' => $date,
  249. ],
  250. [
  251. 'orderby' => 'comment_point_sale ASC, user.name ASC',
  252. 'conditions' => 'date_delete IS NULL'
  253. ]) ;
  254. $distribution = Distribution::searchOne([],[
  255. 'conditions' => 'date LIKE :date',
  256. 'params' => [':date' => $date]
  257. ]) ;
  258. if ($distribution) {
  259. $selectedProductsArray = ProductDistribution::searchByDistribution($distribution->id) ;
  260. $pointsSaleArray = PointSale::searchAll() ;
  261. foreach ($pointsSaleArray as $pointSale) {
  262. $pointSale->initOrders($ordersArray) ;
  263. }
  264. // produits
  265. $productsArray = Product::searchAll() ;
  266. // get your HTML raw content without any layouts or scripts
  267. $content = $this->renderPartial('report', [
  268. 'date' => $date,
  269. 'distribution' => $distribution,
  270. 'selectedProductsArray' => $selectedProductsArray,
  271. 'pointsSaleArray' => $pointsSaleArray,
  272. 'productsArray' => $productsArray,
  273. 'ordersArray' => $ordersArray
  274. ]);
  275. $dateStr = date('d/m/Y', strtotime($date));
  276. if ($save) {
  277. $destination = Pdf::DEST_FILE;
  278. } else {
  279. $destination = Pdf::DEST_BROWSER;
  280. }
  281. $pdf = new Pdf([
  282. // set to use core fonts only
  283. 'mode' => Pdf::MODE_UTF8,
  284. // A4 paper format
  285. 'format' => Pdf::FORMAT_A4,
  286. // portrait orientation
  287. 'orientation' => Pdf::ORIENT_PORTRAIT,
  288. // stream to browser inline
  289. 'destination' => $destination,
  290. 'filename' => Yii::getAlias('@app/web/pdf/Commandes-' . $date . '-' . $idProducer . '.pdf'),
  291. // your html content input
  292. 'content' => $content,
  293. // format content from your own css file if needed or use the
  294. // enhanced bootstrap css built by Krajee for mPDF formatting
  295. //'cssFile' => '@vendor/kartik-v/yii2-mpdf/assets/kv-mpdf-bootstrap.min.css',
  296. // any css to be embedded if required
  297. //'cssInline' => '.kv-heading-1{font-size:18px}',
  298. // set mPDF properties on the fly
  299. //'options' => ['title' => 'Krajee Report Title'],
  300. // call mPDF methods on the fly
  301. 'methods' => [
  302. 'SetHeader' => ['Commandes du ' . $dateStr],
  303. 'SetFooter' => ['{PAGENO}'],
  304. ]
  305. ]);
  306. // return the pdf output as per the destination setting
  307. return $pdf->render();
  308. }
  309. return null ;
  310. }
  311. public function actionAjaxProcessProductQuantityMax($idDistribution, $idProduct, $quantityMax)
  312. {
  313. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  314. $productDistribution = ProductDistribution::searchOne([
  315. 'id_distribution' => $idDistribution,
  316. 'id_product' => $idProduct,
  317. ]) ;
  318. $productDistribution->quantity_max = (!$quantityMax) ? null : (int) $quantityMax ;
  319. $productDistribution->save() ;
  320. return ['success'] ;
  321. }
  322. public function actionAjaxProcessActiveProduct($idDistribution, $idProduct, $active)
  323. {
  324. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  325. $productDistribution = ProductDistribution::searchOne([
  326. 'id_distribution' => $idDistribution,
  327. 'id_product' => $idProduct,
  328. ]) ;
  329. $productDistribution->active = $active ;
  330. $productDistribution->save() ;
  331. return ['success'] ;
  332. }
  333. public function actionAjaxProcessActivePointSale($idDistribution, $idPointSale, $delivery)
  334. {
  335. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  336. $pointSaleDistribution = PointSaleDistribution::searchOne([
  337. 'id_distribution' => $idDistribution,
  338. 'id_point_sale' => $idPointSale,
  339. ]) ;
  340. $pointSaleDistribution->delivery = $delivery ;
  341. $pointSaleDistribution->save() ;
  342. return ['success'] ;
  343. }
  344. /**
  345. * Active/désactive un jour de distribution.
  346. *
  347. * @param integer $idDistribution
  348. * @param string $date
  349. * @param boolean $active
  350. * @return array
  351. */
  352. public function actionAjaxProcessActiveDistribution($idDistribution = 0, $date = '', $active)
  353. {
  354. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  355. if($idDistribution) {
  356. $distribution = Distribution::searchOne([
  357. 'id' => $idDistribution
  358. ]) ;
  359. }
  360. $format = 'Y-m-d' ;
  361. $dateObject = DateTime::createFromFormat($format, $date);
  362. if($dateObject && $dateObject->format($format) === $date) {
  363. $distribution = Distribution::initDistribution($date) ;
  364. }
  365. if($distribution) {
  366. $distribution->active = (int) $active ;
  367. $distribution->save() ;
  368. if ($active) {
  369. // ajout des abonnements
  370. Subscription::addAll($distribution->date);
  371. }
  372. return ['success'] ;
  373. }
  374. return ['error'] ;
  375. }
  376. /**
  377. * Change l'état d'une semaine de production (activé, désactivé).
  378. *
  379. * @param string $date
  380. * @param integer $active
  381. */
  382. public function actionAjaxProcessActiveWeekDistribution($date, $active)
  383. {
  384. $week = sprintf('%02d',date('W',strtotime($date)));
  385. $start = strtotime(date('Y',strtotime($date)).'W'.$week);
  386. $dateMonday = date('Y-m-d',strtotime('Monday',$start)) ;
  387. $dateTuesday = date('Y-m-d',strtotime('Tuesday',$start)) ;
  388. $dateWednesday = date('Y-m-d',strtotime('Wednesday',$start)) ;
  389. $dateThursday = date('Y-m-d',strtotime('Thursday',$start)) ;
  390. $dateFriday = date('Y-m-d',strtotime('Friday',$start)) ;
  391. $dateSaturday = date('Y-m-d',strtotime('Saturday',$start)) ;
  392. $dateSunday = date('Y-m-d',strtotime('Sunday',$start)) ;
  393. $pointsSaleArray = PointSale::searchAll() ;
  394. $activeMonday = false ;
  395. $activeTuesday = false ;
  396. $activeWednesday = false ;
  397. $activeThursday = false ;
  398. $activeFriday = false ;
  399. $activeSaturday = false ;
  400. $activeSunday = false ;
  401. foreach($pointsSaleArray as $pointSale) {
  402. if($pointSale->delivery_monday) $activeMonday = true ;
  403. if($pointSale->delivery_tuesday) $activeTuesday = true ;
  404. if($pointSale->delivery_wednesday) $activeWednesday = true ;
  405. if($pointSale->delivery_thursday) $activeThursday = true ;
  406. if($pointSale->delivery_friday) $activeFriday = true ;
  407. if($pointSale->delivery_saturday) $activeSaturday = true ;
  408. if($pointSale->delivery_sunday) $activeSunday = true ;
  409. }
  410. if($activeMonday || !$active) {
  411. $this->actionAjaxProcessActiveDistribution(0, $dateMonday, $active) ;
  412. }
  413. if($activeTuesday || !$active) {
  414. $this->actionAjaxProcessActiveDistribution(0, $dateTuesday, $active) ;
  415. }
  416. if($activeWednesday || !$active) {
  417. $this->actionAjaxProcessActiveDistribution(0, $dateWednesday, $active) ;
  418. }
  419. if($activeThursday || !$active) {
  420. $this->actionAjaxProcessActiveDistribution(0, $dateThursday, $active) ;
  421. }
  422. if($activeFriday || !$active) {
  423. $this->actionAjaxProcessActiveDistribution(0, $dateFriday, $active) ;
  424. }
  425. if($activeSaturday || !$active) {
  426. $this->actionAjaxProcessActiveDistribution(0, $dateSaturday, $active) ;
  427. }
  428. if($activeSunday || !$active) {
  429. $this->actionAjaxProcessActiveDistribution(0, $dateSunday, $active) ;
  430. }
  431. return ['success'] ;
  432. }
  433. }