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

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