選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

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