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.

956 lines
38KB

  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. 'tiller' => $producer->tiller
  93. ];
  94. $distributionsArray = Distribution::searchAll([
  95. 'active' => 1
  96. ], [
  97. 'conditions' => ['date > :date_begin','date < :date_end'],
  98. 'params' => [':date_begin' => date('Y-m-d', strtotime('-1 month')), ':date_end' => date('Y-m-d', strtotime('+3 month')), ],
  99. ]) ;
  100. $json['distributions'] = $distributionsArray ;
  101. if($dateObject && $dateObject->format($format) === $date) {
  102. // distribution
  103. $distribution = Distribution::initDistribution($date) ;
  104. $json['distribution'] = [
  105. 'id' => $distribution->id,
  106. 'active' => $distribution->active,
  107. 'url_report' => Yii::$app->urlManagerBackend->createUrl(['distribution/report','date' => $distribution->date])
  108. ] ;
  109. // commandes
  110. $ordersArray = Order::searchAll([
  111. 'distribution.id' => $distribution->id,
  112. ],[
  113. 'orderby' => 'user.lastname ASC, user.name ASC'
  114. ]);
  115. // montant et poids des commandes
  116. $revenues = 0;
  117. $weight = 0 ;
  118. if($ordersArray) {
  119. foreach ($ordersArray as $order) {
  120. if(is_null($order->date_delete)) {
  121. $revenues += $order->amount;
  122. $weight += $order->weight;
  123. }
  124. }
  125. }
  126. $json['distribution']['revenues'] = Price::format($revenues);
  127. $json['distribution']['weight'] = number_format($weight, 2);
  128. // products
  129. $productsArray = Product::find()
  130. ->orWhere(['id_producer' => Producer::getId(),])
  131. ->joinWith(['productDistribution' => function($query) use($distribution) {
  132. $query->andOnCondition('product_distribution.id_distribution = '.$distribution->id) ;
  133. }])
  134. ->orderBy('product_distribution.active DESC, order ASC')
  135. ->asArray()
  136. ->all();
  137. $potentialRevenues = 0;
  138. $potentialWeight = 0;
  139. foreach($productsArray as &$theProduct) {
  140. $quantityOrder = Order::getProductQuantity($theProduct['id'], $ordersArray) ;
  141. $theProduct['quantity_ordered'] = $quantityOrder ;
  142. if(!isset($theProduct['productDistribution'][0])) {
  143. $theProductObject = (object) $theProduct ;
  144. $theProduct['productDistribution'][0] = $distribution->linkProduct($theProductObject) ;
  145. }
  146. if(!is_numeric($theProduct['productDistribution'][0]['quantity_max'])) {
  147. $theProduct['quantity_remaining'] = null ;
  148. }
  149. else {
  150. $theProduct['quantity_remaining'] = $theProduct['productDistribution'][0]['quantity_max'] - $quantityOrder ;
  151. }
  152. $theProduct['quantity_form'] = 0 ;
  153. if($theProduct['productDistribution'][0]['active'] && $theProduct['productDistribution'][0]['quantity_max']) {
  154. $potentialRevenues += $theProduct['productDistribution'][0]['quantity_max'] * $theProduct['price'];
  155. $potentialWeight += $theProduct['productDistribution'][0]['quantity_max'] * $theProduct['weight'] / 1000;
  156. }
  157. }
  158. $json['distribution']['potential_revenues'] = Price::format($potentialRevenues) ;
  159. $json['distribution']['potential_weight'] = number_format($potentialWeight, 2) ;
  160. $json['products'] = $productsArray ;
  161. // orders as array
  162. if($ordersArray) {
  163. foreach($ordersArray as &$order) {
  164. $productOrderArray = [] ;
  165. foreach($order->productOrder as $productOrder) {
  166. $productOrderArray[$productOrder->id_product] = [
  167. 'quantity' => $productOrder->quantity * Product::$unitsArray[$productOrder->unit]['coefficient'],
  168. 'unit' => $productOrder->unit,
  169. ] ;
  170. }
  171. foreach($productsArray as $product) {
  172. if(!isset($productOrderArray[$product['id']])) {
  173. $productOrderArray[$product['id']] = [
  174. 'quantity' => 0,
  175. 'unit' => $product['unit']
  176. ] ;
  177. }
  178. }
  179. $creditHistoryArray = [] ;
  180. foreach($order->creditHistory as $creditHistory) {
  181. $creditHistoryArray[] = [
  182. 'date' => date('d/m/Y H:i:s', strtotime($creditHistory->date)),
  183. 'user_action' => $creditHistory->strUserAction(),
  184. 'wording' => $creditHistory->getStrWording(),
  185. 'debit' => ($creditHistory->isTypeDebit() ? '-&nbsp;'.$creditHistory->getAmount(Order::AMOUNT_TOTAL,true) : ''),
  186. 'credit' => ($creditHistory->isTypeCredit() ? '+&nbsp;'.$creditHistory->getAmount(Order::AMOUNT_TOTAL,true) : '')
  187. ] ;
  188. }
  189. $arrayCreditUser = [] ;
  190. if(isset($order->user) && isset($order->user->userProducer)) {
  191. $arrayCreditUser['credit'] = $order->user->userProducer[0]->credit ;
  192. }
  193. $oneProductUnactivated = false ;
  194. foreach($order->productOrder as $productOrder) {
  195. foreach($productsArray as $product) {
  196. if($productOrder->id_product == $product['id'] && !$product['productDistribution'][0]['active']) {
  197. $oneProductUnactivated = true ;
  198. }
  199. }
  200. }
  201. $order = array_merge($order->getAttributes(), [
  202. 'amount' => $order->getAmount(Order::AMOUNT_TOTAL),
  203. 'amount_paid' => $order->getAmount(Order::AMOUNT_PAID),
  204. 'amount_remaining' => $order->getAmount(Order::AMOUNT_REMAINING),
  205. 'amount_surplus' => $order->getAmount(Order::AMOUNT_SURPLUS),
  206. 'user' => (isset($order->user)) ? array_merge($order->user->getAttributes(), $arrayCreditUser) : null,
  207. 'pointSale' => ['id' => $order->pointSale->id, 'name' => $order->pointSale->name],
  208. 'productOrder' => $productOrderArray,
  209. 'creditHistory' => $creditHistoryArray,
  210. 'oneProductUnactivated' => $oneProductUnactivated
  211. ]) ;
  212. }
  213. }
  214. $json['orders'] = $ordersArray ;
  215. // points de vente
  216. $pointsSaleArray = PointSale::find()
  217. ->joinWith(['pointSaleDistribution' => function($q) use ($distribution) {
  218. $q->where(['id_distribution' => $distribution->id]);
  219. }])
  220. ->where([
  221. 'id_producer' => Producer::getId(),
  222. ])
  223. ->asArray()
  224. ->all();
  225. $idPointSaleDefault = 0 ;
  226. foreach($pointsSaleArray as $pointSale) {
  227. if($pointSale['default']) {
  228. $idPointSaleDefault = $pointSale['id'] ;
  229. }
  230. }
  231. $json['points_sale'] = $pointsSaleArray ;
  232. // order create
  233. $productOrderArray = [] ;
  234. foreach($productsArray as $product) {
  235. $productOrderArray[$product['id']] = [
  236. 'quantity' => 0,
  237. 'unit' => $product['unit']
  238. ] ;
  239. }
  240. $json['order_create'] = [
  241. 'id_point_sale' => $idPointSaleDefault,
  242. 'id_user' => 0,
  243. 'username' => '',
  244. 'comment' => '',
  245. 'productOrder' => $productOrderArray
  246. ] ;
  247. // utilisateurs
  248. $usersArray = User::findBy()->all() ;
  249. $json['users'] = $usersArray ;
  250. // une production de la semaine activée ou non
  251. $oneDistributionWeekActive = false ;
  252. $week = sprintf('%02d',date('W',strtotime($date)));
  253. $start = strtotime(date('Y',strtotime($date)).'W'.$week);
  254. $dateMonday = date('Y-m-d',strtotime('Monday',$start)) ;
  255. $dateTuesday = date('Y-m-d',strtotime('Tuesday',$start)) ;
  256. $dateWednesday = date('Y-m-d',strtotime('Wednesday',$start)) ;
  257. $dateThursday = date('Y-m-d',strtotime('Thursday',$start)) ;
  258. $dateFriday = date('Y-m-d',strtotime('Friday',$start)) ;
  259. $dateSaturday = date('Y-m-d',strtotime('Saturday',$start)) ;
  260. $dateSunday = date('Y-m-d',strtotime('Sunday',$start)) ;
  261. $weekDistribution = Distribution::find()
  262. ->andWhere([
  263. 'id_producer' => Producer::getId(),
  264. 'active' => 1,
  265. ])
  266. ->andWhere(['or',
  267. ['date' => $dateMonday],
  268. ['date' => $dateTuesday],
  269. ['date' => $dateWednesday],
  270. ['date' => $dateThursday],
  271. ['date' => $dateFriday],
  272. ['date' => $dateSaturday],
  273. ['date' => $dateSunday],
  274. ])
  275. ->one();
  276. if($weekDistribution) {
  277. $oneDistributionWeekActive = true ;
  278. }
  279. $json['one_distribution_week_active'] = $oneDistributionWeekActive ;
  280. // tiller
  281. if($producer->tiller) {
  282. $tiller = new Tiller() ;
  283. $json['tiller_is_synchro'] = (int) $tiller->isSynchro($date) ;
  284. }
  285. }
  286. return $json ;
  287. }
  288. public function actionAjaxPointSaleFavorite($idUser)
  289. {
  290. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  291. $user = User::findOne(['id' => $idUser]) ;
  292. $favoritePointSale = $user->getFavoritePointSale() ;
  293. $idFavoritePointSale = 0 ;
  294. if($favoritePointSale) {
  295. $idFavoritePointSale = $favoritePointSale->id ;
  296. }
  297. return [
  298. 'id_favorite_point_sale' => $idFavoritePointSale
  299. ] ;
  300. }
  301. /**
  302. * Génére un PDF récapitulatif des des commandes d'un producteur pour une
  303. * date donnée (Méthode appelable via CRON)
  304. *
  305. * @param string $date
  306. * @param boolean $save
  307. * @param integer $idProducer
  308. * @param string $key
  309. * @return PDF|null
  310. */
  311. public function actionReportCron($date = '', $save = false, $idProducer = 0, $key = '')
  312. {
  313. if($key == '64ac0bdab7e9f5e48c4d991ec5201d57') {
  314. $this->actionReport($date, $save, $idProducer) ;
  315. }
  316. }
  317. /**
  318. * Génére un PDF récapitulatif des commandes d'un producteur pour une
  319. * date donnée.
  320. *
  321. * @param string $date
  322. * @param boolean $save
  323. * @param integer $idProducer
  324. * @return PDF|null
  325. */
  326. public function actionReport($date = '', $save = false, $idProducer = 0, $type = "pdf")
  327. {
  328. if (!Yii::$app->user->isGuest) {
  329. $idProducer = Producer::getId() ;
  330. }
  331. $ordersArray = Order::searchAll([
  332. 'distribution.date' => $date,
  333. ],
  334. [
  335. 'orderby' => 'comment_point_sale ASC, user.name ASC',
  336. 'conditions' => 'date_delete IS NULL'
  337. ]) ;
  338. $distribution = Distribution::searchOne([],[
  339. 'conditions' => 'date LIKE :date',
  340. 'params' => [':date' => $date]
  341. ]) ;
  342. if ($distribution) {
  343. $selectedProductsArray = ProductDistribution::searchByDistribution($distribution->id) ;
  344. $pointsSaleArray = PointSale::searchAll() ;
  345. foreach ($pointsSaleArray as $pointSale) {
  346. $pointSale->initOrders($ordersArray) ;
  347. }
  348. // produits
  349. $productsArray = Product::find()
  350. ->joinWith(['productDistribution' => function($q) use ($distribution) {
  351. $q->where(['id_distribution' => $distribution->id]);
  352. }])
  353. ->where([
  354. 'id_producer' => Producer::getId(),
  355. ])
  356. ->orderBy('order ASC')
  357. ->all();
  358. if($type == 'pdf') {
  359. // get your HTML raw content without any layouts or scripts
  360. $content = $this->renderPartial('report', [
  361. 'date' => $date,
  362. 'distribution' => $distribution,
  363. 'selectedProductsArray' => $selectedProductsArray,
  364. 'pointsSaleArray' => $pointsSaleArray,
  365. 'productsArray' => $productsArray,
  366. 'ordersArray' => $ordersArray
  367. ]);
  368. $dateStr = date('d/m/Y', strtotime($date));
  369. if ($save) {
  370. $destination = Pdf::DEST_FILE;
  371. } else {
  372. $destination = Pdf::DEST_BROWSER;
  373. }
  374. $pdf = new Pdf([
  375. // set to use core fonts only
  376. 'mode' => Pdf::MODE_UTF8,
  377. // A4 paper format
  378. 'format' => Pdf::FORMAT_A4,
  379. // portrait orientation
  380. 'orientation' => Pdf::ORIENT_PORTRAIT,
  381. // stream to browser inline
  382. 'destination' => $destination,
  383. 'filename' => Yii::getAlias('@app/web/pdf/Commandes-' . $date . '-' . $idProducer . '.pdf'),
  384. // your html content input
  385. 'content' => $content,
  386. // format content from your own css file if needed or use the
  387. // enhanced bootstrap css built by Krajee for mPDF formatting
  388. //'cssFile' => Yii::getAlias('@web/css/distribution/report.css'),
  389. // any css to be embedded if required
  390. 'cssInline' => '
  391. table {
  392. border-spacing : 0px ;
  393. border-collapse : collapse ;
  394. width: 100% ;
  395. }
  396. table tr th,
  397. table tr td {
  398. padding: 0px ;
  399. margin: 0px ;
  400. border: solid 1px #e0e0e0 ;
  401. padding: 3px 8px ;
  402. vertical-align : top;
  403. }
  404. table tr th {
  405. font-size: 13px ;
  406. }
  407. table tr td {
  408. font-size: 13px ;
  409. }
  410. ',
  411. // set mPDF properties on the fly
  412. //'options' => ['title' => 'Krajee Report Title'],
  413. // call mPDF methods on the fly
  414. 'methods' => [
  415. 'SetHeader' => ['Commandes du ' . $dateStr],
  416. 'SetFooter' => ['{PAGENO}'],
  417. ]
  418. ]);
  419. // return the pdf output as per the destination setting
  420. return $pdf->render();
  421. }
  422. elseif($type == 'csv') {
  423. $datas = [];
  424. // produits en colonne
  425. $productsNameArray = [''] ;
  426. $productsIndexArray = [] ;
  427. $productsHasQuantity = [] ;
  428. $cpt = 1 ;
  429. foreach ($productsArray as $product) {
  430. $productsHasQuantity[$product->id] = 0 ;
  431. foreach(Product::$unitsArray as $unit => $dataUnit) {
  432. $quantity = Order::getProductQuantity($product->id, $ordersArray, true, $unit);
  433. if($quantity) {
  434. $productsHasQuantity[$product->id] += $quantity ;
  435. }
  436. }
  437. if($productsHasQuantity[$product->id] > 0) {
  438. $productsNameArray[] = $product->name .' ('.Product::strUnit($product->unit, 'wording_short', true).')' ;
  439. $productsIndexArray[$product->id] = $cpt ++ ;
  440. }
  441. }
  442. $datas[] = $productsNameArray ;
  443. // points de vente
  444. foreach ($pointsSaleArray as $pointSale) {
  445. if (count($pointSale->orders)) {
  446. // listing commandes
  447. $datas[] = ['> '.$pointSale->name] ;
  448. foreach($pointSale->orders as $order) {
  449. $orderLine = [$order->getStrUser()] ;
  450. foreach($productsIndexArray as $idProduct => $indexProduct) {
  451. $orderLine[$indexProduct] = '' ;
  452. }
  453. foreach($order->productOrder as $productOrder) {
  454. if(strlen($orderLine[$productsIndexArray[$productOrder->id_product]])) {
  455. $orderLine[$productsIndexArray[$productOrder->id_product]] .= ' + ' ;
  456. }
  457. $orderLine[$productsIndexArray[$productOrder->id_product]] .= $productOrder->quantity;
  458. if($productOrder->product->unit != $productOrder->unit) {
  459. $orderLine[$productsIndexArray[$productOrder->id_product]] .= Product::strUnit($productOrder->unit, 'wording_short', true) ;
  460. }
  461. }
  462. $datas[] = $this->_lineOrderReportCSV($orderLine, $cpt) ;
  463. }
  464. // total point de vente
  465. $totalsPointSaleArray = $this->_totalReportCSV(
  466. 'Total',
  467. $pointSale->orders,
  468. $productsArray,
  469. $productsIndexArray
  470. ) ;
  471. $datas[] = $this->_lineOrderReportCSV($totalsPointSaleArray, $cpt) ;
  472. $datas[] = [] ;
  473. }
  474. }
  475. // global
  476. $totalsGlobalArray = $this->_totalReportCSV(
  477. '> Totaux',
  478. $ordersArray,
  479. $productsArray,
  480. $productsIndexArray
  481. ) ;
  482. $datas[] = $this->_lineOrderReportCSV($totalsGlobalArray, $cpt) ;
  483. CSV::downloadSendHeaders('Commandes_'.$date.'.csv');
  484. echo CSV::array2csv($datas);
  485. die();
  486. }
  487. }
  488. return null ;
  489. }
  490. /**
  491. * Génère un export des commandes au format CSV à destination du Google Drive
  492. * de Terre de pains.
  493. *
  494. * @param type $date
  495. * @return CSV
  496. */
  497. public function actionReportTerredepains($date, $key)
  498. {
  499. if($key == 'ef572cc148c001f0180c4a624189ed30') {
  500. $producer = Producer::searchOne([
  501. 'producer.slug' => 'terredepains'
  502. ]) ;
  503. $idProducer = $producer->id ;
  504. $ordersArray = Order::searchAll([
  505. 'distribution.date' => $date,
  506. 'distribution.id_producer' => $idProducer
  507. ],
  508. [
  509. 'orderby' => 'comment_point_sale ASC, user.name ASC',
  510. 'conditions' => 'date_delete IS NULL'
  511. ]) ;
  512. $distribution = Distribution::searchOne([
  513. 'distribution.id_producer' => $idProducer
  514. ],[
  515. 'conditions' => 'date LIKE :date',
  516. 'params' => [
  517. ':date' => $date,
  518. ]
  519. ]) ;
  520. if ($distribution) {
  521. $selectedProductsArray = ProductDistribution::searchByDistribution($distribution->id) ;
  522. $pointsSaleArray = PointSale::searchAll([
  523. 'point_sale.id_producer' => $idProducer
  524. ]) ;
  525. foreach($pointsSaleArray as $pointSale) {
  526. $pointSale->initOrders($ordersArray) ;
  527. }
  528. // produits
  529. $productsArray = Product::find()
  530. ->joinWith(['productDistribution' => function($q) use ($distribution) {
  531. $q->where(['id_distribution' => $distribution->id]);
  532. }])
  533. ->where([
  534. 'id_producer' => $idProducer,
  535. ])
  536. ->orderBy('order ASC')
  537. ->all();
  538. $datas = [];
  539. // produits en colonne
  540. $productsNameArray = [''] ;
  541. $productsIndexArray = [] ;
  542. $productsHasQuantity = [] ;
  543. $cpt = 1 ;
  544. foreach ($productsArray as $product) {
  545. $theUnit = Product::strUnit($product->unit, 'wording_short', true) ;
  546. $theUnit = ($theUnit == 'p.') ? '' : ' ('.$theUnit.')' ;
  547. $productsNameArray[] = $product->name .$theUnit ;
  548. $productsIndexArray[$product->id] = $cpt ++ ;
  549. }
  550. $productsNameArray[] = 'Total' ;
  551. $datas[] = $productsNameArray ;
  552. // global
  553. $totalsGlobalArray = $this->_totalReportCSV(
  554. '> Totaux',
  555. $ordersArray,
  556. $productsArray,
  557. $productsIndexArray
  558. ) ;
  559. $datas[] = $this->_lineOrderReportCSV($totalsGlobalArray, $cpt - 1, true) ;
  560. $datas[] = [] ;
  561. // points de vente
  562. foreach ($pointsSaleArray as $pointSale) {
  563. if (count($pointSale->orders)) {
  564. // listing commandes
  565. $datas[] = ['> '.$pointSale->name] ;
  566. foreach($pointSale->orders as $order) {
  567. $orderLine = [$order->getStrUser()] ;
  568. foreach($productsIndexArray as $idProduct => $indexProduct) {
  569. $orderLine[$indexProduct] = '' ;
  570. }
  571. foreach($order->productOrder as $productOrder) {
  572. if(strlen($orderLine[$productsIndexArray[$productOrder->id_product]])) {
  573. $orderLine[$productsIndexArray[$productOrder->id_product]] .= ' + ' ;
  574. }
  575. $orderLine[$productsIndexArray[$productOrder->id_product]] .= $productOrder->quantity;
  576. if($productOrder->product->unit != $productOrder->unit) {
  577. $orderLine[$productsIndexArray[$productOrder->id_product]] .= Product::strUnit($productOrder->unit, 'wording_short', true) ;
  578. }
  579. }
  580. $datas[] = $this->_lineOrderReportCSV($orderLine, $cpt - 1, true) ;
  581. }
  582. // total point de vente
  583. $totalsPointSaleArray = $this->_totalReportCSV(
  584. 'Total point de vente',
  585. $pointSale->orders,
  586. $productsArray,
  587. $productsIndexArray
  588. ) ;
  589. $datas[] = $this->_lineOrderReportCSV($totalsPointSaleArray, $cpt - 1, true) ;
  590. $datas[] = [] ;
  591. }
  592. }
  593. CSV::downloadSendHeaders('Commandes_'.$date.'.csv');
  594. echo CSV::array2csv($datas);
  595. die();
  596. }
  597. return null ;
  598. }
  599. }
  600. public function _totalReportCSV($label, $ordersArray, $productsArray, $productsIndexArray) {
  601. $totalsPointSaleArray = [$label] ;
  602. foreach ($productsArray as $product) {
  603. foreach(Product::$unitsArray as $unit => $dataUnit) {
  604. $quantity = Order::getProductQuantity($product->id, $ordersArray, false, $unit);
  605. if ($quantity) {
  606. $index = $productsIndexArray[$product->id] ;
  607. if(!isset($totalsPointSaleArray[$index])) {
  608. $totalsPointSaleArray[$index] = '' ;
  609. }
  610. if(strlen($totalsPointSaleArray[$index])) {
  611. $totalsPointSaleArray[$index] .= ' + ' ;
  612. }
  613. $totalsPointSaleArray[$index] .= $quantity ;
  614. if($product->unit != $unit) {
  615. $totalsPointSaleArray[$index] .= ''.Product::strUnit($unit, 'wording_short', true) ;
  616. }
  617. }
  618. }
  619. }
  620. return $totalsPointSaleArray ;
  621. }
  622. public function _lineOrderReportCSV($orderLine, $cptMax, $showTotal = false)
  623. {
  624. $line = [] ;
  625. $cptTotal = 0 ;
  626. for($i = 0; $i <= $cptMax ; $i++) {
  627. if(isset($orderLine[$i]) && $orderLine[$i]) {
  628. $line[] = $orderLine[$i] ;
  629. $cptTotal += $orderLine[$i] ;
  630. }
  631. else {
  632. $line[] = '' ;
  633. }
  634. }
  635. if($cptTotal > 0 && $showTotal) {
  636. $line[] = $cptTotal ;
  637. }
  638. return $line ;
  639. }
  640. public function actionAjaxProcessProductQuantityMax($idDistribution, $idProduct, $quantityMax)
  641. {
  642. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  643. $productDistribution = ProductDistribution::searchOne([
  644. 'id_distribution' => $idDistribution,
  645. 'id_product' => $idProduct,
  646. ]) ;
  647. $productDistribution->quantity_max = (!$quantityMax) ? null : (int) $quantityMax ;
  648. $productDistribution->save() ;
  649. return ['success'] ;
  650. }
  651. public function actionAjaxProcessActiveProduct($idDistribution, $idProduct, $active)
  652. {
  653. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  654. $productDistribution = ProductDistribution::searchOne([
  655. 'id_distribution' => $idDistribution,
  656. 'id_product' => $idProduct,
  657. ]) ;
  658. $productDistribution->active = $active ;
  659. $productDistribution->save() ;
  660. return ['success'] ;
  661. }
  662. public function actionAjaxProcessActivePointSale($idDistribution, $idPointSale, $delivery)
  663. {
  664. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  665. $pointSaleDistribution = PointSaleDistribution::searchOne([
  666. 'id_distribution' => $idDistribution,
  667. 'id_point_sale' => $idPointSale,
  668. ]) ;
  669. $pointSaleDistribution->delivery = $delivery ;
  670. $pointSaleDistribution->save() ;
  671. return ['success'] ;
  672. }
  673. /**
  674. * Active/désactive un jour de distribution.
  675. *
  676. * @param integer $idDistribution
  677. * @param string $date
  678. * @param boolean $active
  679. * @return array
  680. */
  681. public function actionAjaxProcessActiveDistribution($idDistribution = 0, $date = '', $active)
  682. {
  683. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  684. if($idDistribution) {
  685. $distribution = Distribution::searchOne([
  686. 'id' => $idDistribution
  687. ]) ;
  688. }
  689. $format = 'Y-m-d' ;
  690. $dateObject = DateTime::createFromFormat($format, $date);
  691. if($dateObject && $dateObject->format($format) === $date) {
  692. $distribution = Distribution::initDistribution($date) ;
  693. }
  694. if($distribution) {
  695. $distribution->active($active) ;
  696. return ['success'] ;
  697. }
  698. return ['error'] ;
  699. }
  700. /**
  701. * Change l'état d'une semaine de production (activé, désactivé).
  702. *
  703. * @param string $date
  704. * @param integer $active
  705. */
  706. public function actionAjaxProcessActiveWeekDistribution($date, $active)
  707. {
  708. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  709. $week = sprintf('%02d',date('W',strtotime($date)));
  710. $start = strtotime(date('Y',strtotime($date)).'W'.$week);
  711. $dateMonday = date('Y-m-d',strtotime('Monday',$start)) ;
  712. $dateTuesday = date('Y-m-d',strtotime('Tuesday',$start)) ;
  713. $dateWednesday = date('Y-m-d',strtotime('Wednesday',$start)) ;
  714. $dateThursday = date('Y-m-d',strtotime('Thursday',$start)) ;
  715. $dateFriday = date('Y-m-d',strtotime('Friday',$start)) ;
  716. $dateSaturday = date('Y-m-d',strtotime('Saturday',$start)) ;
  717. $dateSunday = date('Y-m-d',strtotime('Sunday',$start)) ;
  718. $pointsSaleArray = PointSale::searchAll() ;
  719. $activeMonday = false ;
  720. $activeTuesday = false ;
  721. $activeWednesday = false ;
  722. $activeThursday = false ;
  723. $activeFriday = false ;
  724. $activeSaturday = false ;
  725. $activeSunday = false ;
  726. foreach($pointsSaleArray as $pointSale) {
  727. if($pointSale->delivery_monday) $activeMonday = true ;
  728. if($pointSale->delivery_tuesday) $activeTuesday = true ;
  729. if($pointSale->delivery_wednesday) $activeWednesday = true ;
  730. if($pointSale->delivery_thursday) $activeThursday = true ;
  731. if($pointSale->delivery_friday) $activeFriday = true ;
  732. if($pointSale->delivery_saturday) $activeSaturday = true ;
  733. if($pointSale->delivery_sunday) $activeSunday = true ;
  734. }
  735. if($activeMonday || !$active) {
  736. $this->actionAjaxProcessActiveDistribution(0, $dateMonday, $active) ;
  737. }
  738. if($activeTuesday || !$active) {
  739. $this->actionAjaxProcessActiveDistribution(0, $dateTuesday, $active) ;
  740. }
  741. if($activeWednesday || !$active) {
  742. $this->actionAjaxProcessActiveDistribution(0, $dateWednesday, $active) ;
  743. }
  744. if($activeThursday || !$active) {
  745. $this->actionAjaxProcessActiveDistribution(0, $dateThursday, $active) ;
  746. }
  747. if($activeFriday || !$active) {
  748. $this->actionAjaxProcessActiveDistribution(0, $dateFriday, $active) ;
  749. }
  750. if($activeSaturday || !$active) {
  751. $this->actionAjaxProcessActiveDistribution(0, $dateSaturday, $active) ;
  752. }
  753. if($activeSunday || !$active) {
  754. $this->actionAjaxProcessActiveDistribution(0, $dateSunday, $active) ;
  755. }
  756. return ['success'] ;
  757. }
  758. /**
  759. * Ajoute les commandes récurrentes pour une date donnée.
  760. *
  761. * @param string $date
  762. */
  763. public function actionAjaxProcessAddSubscriptions($date)
  764. {
  765. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  766. Subscription::addAll($date, true);
  767. return ['success'] ;
  768. }
  769. /**
  770. * Synchronise les commandes avec la plateforme Tiller pour une date donnée.
  771. *
  772. * @param string $date
  773. */
  774. public function actionAjaxProcessSynchroTiller($date)
  775. {
  776. $producerTiller = Producer::getConfig('tiller') ;
  777. if($producerTiller) {
  778. $tiller = new Tiller() ;
  779. $isSynchro = $tiller->isSynchro($date) ;
  780. if(!$isSynchro) {
  781. $orders = Order::searchAll([
  782. 'distribution.date' => $date
  783. ]) ;
  784. $strDate = date('Y-m-d\T12:i:s+0000', strtotime($date) + 1) ;
  785. if($orders && count($orders)) {
  786. foreach($orders as $order) {
  787. $lines = [] ;
  788. foreach($order->productOrder as $productOrder) {
  789. $lines[] = [
  790. 'name' => $productOrder->product->name,
  791. 'price' => $productOrder->price * 100 * $productOrder->quantity,
  792. 'tax' => 5.5,
  793. 'date' => $strDate,
  794. 'quantity' => $productOrder->quantity
  795. ] ;
  796. }
  797. $tiller->postOrder([
  798. 'externalId' => $order->id,
  799. 'type' => 1,
  800. 'status' => "CLOSED",
  801. 'openDate' => $strDate,
  802. 'closeDate' => $strDate,
  803. 'lines' => $lines,
  804. 'payments' => [[
  805. 'type' => 'CASH',
  806. 'amount' => $order->getAmount(Order::AMOUNT_TOTAL) * 100,
  807. 'status' => 'ACCEPTED',
  808. 'date' => $strDate
  809. ]]
  810. ]) ;
  811. }
  812. }
  813. }
  814. }
  815. }
  816. }