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.

896 line
35KB

  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', 'report-terredepains'],
  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. $json['users'] = $usersArray ;
  249. // une production de la semaine activée ou non
  250. $oneDistributionWeekActive = false ;
  251. $week = sprintf('%02d',date('W',strtotime($date)));
  252. $start = strtotime(date('Y',strtotime($date)).'W'.$week);
  253. $dateMonday = date('Y-m-d',strtotime('Monday',$start)) ;
  254. $dateTuesday = date('Y-m-d',strtotime('Tuesday',$start)) ;
  255. $dateWednesday = date('Y-m-d',strtotime('Wednesday',$start)) ;
  256. $dateThursday = date('Y-m-d',strtotime('Thursday',$start)) ;
  257. $dateFriday = date('Y-m-d',strtotime('Friday',$start)) ;
  258. $dateSaturday = date('Y-m-d',strtotime('Saturday',$start)) ;
  259. $dateSunday = date('Y-m-d',strtotime('Sunday',$start)) ;
  260. $weekDistribution = Distribution::find()
  261. ->andWhere([
  262. 'id_producer' => Producer::getId(),
  263. 'active' => 1,
  264. ])
  265. ->andWhere(['or',
  266. ['date' => $dateMonday],
  267. ['date' => $dateTuesday],
  268. ['date' => $dateWednesday],
  269. ['date' => $dateThursday],
  270. ['date' => $dateFriday],
  271. ['date' => $dateSaturday],
  272. ['date' => $dateSunday],
  273. ])
  274. ->one();
  275. if($weekDistribution) {
  276. $oneDistributionWeekActive = true ;
  277. }
  278. $json['one_distribution_week_active'] = $oneDistributionWeekActive ;
  279. }
  280. return $json ;
  281. }
  282. public function actionAjaxPointSaleFavorite($idUser)
  283. {
  284. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  285. $user = User::findOne(['id' => $idUser]) ;
  286. $favoritePointSale = $user->getFavoritePointSale() ;
  287. $idFavoritePointSale = 0 ;
  288. if($favoritePointSale) {
  289. $idFavoritePointSale = $favoritePointSale->id ;
  290. }
  291. return [
  292. 'id_favorite_point_sale' => $idFavoritePointSale
  293. ] ;
  294. }
  295. /**
  296. * Génére un PDF récapitulatif des des commandes d'un producteur pour une
  297. * date donnée (Méthode appelable via CRON)
  298. *
  299. * @param string $date
  300. * @param boolean $save
  301. * @param integer $idProducer
  302. * @param string $key
  303. * @return PDF|null
  304. */
  305. public function actionReportCron($date = '', $save = false, $idProducer = 0, $key = '')
  306. {
  307. if($key == '64ac0bdab7e9f5e48c4d991ec5201d57') {
  308. $this->actionReport($date, $save, $idProducer) ;
  309. }
  310. }
  311. /**
  312. * Génére un PDF récapitulatif des commandes d'un producteur pour une
  313. * date donnée.
  314. *
  315. * @param string $date
  316. * @param boolean $save
  317. * @param integer $idProducer
  318. * @return PDF|null
  319. */
  320. public function actionReport($date = '', $save = false, $idProducer = 0, $type = "pdf")
  321. {
  322. if (!Yii::$app->user->isGuest) {
  323. $idProducer = Producer::getId() ;
  324. }
  325. $ordersArray = Order::searchAll([
  326. 'distribution.date' => $date,
  327. ],
  328. [
  329. 'orderby' => 'comment_point_sale ASC, user.name ASC',
  330. 'conditions' => 'date_delete IS NULL'
  331. ]) ;
  332. $distribution = Distribution::searchOne([],[
  333. 'conditions' => 'date LIKE :date',
  334. 'params' => [':date' => $date]
  335. ]) ;
  336. if ($distribution) {
  337. $selectedProductsArray = ProductDistribution::searchByDistribution($distribution->id) ;
  338. $pointsSaleArray = PointSale::searchAll() ;
  339. foreach ($pointsSaleArray as $pointSale) {
  340. $pointSale->initOrders($ordersArray) ;
  341. }
  342. // produits
  343. $productsArray = Product::find()
  344. ->joinWith(['productDistribution' => function($q) use ($distribution) {
  345. $q->where(['id_distribution' => $distribution->id]);
  346. }])
  347. ->where([
  348. 'id_producer' => Producer::getId(),
  349. ])
  350. ->orderBy('order ASC')
  351. ->all();
  352. if($type == 'pdf') {
  353. // get your HTML raw content without any layouts or scripts
  354. $content = $this->renderPartial('report', [
  355. 'date' => $date,
  356. 'distribution' => $distribution,
  357. 'selectedProductsArray' => $selectedProductsArray,
  358. 'pointsSaleArray' => $pointsSaleArray,
  359. 'productsArray' => $productsArray,
  360. 'ordersArray' => $ordersArray
  361. ]);
  362. $dateStr = date('d/m/Y', strtotime($date));
  363. if ($save) {
  364. $destination = Pdf::DEST_FILE;
  365. } else {
  366. $destination = Pdf::DEST_BROWSER;
  367. }
  368. $pdf = new Pdf([
  369. // set to use core fonts only
  370. 'mode' => Pdf::MODE_UTF8,
  371. // A4 paper format
  372. 'format' => Pdf::FORMAT_A4,
  373. // portrait orientation
  374. 'orientation' => Pdf::ORIENT_PORTRAIT,
  375. // stream to browser inline
  376. 'destination' => $destination,
  377. 'filename' => Yii::getAlias('@app/web/pdf/Commandes-' . $date . '-' . $idProducer . '.pdf'),
  378. // your html content input
  379. 'content' => $content,
  380. // format content from your own css file if needed or use the
  381. // enhanced bootstrap css built by Krajee for mPDF formatting
  382. //'cssFile' => Yii::getAlias('@web/css/distribution/report.css'),
  383. // any css to be embedded if required
  384. 'cssInline' => '
  385. table {
  386. border-spacing : 0px ;
  387. border-collapse : collapse ;
  388. width: 100% ;
  389. }
  390. table tr th,
  391. table tr td {
  392. padding: 0px ;
  393. margin: 0px ;
  394. border: solid 1px #e0e0e0 ;
  395. padding: 3px 8px ;
  396. vertical-align : top;
  397. }
  398. table tr th {
  399. font-size: 13px ;
  400. }
  401. table tr td {
  402. font-size: 13px ;
  403. }
  404. ',
  405. // set mPDF properties on the fly
  406. //'options' => ['title' => 'Krajee Report Title'],
  407. // call mPDF methods on the fly
  408. 'methods' => [
  409. 'SetHeader' => ['Commandes du ' . $dateStr],
  410. 'SetFooter' => ['{PAGENO}'],
  411. ]
  412. ]);
  413. // return the pdf output as per the destination setting
  414. return $pdf->render();
  415. }
  416. elseif($type == 'csv') {
  417. $datas = [];
  418. // produits en colonne
  419. $productsNameArray = [''] ;
  420. $productsIndexArray = [] ;
  421. $productsHasQuantity = [] ;
  422. $cpt = 1 ;
  423. foreach ($productsArray as $product) {
  424. $productsHasQuantity[$product->id] = 0 ;
  425. foreach(Product::$unitsArray as $unit => $dataUnit) {
  426. $quantity = Order::getProductQuantity($product->id, $ordersArray, true, $unit);
  427. if($quantity) {
  428. $productsHasQuantity[$product->id] += $quantity ;
  429. }
  430. }
  431. if($productsHasQuantity[$product->id] > 0) {
  432. $productsNameArray[] = $product->name .' ('.Product::strUnit($product->unit, 'wording_short', true).')' ;
  433. $productsIndexArray[$product->id] = $cpt ++ ;
  434. }
  435. }
  436. $datas[] = $productsNameArray ;
  437. // points de vente
  438. foreach ($pointsSaleArray as $pointSale) {
  439. if (count($pointSale->orders)) {
  440. // listing commandes
  441. $datas[] = ['> '.$pointSale->name] ;
  442. foreach($pointSale->orders as $order) {
  443. $orderLine = [$order->getStrUser()] ;
  444. foreach($productsIndexArray as $idProduct => $indexProduct) {
  445. $orderLine[$indexProduct] = '' ;
  446. }
  447. foreach($order->productOrder as $productOrder) {
  448. if(strlen($orderLine[$productsIndexArray[$productOrder->id_product]])) {
  449. $orderLine[$productsIndexArray[$productOrder->id_product]] .= ' + ' ;
  450. }
  451. $orderLine[$productsIndexArray[$productOrder->id_product]] .= $productOrder->quantity;
  452. if($productOrder->product->unit != $productOrder->unit) {
  453. $orderLine[$productsIndexArray[$productOrder->id_product]] .= Product::strUnit($productOrder->unit, 'wording_short', true) ;
  454. }
  455. }
  456. $datas[] = $this->_lineOrderReportCSV($orderLine, $cpt) ;
  457. }
  458. // total point de vente
  459. $totalsPointSaleArray = $this->_totalReportCSV(
  460. 'Total',
  461. $pointSale->orders,
  462. $productsArray,
  463. $productsIndexArray
  464. ) ;
  465. $datas[] = $this->_lineOrderReportCSV($totalsPointSaleArray, $cpt) ;
  466. $datas[] = [] ;
  467. }
  468. }
  469. // global
  470. $totalsGlobalArray = $this->_totalReportCSV(
  471. '> Totaux',
  472. $ordersArray,
  473. $productsArray,
  474. $productsIndexArray
  475. ) ;
  476. $datas[] = $this->_lineOrderReportCSV($totalsGlobalArray, $cpt) ;
  477. CSV::downloadSendHeaders('Commandes_'.$date.'.csv');
  478. echo CSV::array2csv($datas);
  479. die();
  480. }
  481. }
  482. return null ;
  483. }
  484. /**
  485. * Génère un export des commandes au format CSV à destination du Google Drive
  486. * de Terre de pains.
  487. *
  488. * @param type $date
  489. * @return CSV
  490. */
  491. public function actionReportTerredepains($date, $key)
  492. {
  493. if($key == 'ef572cc148c001f0180c4a624189ed30') {
  494. $producer = Producer::searchOne([
  495. 'producer.slug' => 'terredepains'
  496. ]) ;
  497. $idProducer = $producer->id ;
  498. $ordersArray = Order::searchAll([
  499. 'distribution.date' => $date,
  500. 'distribution.id_producer' => $idProducer
  501. ],
  502. [
  503. 'orderby' => 'comment_point_sale ASC, user.name ASC',
  504. 'conditions' => 'date_delete IS NULL'
  505. ]) ;
  506. $distribution = Distribution::searchOne([
  507. 'distribution.id_producer' => $idProducer
  508. ],[
  509. 'conditions' => 'date LIKE :date',
  510. 'params' => [
  511. ':date' => $date,
  512. ]
  513. ]) ;
  514. if ($distribution) {
  515. $selectedProductsArray = ProductDistribution::searchByDistribution($distribution->id) ;
  516. $pointsSaleArray = PointSale::searchAll([
  517. 'point_sale.id_producer' => $idProducer
  518. ]) ;
  519. foreach($pointsSaleArray as $pointSale) {
  520. $pointSale->initOrders($ordersArray) ;
  521. }
  522. // produits
  523. $productsArray = Product::find()
  524. ->joinWith(['productDistribution' => function($q) use ($distribution) {
  525. $q->where(['id_distribution' => $distribution->id]);
  526. }])
  527. ->where([
  528. 'id_producer' => $idProducer,
  529. ])
  530. ->orderBy('order ASC')
  531. ->all();
  532. $datas = [];
  533. // produits en colonne
  534. $productsNameArray = [''] ;
  535. $productsIndexArray = [] ;
  536. $productsHasQuantity = [] ;
  537. $cpt = 1 ;
  538. foreach ($productsArray as $product) {
  539. $theUnit = Product::strUnit($product->unit, 'wording_short', true) ;
  540. $theUnit = ($theUnit == 'p.') ? '' : ' ('.$theUnit.')' ;
  541. $productsNameArray[] = $product->name .$theUnit ;
  542. $productsIndexArray[$product->id] = $cpt ++ ;
  543. }
  544. $productsNameArray[] = 'Total' ;
  545. $datas[] = $productsNameArray ;
  546. // global
  547. $totalsGlobalArray = $this->_totalReportCSV(
  548. '> Totaux',
  549. $ordersArray,
  550. $productsArray,
  551. $productsIndexArray
  552. ) ;
  553. $datas[] = $this->_lineOrderReportCSV($totalsGlobalArray, $cpt - 1, true) ;
  554. $datas[] = [] ;
  555. // points de vente
  556. foreach ($pointsSaleArray as $pointSale) {
  557. if (count($pointSale->orders)) {
  558. // listing commandes
  559. $datas[] = ['> '.$pointSale->name] ;
  560. foreach($pointSale->orders as $order) {
  561. $orderLine = [$order->getStrUser()] ;
  562. foreach($productsIndexArray as $idProduct => $indexProduct) {
  563. $orderLine[$indexProduct] = '' ;
  564. }
  565. foreach($order->productOrder as $productOrder) {
  566. if(strlen($orderLine[$productsIndexArray[$productOrder->id_product]])) {
  567. $orderLine[$productsIndexArray[$productOrder->id_product]] .= ' + ' ;
  568. }
  569. $orderLine[$productsIndexArray[$productOrder->id_product]] .= $productOrder->quantity;
  570. if($productOrder->product->unit != $productOrder->unit) {
  571. $orderLine[$productsIndexArray[$productOrder->id_product]] .= Product::strUnit($productOrder->unit, 'wording_short', true) ;
  572. }
  573. }
  574. $datas[] = $this->_lineOrderReportCSV($orderLine, $cpt - 1, true) ;
  575. }
  576. // total point de vente
  577. $totalsPointSaleArray = $this->_totalReportCSV(
  578. 'Total point de vente',
  579. $pointSale->orders,
  580. $productsArray,
  581. $productsIndexArray
  582. ) ;
  583. $datas[] = $this->_lineOrderReportCSV($totalsPointSaleArray, $cpt - 1, true) ;
  584. $datas[] = [] ;
  585. }
  586. }
  587. CSV::downloadSendHeaders('Commandes_'.$date.'.csv');
  588. echo CSV::array2csv($datas);
  589. die();
  590. }
  591. return null ;
  592. }
  593. }
  594. public function _totalReportCSV($label, $ordersArray, $productsArray, $productsIndexArray) {
  595. $totalsPointSaleArray = [$label] ;
  596. foreach ($productsArray as $product) {
  597. foreach(Product::$unitsArray as $unit => $dataUnit) {
  598. $quantity = Order::getProductQuantity($product->id, $ordersArray, false, $unit);
  599. if ($quantity) {
  600. $index = $productsIndexArray[$product->id] ;
  601. if(!isset($totalsPointSaleArray[$index])) {
  602. $totalsPointSaleArray[$index] = '' ;
  603. }
  604. if(strlen($totalsPointSaleArray[$index])) {
  605. $totalsPointSaleArray[$index] .= ' + ' ;
  606. }
  607. $totalsPointSaleArray[$index] .= $quantity ;
  608. if($product->unit != $unit) {
  609. $totalsPointSaleArray[$index] .= ''.Product::strUnit($unit, 'wording_short', true) ;
  610. }
  611. }
  612. }
  613. }
  614. return $totalsPointSaleArray ;
  615. }
  616. public function _lineOrderReportCSV($orderLine, $cptMax, $showTotal = false)
  617. {
  618. $line = [] ;
  619. $cptTotal = 0 ;
  620. for($i = 0; $i <= $cptMax ; $i++) {
  621. if(isset($orderLine[$i]) && $orderLine[$i]) {
  622. $line[] = $orderLine[$i] ;
  623. $cptTotal += $orderLine[$i] ;
  624. }
  625. else {
  626. $line[] = '' ;
  627. }
  628. }
  629. if($cptTotal > 0 && $showTotal) {
  630. $line[] = $cptTotal ;
  631. }
  632. return $line ;
  633. }
  634. public function actionAjaxProcessProductQuantityMax($idDistribution, $idProduct, $quantityMax)
  635. {
  636. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  637. $productDistribution = ProductDistribution::searchOne([
  638. 'id_distribution' => $idDistribution,
  639. 'id_product' => $idProduct,
  640. ]) ;
  641. $productDistribution->quantity_max = (!$quantityMax) ? null : (int) $quantityMax ;
  642. $productDistribution->save() ;
  643. return ['success'] ;
  644. }
  645. public function actionAjaxProcessActiveProduct($idDistribution, $idProduct, $active)
  646. {
  647. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  648. $productDistribution = ProductDistribution::searchOne([
  649. 'id_distribution' => $idDistribution,
  650. 'id_product' => $idProduct,
  651. ]) ;
  652. $productDistribution->active = $active ;
  653. $productDistribution->save() ;
  654. return ['success'] ;
  655. }
  656. public function actionAjaxProcessActivePointSale($idDistribution, $idPointSale, $delivery)
  657. {
  658. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  659. $pointSaleDistribution = PointSaleDistribution::searchOne([
  660. 'id_distribution' => $idDistribution,
  661. 'id_point_sale' => $idPointSale,
  662. ]) ;
  663. $pointSaleDistribution->delivery = $delivery ;
  664. $pointSaleDistribution->save() ;
  665. return ['success'] ;
  666. }
  667. /**
  668. * Active/désactive un jour de distribution.
  669. *
  670. * @param integer $idDistribution
  671. * @param string $date
  672. * @param boolean $active
  673. * @return array
  674. */
  675. public function actionAjaxProcessActiveDistribution($idDistribution = 0, $date = '', $active)
  676. {
  677. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  678. if($idDistribution) {
  679. $distribution = Distribution::searchOne([
  680. 'id' => $idDistribution
  681. ]) ;
  682. }
  683. $format = 'Y-m-d' ;
  684. $dateObject = DateTime::createFromFormat($format, $date);
  685. if($dateObject && $dateObject->format($format) === $date) {
  686. $distribution = Distribution::initDistribution($date) ;
  687. }
  688. if($distribution) {
  689. $distribution->active($active) ;
  690. return ['success'] ;
  691. }
  692. return ['error'] ;
  693. }
  694. /**
  695. * Change l'état d'une semaine de production (activé, désactivé).
  696. *
  697. * @param string $date
  698. * @param integer $active
  699. */
  700. public function actionAjaxProcessActiveWeekDistribution($date, $active)
  701. {
  702. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  703. $week = sprintf('%02d',date('W',strtotime($date)));
  704. $start = strtotime(date('Y',strtotime($date)).'W'.$week);
  705. $dateMonday = date('Y-m-d',strtotime('Monday',$start)) ;
  706. $dateTuesday = date('Y-m-d',strtotime('Tuesday',$start)) ;
  707. $dateWednesday = date('Y-m-d',strtotime('Wednesday',$start)) ;
  708. $dateThursday = date('Y-m-d',strtotime('Thursday',$start)) ;
  709. $dateFriday = date('Y-m-d',strtotime('Friday',$start)) ;
  710. $dateSaturday = date('Y-m-d',strtotime('Saturday',$start)) ;
  711. $dateSunday = date('Y-m-d',strtotime('Sunday',$start)) ;
  712. $pointsSaleArray = PointSale::searchAll() ;
  713. $activeMonday = false ;
  714. $activeTuesday = false ;
  715. $activeWednesday = false ;
  716. $activeThursday = false ;
  717. $activeFriday = false ;
  718. $activeSaturday = false ;
  719. $activeSunday = false ;
  720. foreach($pointsSaleArray as $pointSale) {
  721. if($pointSale->delivery_monday) $activeMonday = true ;
  722. if($pointSale->delivery_tuesday) $activeTuesday = true ;
  723. if($pointSale->delivery_wednesday) $activeWednesday = true ;
  724. if($pointSale->delivery_thursday) $activeThursday = true ;
  725. if($pointSale->delivery_friday) $activeFriday = true ;
  726. if($pointSale->delivery_saturday) $activeSaturday = true ;
  727. if($pointSale->delivery_sunday) $activeSunday = true ;
  728. }
  729. if($activeMonday || !$active) {
  730. $this->actionAjaxProcessActiveDistribution(0, $dateMonday, $active) ;
  731. }
  732. if($activeTuesday || !$active) {
  733. $this->actionAjaxProcessActiveDistribution(0, $dateTuesday, $active) ;
  734. }
  735. if($activeWednesday || !$active) {
  736. $this->actionAjaxProcessActiveDistribution(0, $dateWednesday, $active) ;
  737. }
  738. if($activeThursday || !$active) {
  739. $this->actionAjaxProcessActiveDistribution(0, $dateThursday, $active) ;
  740. }
  741. if($activeFriday || !$active) {
  742. $this->actionAjaxProcessActiveDistribution(0, $dateFriday, $active) ;
  743. }
  744. if($activeSaturday || !$active) {
  745. $this->actionAjaxProcessActiveDistribution(0, $dateSaturday, $active) ;
  746. }
  747. if($activeSunday || !$active) {
  748. $this->actionAjaxProcessActiveDistribution(0, $dateSunday, $active) ;
  749. }
  750. return ['success'] ;
  751. }
  752. /**
  753. * Ajoute les commandes récurrentes pour une date donnée.
  754. *
  755. * @param string $date
  756. */
  757. public function actionAjaxProcessAddSubscriptions($date)
  758. {
  759. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  760. Subscription::addAll($date, true);
  761. return ['success'] ;
  762. }
  763. }