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 27KB

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