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