No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

977 líneas
39KB

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