1303 lines
67KB

  1. <?php
  2. /**
  3. * Copyright distrib (2018)
  4. *
  5. * contact@opendistrib.net
  6. *
  7. * Ce logiciel est un programme informatique servant à aider les producteurs
  8. * à distribuer leur production en circuits courts.
  9. *
  10. * Ce logiciel est régi par la licence CeCILL soumise au droit français et
  11. * respectant les principes de diffusion des logiciels libres. Vous pouvez
  12. * utiliser, modifier et/ou redistribuer ce programme sous les conditions
  13. * de la licence CeCILL telle que diffusée par le CEA, le CNRS et l'INRIA
  14. * sur le site "http://www.cecill.info".
  15. *
  16. * En contrepartie de l'accessibilité au code source et des droits de copie,
  17. * de modification et de redistribution accordés par cette licence, il n'est
  18. * offert aux utilisateurs qu'une garantie limitée. Pour les mêmes raisons,
  19. * seule une responsabilité restreinte pèse sur l'auteur du programme, le
  20. * titulaire des droits patrimoniaux et les concédants successifs.
  21. *
  22. * A cet égard l'attention de l'utilisateur est attirée sur les risques
  23. * associés au chargement, à l'utilisation, à la modification et/ou au
  24. * développement et à la reproduction du logiciel par l'utilisateur étant
  25. * donné sa spécificité de logiciel libre, qui peut le rendre complexe à
  26. * manipuler et qui le réserve donc à des développeurs et des professionnels
  27. * avertis possédant des connaissances informatiques approfondies. Les
  28. * utilisateurs sont donc invités à charger et tester l'adéquation du
  29. * logiciel à leurs besoins dans des conditions permettant d'assurer la
  30. * sécurité de leurs systèmes et ou de leurs données et, plus généralement,
  31. * à l'utiliser et l'exploiter dans les mêmes conditions de sécurité.
  32. *
  33. * Le fait que vous puissiez accéder à cet en-tête signifie que vous avez
  34. * pris connaissance de la licence CeCILL, et que vous en avez accepté les
  35. * termes.
  36. */
  37. namespace backend\controllers;
  38. use backend\controllers\BackendController;
  39. use common\helpers\GlobalParam;
  40. use common\models\DeliveryNote;
  41. use common\models\Distribution;
  42. use common\models\Document;
  43. use common\models\Product;
  44. use common\models\Producer;
  45. use common\models\Order;
  46. use common\models\User;
  47. use common\models\Subscription;
  48. use common\helpers\Price;
  49. use common\models\PointSaleDistribution;
  50. use common\models\UserProducer;
  51. use DateTime;
  52. class DistributionController extends BackendController
  53. {
  54. public function behaviors()
  55. {
  56. return [
  57. 'access' => [
  58. 'class' => AccessControl::className(),
  59. 'rules' => [
  60. [
  61. 'actions' => ['report-cron', 'report-terredepains'],
  62. 'allow' => true,
  63. 'roles' => ['?']
  64. ],
  65. [
  66. 'allow' => true,
  67. 'roles' => ['@'],
  68. 'matchCallback' => function ($rule, $action) {
  69. return User::getCurrentStatus() == USER::STATUS_ADMIN
  70. || User::getCurrentStatus() == USER::STATUS_PRODUCER;
  71. }
  72. ]
  73. ],
  74. ],
  75. ];
  76. }
  77. public function actionIndex($date = '')
  78. {
  79. $this->checkProductsPointsSale();
  80. $format = 'Y-m-d';
  81. $theDate = '';
  82. $dateObject = DateTime::createFromFormat($format, $date);
  83. if ($dateObject && $dateObject->format($format) === $date) {
  84. $theDate = $date;
  85. }
  86. return $this->render('index', [
  87. 'date' => $theDate
  88. ]);
  89. }
  90. public function actionAjaxInfos($date = '')
  91. {
  92. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  93. $json = [
  94. 'distribution' => [],
  95. 'products' => []
  96. ];
  97. $format = 'Y-m-d';
  98. $dateObject = DateTime::createFromFormat($format, $date);
  99. $producer = GlobalParam::getCurrentProducer();
  100. $json['producer'] = [
  101. 'credit' => $producer->credit,
  102. 'tiller' => $producer->tiller
  103. ];
  104. $json['means_payment'] = MeanPayment::getAll();
  105. $distributionsArray = Distribution::searchAll([
  106. 'active' => 1
  107. ], [
  108. 'conditions' => ['date > :date_begin', 'date < :date_end'],
  109. 'params' => [':date_begin' => date('Y-m-d', strtotime('-1 month')), ':date_end' => date('Y-m-d', strtotime('+3 month')),],
  110. ]);
  111. $json['distributions'] = $distributionsArray;
  112. if ($dateObject && $dateObject->format($format) === $date) {
  113. // distribution
  114. $distribution = Distribution::initDistribution($date);
  115. $json['distribution'] = [
  116. 'id' => $distribution->id,
  117. 'active' => $distribution->active,
  118. 'url_report' => Yii::$app->urlManagerBackend->createUrl(['distribution/report', 'date' => $distribution->date])
  119. ];
  120. // commandes
  121. $ordersArray = Order::searchAll([
  122. 'distribution.id' => $distribution->id,
  123. ], [
  124. 'orderby' => 'user.lastname ASC, user.name ASC'
  125. ]);
  126. // montant et poids des commandes
  127. $revenues = 0;
  128. $weight = 0;
  129. if ($ordersArray) {
  130. foreach ($ordersArray as $order) {
  131. if (is_null($order->date_delete)) {
  132. $revenues += $order->getAmountWithTax();
  133. $weight += $order->weight;
  134. }
  135. }
  136. }
  137. $json['distribution']['revenues'] = Price::format($revenues);
  138. $json['distribution']['weight'] = number_format($weight, 2);
  139. // products
  140. $productsArray = Product::find()
  141. ->orWhere(['id_producer' => GlobalParam::getCurrentProducerId(),])
  142. ->joinWith(['taxRate','productDistribution' => function ($query) use ($distribution) {
  143. $query->andOnCondition('product_distribution.id_distribution = ' . $distribution->id);
  144. }])
  145. ->orderBy('product_distribution.active DESC, order ASC')
  146. ->asArray()
  147. ->all();
  148. $potentialRevenues = 0;
  149. $potentialWeight = 0;
  150. foreach ($productsArray as &$theProduct) {
  151. $quantityOrder = Order::getProductQuantity($theProduct['id'], $ordersArray);
  152. $theProduct['quantity_ordered'] = $quantityOrder;
  153. if (!isset($theProduct['productDistribution'][0])) {
  154. $theProductObject = (object)$theProduct;
  155. $theProduct['productDistribution'][0] = $distribution->linkProduct($theProductObject);
  156. }
  157. if (!is_numeric($theProduct['productDistribution'][0]['quantity_max'])) {
  158. $theProduct['quantity_remaining'] = null;
  159. } else {
  160. $theProduct['quantity_remaining'] = $theProduct['productDistribution'][0]['quantity_max'] - $quantityOrder;
  161. }
  162. $theProduct['quantity_form'] = 0;
  163. if ($theProduct['productDistribution'][0]['active'] && $theProduct['productDistribution'][0]['quantity_max']) {
  164. $potentialRevenues += $theProduct['productDistribution'][0]['quantity_max'] * $theProduct['price'];
  165. $potentialWeight += $theProduct['productDistribution'][0]['quantity_max'] * $theProduct['weight'] / 1000;
  166. }
  167. if(!isset($theProduct['taxRate'])) {
  168. $theProduct['taxRate'] = $producer->taxRate ;
  169. }
  170. }
  171. $json['distribution']['potential_revenues'] = Price::format($potentialRevenues);
  172. $json['distribution']['potential_weight'] = number_format($potentialWeight, 2);
  173. $json['products'] = $productsArray;
  174. // orders as array
  175. $ordersArrayObject = $ordersArray ;
  176. if ($ordersArray) {
  177. foreach ($ordersArray as &$order) {
  178. $productOrderArray = [];
  179. foreach ($order->productOrder as $productOrder) {
  180. $productOrderArray[$productOrder->id_product] = [
  181. 'quantity' => $productOrder->quantity * Product::$unitsArray[$productOrder->unit]['coefficient'],
  182. 'unit' => $productOrder->unit,
  183. 'price' => Price::getPriceWithTax($productOrder->price, $productOrder->taxRate->value)
  184. ];
  185. }
  186. foreach ($productsArray as $product) {
  187. if (!isset($productOrderArray[$product['id']])) {
  188. $productOrderArray[$product['id']] = [
  189. 'quantity' => 0,
  190. 'unit' => $product['unit'],
  191. 'price' => Price::getPriceWithTax($product['price'], $product['taxRate']['value']),
  192. ];
  193. }
  194. }
  195. $creditHistoryArray = [];
  196. foreach ($order->creditHistory as $creditHistory) {
  197. $creditHistoryArray[] = [
  198. 'date' => date('d/m/Y H:i:s', strtotime($creditHistory->date)),
  199. 'user_action' => $creditHistory->strUserAction(),
  200. 'wording' => $creditHistory->getStrWording(),
  201. 'debit' => ($creditHistory->isTypeDebit() ? '-&nbsp;' . $creditHistory->getAmount(Order::AMOUNT_TOTAL, true) : ''),
  202. 'credit' => ($creditHistory->isTypeCredit() ? '+&nbsp;' . $creditHistory->getAmount(Order::AMOUNT_TOTAL, true) : '')
  203. ];
  204. }
  205. $arrayCreditUser = [];
  206. if (isset($order->user) && isset($order->user->userProducer)) {
  207. $arrayCreditUser['credit'] = $order->user->userProducer[0]->credit;
  208. }
  209. $oneProductUnactivated = false;
  210. foreach ($order->productOrder as $productOrder) {
  211. foreach ($productsArray as $product) {
  212. if ($productOrder->id_product == $product['id'] && !$product['productDistribution'][0]['active']) {
  213. $oneProductUnactivated = true;
  214. }
  215. }
  216. }
  217. $order = array_merge($order->getAttributes(), [
  218. 'selected' => false,
  219. 'amount' => $order->getAmountWithTax(Order::AMOUNT_TOTAL),
  220. 'amount_paid' => $order->getAmount(Order::AMOUNT_PAID),
  221. 'amount_remaining' => $order->getAmount(Order::AMOUNT_REMAINING),
  222. 'amount_surplus' => $order->getAmount(Order::AMOUNT_SURPLUS),
  223. 'user' => (isset($order->user)) ? array_merge($order->user->getAttributes(), $arrayCreditUser) : null,
  224. 'pointSale' => ['id' => $order->pointSale->id, 'name' => $order->pointSale->name],
  225. 'productOrder' => $productOrderArray,
  226. 'creditHistory' => $creditHistoryArray,
  227. 'oneProductUnactivated' => $oneProductUnactivated
  228. ]);
  229. }
  230. }
  231. $json['orders'] = $ordersArray;
  232. // points de vente
  233. $pointsSaleArray = PointSale::find()
  234. ->joinWith(['pointSaleDistribution' => function ($q) use ($distribution) {
  235. $q->where(['id_distribution' => $distribution->id]);
  236. }])
  237. ->where([
  238. 'id_producer' => GlobalParam::getCurrentProducerId(),
  239. ])
  240. ->asArray()
  241. ->all();
  242. $idPointSaleDefault = 0;
  243. foreach ($pointsSaleArray as $pointSale) {
  244. if ($pointSale['default']) {
  245. $idPointSaleDefault = $pointSale['id'] ;
  246. }
  247. }
  248. $json['points_sale'] = $pointsSaleArray;
  249. // bons de livraison
  250. $deliveryNotesArray = DeliveryNote::searchAll([
  251. 'distribution.date' => $date,
  252. ]) ;
  253. $deliveryNotesByPointSaleArray = [] ;
  254. foreach($deliveryNotesArray as $deliveryNote) {
  255. if(isset($deliveryNote->orders[0])) {
  256. $deliveryNotesByPointSaleArray[$deliveryNote->orders[0]->id_point_sale] =
  257. $deliveryNote->getAttributes() ;
  258. }
  259. }
  260. $json['delivery_notes'] = $deliveryNotesByPointSaleArray ;
  261. // order create
  262. $productOrderArray = [];
  263. foreach ($productsArray as $product) {
  264. $productOrderArray[$product['id']] = [
  265. 'quantity' => 0,
  266. 'unit' => $product['unit'],
  267. 'price' => Price::getPriceWithTax($product['price'], $product['taxRate']['value']),
  268. ];
  269. }
  270. $json['order_create'] = [
  271. 'id_point_sale' => $idPointSaleDefault,
  272. 'id_user' => 0,
  273. 'username' => '',
  274. 'comment' => '',
  275. 'productOrder' => $productOrderArray
  276. ];
  277. // utilisateurs
  278. $usersArray = User::findBy()->all();
  279. $json['users'] = $usersArray;
  280. // une production de la semaine activée ou non
  281. $oneDistributionWeekActive = false;
  282. $week = sprintf('%02d', date('W', strtotime($date)));
  283. $start = strtotime(date('Y', strtotime($date)) . 'W' . $week);
  284. $dateMonday = date('Y-m-d', strtotime('Monday', $start));
  285. $dateTuesday = date('Y-m-d', strtotime('Tuesday', $start));
  286. $dateWednesday = date('Y-m-d', strtotime('Wednesday', $start));
  287. $dateThursday = date('Y-m-d', strtotime('Thursday', $start));
  288. $dateFriday = date('Y-m-d', strtotime('Friday', $start));
  289. $dateSaturday = date('Y-m-d', strtotime('Saturday', $start));
  290. $dateSunday = date('Y-m-d', strtotime('Sunday', $start));
  291. $weekDistribution = Distribution::find()
  292. ->andWhere([
  293. 'id_producer' => GlobalParam::getCurrentProducerId(),
  294. 'active' => 1,
  295. ])
  296. ->andWhere(['or',
  297. ['date' => $dateMonday],
  298. ['date' => $dateTuesday],
  299. ['date' => $dateWednesday],
  300. ['date' => $dateThursday],
  301. ['date' => $dateFriday],
  302. ['date' => $dateSaturday],
  303. ['date' => $dateSunday],
  304. ])
  305. ->one();
  306. if ($weekDistribution) {
  307. $oneDistributionWeekActive = true;
  308. }
  309. $json['one_distribution_week_active'] = $oneDistributionWeekActive;
  310. // tiller
  311. if ($producer->tiller) {
  312. $tiller = new Tiller();
  313. $json['tiller_is_synchro'] = (int)$tiller->isSynchro($date);
  314. }
  315. }
  316. return $json;
  317. }
  318. public function actionAjaxPointSaleFavorite($idUser)
  319. {
  320. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  321. $user = User::findOne(['id' => $idUser]);
  322. $favoritePointSale = $user->getFavoritePointSale();
  323. $idFavoritePointSale = 0;
  324. if ($favoritePointSale) {
  325. $idFavoritePointSale = $favoritePointSale->id;
  326. }
  327. return [
  328. 'id_favorite_point_sale' => $idFavoritePointSale
  329. ];
  330. }
  331. /**
  332. * Génére un PDF récapitulatif des des commandes d'un producteur pour une
  333. * date donnée (Méthode appelable via CRON)
  334. *
  335. * @param string $date
  336. * @param boolean $save
  337. * @param integer $idProducer
  338. * @param string $key
  339. * @return PDF|null
  340. */
  341. public function actionReportCron($date = '', $save = false, $idProducer = 0, $key = '')
  342. {
  343. if ($key == '64ac0bdab7e9f5e48c4d991ec5201d57') {
  344. $this->actionReport($date, $save, $idProducer);
  345. }
  346. }
  347. /**
  348. * Génére un PDF récapitulatif des commandes d'un producteur pour une
  349. * date donnée.
  350. *
  351. * @param string $date
  352. * @param boolean $save
  353. * @param integer $idProducer
  354. * @return PDF|null
  355. */
  356. public function actionReport($date = '', $save = false, $idProducer = 0, $type = "pdf")
  357. {
  358. if (!Yii::$app->user->isGuest) {
  359. $idProducer = GlobalParam::getCurrentProducerId();
  360. }
  361. $ordersArray = Order::searchAll([
  362. 'distribution.date' => $date,
  363. 'distribution.id_producer' => $idProducer
  364. ],
  365. [
  366. 'orderby' => 'user.lastname ASC, user.name ASC, comment_point_sale ASC',
  367. 'conditions' => 'date_delete IS NULL'
  368. ]);
  369. $distribution = Distribution::searchOne([
  370. 'id_producer' => $idProducer
  371. ], [
  372. 'conditions' => 'date LIKE :date',
  373. 'params' => [':date' => $date]
  374. ]);
  375. if ($distribution) {
  376. $selectedProductsArray = ProductDistribution::searchByDistribution($distribution->id);
  377. $pointsSaleArray = PointSale::searchAll([
  378. 'point_sale.id_producer' => $idProducer
  379. ]);
  380. foreach ($pointsSaleArray as $pointSale) {
  381. $pointSale->initOrders($ordersArray);
  382. }
  383. // produits
  384. $productsArray = Product::find()
  385. ->joinWith(['productDistribution' => function ($q) use ($distribution) {
  386. $q->where(['id_distribution' => $distribution->id]);
  387. }])
  388. ->where([
  389. 'id_producer' => $idProducer,
  390. ])
  391. ->orderBy('order ASC')
  392. ->all();
  393. if ($type == 'pdf') {
  394. $viewPdf = 'report' ;
  395. $orientationPdf = Pdf::ORIENT_PORTRAIT ;
  396. $producer = GlobalParam::getCurrentProducer() ;
  397. if($producer->slug == 'bourlinguepacotille') {
  398. $viewPdf = 'report-bourlingue' ;
  399. $orientationPdf = Pdf::ORIENT_LANDSCAPE ;
  400. }
  401. // get your HTML raw content without any layouts or scripts
  402. $content = $this->renderPartial($viewPdf, [
  403. 'date' => $date,
  404. 'distribution' => $distribution,
  405. 'selectedProductsArray' => $selectedProductsArray,
  406. 'pointsSaleArray' => $pointsSaleArray,
  407. 'productsArray' => $productsArray,
  408. 'ordersArray' => $ordersArray
  409. ]);
  410. $dateStr = date('d/m/Y', strtotime($date));
  411. if ($save) {
  412. $destination = Pdf::DEST_FILE;
  413. } else {
  414. $destination = Pdf::DEST_BROWSER;
  415. }
  416. $pdf = new Pdf([
  417. // set to use core fonts only
  418. 'mode' => Pdf::MODE_UTF8,
  419. // A4 paper format
  420. 'format' => Pdf::FORMAT_A4,
  421. // portrait orientation
  422. 'orientation' => $orientationPdf,
  423. // stream to browser inline
  424. 'destination' => $destination,
  425. 'filename' => Yii::getAlias('@app/web/pdf/Commandes-' . $date . '-' . $idProducer . '.pdf'),
  426. // your html content input
  427. 'content' => $content,
  428. // format content from your own css file if needed or use the
  429. // enhanced bootstrap css built by Krajee for mPDF formatting
  430. //'cssFile' => Yii::getAlias('@web/css/distribution/report.css'),
  431. // any css to be embedded if required
  432. 'cssInline' => '
  433. table {
  434. border-spacing : 0px ;
  435. border-collapse : collapse ;
  436. width: 100% ;
  437. }
  438. table tr th,
  439. table tr td {
  440. padding: 0px ;
  441. margin: 0px ;
  442. border: solid 1px #e0e0e0 ;
  443. padding: 3px 8px ;
  444. vertical-align : top;
  445. page-break-inside: avoid !important;
  446. }
  447. table tr th {
  448. font-size: 13px ;
  449. }
  450. table tr td {
  451. font-size: 13px ;
  452. }
  453. ',
  454. // set mPDF properties on the fly
  455. //'options' => ['title' => 'Krajee Report Title'],
  456. // call mPDF methods on the fly
  457. 'methods' => [
  458. 'SetHeader' => ['Commandes du ' . $dateStr],
  459. 'SetFooter' => ['{PAGENO}'],
  460. ]
  461. ]);
  462. // return the pdf output as per the destination setting
  463. return $pdf->render();
  464. } elseif ($type == 'csv') {
  465. $datas = [];
  466. $optionCsvExportAllProducts = Producer::getConfig('option_csv_export_all_products') ;
  467. // produits en colonne
  468. $productsNameArray = [''];
  469. $productsIndexArray = [];
  470. $productsHasQuantity = [];
  471. $cpt = 1;
  472. foreach ($productsArray as $product) {
  473. $productsHasQuantity[$product->id] = 0;
  474. foreach (Product::$unitsArray as $unit => $dataUnit) {
  475. $quantity = Order::getProductQuantity($product->id, $ordersArray, true, $unit);
  476. if ($quantity) {
  477. $productsHasQuantity[$product->id] += $quantity;
  478. }
  479. }
  480. if ($productsHasQuantity[$product->id] > 0 || $optionCsvExportAllProducts) {
  481. $productsNameArray[] = $product->name . ' (' . Product::strUnit($product->unit, 'wording_short', true) . ')';
  482. $productsIndexArray[$product->id] = $cpt++;
  483. }
  484. }
  485. $datas[] = $productsNameArray;
  486. // points de vente
  487. foreach ($pointsSaleArray as $pointSale) {
  488. if (count($pointSale->orders)) {
  489. // listing commandes
  490. $datas[] = ['> ' . $pointSale->name];
  491. foreach ($pointSale->orders as $order) {
  492. $orderLine = [$order->getStrUser()];
  493. foreach ($productsIndexArray as $idProduct => $indexProduct) {
  494. $orderLine[$indexProduct] = '';
  495. }
  496. foreach ($order->productOrder as $productOrder) {
  497. if (strlen($orderLine[$productsIndexArray[$productOrder->id_product]])) {
  498. $orderLine[$productsIndexArray[$productOrder->id_product]] .= ' + ';
  499. }
  500. $orderLine[$productsIndexArray[$productOrder->id_product]] .= $productOrder->quantity;
  501. if ($productOrder->product->unit != $productOrder->unit) {
  502. $orderLine[$productsIndexArray[$productOrder->id_product]] .= Product::strUnit($productOrder->unit, 'wording_short', true);
  503. }
  504. }
  505. $datas[] = $this->_lineOrderReportCSV($orderLine, $cpt);
  506. }
  507. // total point de vente
  508. $totalsPointSaleArray = $this->_totalReportCSV(
  509. ' Total (unité)',
  510. $pointSale->orders,
  511. $productsArray,
  512. $productsIndexArray
  513. );
  514. $datas[] = $this->_lineOrderReportCSV($totalsPointSaleArray, $cpt);
  515. $totalsGlobalPiecesArray = $this->_totalReportPiecesCSV(
  516. ' Total (pièces)',
  517. $ordersArray,
  518. $productsArray,
  519. $productsIndexArray
  520. );
  521. $datas[] = $this->_lineOrderReportCSV($totalsGlobalPiecesArray, $cpt);
  522. $datas[] = [];
  523. }
  524. }
  525. // global
  526. $totalsGlobalArray = $this->_totalReportCSV(
  527. '> Totaux (unité)',
  528. $ordersArray,
  529. $productsArray,
  530. $productsIndexArray
  531. );
  532. $datas[] = $this->_lineOrderReportCSV($totalsGlobalArray, $cpt);
  533. // global (pièces)
  534. $totalsGlobalPiecesArray = $this->_totalReportPiecesCSV(
  535. '> Totaux (pièces)',
  536. $ordersArray,
  537. $productsArray,
  538. $productsIndexArray
  539. );
  540. $datas[] = $this->_lineOrderReportCSV($totalsGlobalPiecesArray, $cpt);
  541. CSV::downloadSendHeaders('Commandes_' . $date . '.csv');
  542. echo CSV::array2csv($datas);
  543. die();
  544. }
  545. }
  546. return null;
  547. }
  548. /**
  549. * Génère un export des commandes au format CSV à destination du Google Drive
  550. * de Terre de pains.
  551. *
  552. * @param type $date
  553. * @return CSV
  554. */
  555. public function actionReportTerredepains($date, $key)
  556. {
  557. if ($key == 'ef572cc148c001f0180c4a624189ed30') {
  558. $producer = Producer::searchOne([
  559. 'producer.slug' => 'terredepains'
  560. ]);
  561. $idProducer = $producer->id;
  562. $ordersArray = Order::searchAll([
  563. 'distribution.date' => $date,
  564. 'distribution.id_producer' => $idProducer
  565. ],
  566. [
  567. 'orderby' => 'user.lastname ASC, user.name ASC, comment_point_sale ASC',
  568. 'conditions' => 'date_delete IS NULL'
  569. ]);
  570. $distribution = Distribution::searchOne([
  571. 'distribution.id_producer' => $idProducer
  572. ], [
  573. 'conditions' => 'date LIKE :date',
  574. 'params' => [
  575. ':date' => $date,
  576. ]
  577. ]);
  578. if ($distribution) {
  579. $selectedProductsArray = ProductDistribution::searchByDistribution($distribution->id);
  580. $pointsSaleArray = PointSale::searchAll([
  581. 'point_sale.id_producer' => $idProducer
  582. ]);
  583. foreach ($pointsSaleArray as $pointSale) {
  584. $pointSale->initOrders($ordersArray);
  585. }
  586. // produits
  587. $productsArray = Product::find()
  588. ->joinWith(['productDistribution' => function ($q) use ($distribution) {
  589. $q->where(['id_distribution' => $distribution->id]);
  590. }])
  591. ->where([
  592. 'id_producer' => $idProducer,
  593. ])
  594. ->orderBy('order ASC')
  595. ->all();
  596. $datas = [];
  597. // produits en colonne
  598. $productsNameArray = [''];
  599. $productsIndexArray = [];
  600. $productsHasQuantity = [];
  601. $cpt = 1;
  602. foreach ($productsArray as $product) {
  603. $theUnit = Product::strUnit($product->unit, 'wording_short', true);
  604. $theUnit = ($theUnit == 'p.') ? '' : ' (' . $theUnit . ')';
  605. $productsNameArray[] = $product->name . $theUnit;
  606. $productsIndexArray[$product->id] = $cpt++;
  607. }
  608. $productsNameArray[] = 'Total';
  609. $datas[] = $productsNameArray;
  610. // global
  611. $totalsGlobalArray = $this->_totalReportCSV(
  612. '> Totaux',
  613. $ordersArray,
  614. $productsArray,
  615. $productsIndexArray
  616. );
  617. $datas[] = $this->_lineOrderReportCSV($totalsGlobalArray, $cpt - 1, true);
  618. $datas[] = [];
  619. // points de vente
  620. foreach ($pointsSaleArray as $pointSale) {
  621. if (count($pointSale->orders)) {
  622. // listing commandes
  623. /*foreach ($pointSale->orders as $order) {
  624. $orderLine = [$order->getStrUser()];
  625. foreach ($productsIndexArray as $idProduct => $indexProduct) {
  626. $orderLine[$indexProduct] = '';
  627. }
  628. foreach ($order->productOrder as $productOrder) {
  629. if (strlen($orderLine[$productsIndexArray[$productOrder->id_product]])) {
  630. $orderLine[$productsIndexArray[$productOrder->id_product]] .= ' + ';
  631. }
  632. $orderLine[$productsIndexArray[$productOrder->id_product]] .= $productOrder->quantity;
  633. if ($productOrder->product->unit != $productOrder->unit) {
  634. $orderLine[$productsIndexArray[$productOrder->id_product]] .= Product::strUnit($productOrder->unit, 'wording_short', true);
  635. }
  636. }
  637. $datas[] = $this->_lineOrderReportCSV($orderLine, $cpt - 1, true);
  638. }*/
  639. // total point de vente
  640. $totalsPointSaleArray = $this->_totalReportCSV(
  641. '> ' . $pointSale->name,
  642. $pointSale->orders,
  643. $productsArray,
  644. $productsIndexArray
  645. );
  646. $datas[] = $this->_lineOrderReportCSV($totalsPointSaleArray, $cpt - 1, true);
  647. }
  648. }
  649. CSV::downloadSendHeaders('Commandes_' . $date . '.csv');
  650. echo CSV::array2csv($datas);
  651. die();
  652. }
  653. return null;
  654. }
  655. }
  656. public function _totalReportCSV($label, $ordersArray, $productsArray, $productsIndexArray)
  657. {
  658. $totalsPointSaleArray = [$label];
  659. foreach ($productsArray as $product) {
  660. foreach (Product::$unitsArray as $unit => $dataUnit) {
  661. $quantity = Order::getProductQuantity($product->id, $ordersArray, false, $unit);
  662. if ($quantity) {
  663. $index = $productsIndexArray[$product->id];
  664. if (!isset($totalsPointSaleArray[$index])) {
  665. $totalsPointSaleArray[$index] = '';
  666. }
  667. if (strlen($totalsPointSaleArray[$index])) {
  668. $totalsPointSaleArray[$index] .= ' + ';
  669. }
  670. $totalsPointSaleArray[$index] .= $quantity;
  671. if ($product->unit != $unit) {
  672. $totalsPointSaleArray[$index] .= '' . Product::strUnit($unit, 'wording_short', true);
  673. }
  674. }
  675. }
  676. }
  677. return $totalsPointSaleArray;
  678. }
  679. public function _totalReportPiecesCSV($label, $ordersArray, $productsArray, $productsIndexArray)
  680. {
  681. $totalsPointSaleArray = [$label];
  682. foreach ($productsArray as $product) {
  683. $quantity = 0 ;
  684. foreach (Product::$unitsArray as $unit => $dataUnit) {
  685. $quantityProduct = Order::getProductQuantity($product->id, $ordersArray, false, $unit);
  686. if($unit == 'piece') {
  687. $quantity += $quantityProduct ;
  688. }
  689. else {
  690. if($product->weight > 0) {
  691. $quantity += ($quantityProduct * $dataUnit['coefficient']) / $product->weight ;
  692. }
  693. }
  694. }
  695. if($quantity) {
  696. $index = $productsIndexArray[$product->id];
  697. $totalsPointSaleArray[$index] = $quantity;
  698. }
  699. }
  700. return $totalsPointSaleArray;
  701. }
  702. public function _lineOrderReportCSV($orderLine, $cptMax, $showTotal = false)
  703. {
  704. $line = [];
  705. $cptTotal = 0;
  706. for ($i = 0; $i <= $cptMax; $i++) {
  707. if (isset($orderLine[$i]) && $orderLine[$i]) {
  708. $line[] = $orderLine[$i];
  709. if(is_numeric($orderLine[$i])) {
  710. $cptTotal += $orderLine[$i];
  711. }
  712. } else {
  713. $line[] = '';
  714. }
  715. }
  716. if ($cptTotal > 0 && $showTotal) {
  717. $line[] = $cptTotal;
  718. }
  719. return $line;
  720. }
  721. public function actionAjaxProcessProductQuantityMax($idDistribution, $idProduct, $quantityMax)
  722. {
  723. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  724. $productDistribution = ProductDistribution::searchOne([
  725. 'id_distribution' => $idDistribution,
  726. 'id_product' => $idProduct,
  727. ]);
  728. $productDistribution->quantity_max = (!$quantityMax) ? null : (float) $quantityMax;
  729. $productDistribution->save();
  730. return ['success'];
  731. }
  732. public function actionAjaxProcessActiveProduct($idDistribution, $idProduct, $active)
  733. {
  734. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  735. $productDistribution = ProductDistribution::searchOne([
  736. 'id_distribution' => $idDistribution,
  737. 'id_product' => $idProduct,
  738. ]);
  739. $productDistribution->active = $active;
  740. $productDistribution->save();
  741. return ['success'];
  742. }
  743. public function actionAjaxProcessActivePointSale($idDistribution, $idPointSale, $delivery)
  744. {
  745. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  746. $pointSaleDistribution = PointSaleDistribution::searchOne([
  747. 'id_distribution' => $idDistribution,
  748. 'id_point_sale' => $idPointSale,
  749. ]);
  750. $pointSaleDistribution->delivery = $delivery;
  751. $pointSaleDistribution->save();
  752. return ['success'];
  753. }
  754. /**
  755. * Active/désactive un jour de distribution.
  756. *
  757. * @param integer $idDistribution
  758. * @param string $date
  759. * @param boolean $active
  760. * @return array
  761. */
  762. public function actionAjaxProcessActiveDistribution($idDistribution = 0, $date = '', $active)
  763. {
  764. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  765. if ($idDistribution) {
  766. $distribution = Distribution::searchOne([
  767. 'id' => $idDistribution
  768. ]);
  769. }
  770. $format = 'Y-m-d';
  771. $dateObject = DateTime::createFromFormat($format, $date);
  772. if ($dateObject && $dateObject->format($format) === $date) {
  773. $distribution = Distribution::initDistribution($date);
  774. }
  775. if ($distribution) {
  776. $distribution->active($active);
  777. return ['success'];
  778. }
  779. return ['error'];
  780. }
  781. /**
  782. * Change l'état d'une semaine de production (activé, désactivé).
  783. *
  784. * @param string $date
  785. * @param integer $active
  786. */
  787. public function actionAjaxProcessActiveWeekDistribution($date, $active)
  788. {
  789. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  790. $week = sprintf('%02d', date('W', strtotime($date)));
  791. $start = strtotime(date('Y', strtotime($date)) . 'W' . $week);
  792. $dateMonday = date('Y-m-d', strtotime('Monday', $start));
  793. $dateTuesday = date('Y-m-d', strtotime('Tuesday', $start));
  794. $dateWednesday = date('Y-m-d', strtotime('Wednesday', $start));
  795. $dateThursday = date('Y-m-d', strtotime('Thursday', $start));
  796. $dateFriday = date('Y-m-d', strtotime('Friday', $start));
  797. $dateSaturday = date('Y-m-d', strtotime('Saturday', $start));
  798. $dateSunday = date('Y-m-d', strtotime('Sunday', $start));
  799. $pointsSaleArray = PointSale::searchAll();
  800. $activeMonday = false;
  801. $activeTuesday = false;
  802. $activeWednesday = false;
  803. $activeThursday = false;
  804. $activeFriday = false;
  805. $activeSaturday = false;
  806. $activeSunday = false;
  807. foreach ($pointsSaleArray as $pointSale) {
  808. if ($pointSale->delivery_monday) $activeMonday = true;
  809. if ($pointSale->delivery_tuesday) $activeTuesday = true;
  810. if ($pointSale->delivery_wednesday) $activeWednesday = true;
  811. if ($pointSale->delivery_thursday) $activeThursday = true;
  812. if ($pointSale->delivery_friday) $activeFriday = true;
  813. if ($pointSale->delivery_saturday) $activeSaturday = true;
  814. if ($pointSale->delivery_sunday) $activeSunday = true;
  815. }
  816. if ($activeMonday || !$active) {
  817. $this->actionAjaxProcessActiveDistribution(0, $dateMonday, $active);
  818. }
  819. if ($activeTuesday || !$active) {
  820. $this->actionAjaxProcessActiveDistribution(0, $dateTuesday, $active);
  821. }
  822. if ($activeWednesday || !$active) {
  823. $this->actionAjaxProcessActiveDistribution(0, $dateWednesday, $active);
  824. }
  825. if ($activeThursday || !$active) {
  826. $this->actionAjaxProcessActiveDistribution(0, $dateThursday, $active);
  827. }
  828. if ($activeFriday || !$active) {
  829. $this->actionAjaxProcessActiveDistribution(0, $dateFriday, $active);
  830. }
  831. if ($activeSaturday || !$active) {
  832. $this->actionAjaxProcessActiveDistribution(0, $dateSaturday, $active);
  833. }
  834. if ($activeSunday || !$active) {
  835. $this->actionAjaxProcessActiveDistribution(0, $dateSunday, $active);
  836. }
  837. return ['success'];
  838. }
  839. /**
  840. * Ajoute les commandes récurrentes pour une date donnée.
  841. *
  842. * @param string $date
  843. */
  844. public function actionAjaxProcessAddSubscriptions($date)
  845. {
  846. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  847. Subscription::addAll($date, true);
  848. return ['success'];
  849. }
  850. /**
  851. * Synchronise les commandes avec la plateforme Tiller pour une date donnée.
  852. *
  853. * @param string $date
  854. */
  855. public function actionAjaxProcessSynchroTiller($date)
  856. {
  857. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  858. $return = [] ;
  859. $producerTiller = Producer::getConfig('tiller');
  860. if ($producerTiller) {
  861. $tiller = new Tiller();
  862. $isSynchro = $tiller->isSynchro($date);
  863. if (!$isSynchro) {
  864. $orders = Order::searchAll([
  865. 'distribution.date' => $date,
  866. 'order.tiller_synchronization' => 1
  867. ]);
  868. $strDate = date('Y-m-d\T12:i:s+0000', strtotime($date) + 1);
  869. if ($orders && count($orders)) {
  870. foreach ($orders as $order) {
  871. $lines = [];
  872. foreach ($order->productOrder as $productOrder) {
  873. $lines[] = [
  874. 'name' => $productOrder->product->name,
  875. 'price' => $productOrder->getPriceWithTax() * 100 * $productOrder->quantity,
  876. 'tax' => $productOrder->taxRate->value * 100,
  877. 'date' => $strDate,
  878. 'quantity' => $productOrder->quantity
  879. ];
  880. }
  881. $typePaymentTiller = '';
  882. if ($order->mean_payment == MeanPayment::MONEY
  883. || $order->mean_payment == MeanPayment::CREDIT
  884. || $order->mean_payment == MeanPayment::TRANSFER
  885. || $order->mean_payment == MeanPayment::OTHER) {
  886. $typePaymentTiller = 'CASH';
  887. }
  888. if ($order->mean_payment == MeanPayment::CREDIT_CARD) {
  889. $typePaymentTiller = 'CARD';
  890. }
  891. if ($order->mean_payment == MeanPayment::CHEQUE) {
  892. $typePaymentTiller = 'BANK_CHECK';
  893. }
  894. if (!strlen($typePaymentTiller) || !$order->mean_payment) {
  895. $typePaymentTiller = 'CASH';
  896. }
  897. $return[] = $tiller->postOrder([
  898. 'externalId' => $order->id,
  899. 'type' => 1,
  900. 'status' => "CLOSED",
  901. 'openDate' => $strDate,
  902. 'closeDate' => $strDate,
  903. 'lines' => $lines,
  904. 'payments' => [[
  905. 'type' => $typePaymentTiller,
  906. 'amount' => $order->getAmountWithTax(Order::AMOUNT_TOTAL) * 100,
  907. 'status' => 'ACCEPTED',
  908. 'date' => $strDate
  909. ]]
  910. ]);
  911. }
  912. }
  913. }
  914. }
  915. return $return ;
  916. }
  917. public function actionAjaxValidateDeliveryNotes($idOrders)
  918. {
  919. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  920. if (strlen($idOrders)) {
  921. $idOrders = json_decode($idOrders, true);
  922. if (is_array($idOrders) && count($idOrders) > 0) {
  923. foreach($idOrders as $idOrder) {
  924. $order = Order::searchOne([
  925. 'id' => (int)$idOrder
  926. ]);
  927. if($order && $order->distribution->id_producer == GlobalParam::getCurrentProducerId()) {
  928. $deliveryNote = DeliveryNote::searchOne([
  929. 'id' => (int) $order->id_delivery_note
  930. ]) ;
  931. if($deliveryNote && $deliveryNote->isStatusDraft()) {
  932. $deliveryNote->changeStatus(Document::STATUS_VALID);
  933. $deliveryNote->save();
  934. }
  935. }
  936. }
  937. return [
  938. 'return' => 'success',
  939. 'alert' => [
  940. 'type' => 'success',
  941. 'message' => 'Bon(s) de livraison validé(s)'
  942. ]
  943. ] ;
  944. }
  945. }
  946. return [
  947. 'return' => 'error',
  948. 'alert' => [
  949. 'type' => 'danger',
  950. 'message' => 'Une erreur est survenue lors de la validation des bons de livraison'
  951. ]
  952. ];
  953. }
  954. public function actionAjaxGenerateDeliveryNoteEachUser($idOrders)
  955. {
  956. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  957. if (strlen($idOrders)) {
  958. $idOrders = json_decode($idOrders, true);
  959. if (is_array($idOrders) && count($idOrders) > 0) {
  960. foreach ($idOrders as $idOrder) {
  961. $order = Order::searchOne([
  962. 'id' => (int)$idOrder
  963. ]);
  964. if($order && $order->distribution->id_producer == GlobalParam::getCurrentProducerId()) {
  965. $deliveryNote = null ;
  966. $idDeliveryNote = $order->id_delivery_note ;
  967. if($idDeliveryNote) {
  968. $deliveryNote = DeliveryNote::searchOne([
  969. 'id' => (int) $idDeliveryNote
  970. ]);
  971. }
  972. // on regénére le document si c'est un brouillon
  973. if($deliveryNote && $deliveryNote->isStatusDraft()) {
  974. $deliveryNote->delete() ;
  975. $deliveryNote = null ;
  976. }
  977. if(!$deliveryNote) {
  978. $deliveryNote = new DeliveryNote() ;
  979. $deliveryNote->id_producer = GlobalParam::getCurrentProducerId();
  980. $deliveryNote->id_user = $order->id_user;
  981. $deliveryNote->name = 'Bon de livraison ' . $order->getUsername() . ' (' . date('d/m/Y', strtotime($order->distribution->date)) . ')';
  982. $deliveryNote->address = $order->user->getFullAddress() ;
  983. $deliveryNote->save();
  984. }
  985. if($deliveryNote) {
  986. $order->id_delivery_note = $deliveryNote->id;
  987. $order->save();
  988. }
  989. }
  990. }
  991. }
  992. return [
  993. 'return' => 'success',
  994. 'alert' => [
  995. 'type' => 'success',
  996. 'message' => 'Bon(s) de livraison généré(s)'
  997. ]
  998. ] ;
  999. }
  1000. return [
  1001. 'return' => 'error',
  1002. 'alert' => [
  1003. 'type' => 'danger',
  1004. 'message' => 'Une erreur est survenue lors de la génération du bon de livraison.'
  1005. ]
  1006. ];
  1007. }
  1008. public function actionAjaxGenerateDeliveryNote($idOrders)
  1009. {
  1010. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  1011. if (strlen($idOrders)) {
  1012. $idOrders = json_decode($idOrders, true);
  1013. if (is_array($idOrders) && count($idOrders) > 0) {
  1014. // récupération première commande pour obtenir des infos
  1015. reset($idOrders) ;
  1016. $firstOrder = Order::searchOne([
  1017. 'id' => (int)$idOrders[key($idOrders)]
  1018. ]);
  1019. // deliveryNote existant
  1020. $deliveryNote = null ;
  1021. $isUpdate = false ;
  1022. $i = 0 ;
  1023. $ordersArray = Order::searchAll([
  1024. 'id' => $idOrders,
  1025. ]) ;
  1026. do {
  1027. $order = $ordersArray[$i] ;
  1028. if($order->distribution->id_producer == GlobalParam::getCurrentProducerId() && $order->id_delivery_note > 0) {
  1029. $deliveryNote = DeliveryNote::searchOne([
  1030. 'id' => $order->id_delivery_note
  1031. ]) ;
  1032. $isUpdate = true ;
  1033. }
  1034. $i ++ ;
  1035. } while($deliveryNote == null && isset($ordersArray[$i])) ;
  1036. if($deliveryNote && $deliveryNote->status == Document::STATUS_VALID) {
  1037. return [
  1038. 'return' => 'error',
  1039. 'alert' => [
  1040. 'type' => 'danger',
  1041. 'message' => 'Vous ne pouvez pas modifier un bon de livraison déjà validé.'
  1042. ]
  1043. ] ;
  1044. }
  1045. if ($firstOrder) {
  1046. // génération du BL
  1047. if(!$deliveryNote) {
  1048. $deliveryNote = new DeliveryNote;
  1049. $deliveryNote->name = 'Bon de livraison ' . $firstOrder->pointSale->name . ' (' . date('d/m/Y', strtotime($firstOrder->distribution->date)) . ')';
  1050. $deliveryNote->id_producer = GlobalParam::getCurrentProducerId();
  1051. if($firstOrder->pointSale->id_user) {
  1052. $deliveryNote->id_user = $firstOrder->pointSale->id_user;
  1053. }
  1054. else {
  1055. $user = new User ;
  1056. $user->type = User::TYPE_LEGAL_PERSON ;
  1057. $user->name_legal_person = $firstOrder->pointSale->name ;
  1058. $user->address = $firstOrder->pointSale->address ;
  1059. $user->id_producer = 0 ;
  1060. $user->setPassword(Password::generate());
  1061. $user->generateAuthKey();
  1062. $user->email = '' ;
  1063. if (!strlen($user->email)) {
  1064. $user->username = 'inconnu@opendistrib.net';
  1065. }
  1066. $user->save() ;
  1067. $userProducer = new UserProducer;
  1068. $userProducer->id_user = $user->id;
  1069. $userProducer->id_producer = GlobalParam::getCurrentProducerId();
  1070. $userProducer->credit = 0;
  1071. $userProducer->active = 1;
  1072. $userProducer->save();
  1073. $firstOrder->pointSale->id_user = $user->id ;
  1074. $firstOrder->pointSale->save() ;
  1075. $deliveryNote->id_user = $user->id;
  1076. }
  1077. if(!isset($user)) {
  1078. $user = User::searchOne([
  1079. 'id' => $deliveryNote->id_user
  1080. ]) ;
  1081. }
  1082. $deliveryNote->address = $user->getFullAddress() ;
  1083. $deliveryNote->save();
  1084. }
  1085. else {
  1086. // réinitialisation des order.id_delivery_order
  1087. Order::updateAll([
  1088. 'id_delivery_note' => null
  1089. ], [
  1090. 'id_delivery_note' => $deliveryNote->id
  1091. ]) ;
  1092. }
  1093. // affectation du BL aux commandes
  1094. foreach ($idOrders as $idOrder) {
  1095. $order = Order::searchOne([
  1096. 'id' => (int)$idOrder
  1097. ]);
  1098. if ($order && $order->distribution->id_producer == GlobalParam::getCurrentProducerId()) {
  1099. $order->id_delivery_note = $deliveryNote->id;
  1100. $order->save();
  1101. }
  1102. }
  1103. return [
  1104. 'return' => 'success',
  1105. 'alert' => [
  1106. 'type' => 'success',
  1107. 'message' => 'Bon de livraison '.($isUpdate ? 'modifié' : 'généré')
  1108. ]
  1109. ] ;
  1110. }
  1111. }
  1112. }
  1113. return [
  1114. 'return' => 'error',
  1115. 'alert' => [
  1116. 'type' => 'danger',
  1117. 'message' => 'Une erreur est survenue lors de la génération du bon de livraison.'
  1118. ]
  1119. ];
  1120. }
  1121. }