Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

DistributionController.php 28KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698
  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.id' => $distribution->id,
  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. if(!isset($theProduct['productDistribution'][0])) {
  142. $theProductObject = (object) $theProduct ;
  143. $theProduct['productDistribution'][0] = $distribution->linkProduct($theProductObject) ;
  144. }
  145. if(!is_numeric($theProduct['productDistribution'][0]['quantity_max'])) {
  146. $theProduct['quantity_remaining'] = null ;
  147. }
  148. else {
  149. $theProduct['quantity_remaining'] = $theProduct['productDistribution'][0]['quantity_max'] - $quantityOrder ;
  150. }
  151. $theProduct['quantity_form'] = 0 ;
  152. if($theProduct['productDistribution'][0]['active'] && $theProduct['productDistribution'][0]['quantity_max']) {
  153. $potentialRevenues += $theProduct['productDistribution'][0]['quantity_max'] * $theProduct['price'];
  154. $potentialWeight += $theProduct['productDistribution'][0]['quantity_max'] * $theProduct['weight'] / 1000;
  155. }
  156. }
  157. $json['distribution']['potential_revenues'] = Price::format($potentialRevenues) ;
  158. $json['distribution']['potential_weight'] = number_format($potentialWeight, 2) ;
  159. $json['products'] = $productsArray ;
  160. // orders as array
  161. if($ordersArray) {
  162. foreach($ordersArray as &$order) {
  163. $productOrderArray = [] ;
  164. foreach($order->productOrder as $productOrder) {
  165. $productOrderArray[$productOrder->id_product] = [
  166. 'quantity' => $productOrder->quantity * Product::$unitsArray[$productOrder->unit]['coefficient'],
  167. 'unit' => $productOrder->unit,
  168. ] ;
  169. }
  170. foreach($productsArray as $product) {
  171. if(!isset($productOrderArray[$product['id']])) {
  172. $productOrderArray[$product['id']] = [
  173. 'quantity' => 0,
  174. 'unit' => $product['unit']
  175. ] ;
  176. }
  177. }
  178. $creditHistoryArray = [] ;
  179. foreach($order->creditHistory as $creditHistory) {
  180. $creditHistoryArray[] = [
  181. 'date' => date('d/m/Y H:i:s', strtotime($creditHistory->date)),
  182. 'user_action' => $creditHistory->strUserAction(),
  183. 'wording' => $creditHistory->getStrWording(),
  184. 'debit' => ($creditHistory->isTypeDebit() ? '-&nbsp;'.$creditHistory->getAmount(Order::AMOUNT_TOTAL,true) : ''),
  185. 'credit' => ($creditHistory->isTypeCredit() ? '+&nbsp;'.$creditHistory->getAmount(Order::AMOUNT_TOTAL,true) : '')
  186. ] ;
  187. }
  188. $arrayCreditUser = [] ;
  189. if(isset($order->user) && isset($order->user->userProducer)) {
  190. $arrayCreditUser['credit'] = $order->user->userProducer[0]->credit ;
  191. }
  192. $oneProductUnactivated = false ;
  193. foreach($order->productOrder as $productOrder) {
  194. foreach($productsArray as $product) {
  195. if($productOrder->id_product == $product['id'] && !$product['productDistribution'][0]['active']) {
  196. $oneProductUnactivated = true ;
  197. }
  198. }
  199. }
  200. $order = array_merge($order->getAttributes(), [
  201. 'amount' => $order->getAmount(Order::AMOUNT_TOTAL),
  202. 'amount_paid' => $order->getAmount(Order::AMOUNT_PAID),
  203. 'amount_remaining' => $order->getAmount(Order::AMOUNT_REMAINING),
  204. 'amount_surplus' => $order->getAmount(Order::AMOUNT_SURPLUS),
  205. 'user' => (isset($order->user)) ? array_merge($order->user->getAttributes(), $arrayCreditUser) : null,
  206. 'pointSale' => ['id' => $order->pointSale->id, 'name' => $order->pointSale->name],
  207. 'productOrder' => $productOrderArray,
  208. 'creditHistory' => $creditHistoryArray,
  209. 'oneProductUnactivated' => $oneProductUnactivated
  210. ]) ;
  211. }
  212. }
  213. $json['orders'] = $ordersArray ;
  214. // points de vente
  215. $pointsSaleArray = PointSale::find()
  216. ->joinWith(['pointSaleDistribution' => function($q) use ($distribution) {
  217. $q->where(['id_distribution' => $distribution->id]);
  218. }])
  219. ->where([
  220. 'id_producer' => Producer::getId(),
  221. ])
  222. ->asArray()
  223. ->all();
  224. $idPointSaleDefault = 0 ;
  225. foreach($pointsSaleArray as $pointSale) {
  226. if($pointSale['default']) {
  227. $idPointSaleDefault = $pointSale['id'] ;
  228. }
  229. }
  230. $json['points_sale'] = $pointsSaleArray ;
  231. // order create
  232. $productOrderArray = [] ;
  233. foreach($productsArray as $product) {
  234. $productOrderArray[$product['id']] = [
  235. 'quantity' => 0,
  236. 'unit' => $product['unit']
  237. ] ;
  238. }
  239. $json['order_create'] = [
  240. 'id_point_sale' => $idPointSaleDefault,
  241. 'id_user' => 0,
  242. 'username' => '',
  243. 'comment' => '',
  244. 'productOrder' => $productOrderArray
  245. ] ;
  246. // utilisateurs
  247. $usersArray = User::findBy()->all() ;
  248. foreach($usersArray as &$user) {
  249. $userObject = User::findOne(['id' => $user['user_id']]) ;
  250. $favoritePointSale = $userObject->getFavoritePointSale() ;
  251. if($favoritePointSale) {
  252. $user['id_point_sale_favorite'] = $favoritePointSale->id ;
  253. }
  254. }
  255. $json['users'] = $usersArray ;
  256. // une production de la semaine activée ou non
  257. $oneDistributionWeekActive = false ;
  258. $week = sprintf('%02d',date('W',strtotime($date)));
  259. $start = strtotime(date('Y',strtotime($date)).'W'.$week);
  260. $dateMonday = date('Y-m-d',strtotime('Monday',$start)) ;
  261. $dateTuesday = date('Y-m-d',strtotime('Tuesday',$start)) ;
  262. $dateWednesday = date('Y-m-d',strtotime('Wednesday',$start)) ;
  263. $dateThursday = date('Y-m-d',strtotime('Thursday',$start)) ;
  264. $dateFriday = date('Y-m-d',strtotime('Friday',$start)) ;
  265. $dateSaturday = date('Y-m-d',strtotime('Saturday',$start)) ;
  266. $dateSunday = date('Y-m-d',strtotime('Sunday',$start)) ;
  267. $weekDistribution = Distribution::find()
  268. ->andWhere([
  269. 'id_producer' => Producer::getId(),
  270. 'active' => 1,
  271. ])
  272. ->andWhere(['or',
  273. ['date' => $dateMonday],
  274. ['date' => $dateTuesday],
  275. ['date' => $dateWednesday],
  276. ['date' => $dateThursday],
  277. ['date' => $dateFriday],
  278. ['date' => $dateSaturday],
  279. ['date' => $dateSunday],
  280. ])
  281. ->one();
  282. if($weekDistribution) {
  283. $oneDistributionWeekActive = true ;
  284. }
  285. $json['one_distribution_week_active'] = $oneDistributionWeekActive ;
  286. }
  287. return $json ;
  288. }
  289. /**
  290. * Génére un PDF récapitulatif des des commandes d'un producteur pour une
  291. * date donnée (Méthode appelable via CRON)
  292. *
  293. * @param string $date
  294. * @param boolean $save
  295. * @param integer $idProducer
  296. * @param string $key
  297. * @return PDF|null
  298. */
  299. public function actionReportCron($date = '', $save = false, $idProducer = 0, $key = '')
  300. {
  301. if($key == '64ac0bdab7e9f5e48c4d991ec5201d57') {
  302. $this->actionReport($date, $save, $idProducer) ;
  303. }
  304. }
  305. /**
  306. * Génére un PDF récapitulatif des commandes d'un producteur pour une
  307. * date donnée.
  308. *
  309. * @param string $date
  310. * @param boolean $save
  311. * @param integer $idProducer
  312. * @return PDF|null
  313. */
  314. public function actionReport($date = '', $save = false, $idProducer = 0, $type = "pdf")
  315. {
  316. if (!Yii::$app->user->isGuest) {
  317. $idProducer = Producer::getId() ;
  318. }
  319. $ordersArray = Order::searchAll([
  320. 'distribution.date' => $date,
  321. ],
  322. [
  323. 'orderby' => 'comment_point_sale ASC, user.name ASC',
  324. 'conditions' => 'date_delete IS NULL'
  325. ]) ;
  326. $distribution = Distribution::searchOne([],[
  327. 'conditions' => 'date LIKE :date',
  328. 'params' => [':date' => $date]
  329. ]) ;
  330. if ($distribution) {
  331. $selectedProductsArray = ProductDistribution::searchByDistribution($distribution->id) ;
  332. $pointsSaleArray = PointSale::searchAll() ;
  333. foreach ($pointsSaleArray as $pointSale) {
  334. $pointSale->initOrders($ordersArray) ;
  335. }
  336. // produits
  337. $productsArray = Product::find()
  338. ->joinWith(['productDistribution' => function($q) use ($distribution) {
  339. $q->where(['id_distribution' => $distribution->id]);
  340. }])
  341. ->where([
  342. 'id_producer' => Producer::getId(),
  343. ])
  344. ->orderBy('order ASC')
  345. ->all();
  346. if($type == 'pdf') {
  347. // get your HTML raw content without any layouts or scripts
  348. $content = $this->renderPartial('report', [
  349. 'date' => $date,
  350. 'distribution' => $distribution,
  351. 'selectedProductsArray' => $selectedProductsArray,
  352. 'pointsSaleArray' => $pointsSaleArray,
  353. 'productsArray' => $productsArray,
  354. 'ordersArray' => $ordersArray
  355. ]);
  356. $dateStr = date('d/m/Y', strtotime($date));
  357. if ($save) {
  358. $destination = Pdf::DEST_FILE;
  359. } else {
  360. $destination = Pdf::DEST_BROWSER;
  361. }
  362. $pdf = new Pdf([
  363. // set to use core fonts only
  364. 'mode' => Pdf::MODE_UTF8,
  365. // A4 paper format
  366. 'format' => Pdf::FORMAT_A4,
  367. // portrait orientation
  368. 'orientation' => Pdf::ORIENT_PORTRAIT,
  369. // stream to browser inline
  370. 'destination' => $destination,
  371. 'filename' => Yii::getAlias('@app/web/pdf/Commandes-' . $date . '-' . $idProducer . '.pdf'),
  372. // your html content input
  373. 'content' => $content,
  374. // format content from your own css file if needed or use the
  375. // enhanced bootstrap css built by Krajee for mPDF formatting
  376. //'cssFile' => '@vendor/kartik-v/yii2-mpdf/assets/kv-mpdf-bootstrap.min.css',
  377. // any css to be embedded if required
  378. //'cssInline' => '.kv-heading-1{font-size:18px}',
  379. // set mPDF properties on the fly
  380. //'options' => ['title' => 'Krajee Report Title'],
  381. // call mPDF methods on the fly
  382. 'methods' => [
  383. 'SetHeader' => ['Commandes du ' . $dateStr],
  384. 'SetFooter' => ['{PAGENO}'],
  385. ]
  386. ]);
  387. // return the pdf output as per the destination setting
  388. return $pdf->render();
  389. }
  390. elseif($type == 'csv') {
  391. $datas = [];
  392. // produits en colonne
  393. $productsNameArray = [''] ;
  394. $productsIndexArray = [] ;
  395. $cpt = 1 ;
  396. foreach ($productsArray as $product) {
  397. $quantity = Order::getProductQuantity($product->id, $ordersArray);
  398. if($quantity) {
  399. $productsNameArray[] = $product->name ;
  400. $productsIndexArray[$product->id] = $cpt ++ ;
  401. }
  402. }
  403. $datas[] = $productsNameArray ;
  404. // points de vente
  405. foreach ($pointsSaleArray as $pointSale) {
  406. if (count($pointSale->orders)) {
  407. // listing commandes
  408. $datas[] = ['> '.$pointSale->name] ;
  409. foreach($pointSale->orders as $order) {
  410. $orderLine = [$order->getStrUser()] ;
  411. foreach($order->productOrder as $productOrder) {
  412. $orderLine[$productsIndexArray[$productOrder->id_product]] = $productOrder->quantity . ' '.Product::strUnit($productOrder->unit, 'wording_short', true);
  413. }
  414. $datas[] = $this->_lineOrderReportCSV($orderLine, $cpt) ;
  415. }
  416. // total point de vente
  417. $totalsPointSaleArray = ['Total'] ;
  418. foreach ($productsArray as $product) {
  419. foreach(Product::$unitsArray as $unit => $dataUnit) {
  420. $quantity = Order::getProductQuantity($product->id, $pointSale->orders, false, $unit);
  421. if ($quantity) {
  422. $index = $productsIndexArray[$product->id] ;
  423. if(!isset($totalsPointSaleArray[$index])) {
  424. $totalsPointSaleArray[$index] = '' ;
  425. }
  426. $totalsPointSaleArray[$index] .= $quantity . ' '.Product::strUnit($unit, 'wording_short', true).' ';
  427. }
  428. }
  429. }
  430. $datas[] = $this->_lineOrderReportCSV($totalsPointSaleArray, $cpt) ;
  431. $datas[] = [] ;
  432. }
  433. }
  434. // global
  435. $totalsGlobalArray = ['> Totaux'] ;
  436. foreach ($productsArray as $product) {
  437. foreach(Product::$unitsArray as $unit => $dataUnit) {
  438. $quantity = Order::getProductQuantity($product->id, $ordersArray, false, $unit);
  439. if ($quantity) {
  440. $index = $productsIndexArray[$product->id] ;
  441. if(!isset($totalsGlobalArray[$index])) {
  442. $totalsGlobalArray[$index] = '' ;
  443. }
  444. $totalsGlobalArray[$index] .= $quantity . ' '.Product::strUnit($unit, 'wording_short', true).' ';
  445. }
  446. }
  447. }
  448. $datas[] = $this->_lineOrderReportCSV($totalsGlobalArray, $cpt) ;
  449. CSV::downloadSendHeaders('Commandes_'.$date.'.csv');
  450. echo CSV::array2csv($datas);
  451. die();
  452. }
  453. }
  454. return null ;
  455. }
  456. public function _lineOrderReportCSV($orderLine, $cptMax)
  457. {
  458. $line = [] ;
  459. for($i = 0; $i <= $cptMax ; $i++) {
  460. if(isset($orderLine[$i]) && $orderLine[$i]) {
  461. $line[] = $orderLine[$i] ;
  462. }
  463. else {
  464. $line[] = '' ;
  465. }
  466. }
  467. return $line ;
  468. }
  469. public function actionAjaxProcessProductQuantityMax($idDistribution, $idProduct, $quantityMax)
  470. {
  471. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  472. $productDistribution = ProductDistribution::searchOne([
  473. 'id_distribution' => $idDistribution,
  474. 'id_product' => $idProduct,
  475. ]) ;
  476. $productDistribution->quantity_max = (!$quantityMax) ? null : (int) $quantityMax ;
  477. $productDistribution->save() ;
  478. return ['success'] ;
  479. }
  480. public function actionAjaxProcessActiveProduct($idDistribution, $idProduct, $active)
  481. {
  482. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  483. $productDistribution = ProductDistribution::searchOne([
  484. 'id_distribution' => $idDistribution,
  485. 'id_product' => $idProduct,
  486. ]) ;
  487. $productDistribution->active = $active ;
  488. $productDistribution->save() ;
  489. return ['success'] ;
  490. }
  491. public function actionAjaxProcessActivePointSale($idDistribution, $idPointSale, $delivery)
  492. {
  493. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  494. $pointSaleDistribution = PointSaleDistribution::searchOne([
  495. 'id_distribution' => $idDistribution,
  496. 'id_point_sale' => $idPointSale,
  497. ]) ;
  498. $pointSaleDistribution->delivery = $delivery ;
  499. $pointSaleDistribution->save() ;
  500. return ['success'] ;
  501. }
  502. /**
  503. * Active/désactive un jour de distribution.
  504. *
  505. * @param integer $idDistribution
  506. * @param string $date
  507. * @param boolean $active
  508. * @return array
  509. */
  510. public function actionAjaxProcessActiveDistribution($idDistribution = 0, $date = '', $active)
  511. {
  512. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  513. if($idDistribution) {
  514. $distribution = Distribution::searchOne([
  515. 'id' => $idDistribution
  516. ]) ;
  517. }
  518. $format = 'Y-m-d' ;
  519. $dateObject = DateTime::createFromFormat($format, $date);
  520. if($dateObject && $dateObject->format($format) === $date) {
  521. $distribution = Distribution::initDistribution($date) ;
  522. }
  523. if($distribution) {
  524. $distribution->active($active) ;
  525. return ['success'] ;
  526. }
  527. return ['error'] ;
  528. }
  529. /**
  530. * Change l'état d'une semaine de production (activé, désactivé).
  531. *
  532. * @param string $date
  533. * @param integer $active
  534. */
  535. public function actionAjaxProcessActiveWeekDistribution($date, $active)
  536. {
  537. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  538. $week = sprintf('%02d',date('W',strtotime($date)));
  539. $start = strtotime(date('Y',strtotime($date)).'W'.$week);
  540. $dateMonday = date('Y-m-d',strtotime('Monday',$start)) ;
  541. $dateTuesday = date('Y-m-d',strtotime('Tuesday',$start)) ;
  542. $dateWednesday = date('Y-m-d',strtotime('Wednesday',$start)) ;
  543. $dateThursday = date('Y-m-d',strtotime('Thursday',$start)) ;
  544. $dateFriday = date('Y-m-d',strtotime('Friday',$start)) ;
  545. $dateSaturday = date('Y-m-d',strtotime('Saturday',$start)) ;
  546. $dateSunday = date('Y-m-d',strtotime('Sunday',$start)) ;
  547. $pointsSaleArray = PointSale::searchAll() ;
  548. $activeMonday = false ;
  549. $activeTuesday = false ;
  550. $activeWednesday = false ;
  551. $activeThursday = false ;
  552. $activeFriday = false ;
  553. $activeSaturday = false ;
  554. $activeSunday = false ;
  555. foreach($pointsSaleArray as $pointSale) {
  556. if($pointSale->delivery_monday) $activeMonday = true ;
  557. if($pointSale->delivery_tuesday) $activeTuesday = true ;
  558. if($pointSale->delivery_wednesday) $activeWednesday = true ;
  559. if($pointSale->delivery_thursday) $activeThursday = true ;
  560. if($pointSale->delivery_friday) $activeFriday = true ;
  561. if($pointSale->delivery_saturday) $activeSaturday = true ;
  562. if($pointSale->delivery_sunday) $activeSunday = true ;
  563. }
  564. if($activeMonday || !$active) {
  565. $this->actionAjaxProcessActiveDistribution(0, $dateMonday, $active) ;
  566. }
  567. if($activeTuesday || !$active) {
  568. $this->actionAjaxProcessActiveDistribution(0, $dateTuesday, $active) ;
  569. }
  570. if($activeWednesday || !$active) {
  571. $this->actionAjaxProcessActiveDistribution(0, $dateWednesday, $active) ;
  572. }
  573. if($activeThursday || !$active) {
  574. $this->actionAjaxProcessActiveDistribution(0, $dateThursday, $active) ;
  575. }
  576. if($activeFriday || !$active) {
  577. $this->actionAjaxProcessActiveDistribution(0, $dateFriday, $active) ;
  578. }
  579. if($activeSaturday || !$active) {
  580. $this->actionAjaxProcessActiveDistribution(0, $dateSaturday, $active) ;
  581. }
  582. if($activeSunday || !$active) {
  583. $this->actionAjaxProcessActiveDistribution(0, $dateSunday, $active) ;
  584. }
  585. return ['success'] ;
  586. }
  587. /**
  588. * Ajoute les commandes récurrentes pour une date donnée.
  589. *
  590. * @param string $date
  591. */
  592. public function actionAjaxProcessAddSubscriptions($date)
  593. {
  594. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  595. Subscription::addAll($date, true);
  596. return ['success'] ;
  597. }
  598. }