選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

DistributionController.php 39KB

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