You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1340 lines
70KB

  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. // abonnements manquants
  316. $arraySubscriptions = Subscription::searchByDate($date);
  317. $json['missing_subscriptions'] = [] ;
  318. foreach ($arraySubscriptions as $subscription) {
  319. if (!$subscription->hasOrderAlreadyExist($ordersArrayObject)) {
  320. $json['missing_subscriptions'][] = [
  321. 'username' => $subscription->getUsername()
  322. ] ;
  323. }
  324. }
  325. }
  326. return $json;
  327. }
  328. public function actionAjaxPointSaleFavorite($idUser)
  329. {
  330. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  331. $user = User::findOne(['id' => $idUser]);
  332. $favoritePointSale = $user->getFavoritePointSale();
  333. $idFavoritePointSale = 0;
  334. if ($favoritePointSale) {
  335. $idFavoritePointSale = $favoritePointSale->id;
  336. }
  337. return [
  338. 'id_favorite_point_sale' => $idFavoritePointSale
  339. ];
  340. }
  341. /**
  342. * Génére un PDF récapitulatif des des commandes d'un producteur pour une
  343. * date donnée (Méthode appelable via CRON)
  344. *
  345. * @param string $date
  346. * @param boolean $save
  347. * @param integer $idProducer
  348. * @param string $key
  349. * @return PDF|null
  350. */
  351. public function actionReportCron($date = '', $save = false, $idProducer = 0, $key = '')
  352. {
  353. if ($key == '64ac0bdab7e9f5e48c4d991ec5201d57') {
  354. $this->actionReport($date, $save, $idProducer);
  355. }
  356. }
  357. /**
  358. * Génére un PDF récapitulatif des commandes d'un producteur pour une
  359. * date donnée.
  360. *
  361. * @param string $date
  362. * @param boolean $save
  363. * @param integer $idProducer
  364. * @return PDF|null
  365. */
  366. public function actionReport($date = '', $save = false, $idProducer = 0, $type = "pdf")
  367. {
  368. if (!Yii::$app->user->isGuest) {
  369. $idProducer = GlobalParam::getCurrentProducerId();
  370. }
  371. $ordersArray = Order::searchAll([
  372. 'distribution.date' => $date,
  373. 'distribution.id_producer' => $idProducer
  374. ],
  375. [
  376. 'orderby' => 'user.lastname ASC, user.name ASC, comment_point_sale ASC',
  377. 'conditions' => 'date_delete IS NULL'
  378. ]);
  379. $distribution = Distribution::searchOne([
  380. 'id_producer' => $idProducer
  381. ], [
  382. 'conditions' => 'date LIKE :date',
  383. 'params' => [':date' => $date]
  384. ]);
  385. if ($distribution) {
  386. $selectedProductsArray = ProductDistribution::searchByDistribution($distribution->id);
  387. $pointsSaleArray = PointSale::searchAll([
  388. 'point_sale.id_producer' => $idProducer
  389. ]);
  390. foreach ($pointsSaleArray as $pointSale) {
  391. $pointSale->initOrders($ordersArray);
  392. }
  393. // produits
  394. $productsArray = Product::find()
  395. ->joinWith(['productDistribution' => function ($q) use ($distribution) {
  396. $q->where(['id_distribution' => $distribution->id]);
  397. }])
  398. ->where([
  399. 'id_producer' => $idProducer,
  400. ])
  401. ->orderBy('order ASC')
  402. ->all();
  403. if ($type == 'pdf') {
  404. $viewPdf = 'report' ;
  405. $orientationPdf = Pdf::ORIENT_PORTRAIT ;
  406. $producer = GlobalParam::getCurrentProducer() ;
  407. if($producer->slug == 'bourlinguepacotille') {
  408. $viewPdf = 'report-bourlingue' ;
  409. $orientationPdf = Pdf::ORIENT_LANDSCAPE ;
  410. }
  411. // get your HTML raw content without any layouts or scripts
  412. $content = $this->renderPartial($viewPdf, [
  413. 'date' => $date,
  414. 'distribution' => $distribution,
  415. 'selectedProductsArray' => $selectedProductsArray,
  416. 'pointsSaleArray' => $pointsSaleArray,
  417. 'productsArray' => $productsArray,
  418. 'ordersArray' => $ordersArray
  419. ]);
  420. $dateStr = date('d/m/Y', strtotime($date));
  421. if ($save) {
  422. $destination = Pdf::DEST_FILE;
  423. } else {
  424. $destination = Pdf::DEST_BROWSER;
  425. }
  426. $pdf = new Pdf([
  427. // set to use core fonts only
  428. 'mode' => Pdf::MODE_UTF8,
  429. // A4 paper format
  430. 'format' => Pdf::FORMAT_A4,
  431. // portrait orientation
  432. 'orientation' => $orientationPdf,
  433. // stream to browser inline
  434. 'destination' => $destination,
  435. 'filename' => Yii::getAlias('@app/web/pdf/Commandes-' . $date . '-' . $idProducer . '.pdf'),
  436. // your html content input
  437. 'content' => $content,
  438. // format content from your own css file if needed or use the
  439. // enhanced bootstrap css built by Krajee for mPDF formatting
  440. //'cssFile' => Yii::getAlias('@web/css/distribution/report.css'),
  441. // any css to be embedded if required
  442. 'cssInline' => '
  443. table {
  444. border-spacing : 0px ;
  445. border-collapse : collapse ;
  446. width: 100% ;
  447. }
  448. table tr th,
  449. table tr td {
  450. padding: 0px ;
  451. margin: 0px ;
  452. border: solid 1px #e0e0e0 ;
  453. padding: 3px 8px ;
  454. vertical-align : top;
  455. page-break-inside: avoid !important;
  456. }
  457. table tr th {
  458. font-size: 13px ;
  459. }
  460. table tr td {
  461. font-size: 13px ;
  462. }
  463. ',
  464. // set mPDF properties on the fly
  465. //'options' => ['title' => 'Krajee Report Title'],
  466. // call mPDF methods on the fly
  467. 'methods' => [
  468. 'SetHeader' => ['Commandes du ' . $dateStr],
  469. 'SetFooter' => ['{PAGENO}'],
  470. ]
  471. ]);
  472. // return the pdf output as per the destination setting
  473. return $pdf->render();
  474. }
  475. elseif ($type == 'csv') {
  476. $datas = [];
  477. $optionCsvExportAllProducts = Producer::getConfig('option_csv_export_all_products') ;
  478. $optionCsvExportByPiece = Producer::getConfig('option_csv_export_by_piece') ;
  479. // produits en colonne
  480. $productsNameArray = [''];
  481. $productsIndexArray = [];
  482. $productsHasQuantity = [];
  483. $cpt = 1;
  484. foreach ($productsArray as $product) {
  485. $productsHasQuantity[$product->id] = 0;
  486. foreach (Product::$unitsArray as $unit => $dataUnit) {
  487. $quantity = Order::getProductQuantity($product->id, $ordersArray, true, $unit);
  488. if ($quantity) {
  489. $productsHasQuantity[$product->id] += $quantity;
  490. }
  491. }
  492. if ($productsHasQuantity[$product->id] > 0 || $optionCsvExportAllProducts) {
  493. $productName = $product->name ;
  494. if($optionCsvExportByPiece) {
  495. $productUnit = 'piece' ;
  496. }
  497. else {
  498. $productUnit = $product->unit ;
  499. }
  500. $productName .= ' (' . Product::strUnit($productUnit, 'wording_short', true) . ')';
  501. $productsNameArray[] = $productName ;
  502. $productsIndexArray[$product->id] = $cpt++;
  503. }
  504. }
  505. $datas[] = $productsNameArray;
  506. // points de vente
  507. foreach ($pointsSaleArray as $pointSale) {
  508. if (count($pointSale->orders)) {
  509. // listing commandes
  510. $datas[] = ['> ' . $pointSale->name];
  511. foreach ($pointSale->orders as $order) {
  512. $orderLine = [$order->getStrUser()];
  513. if($optionCsvExportByPiece) {
  514. foreach ($order->productOrder as $productOrder) {
  515. $orderLine[$productsIndexArray[$productOrder->id_product]] = Order::getProductQuantityPieces($productOrder->id_product, [$order]) ;
  516. }
  517. }
  518. else {
  519. foreach ($productsIndexArray as $idProduct => $indexProduct) {
  520. $orderLine[$indexProduct] = '';
  521. }
  522. foreach ($order->productOrder as $productOrder) {
  523. if (strlen($orderLine[$productsIndexArray[$productOrder->id_product]])) {
  524. $orderLine[$productsIndexArray[$productOrder->id_product]] .= ' + ';
  525. }
  526. $orderLine[$productsIndexArray[$productOrder->id_product]] .= $productOrder->quantity;
  527. if ($productOrder->product->unit != $productOrder->unit) {
  528. $orderLine[$productsIndexArray[$productOrder->id_product]] .= Product::strUnit($productOrder->unit, 'wording_short', true);
  529. }
  530. }
  531. }
  532. $datas[] = $this->_lineOrderReportCSV($orderLine, $cpt);
  533. }
  534. // total point de vente
  535. if($optionCsvExportByPiece) {
  536. $totalsPointSaleArray = $this->_totalReportPiecesCSV(
  537. 'Total',
  538. $pointSale->orders,
  539. $productsArray,
  540. $productsIndexArray
  541. );
  542. }
  543. else {
  544. $totalsPointSaleArray = $this->_totalReportCSV(
  545. 'Total',
  546. $pointSale->orders,
  547. $productsArray,
  548. $productsIndexArray
  549. );
  550. }
  551. $datas[] = $this->_lineOrderReportCSV($totalsPointSaleArray, $cpt);
  552. $datas[] = [];
  553. }
  554. }
  555. // global
  556. if($optionCsvExportByPiece) {
  557. $totalsGlobalArray = $this->_totalReportPiecesCSV(
  558. '> Totaux',
  559. $ordersArray,
  560. $productsArray,
  561. $productsIndexArray
  562. );
  563. }
  564. else {
  565. $totalsGlobalArray = $this->_totalReportCSV(
  566. '> Totaux',
  567. $ordersArray,
  568. $productsArray,
  569. $productsIndexArray
  570. );
  571. }
  572. $datas[] = $this->_lineOrderReportCSV($totalsGlobalArray, $cpt);
  573. CSV::downloadSendHeaders('Commandes_' . $date . '.csv');
  574. echo CSV::array2csv($datas);
  575. die();
  576. }
  577. }
  578. return null;
  579. }
  580. /**
  581. * Génère un export des commandes au format CSV à destination du Google Drive
  582. * de Terre de pains.
  583. *
  584. * @param type $date
  585. * @return CSV
  586. */
  587. public function actionReportTerredepains($date, $key)
  588. {
  589. if ($key == 'ef572cc148c001f0180c4a624189ed30') {
  590. $producer = Producer::searchOne([
  591. 'producer.slug' => 'terredepains'
  592. ]);
  593. $idProducer = $producer->id;
  594. $ordersArray = Order::searchAll([
  595. 'distribution.date' => $date,
  596. 'distribution.id_producer' => $idProducer
  597. ],
  598. [
  599. 'orderby' => 'user.lastname ASC, user.name ASC, comment_point_sale ASC',
  600. 'conditions' => 'date_delete IS NULL'
  601. ]);
  602. $distribution = Distribution::searchOne([
  603. 'distribution.id_producer' => $idProducer
  604. ], [
  605. 'conditions' => 'date LIKE :date',
  606. 'params' => [
  607. ':date' => $date,
  608. ]
  609. ]);
  610. if ($distribution) {
  611. $selectedProductsArray = ProductDistribution::searchByDistribution($distribution->id);
  612. $pointsSaleArray = PointSale::searchAll([
  613. 'point_sale.id_producer' => $idProducer
  614. ]);
  615. foreach ($pointsSaleArray as $pointSale) {
  616. $pointSale->initOrders($ordersArray);
  617. }
  618. // produits
  619. $productsArray = Product::find()
  620. ->joinWith(['productDistribution' => function ($q) use ($distribution) {
  621. $q->where(['id_distribution' => $distribution->id]);
  622. }])
  623. ->where([
  624. 'id_producer' => $idProducer,
  625. ])
  626. ->orderBy('order ASC')
  627. ->all();
  628. $datas = [];
  629. // produits en colonne
  630. $productsNameArray = [''];
  631. $productsIndexArray = [];
  632. $productsHasQuantity = [];
  633. $cpt = 1;
  634. foreach ($productsArray as $product) {
  635. $theUnit = Product::strUnit($product->unit, 'wording_short', true);
  636. $theUnit = ($theUnit == 'p.') ? '' : ' (' . $theUnit . ')';
  637. $productsNameArray[] = $product->name . $theUnit;
  638. $productsIndexArray[$product->id] = $cpt++;
  639. }
  640. $productsNameArray[] = 'Total';
  641. $datas[] = $productsNameArray;
  642. // global
  643. $totalsGlobalArray = $this->_totalReportCSV(
  644. '> Totaux',
  645. $ordersArray,
  646. $productsArray,
  647. $productsIndexArray
  648. );
  649. $datas[] = $this->_lineOrderReportCSV($totalsGlobalArray, $cpt - 1, true);
  650. $datas[] = [];
  651. // points de vente
  652. foreach ($pointsSaleArray as $pointSale) {
  653. if (count($pointSale->orders)) {
  654. // listing commandes
  655. /*foreach ($pointSale->orders as $order) {
  656. $orderLine = [$order->getStrUser()];
  657. foreach ($productsIndexArray as $idProduct => $indexProduct) {
  658. $orderLine[$indexProduct] = '';
  659. }
  660. foreach ($order->productOrder as $productOrder) {
  661. if (strlen($orderLine[$productsIndexArray[$productOrder->id_product]])) {
  662. $orderLine[$productsIndexArray[$productOrder->id_product]] .= ' + ';
  663. }
  664. $orderLine[$productsIndexArray[$productOrder->id_product]] .= $productOrder->quantity;
  665. if ($productOrder->product->unit != $productOrder->unit) {
  666. $orderLine[$productsIndexArray[$productOrder->id_product]] .= Product::strUnit($productOrder->unit, 'wording_short', true);
  667. }
  668. }
  669. $datas[] = $this->_lineOrderReportCSV($orderLine, $cpt - 1, true);
  670. }*/
  671. // total point de vente
  672. $totalsPointSaleArray = $this->_totalReportCSV(
  673. '> ' . $pointSale->name,
  674. $pointSale->orders,
  675. $productsArray,
  676. $productsIndexArray
  677. );
  678. $datas[] = $this->_lineOrderReportCSV($totalsPointSaleArray, $cpt - 1, true);
  679. }
  680. }
  681. CSV::downloadSendHeaders('Commandes_' . $date . '.csv');
  682. echo CSV::array2csv($datas);
  683. die();
  684. }
  685. return null;
  686. }
  687. }
  688. public function _totalReportCSV($label, $ordersArray, $productsArray, $productsIndexArray)
  689. {
  690. $totalsPointSaleArray = [$label];
  691. foreach ($productsArray as $product) {
  692. foreach (Product::$unitsArray as $unit => $dataUnit) {
  693. $quantity = Order::getProductQuantity($product->id, $ordersArray, false, $unit);
  694. if ($quantity) {
  695. $index = $productsIndexArray[$product->id];
  696. if (!isset($totalsPointSaleArray[$index])) {
  697. $totalsPointSaleArray[$index] = '';
  698. }
  699. if (strlen($totalsPointSaleArray[$index])) {
  700. $totalsPointSaleArray[$index] .= ' + ';
  701. }
  702. $totalsPointSaleArray[$index] .= $quantity;
  703. if ($product->unit != $unit) {
  704. $totalsPointSaleArray[$index] .= '' . Product::strUnit($unit, 'wording_short', true);
  705. }
  706. }
  707. }
  708. }
  709. return $totalsPointSaleArray;
  710. }
  711. public function _totalReportPiecesCSV($label, $ordersArray, $productsArray, $productsIndexArray)
  712. {
  713. $totalsPointSaleArray = [$label];
  714. foreach ($productsArray as $product) {
  715. $quantity = 0 ;
  716. foreach (Product::$unitsArray as $unit => $dataUnit) {
  717. $quantityProduct = Order::getProductQuantity($product->id, $ordersArray, false, $unit);
  718. if($unit == 'piece') {
  719. $quantity += $quantityProduct ;
  720. }
  721. else {
  722. if($product->weight > 0) {
  723. $quantity += ($quantityProduct * $dataUnit['coefficient']) / $product->weight ;
  724. }
  725. }
  726. }
  727. if($quantity) {
  728. $index = $productsIndexArray[$product->id];
  729. $totalsPointSaleArray[$index] = $quantity;
  730. }
  731. }
  732. return $totalsPointSaleArray;
  733. }
  734. public function _lineOrderReportCSV($orderLine, $cptMax, $showTotal = false)
  735. {
  736. $line = [];
  737. $cptTotal = 0;
  738. for ($i = 0; $i <= $cptMax; $i++) {
  739. if (isset($orderLine[$i]) && $orderLine[$i]) {
  740. $line[] = $orderLine[$i];
  741. if(is_numeric($orderLine[$i])) {
  742. $cptTotal += $orderLine[$i];
  743. }
  744. } else {
  745. $line[] = '';
  746. }
  747. }
  748. if ($cptTotal > 0 && $showTotal) {
  749. $line[] = $cptTotal;
  750. }
  751. return $line;
  752. }
  753. public function actionAjaxProcessProductQuantityMax($idDistribution, $idProduct, $quantityMax)
  754. {
  755. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  756. $productDistribution = ProductDistribution::searchOne([
  757. 'id_distribution' => $idDistribution,
  758. 'id_product' => $idProduct,
  759. ]);
  760. $productDistribution->quantity_max = (!$quantityMax) ? null : (float) $quantityMax;
  761. $productDistribution->save();
  762. return ['success'];
  763. }
  764. public function actionAjaxProcessActiveProduct($idDistribution, $idProduct, $active)
  765. {
  766. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  767. $productDistribution = ProductDistribution::searchOne([
  768. 'id_distribution' => $idDistribution,
  769. 'id_product' => $idProduct,
  770. ]);
  771. $productDistribution->active = $active;
  772. $productDistribution->save();
  773. return ['success'];
  774. }
  775. public function actionAjaxProcessActivePointSale($idDistribution, $idPointSale, $delivery)
  776. {
  777. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  778. $pointSaleDistribution = PointSaleDistribution::searchOne([
  779. 'id_distribution' => $idDistribution,
  780. 'id_point_sale' => $idPointSale,
  781. ]);
  782. $pointSaleDistribution->delivery = $delivery;
  783. $pointSaleDistribution->save();
  784. return ['success'];
  785. }
  786. /**
  787. * Active/désactive un jour de distribution.
  788. *
  789. * @param integer $idDistribution
  790. * @param string $date
  791. * @param boolean $active
  792. * @return array
  793. */
  794. public function actionAjaxProcessActiveDistribution($idDistribution = 0, $date = '', $active)
  795. {
  796. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  797. if ($idDistribution) {
  798. $distribution = Distribution::searchOne([
  799. 'id' => $idDistribution
  800. ]);
  801. }
  802. $format = 'Y-m-d';
  803. $dateObject = DateTime::createFromFormat($format, $date);
  804. if ($dateObject && $dateObject->format($format) === $date) {
  805. $distribution = Distribution::initDistribution($date);
  806. }
  807. if ($distribution) {
  808. $distribution->active($active);
  809. return ['success'];
  810. }
  811. return ['error'];
  812. }
  813. /**
  814. * Change l'état d'une semaine de production (activé, désactivé).
  815. *
  816. * @param string $date
  817. * @param integer $active
  818. */
  819. public function actionAjaxProcessActiveWeekDistribution($date, $active)
  820. {
  821. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  822. $week = sprintf('%02d', date('W', strtotime($date)));
  823. $start = strtotime(date('Y', strtotime($date)) . 'W' . $week);
  824. $dateMonday = date('Y-m-d', strtotime('Monday', $start));
  825. $dateTuesday = date('Y-m-d', strtotime('Tuesday', $start));
  826. $dateWednesday = date('Y-m-d', strtotime('Wednesday', $start));
  827. $dateThursday = date('Y-m-d', strtotime('Thursday', $start));
  828. $dateFriday = date('Y-m-d', strtotime('Friday', $start));
  829. $dateSaturday = date('Y-m-d', strtotime('Saturday', $start));
  830. $dateSunday = date('Y-m-d', strtotime('Sunday', $start));
  831. $pointsSaleArray = PointSale::searchAll();
  832. $activeMonday = false;
  833. $activeTuesday = false;
  834. $activeWednesday = false;
  835. $activeThursday = false;
  836. $activeFriday = false;
  837. $activeSaturday = false;
  838. $activeSunday = false;
  839. foreach ($pointsSaleArray as $pointSale) {
  840. if ($pointSale->delivery_monday) $activeMonday = true;
  841. if ($pointSale->delivery_tuesday) $activeTuesday = true;
  842. if ($pointSale->delivery_wednesday) $activeWednesday = true;
  843. if ($pointSale->delivery_thursday) $activeThursday = true;
  844. if ($pointSale->delivery_friday) $activeFriday = true;
  845. if ($pointSale->delivery_saturday) $activeSaturday = true;
  846. if ($pointSale->delivery_sunday) $activeSunday = true;
  847. }
  848. if ($activeMonday || !$active) {
  849. $this->actionAjaxProcessActiveDistribution(0, $dateMonday, $active);
  850. }
  851. if ($activeTuesday || !$active) {
  852. $this->actionAjaxProcessActiveDistribution(0, $dateTuesday, $active);
  853. }
  854. if ($activeWednesday || !$active) {
  855. $this->actionAjaxProcessActiveDistribution(0, $dateWednesday, $active);
  856. }
  857. if ($activeThursday || !$active) {
  858. $this->actionAjaxProcessActiveDistribution(0, $dateThursday, $active);
  859. }
  860. if ($activeFriday || !$active) {
  861. $this->actionAjaxProcessActiveDistribution(0, $dateFriday, $active);
  862. }
  863. if ($activeSaturday || !$active) {
  864. $this->actionAjaxProcessActiveDistribution(0, $dateSaturday, $active);
  865. }
  866. if ($activeSunday || !$active) {
  867. $this->actionAjaxProcessActiveDistribution(0, $dateSunday, $active);
  868. }
  869. return ['success'];
  870. }
  871. /**
  872. * Ajoute les commandes récurrentes pour une date donnée.
  873. *
  874. * @param string $date
  875. */
  876. public function actionAjaxProcessAddSubscriptions($date)
  877. {
  878. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  879. Subscription::addAll($date, true);
  880. return ['success'];
  881. }
  882. /**
  883. * Synchronise les commandes avec la plateforme Tiller pour une date donnée.
  884. *
  885. * @param string $date
  886. */
  887. public function actionAjaxProcessSynchroTiller($date)
  888. {
  889. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  890. $return = [] ;
  891. $producerTiller = Producer::getConfig('tiller');
  892. if ($producerTiller) {
  893. $tiller = new Tiller();
  894. $isSynchro = $tiller->isSynchro($date);
  895. if (!$isSynchro) {
  896. $orders = Order::searchAll([
  897. 'distribution.date' => $date,
  898. 'order.tiller_synchronization' => 1
  899. ]);
  900. $strDate = date('Y-m-d\T12:i:s+0000', strtotime($date) + 1);
  901. if ($orders && count($orders)) {
  902. foreach ($orders as $order) {
  903. $lines = [];
  904. foreach ($order->productOrder as $productOrder) {
  905. $lines[] = [
  906. 'name' => $productOrder->product->name,
  907. 'price' => $productOrder->getPriceWithTax() * 100 * $productOrder->quantity,
  908. 'tax' => $productOrder->taxRate->value * 100,
  909. 'date' => $strDate,
  910. 'quantity' => $productOrder->quantity
  911. ];
  912. }
  913. $typePaymentTiller = '';
  914. if ($order->mean_payment == MeanPayment::MONEY
  915. || $order->mean_payment == MeanPayment::CREDIT
  916. || $order->mean_payment == MeanPayment::TRANSFER
  917. || $order->mean_payment == MeanPayment::OTHER) {
  918. $typePaymentTiller = 'CASH';
  919. }
  920. if ($order->mean_payment == MeanPayment::CREDIT_CARD) {
  921. $typePaymentTiller = 'CARD';
  922. }
  923. if ($order->mean_payment == MeanPayment::CHEQUE) {
  924. $typePaymentTiller = 'BANK_CHECK';
  925. }
  926. if (!strlen($typePaymentTiller) || !$order->mean_payment) {
  927. $typePaymentTiller = 'CASH';
  928. }
  929. $return[] = $tiller->postOrder([
  930. 'externalId' => $order->id,
  931. 'type' => 1,
  932. 'status' => "CLOSED",
  933. 'openDate' => $strDate,
  934. 'closeDate' => $strDate,
  935. 'lines' => $lines,
  936. 'payments' => [[
  937. 'type' => $typePaymentTiller,
  938. 'amount' => $order->getAmountWithTax(Order::AMOUNT_TOTAL) * 100,
  939. 'status' => 'ACCEPTED',
  940. 'date' => $strDate
  941. ]]
  942. ]);
  943. }
  944. }
  945. }
  946. }
  947. return $return ;
  948. }
  949. public function actionAjaxValidateDeliveryNotes($idOrders)
  950. {
  951. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  952. if (strlen($idOrders)) {
  953. $idOrders = json_decode($idOrders, true);
  954. if (is_array($idOrders) && count($idOrders) > 0) {
  955. foreach($idOrders as $idOrder) {
  956. $order = Order::searchOne([
  957. 'id' => (int)$idOrder
  958. ]);
  959. if($order && $order->distribution->id_producer == GlobalParam::getCurrentProducerId()) {
  960. $deliveryNote = DeliveryNote::searchOne([
  961. 'id' => (int) $order->id_delivery_note
  962. ]) ;
  963. if($deliveryNote && $deliveryNote->isStatusDraft()) {
  964. $deliveryNote->changeStatus(Document::STATUS_VALID);
  965. $deliveryNote->save();
  966. }
  967. }
  968. }
  969. return [
  970. 'return' => 'success',
  971. 'alert' => [
  972. 'type' => 'success',
  973. 'message' => 'Bon(s) de livraison validé(s)'
  974. ]
  975. ] ;
  976. }
  977. }
  978. return [
  979. 'return' => 'error',
  980. 'alert' => [
  981. 'type' => 'danger',
  982. 'message' => 'Une erreur est survenue lors de la validation des bons de livraison'
  983. ]
  984. ];
  985. }
  986. public function actionAjaxGenerateDeliveryNoteEachUser($idOrders)
  987. {
  988. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  989. if (strlen($idOrders)) {
  990. $idOrders = json_decode($idOrders, true);
  991. if (is_array($idOrders) && count($idOrders) > 0) {
  992. foreach ($idOrders as $idOrder) {
  993. $order = Order::searchOne([
  994. 'id' => (int)$idOrder
  995. ]);
  996. if($order && $order->distribution->id_producer == GlobalParam::getCurrentProducerId()) {
  997. $deliveryNote = null ;
  998. $idDeliveryNote = $order->id_delivery_note ;
  999. if($idDeliveryNote) {
  1000. $deliveryNote = DeliveryNote::searchOne([
  1001. 'id' => (int) $idDeliveryNote
  1002. ]);
  1003. }
  1004. // on regénére le document si c'est un brouillon
  1005. if($deliveryNote && $deliveryNote->isStatusDraft()) {
  1006. $deliveryNote->delete() ;
  1007. $deliveryNote = null ;
  1008. }
  1009. if(!$deliveryNote) {
  1010. $deliveryNote = new DeliveryNote() ;
  1011. $deliveryNote->id_producer = GlobalParam::getCurrentProducerId();
  1012. $deliveryNote->id_user = $order->id_user;
  1013. $deliveryNote->name = 'Bon de livraison ' . $order->getUsername() . ' (' . date('d/m/Y', strtotime($order->distribution->date)) . ')';
  1014. $deliveryNote->address = $order->user->getFullAddress() ;
  1015. $deliveryNote->save();
  1016. }
  1017. if($deliveryNote) {
  1018. $order->id_delivery_note = $deliveryNote->id;
  1019. $order->save();
  1020. }
  1021. }
  1022. }
  1023. }
  1024. return [
  1025. 'return' => 'success',
  1026. 'alert' => [
  1027. 'type' => 'success',
  1028. 'message' => 'Bon(s) de livraison généré(s)'
  1029. ]
  1030. ] ;
  1031. }
  1032. return [
  1033. 'return' => 'error',
  1034. 'alert' => [
  1035. 'type' => 'danger',
  1036. 'message' => 'Une erreur est survenue lors de la génération du bon de livraison.'
  1037. ]
  1038. ];
  1039. }
  1040. public function actionAjaxGenerateDeliveryNote($idOrders)
  1041. {
  1042. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  1043. if (strlen($idOrders)) {
  1044. $idOrders = json_decode($idOrders, true);
  1045. if (is_array($idOrders) && count($idOrders) > 0) {
  1046. // récupération première commande pour obtenir des infos
  1047. reset($idOrders) ;
  1048. $firstOrder = Order::searchOne([
  1049. 'id' => (int)$idOrders[key($idOrders)]
  1050. ]);
  1051. // deliveryNote existant
  1052. $deliveryNote = null ;
  1053. $isUpdate = false ;
  1054. $i = 0 ;
  1055. $ordersArray = Order::searchAll([
  1056. 'id' => $idOrders,
  1057. ]) ;
  1058. do {
  1059. $order = $ordersArray[$i] ;
  1060. if($order->distribution->id_producer == GlobalParam::getCurrentProducerId() && $order->id_delivery_note > 0) {
  1061. $deliveryNote = DeliveryNote::searchOne([
  1062. 'id' => $order->id_delivery_note
  1063. ]) ;
  1064. $isUpdate = true ;
  1065. }
  1066. $i ++ ;
  1067. } while($deliveryNote == null && isset($ordersArray[$i])) ;
  1068. if($deliveryNote && $deliveryNote->status == Document::STATUS_VALID) {
  1069. return [
  1070. 'return' => 'error',
  1071. 'alert' => [
  1072. 'type' => 'danger',
  1073. 'message' => 'Vous ne pouvez pas modifier un bon de livraison déjà validé.'
  1074. ]
  1075. ] ;
  1076. }
  1077. if ($firstOrder) {
  1078. // génération du BL
  1079. if(!$deliveryNote) {
  1080. $deliveryNote = new DeliveryNote;
  1081. $deliveryNote->name = 'Bon de livraison ' . $firstOrder->pointSale->name . ' (' . date('d/m/Y', strtotime($firstOrder->distribution->date)) . ')';
  1082. $deliveryNote->id_producer = GlobalParam::getCurrentProducerId();
  1083. if($firstOrder->pointSale->id_user) {
  1084. $deliveryNote->id_user = $firstOrder->pointSale->id_user;
  1085. }
  1086. else {
  1087. $user = new User ;
  1088. $user->type = User::TYPE_LEGAL_PERSON ;
  1089. $user->name_legal_person = $firstOrder->pointSale->name ;
  1090. $user->address = $firstOrder->pointSale->address ;
  1091. $user->id_producer = 0 ;
  1092. $user->setPassword(Password::generate());
  1093. $user->generateAuthKey();
  1094. $user->email = '' ;
  1095. if (!strlen($user->email)) {
  1096. $user->username = 'inconnu@opendistrib.net';
  1097. }
  1098. $user->save() ;
  1099. $userProducer = new UserProducer;
  1100. $userProducer->id_user = $user->id;
  1101. $userProducer->id_producer = GlobalParam::getCurrentProducerId();
  1102. $userProducer->credit = 0;
  1103. $userProducer->active = 1;
  1104. $userProducer->save();
  1105. $firstOrder->pointSale->id_user = $user->id ;
  1106. $firstOrder->pointSale->save() ;
  1107. $deliveryNote->id_user = $user->id;
  1108. }
  1109. if(!isset($user)) {
  1110. $user = User::searchOne([
  1111. 'id' => $deliveryNote->id_user
  1112. ]) ;
  1113. }
  1114. $deliveryNote->address = $user->getFullAddress() ;
  1115. $deliveryNote->save();
  1116. }
  1117. else {
  1118. // réinitialisation des order.id_delivery_order
  1119. Order::updateAll([
  1120. 'id_delivery_note' => null
  1121. ], [
  1122. 'id_delivery_note' => $deliveryNote->id
  1123. ]) ;
  1124. }
  1125. // affectation du BL aux commandes
  1126. foreach ($idOrders as $idOrder) {
  1127. $order = Order::searchOne([
  1128. 'id' => (int)$idOrder
  1129. ]);
  1130. if ($order && $order->distribution->id_producer == GlobalParam::getCurrentProducerId()) {
  1131. $order->id_delivery_note = $deliveryNote->id;
  1132. $order->save();
  1133. }
  1134. }
  1135. return [
  1136. 'return' => 'success',
  1137. 'alert' => [
  1138. 'type' => 'success',
  1139. 'message' => 'Bon de livraison '.($isUpdate ? 'modifié' : 'généré')
  1140. ]
  1141. ] ;
  1142. }
  1143. }
  1144. }
  1145. return [
  1146. 'return' => 'error',
  1147. 'alert' => [
  1148. 'type' => 'danger',
  1149. 'message' => 'Une erreur est survenue lors de la génération du bon de livraison.'
  1150. ]
  1151. ];
  1152. }
  1153. }