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.

494 satır
19KB

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