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.

577 satır
22KB

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