Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

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