Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

1117 lines
58KB

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