No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

1133 líneas
59KB

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